岩石剪刀 - Python 3 - 初学者

时间:2013-10-01 17:45:28

标签: python if-statement python-3.x

我想要模拟一个石头剪刀游戏,这是我迄今为止所拥有的。它不是让我在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)

2 个答案:

答案 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":