gpt4 book ai didi

python - 剪刀石头布游戏没有按预期循环

转载 作者:行者123 更新时间:2023-11-28 20:16:41 25 4
gpt4 key购买 nike

我是 Python 的新手(以及相关的编码),并且正在进行石头剪刀布练习。在第二场比赛之后,我下面的代码不会询问我是否想再玩一场,而是自动调用游戏函数。有谁知道我可能哪里出错了?

import sys

print("Welcome to rock, paper, scissors!")

player_a = input("Player A input one of the following; rock, paper or scissors: ")
player_b = input("Player B input one of the following; rock, paper or scissors: ")

def game(p1, p2):
if p1 == p2:
print("It is a draw!")
elif p1 == "rock" and p2 == "scissors":
print("Player A wins!")
elif p1 == "rock" and p2 == "paper":
print("Player B wins!")
elif p1 == "paper" and p2 == "rock":
print("Player A wins!")
elif p1 == "paper" and p2 == "scissors":
print("Player B wins!")
elif p1 == "scissors" and p2 == "rock":
print("Player A wins!")
elif p1 == "scissors" and p2 == "paper":
print("Player B wins!")

game(player_a, player_b)

playAgain = input("Would you like to play again? (Insert Y or N): ")

while playAgain == "Y":
player_a = input("Player A input one of the following; rock, paper or scissors: ")
player_b = input("Player B input one of the following; rock, paper or scissors: ")
game(player_a, player_b)
else:
print("Thanks for playing!")
sys.exit()

最佳答案

你只需要问“再玩一次?”循环中的问题。

编码的一个重要原则是DRY:Don't Repeat Yourself .通过一点点重组,我们可以消除代码中的一些重复。

在下面的代码中,我们假设在程序开始时用户已经对“再玩一次?”回答“Y”。问题。

print("Welcome to rock, paper, scissors!")

def game(p1, p2):
if p1 == p2:
print("It is a draw!")
elif p1 == "rock" and p2 == "scissors":
print("Player A wins!")
elif p1 == "rock" and p2 == "paper":
print("Player B wins!")
elif p1 == "paper" and p2 == "rock":
print("Player A wins!")
elif p1 == "paper" and p2 == "scissors":
print("Player B wins!")
elif p1 == "scissors" and p2 == "rock":
print("Player A wins!")
elif p1 == "scissors" and p2 == "paper":
print("Player B wins!")

playAgain = "Y"
while playAgain == "Y":
player_a = input("Player A input one of the following; rock, paper or scissors: ")
player_b = input("Player B input one of the following; rock, paper or scissors: ")
game(player_a, player_b)
playAgain = input("Would you like to play again? (Insert Y or N): ")
else:
print("Thanks for playing!")

请注意,无需调用sys.exit(),我们可以让程序自然终止。


我们还可以大大压缩 game 函数。如果不是平局,并且 A 没有赢,那么 B 必须赢。所以我们不需要做所有那些 B 测试。我们可以使用 运算符将 A 测试合并为一个测试。

def game(p1, p2):
if p1 == p2:
print("It is a draw!")
elif ((p1 == "rock" and p2 == "scissors")
or (p1 == "paper" and p2 == "rock")
or (p1 == "scissors" and p2 == "paper")):
print("Player A wins!")
else:
print("Player B wins!")

进行测试的更高级(和稍微更 Pythonic)的方法是使用元组:

def game(p1, p2):
if p1 == p2:
print("It is a draw!")
elif (p1, p2) in (("rock", "scissors"), ("paper", "rock"), ("scissors", "paper")):
print("Player A wins!")
else:
print("Player B wins!")

关于python - 剪刀石头布游戏没有按预期循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42089905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com