Using getpass to hide user input in terminal - python

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

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

Related

First little program, cant seem to fix the capitalization error

This is my first little program I have created. Can anyone help me with making it so it works with the first letter being capitalized?
# Rock Paper Scissors
import time
import random
user_wins = 0
computer_wins = 0
def RockPaperScissors():
user_choice = input("Enter your choice in a game of Rock, Paper, Scissors: ")
if user_choice == "rock" or user_choice == "paper" or user_choice == "scissors":
print("Good choice, lets see who wins.")
time.sleep(1.5)
else:
print('Please enter either "rock", "paper", or "scissors"')
computer_choice = ["rock", "paper", "scissors"]
rand_choice = random.choice(computer_choice)
print("The computer chose", rand_choice)
if user_choice == "rock" and rand_choice == "scissors":
print("You won!")
elif user_choice == "scissors" and rand_choice == "rock":
print("The computer won, try again.")
elif user_choice == "paper" and rand_choice == "rock":
print("You won!")
elif user_choice == "rock" and rand_choice == "paper":
print("The computer won, try again")
elif user_choice == "scissors" and rand_choice == "paper":
print("You won!")
elif user_choice == "paper" and rand_choice == "scissors":
print("The computer won, try again")
RockPaperScissors()
I also have a slight issue with if you capitalize the first letter, the program does not run as intended. Appreciate the help!

Why does the if statements in my program not function when it's put in a function that's meant to run?

I have created a rock, paper scissors game in Python, posted it on replit, and now the 'if statements' refuse to function.
print("Welcome to the official game of Rock, Paper, Scissors!")
option = input('''Pick an option: Rock, Paper, Scissors
>>> ''').lower()
import random
game_op =["rock", "paper", "scissors"]
computer_option = print(random.choice(game_op))
def options():
if option == "rock" and computer_option == "rock":
print("You and the Computer chose the same options.")
print('The end')
elif option == "rock" and computer_option == "paper":
print("The Computer wins!")
print('The end')
elif option == "rock" and computer_option == "scissors":
print("You win!")
print('The end')
elif option == "paper" and computer_option == "rock":
print("You win!")
print('The end')
elif option == "paper" and computer_option == "paper":
print("You and the Computer chose the same options.")
print('The end')
elif option == "paper" and computer_option == "scissors":
print("The Computer wins!")
print('The end')
elif option == "scissors" and computer_option == "rock":
print("The Computer wins!")
print('The end')
elif option == "scissors" and computer_option == "scissors":
print("You and the Computer chose the same options.")
print('The end')
elif option == "scissors" and computer_option == "paper":
print("You win!")
print('The end')`enter code here`
print(options())
I tried making a function to handle the if statements and when you and the computer have decided on your move, the function works, but all its printing is 'None'.
In your code, you have the line option.lower. This does not call any function nor does it reassign option to anything. Thus, if the user inputs "ROCK", all the if and elif clauses will be ignored. Rewrite the first few lines to:
print("Welcome to the official game of Rock, Paper, Scissors!")
option = input('''Pick an option: Rock, Paper, Scissors
>>> ''').lower()
Note that inputting something like "banana" will still cause all of the if and elif clauses to be ignored.

Program functions when "elif" is used, but does not when "elif" is replaced with "if". I am having trouble figuring out why? (Python)

I am making a small rock paper scissors program in python. The following code is functional. When I replace the "elif" with "if" the program is not completely functional (returns the else statement often) and I do not understand why. I am aware that elif should be used, but I still do not understand why using "if" is causing a loss in functionality. Thanks!
import random
game = ("rock", "paper", "scissors")
userchoice = str(input("rock, paper, or scissors?"))
while (userchoice == "rock" or "paper" or "scissors"):
computerchoice = random.choice(game)
if (computerchoice == "rock" and userchoice == "scissors"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "scissors" and userchoice == "paper"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "paper" and userchoice == "rock"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "rock" and userchoice == "paper"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "scissors" and userchoice == "rock"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "paper" and userchoice == "scissors"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == userchoice):
print("tie")
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
print("what?")
userchoice = str(input("try again, rock, paper, or scissors?"))
If you change the elif to if the program won't work correctly
For example,
take 1st case if computerchoice is rock userchoice is scissors then it asks for input again. But now the execution continues from the next if statement ie
if (computerchoice == "scissors" and userchoice == "paper"):
So if you the same case comes again ie computerchoice is rock userchoice is scissors it wont check the first condition and execute else block.
For further explanation comment
Simple explanation to this is that if there are MULTIPLE if statements in a loop then ONLY the first occurrence of if/else statement is executed and the loop completes and continues the next loop without checking other if statements. Your program works correctly in case of elif statement is because, after the if statement program continues checking all other elif statements
To use if..else statement, you must change the code in this way:
import random
game = ("rock", "paper", "scissors")
userchoice = str(input("rock, paper, or scissors?"))
while (userchoice in game):
computerchoice = random.choice(game)
if (computerchoice == "rock" and userchoice == "scissors"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "scissors" and userchoice == "paper"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "paper" and userchoice == "rock"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "rock" and userchoice == "paper"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "scissors" and userchoice == "rock"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "paper" and userchoice == "scissors"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == userchoice):
print("tie")
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
print("what?")
rockuserchoice = str(input("try again, rock, paper, or scissors?"))

Program keeps looping in an infinite function?

Currently working on a Rock Paper Scissors game for a basic python class. I've been working on it for about the past week, as I looked up how to make a basic python game and stumbled upon an article here and went off of it. Not sure why though, but it keeps looping. I want to keep the structure similar to this also, as my instructor asked me to keep it like this.
I've tried changing cpu_rand and cpu_choice, and also putting the function results() in different locations but also did not work.
import random #import random module
import sys #import system module
def playgame():
while True:
player_choice = input("Rock, Paper, or Scissors?")
cpu_rand = random.randint(1,3) #Generate random integer 1-3
cpu_choice = None
if cpu_rand == 1: #if cpu_choice = 1, cpu_choice = "Rock"
cpu_choice = "Rock"
elif cpu_rand == 2: #if cpu_choice = 2, cpu_choice = "Scissors"
cpu_choice = "Scissors"
elif cpu_rand == 3: #if cpu_choice = 3, cpu_choice = "Paper"
cpu_choice = "Paper"
def results(): #check results of player choice v computer choice
play_again = None #Sets this to null for future reference, for asking if playing again.
if(player_choice == cpu_choice): #Tie
print("It's a Tie")
play_again = input("Retry?")
#Rock Outcomes
elif(player_choice == "Rock" and cpu_choice == "Scissors"):
print("You Win!")
play_again = input("Play again?")
elif(player_choice == "Rock" and cpu_choice == "Paper"):
print("You Lose!")
play_again = input("Play again?")
#Paper Outcomes
elif(player_choice == "Paper" and cpu_choice == "Scissors"):
print("You Lose!")
play_again = input("Play again?cpu")
elif(player_choice == "Paper" and cpu_choice == "Rock"):
print("You Win!")
play_again = input("Play again?")
#Scissors Outcomes
elif(player_choice == "Scissors" and cpu_choice == "Rock"):
print("You Lose!")
play_again = input("Play again?")
elif(player_choice == "Scissors" and cpu_choice == "Paper"):
print("You Win!")
play_again = input("Play again?")
if play_again == "Yes": #if elif play again statements, from if/elif statements, play_again is changed to an input
playgame()
elif play_again == "No":
print("You Lose!")
sys.exit()
else:
print("Invalid Command")
play_again = input("play again?")
return play_again
results()
def start():
while True:
gamestart = input("You ready to play some Rock, Paper, Scissors? (y/n)")
if gamestart == "y":
playgame()
return gamestart
elif gamestart == "n":
print("Game Over!")
break
else:
print("Invalid Command")
start()
The result I was looking to be returned was everything under the results function, so if player_choice == cpu_choice then it would print out what is under that. Instead it loops back to "Rock, Paper, or Scissors?"
You never called the results function in your code so it never ran.
You didn't call results(). Moreover player_choice and cpu_choice were local variables in playgame().
import random #import random module
import sys #import system module
def playgame():
while True:
player_choice = input("Rock, Paper, or Scissors?")
cpu_rand = random.randint(1,3) #Generate random integer 1-3
cpu_choice = None
if cpu_rand == 1: #if cpu_choice = 1, cpu_choice = "Rock"
cpu_choice = "Rock"
elif cpu_rand == 2: #if cpu_choice = 2, cpu_choice = "Scissors"
cpu_choice = "Scissors"
elif cpu_rand == 3: #if cpu_choice = 3, cpu_choice = "Paper"
cpu_choice = "Paper"
results(player_choice, cpu_choice)
def results(player_choice, cpu_choice): #check results of player choice v computer choice
play_again = None #Sets this to null for future reference, for asking if playing again.
if(player_choice == cpu_choice): #Tie
print("It's a Tie")
play_again = input("Retry?")
#Rock Outcomes
elif(player_choice == "Rock" and cpu_choice == "Scissors"):
print("You Win!")
play_again = input("Play again?")
elif(player_choice == "Rock" and cpu_choice == "Paper"):
print("You Lose!")
play_again = input("Play again?")
#Paper Outcomes
elif(player_choice == "Paper" and cpu_choice == "Scissors"):
print("You Lose!")
play_again = input("Play again?cpu")
elif(player_choice == "Paper" and cpu_choice == "Rock"):
print("You Win!")
play_again = input("Play again?")
#Scissors Outcomes
elif(player_choice == "Scissors" and cpu_choice == "Rock"):
print("You Lose!")
play_again = input("Play again?")
elif(player_choice == "Scissors" and cpu_choice == "Paper"):
print("You Win!")
play_again = input("Play again?")
if play_again == "Yes": #if elif play again statements, from if/elif statements, play_again is changed to an input
playgame()
elif play_again == "No":
print("You Lose!")
sys.exit()
else:
print("Invalid Command")
play_again = input("play again?")
return play_again
results()
def start():
while True:
gamestart = input("You ready to play some Rock, Paper, Scissors? (y/n)")
if gamestart == "y":
playgame()
return gamestart
elif gamestart == "n":
print("Game Over!")
break
else:
print("Invalid Command")
start()
Your code is so dense and repetitive, may I suggest another approach?:
import random
wins = [
('paper', 'rock'), # paper wins over rock
('rock', 'scissors'),
('scissors', 'paper'),
]
items = ['rock', 'paper', 'scissors']
def computer_choice():
return random.choice(items)
def player_choice():
for i, item in enumerate(items):
print i, item
while 1:
choice = input("choose [0..%d]: " % (len(items)-1))
if 0 <= choice < len(items):
break
return items[choice]
while 1:
cpu = computer_choice()
human = player_choice()
print "CPU: %s, HUMAN: %s" % (cpu, human)
if cpu == human:
print 'tie..'
elif (cpu, human) in wins:
print "CPU wins."
else:
print "HUMAN wins."
again = raw_input("play again? [q to quit]: ")
print
if again.lower() == 'q':
break
sample session:
0 rock
1 paper
2 scissors
choose [0..2]: 0
CPU: scissors, HUMAN: rock
HUMAN wins.
play again? [q to quit]:
0 rock
1 paper
2 scissors
choose [0..2]: 1
CPU: paper, HUMAN: paper
tie..
play again? [q to quit]:
0 rock
1 paper
2 scissors
choose [0..2]: 1
CPU: scissors, HUMAN: paper
CPU wins.
play again? [q to quit]:
the only changes to make this play rock, paper, scissors, lizard, spock (https://bigbangtheory.fandom.com/wiki/Rock,_Paper,_Scissors,_Lizard,_Spock) are:
wins = [
('scissors', 'paper'), # Scissors cuts Paper
('paper', 'rock'), # Paper covers Rock
('rock', 'lizard'), # Rock crushes Lizard
('lizard', 'spock'), # Lizard poisons Spock
('spock', 'scissors'), # Spock smashes Scissors
('scissors', 'lizard'), # Scissors decapitates Lizard
('lizard', 'paper'), # Lizard eats Paper
('paper', 'spock'), # Paper disproves Spock
('spock', 'rock'), # Spock vaporizes Rock
('rock', 'scissors'), # (and as it always has) Rock crushes Scissors
]
items = ['rock', 'paper', 'scissors', 'lizard', 'spock']
sample run
0 rock
1 paper
2 scissors
3 lizard
4 spock
choose [0..4]: 4
CPU: scissors, HUMAN: spock
HUMAN wins.
play again? [q to quit]:
0 rock
1 paper
2 scissors
3 lizard
4 spock
choose [0..4]: 2
CPU: spock, HUMAN: scissors
CPU wins.
play again? [q to quit]:

better write rock paper scissors (python)

Hey guys I'm new to python and I have made this simple rock paper scissors game but I wonder if there is a better way to program this without a super long if else statement.
import random
options = ["scissors", "paper", "rock"]
i = random.randint(0, (len(options) - 1))
playedHand = input("PLay rock, paper or scissors please: ")
computerPlayedHand = options[i]
if playedHand == "rock" and computerPlayedHand == "scissors":
print("the computer had scissors, you win")
elif playedHand == "rock" and computerPlayedHand == "paper":
print("the computer had paper, you lose")
elif playedHand == "rock" and computerPlayedHand == "rock":
print("the computer also had rock, its a tie")
elif playedHand == "paper" and computerPlayedHand == "rock":
print("the computer had rock, you win")
elif playedHand == "paper" and computerPlayedHand == "scissors":
print("the computer had scissors, you lose")
elif playedHand == "paper" and computerPlayedHand == "paper":
print("the computer also had paper, its a tie")
elif playedHand == "scissors" and computerPlayedHand == "paper":
print("the computer had paper, you win")
elif playedHand == "scissors" and computerPlayedHand == "scissors":
print("the computer also had scissors, its a tie")
elif playedHand == "scissors" and computerPlayedHand == "rock":
print("the computer had rock, you lose")
else:
print("please only state rock, paper or scissors")
Here is what I threw together trying to reuse your code where possible.
The key part is noticing that the options list can be treated as a cycle where an option always beats the next option. You can check this by finding the indices and then using modulo to make the indices cyclic.
import random
options = ["scissors", "paper", "rock"] # everything loses to the previous thing
comp_index = random.randint(0, (len(options) - 1))
playedHand = input("Play rock, paper or scissors please: ")
computerPlayedHand = options[comp_index]
try:
player_index = options.index(playedHand)
except ValueError:
print("please only state rock, paper or scissors")
else:
if player_index == comp_index:
res = "the computer also had {}, its a tie"
# the key part
elif (player_index - comp_index) % 3 == 1:
res = "the computer had {}, you lose"
else:
res = "the computer had {}, you win"
print(res.format(computerPlayedHand))
Using a dictionary to represent which hand beat which can significantly shorten your code. But since we are there, let's make this even neater with an object-oriented solution.
import random
class Hand:
_ordering = {
'rock': 'scissor',
'scissor': 'paper',
'paper': 'rock'
}
def __init__(self, kind):
if kind in self._ordering:
self.kind = kind
else:
raise ValueError(
"It's rock, paper, scissor... Not rock, {}, scissor.".format(kind)
)
#classmethod
def random_hand(cls):
return cls(random.choice(list(cls._ordering)))
def beats(self, other):
return self._ordering[self.kind] == other.kind
playedHand = Hand(input("Play rock, paper or scissors please: "))
computerPlayedHand = Hand.random_hand()
if playedHand.beats(computerPlayedHand):
print('You won! The computer had {}.'.format(computerPlayedHand.kind))
elif computerPlayedHand.beats(playedHand):
print('You lost... The computer had {}.'.format(computerPlayedHand.kind))
else:
print("It's a tie.")
You don't need to use any "if" statements other than typical error management. Look at the following example:
import random
def play():
table = [[2, 0, 1],
[1, 2, 0],
[0, 1, 2]]
options = ["Rock", "Paper", "Scissors"]
results = ["Defeat", "Win", "Tie"]
conv = {"R": 0 , "P": 1, "S": 2}
while True:
i = random.randint(0, (len(options) - 1))
p = input("Play rock, Paper or Scissors please (R, P, S): ")
if p not in conv.keys():
print("Unavailable option. Left the Game.")
return
print("Computer played %s. You have a %s"%(options[i], results[table[conv[p]][i]]))
play()
If you have a table like this:
# Rock Paper Scissor
# Rock 2 0 1
# Paper 1 2 0
# Scissor 0 1 2
...you can make the user play in rows, and the computer in columns. The result is being indexed directly by whatever is the number in the table. Thus playing the game in the example would look like this:
Here's another possible version:
import random
try:
options = [('rock', 'scissors'), ('paper', 'rock'), ('scissors', 'paper')]
human_choice = int(input("Play rock(0), paper(1) or scissors(2) please: "))
human_hand = options[human_choice]
computer_hand = options[random.randint(0, (len(options) - 1))]
text = "the computer {} {}, {}"
if human_hand[0] == computer_hand[0]:
print(text.format("also had", computer_hand[0], "it's a tie"))
elif human_hand[1] == computer_hand[0]:
print(text.format("had", computer_hand[0], "you win"))
else:
print(text.format("had", computer_hand[0], "you lose"))
except Exception as e:
print("please only state rock, paper or scissors")

Categories

Resources