使用 getpass 隐藏终端中的用户输入

Using getpass to hide user input in terminal

我正在自学 python 我的一个小项目是剪刀石头布游戏。

代码运行良好。不过,我想添加一个额外的功能。每当用户输入 Rock, Paper or 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!")

getpass.getpass() 中你不应该也有输入,因为输入要求纯文本。

P1inp = getpass.getpass(("%s, Rock, Paper or Scissors?"%P1))
P2inp = getpass.getpass(("%s, Rock, Paper or Scissors?"%P2))