我正在自学python,我的一个小项目是Rock,Paper,Scissors 游戏。
代码运行良好。不过,我想添加一个额外的功能。每当用户输入 Rock、Paper 或 Scissor 时,输入都会保留在终端中。这当然会导致第二名玩家出现一些不公平的情况。
为了避免这种情况,我使用了 getpass 函数。不幸的是,在我的代码中使用带有 P1inp 和 P2inp 的 getpass 后,输入仍然保留在终端上。谁能指出更好的解决方案或将我推向正确的方向?
import sys
import getpass
rules = "Rules:Rock beats Scissors, Scissors beats Paper, and Paper beats Rock"
print(rules)
print("Would you like to play?")
decision = input("Yes or No?")
P1 = str(input("What's the name of Player 1?"))
P2 = str(input("What's the name of Player 2?"))
P1inp = getpass.getpass(input("%s, Rock, Paper or Scissors?"%P1))
P2inp = getpass.getpass(input("%s, Rock, Paper or Scissors?"%P2))
def play(decision):
if decision == "Yes":
compare(P1inp,P2inp)
else:
print("See you next time!")
def compare(P1inp,P2inp):
if P1inp == P2inp:
print("It's a tie!")
elif P1inp == "Rock" and P2inp == "Scissors":
print("%s wins!!"%P1)
elif P1inp == "Rock" and P2inp == "Paper":
print("%s wins!!"%P2)
elif P1inp == "Paper" and P2inp == "Scissors":
print("%s wins!!"%P2)
elif P1inp == "Paper" and P2inp == "Rock":
print("%s wins!!"%P1)
elif P1inp == "Scissors" and P2inp == "Rock":
print("%s wins!!"%P2)
elif P1inp == "Scissors" and P2inp == "Paper":
print("%s wins!!"%P1)
else:
return("Invalid input")
sys.exit()
print(compare(P1inp,P2inp))
print ("Would you like to play again?")
result = input("Yes or No?")
while result == "Yes":
samePlayers = input("Are P1 and P2 still the same?")
if samePlayers == "Yes":
P1inp = input("%s, Rock, Paper or Scissors?"%P1)
P2inp = input("%s, Rock, Paper or Scissors?"%P2)
play(result)
print(compare(P1inp,P2inp))
print ("Would you like to play again?")
result = input("Yes or No?")
else:
P1 = str(input("What's the name of Player 1?"))
P2 = str(input("What's the name of Player 2?"))
P1inp = input("%s, Rock, Paper or Scissors?"%P1)
P2inp = input("%s, Rock, Paper or Scissors?"%P2)
play(result)
print(compare(P1inp,P2inp))
print ("Would you like to play again?")
result = input("Yes or No?")
else:
print("Thanks for playing!")