【发布时间】:2021-12-02 19:32:25
【问题描述】:
我正在用 Python 制作二十一点游戏,并且正在使用 while 循环。在我的代码中,我得到了一个带有 if 语句的输入,如果玩家选择再玩一轮(输入“Y”),游戏就会重新开始(我没有问题)。我的问题是,如果玩家输入“N”(表示否),游戏仍然会重新运行。我想做的是当玩家输入“N”时,游戏结束。我的代码有什么问题?我被卡住了,无法弄清楚。
您也可以在我的代码中看到,我在 while 循环中多次使用 closed = True 并且它有效(例如,如果玩家获得 21 分,则游戏结束)。唯一一次 closed = True 不起作用是在我的代码的elif play_again.lower() != "Y": closed = True 部分。
closed = False
while not closed:
if player_total == 21:
print("\nCongrats, the player got a Blackjack!")
closed = True
else:
input_answer = int(input("\n1 - Hit \n2 - Stand \n \nDo you wish to Hit or Stand? "))
if input_answer == 1:
print("You chose to Hit.")
give_cards(player_hand, 1)
player_total = bjm.calculate_hand_value(player_hand)
print(f'\nThe player has got a new card: {player_hand[2]}. \nThe player currently has {", ".join(player_hand)},'
f' with a total value of {player_total}.')
if player_total > 21:
print("Busted! You got a total value over 21.")
closed = True
elif input_answer == 2:
print("\nYou chose to Stand.")
print(f'The dealers cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
print(f'The players cards are {", ".join(player_hand)} with a total value of {player_total}.')
print_result(player_hand, dealer_hand)
play_again = input("\nDo you want to play another round? Y/N: ")
if play_again.lower() != "N":
print("You wanted to play another round, you will be dealt two new cards.\n")
player_hand.clear()
dealer_hand.clear()
give_cards(player_hand, 2)
give_cards(dealer_hand, 2)
print(f'\nThe players new cards are: {" and a ".join(player_hand)}, with a total value of {player_total}.')
print(f'The dealers new cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
elif play_again.lower() != "Y":
closed = True
closed = True
【问题讨论】:
-
.lower()的东西永远不会等于大写 Y
标签: python while-loop blackjack