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)
你需要测试字符串 ; 您现在正在测试变量名称:
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)
归档时间: |
|
查看次数: |
1710 次 |
最近记录: |