Python二十一点循环

时间:2013-11-11 14:51:31

标签: python blackjack

我的二十一点游戏有效,但我怎么能循环它以便在游戏结束时,他们可以选择再玩一次?非常感谢!只需要循环。欢呼声

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

2 个答案:

答案 0 :(得分:0)

您可以将其包装在另一个while循环中,或者具有两个单独的函数。

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

甚至将其分成不同的功能:

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()

答案 1 :(得分:0)

通过在循环结束时添加以下行,您的问题应该得到解决。

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!")