Search code examples
pythongetpass

Using getpass to hide user input in terminal


I'm teaching myself python and one of my little starting projects is a Rock, Paper, Scissors game.

The code runs fine. I would like to add an extra feature though. Whenever a user enters Rock, Paper or Scissor the input remains in the terminal. That of course leads to some unfair circumstances for the second player.

In order to try to circumvent this, I'm using the getpass function. Unfortunately, after using getpass with P1inp and P2inp in my code, the input still remains on the terminal. Could anyone point out a better solution or nudge me in the right direction?

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!")

Solution

  • In getpass.getpass() you should not also have input because Input asks for plain text.

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