我不能在21点游戏中关闭我的whileloop

2024-05-08 03:11:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python制作一个21点游戏,我正在使用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 

Tags: totrue游戏inputplayifvaluetotal
3条回答

拆下.lower()。您正在尝试使用Y或N小写并验证它,这将永远不会到达else语句

示例-


play_again = input("\nDo you want to play another round? Y/N: ")

if play_again != "N":
    print("You wanted to play another round, you will be dealt two new cards.\n")

elif play_again != "Y":
    print("Dont want to play")

比您现在使用的结束循环更好的方法是简单地将closed = True中的条件替换为break

此外,代码无法运行的原因是,您试图将.lower()(它将始终为您提供小写字母)与大写字母进行比较,这意味着以下情况:

            elif play_again.lower() != "Y":
                closed = True

永远不会是真的

将其替换为"y",而不是"Y"

我不知道你为什么用双底片。请尝试以下方法:

while True:
    ...
    elif play_again.lower() != "Y":
        break #instead of closed=True

相关问题 更多 >