我想要模拟一个石头剪刀游戏,这是我迄今为止所拥有的。它不是让我在scoregame
函数中输入字母。我该如何解决这个问题?
def scoregame(player1, player2):
if player1 == R and player2 == R:
scoregame = "It's a tie, nobody wins."
if player1 == S and player2 == S:
scoregame == "It's a tie, nobody wins."
if player1 == P and player2 == P:
scoregame = "It's a tie, nobody wins."
if player1 == R and player2 == S:
scoregame = "Player 1 wins."
if player1 == S and player2 == P:
scoregame = "Player 1 wins."
if player1 == P and player2 == R:
scoregame = "Player 1 wins."
if player1 == R and player2 == P:
scoregame == "Player 2 wins."
if player1 == S and player2 == R:
scoregame == "Player 2 wins."
if player1 == P and player2 == S:
scoregame = "Player 2 wins."
print(scoregame)
答案 0 :(得分:5)
您需要针对字符串进行测试;您现在正在测试变量名称:
if player1 == 'R' and player2 == 'R':
但你可以简化两个玩家选择相同选项的情况,如果他们是相同的话:
if player1 == player2:
scoregame = "It's a tie, nobody wins."
接下来,我将使用一个映射,一个字典,来编写什么比什么更胜一筹:
beats = {'R': 'S', 'S': 'P', 'P': 'R'}
if beats[player1] == player2:
scoregame = "Player 1 wins."
else:
scoregame = "Player 2 wins."
现在您的游戏可以在2个测试中进行测试。全部放在一起:
def scoregame(player1, player2):
beats = {'R': 'S', 'S': 'P', 'P': 'R'}
if player1 == player2:
scoregame = "It's a tie, nobody wins."
elif beats[player1] == player2:
scoregame = "Player 1 wins."
else:
scoregame = "Player 2 wins."
print(scoregame)
答案 1 :(得分:1)
你使用没有引号的字母,所以它寻找一个名为P的变量,但你想要的是一个 String “P”,所以把这些字母放在引号中:
if player1 == "P" and player2 == "S":