剪刀石头布 - Python 3 - 初学者

2024-02-08

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

你需要测试strings;您现在正在测试变量名称:

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

剪刀石头布 - Python 3 - 初学者 的相关文章

随机推荐