python - 我无法在二十一点游戏中关闭我的 while 循环
问题描述
我正在用 Python 制作二十一点游戏,并且正在使用 while 循环。在我的代码中,我得到了一个带有 if 语句的输入,如果玩家选择再玩一轮(输入“Y”),游戏就会重新开始(我没有问题)。我的问题是,如果玩家输入“N”(表示否),游戏仍然会重新运行。我想做的是当玩家输入“N”时,游戏结束。我的代码有什么问题?我被卡住了,无法弄清楚。
此外,正如您在我的代码中看到的那样,我在 while 循环中多次使用 closed = True 并且它有效(例如,如果玩家获得 21 分,则游戏结束)。唯一一次关闭 = 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
解决方案
A better way than what you are using right now to end the loop is to simply replace your condition in closed = True
with break
.
Additionally, the reason your code isn't working is because you are trying to compare the .lower() (which will always give you a lower case letter) with a capital case letter, which means that this condition:
elif play_again.lower() != "Y":
closed = True
will never be true.
replace it with "y"
instead of "Y"
推荐阅读
- reactjs - .js 文件重命名为 .tsx 文件后的打字稿混淆错误
- python - 为什么将 GNN 与 dgl 异形图一起使用会遇到行数据不匹配错误?
- java - okhttp 客户端在 # 符号处截断 http URL
- django - 编辑多选字段?
- python - 如何在 Django 中保存静态/类变量
- r - 应用 weighted.mean() 不会影响结果?
- java - 无法加载类“com.squareup.javawriter.JavaWriter”
- nlp - 如何准备数据以使用新语言从头开始训练 GPT 模型
- javascript - CSS动画属性不适用于位置元素
- php - 你知道为什么按钮没有出现吗?