岩石剪刀 - Python 3 - 初学者

jer*_*144 -2 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)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

你需要测试字符串 ; 您现在正在测试变量名称:

if player1 == 'R' and player2 == 'R':
Run Code Online (Sandbox Code Playgroud)

但是你可以通过测试两个玩家是否相同来简化两个玩家选择相同选项的情况:

if player1 == player2:
    scoregame = "It's a tie, nobody wins."
Run Code Online (Sandbox Code Playgroud)

接下来,我将使用一个映射,一个字典,来编写什么节拍:

beats = {'R': 'S', 'S': 'P', 'P': 'R'}

if beats[player1] == player2:
    scoregame = "Player 1 wins."
else:
    scoregame = "Player 2 wins."
Run Code Online (Sandbox Code Playgroud)

现在你的游戏可以在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)
Run Code Online (Sandbox Code Playgroud)

  • @ jerry2144:为什么要污损?如果你在作业中使用我的帖子,那那就是你的问题,而不是我的问题.请不要破坏我的工作,因为它让你感到尴尬. (2认同)