Question

My Blackjack game works, but how could i loop it so that at the end of the game, they have an option to play again? Thanks a lot guys! Just need the loop. cheers

import random
endGame = (False)


dealer = random.randrange(2,20)
player = random.randrange(2,20)

print ("\n*********LETS PLAY BLACK JACK***********\n")
print ("Your starting total is "+str(player))



while endGame==(False):
    action =input("What do you want to do? stick[s] or twist[t]? ")
    if action == ("s"):
        print ("Your total is "+str(player))
        print ("Dealer's total is "+str(dealer))
        if player > dealer:
            print ("*You win!*")
        else:
            print ("Dealer wins")
            endGame = True

    if action == ("t"):
        newCard = random.randrange(1,10)
        print ("You drew "+str(newCard))
        player = player + newCard
        if player > 21:
            print ("*Bust! You lose*")
            endGame = True
        else:
            print ("Your total is now "+str(player))
            if dealer < 17:
                newDealer = random.randrange(1,10)
                dealer = dealer + newDealer

                if dealer > 21:
                    print ("*Dealer has bust! You win!")
                    endGame = True
Was it helpful?

Solution

You could wrap this in another while loop or have two separate functions.

while True:
    endgame = False
    while not endgame:
        #game actions
    play_again = raw_input("Play again y or n?")
    if play_again == 'n':
        break

or even separate this into diffrent functions:

def play_again():
    play_option = raw_input("Play again y or n?")
    if play_option == 'y': game_play()


def game_play():
    endgame = False
    while not endgame:
        #game_actions
    play_again()

OTHER TIPS

By adding the following lines at the end of the loop your problem should be fixed.

if (endGame) :
  print ("Do you want to play again? Press 1") #and take then change endGame to false
  #get the input
  #confirm it is the value you want
  if(input == 1):
     endGame=False
     #reset the values for dealer and player
     #clear screen, print the infos
  else:
     print("Thank you for playing black jack!")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top