石头布剪刀Python3贝金

2024-09-28 22:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: and函数游戏if字母itplayer石头
2条回答

您使用的是没有引号的字母,因此它需要一个名为p的变量,但您需要的是一个字符串“p”,因此请将字母用引号括起来:

if player1 == "P" and player2 == "S":

您需要针对字符串进行测试;现在针对变量名进行测试:

if player1 == 'R' and player2 == 'R':

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

^{pr2}$

接下来,我会用一个地图,一本字典来编纂什么胜过什么:

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

if beats[player1] == player2:
    scoregame = "Player 1 wins."
else:
    scoregame = "Player 2 wins."

现在你的游戏可以在两个测试中测试。总而言之:

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)

相关问题 更多 >