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

时间:2016-12-26 20:10:30

标签: python getpass

我自学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!")

1 个答案:

答案 0 :(得分:1)

getpass.getpass()中,您不应该输入,因为输入要求提供纯文本。

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