-2

我想模拟一个石头剪刀布游戏,这就是我到目前为止所拥有的。它不允许我在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)
4

2 回答 2

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)
于 2013-10-01T17:49:17.563 回答
1

您正在使用不带引号的字母,因此它正在寻找一个名为 P 的变量,但您想要的是一个字符串“P”,所以将字母放在引号中:

if player1 == "P" and player2 == "S":
于 2013-10-01T17:53:51.420 回答