I'm building a rock paper scissors game and I would like to add a counter to the code I already have.
I want to count wins, losses and ties, and print these when the player does not want to play anymore.
This code does just about everything else I set out to do. I have seen a few other ideas on the site, but none of them seem to be adaptable to my code. Any ideas?
Here is the code:
import random
def rock(rand):
if rand == (1):
print("Tie Game!")
elif rand == (2):
print("Your rock got covered by opponent's paper. You Lose!")
elif rand == (3):
print("You crushed the opponent's scissors with your rock! You Win!")
print("Good game!")
def paper(rand):
if rand == (1):
print("You covered opponent's rock with your paper. You Win!")
print("Good game!")
elif rand == (2):
print("Tie Game!")
elif rand == (3):
print("Your opponent cut your paper with its scissors. You Lose!")
def scissors(rand):
if rand == (1):
print("Your opponent's rock crushed your scissors. You Lose!")
elif rand == (2):
print("Your scissors cut opponent's paper. You Win!")
print("Good game!")
elif rand == (3):
print("Tie Game!")
def main():
name = input("What is your name? ")
print("Hello, " + name + "! I'm a rock paper scissors game.")
while True:
choice = input("Would you like to play? (yes/no) ").upper()[0]
if choice == "N":
print("Let's play later!")
break
elif choice == "Y":
print("Ok, lets play!")
print("Rules: Rock breaks Scissors, Scissors cuts Paper, Paper covers Rock. ")
raw = input("Choose rock, paper, or scissors ").upper()
try:
answer = raw[0]
except:
IndexError
print("Illegal input! Exiting.")
break
rand = random.randint(1, 3) # 1 = rock, 2 =Paper 3 = Scissors
if answer == "S":
scissors(rand)
elif answer == "P":
paper(rand)
elif answer == "R":
rock(rand)
else:
print("Enter a valid answer!")
main()
It would be better to put all the methods in a class instead of using global variables.
Here you go.
import random
my_win = 0
my_loss = 0
my_tie = 0
def rock(rand):
global my_tie, my_loss, my_win
if rand == (1):
print("Tie Game!")
my_tie += 1
elif rand == (2):
print("Your rock got covered by opponent's paper. You Lose!")
my_loss += 1
elif rand == (3):
print("You crushed the opponent's scissors with your rock! You Win!")
print("Good game!")
my_win += 1
def paper(rand):
if rand == (1):
print("You covered opponent's rock with your paper. You Win!")
print("Good game!")
my_win += 1
elif rand == (2):
print("Tie Game!")
my_tie += 1
elif rand == (3):
print("Your opponent cut your paper with its scissors. You Lose!")
my_loss += 1
def scissors(rand):
if rand == (1):
print("Your opponent's rock crushed your scissors. You Lose!")
my_loss += 1
elif rand == (2):
print("Your scissors cut opponent's paper. You Win!")
print("Good game!")
my_win += 1
elif rand == (3):
print("Tie Game!")
my_tie += 1
def main():
name = input("What is your name? ")
print("Hello, " + name + "! I'm a rock paper scissors game.")
while True:
choice = input("Would you like to play? (yes/no) ").upper()[0]
if choice == "N":
print("Let's play later!")
break
elif choice == "Y":
print("Ok, lets play!")
print("Rules: Rock breaks Scissors, Scissors cuts Paper, Paper covers Rock. ")
raw = input("Choose rock, paper, or scissors ").upper()
try:
answer = raw[0]
except:
print("Illegal input! Exiting.")
break
rand = random.randint(1, 3) # 1 = rock, 2 =Paper 3 = Scissors
if answer == "S":
scissors(rand)
elif answer == "P":
paper(rand)
elif answer == "R":
rock(rand)
else:
print("Enter a valid answer!")
print ("You win %d times!" % my_win)
print ("You lose %d times!" % my_loss)
print ("You tie %d times!" % my_tie)
main()
OUTPUT:
What is your name? a
Hello, a! I'm a rock paper scissors game.
Would you like to play? (yes/no) y
Ok, lets play!
Rules: Rock breaks Scissors, Scissors cuts Paper, Paper covers Rock.
Choose rock, paper, or scissors Rock
Tie Game!
Would you like to play? (yes/no) no
Let's play later!
You win 0 times!
You lose 0 times!
You tie 1 times!
Process finished with exit code 0
Related
I'm trying to make a rock, paper, scissors game, but each time I run it, when the game is supposed to be over, it asks the user to input rock, paper or scissors again. It doesn't add the result of that extra round into the counter, and it doesn't matter what the user input as long as the input something. I've been stuck at this and to me the entire code looks fine, but I want it to end right after either the computer or user get 3 wins. Here is the code:
import random
print("Welcome to rock, paper, scissors, where you will verse a computer, and the first one to win 3 rounds, wins!\n"
"to chose rock, enter r, to chose paper, enter p, to enter scissors enter s.")
computer = random.choice("rps")
print(computer)
player = str(input("Rock, Paper, Scissors, Shoot! "))
player_counter = 0
computer_counter = 0
player_win = 0
computer_win = 0
while player_counter <= 2 and computer_counter <= 2:
if player == "s" and computer == "s" or player == "p" and computer == "p" or player == "r" and computer == "r":
print("You and the computer tied!")
computer = random.choice("rps")
print(computer)
print("Your score is:", player_counter, "and the computer's score is:", computer_counter)
player = str(input("Rock, Paper, Scissors, Shoot! "))
elif player == "r" and computer == "p" or player == "p" and computer == "s" or player == "s" and computer == "r":
print("computer wins!")
computer_counter += 1
computer = random.choice("rps")
print(computer)
print("Your score is:", player_counter, "and the computer's score is:", computer_counter)
player = str(input("Rock, Paper, Scissors, Shoot! "))
elif player == "r" and computer == "s" or player == "p" and computer == "r" or player == "s" and computer == "p":
print("You win!")
player_counter += 1
computer = random.choice("rps")
print(computer)
print("Your score is:", player_counter, "and the computer's score is:", computer_counter)
player = str(input("Rock, Paper, Scissors, Shoot! "))
if player_counter == 3:
print("You win the game!")
elif computer_counter == 3:
print("You lose the game!")
The problem is that everything in your loop is offset — you start a new round before the loop restarts and before the winning condition is rechecked. On the next pass through the loop, it terminates.
You can fix this bug and delete a lot of unnecessary code by simply putting the choice at the start of the loop, in one spot, rather than having it copy+pasted into every individual if block after the score has been updated:
import random
print(
"Welcome to rock, paper, scissors, where you will verse a computer, "
"and the first one to win 3 rounds, wins!\n"
"To chose rock, enter r, to chose paper, enter p, "
"to enter scissors enter s."
)
player_counter = 0
computer_counter = 0
while player_counter < 3 and computer_counter < 3:
player = input("Rock, Paper, Scissors, Shoot! ")
computer = random.choice("rps")
print(computer)
if player == computer:
print("You and the computer tied!")
elif player + computer in ("rp", "ps", "sr"):
print("computer wins!")
computer_counter += 1
elif player + computer in ("rs", "pr", "sp"):
print("You win!")
player_counter += 1
else:
print(f"Invalid choice '{player}'.")
print(
f"Your score is: {player_counter} "
f"and the computer's score is: {computer_counter}"
)
if player_counter == 3:
print("You win the game!")
elif computer_counter == 3:
print("You lose the game!")
First of all, you enter the loop 3 times and read the input 3 times, but you read the input one time before the loop here,
player = str(input("Rock, Paper, Scissors, Shoot! "))
that's why you see that unnecessary input.
Secondly, you should read input only at the beginning of the loop, not inside of each condition. Here is a modified working code
import random
print("Welcome to rock, paper, scissors, where you will verse a computer, and the first one to win 3 rounds, wins!\n",
"to chose rock, enter r, to chose paper, enter p, to enter scissors enter s.")
computer = random.choice("rps")
print(computer)
#player = str(input("Rock, Paper, Scissors, Shoot! "))
player_counter = 0
computer_counter = 0
player_win = 0
computer_win = 0
while player_counter <= 2 and computer_counter <= 2:
player = str(input("Rock, Paper, Scissors, Shoot! "))
if player == "s" and computer == "s" or player == "p" and computer == "p" or player == "r" and computer == "r":
print("You and the computer tied!")
computer = random.choice("rps")
print(computer)
print("Your score is:", player_counter, "and the computer's score is:", computer_counter)
elif player == "r" and computer == "p" or player == "p" and computer == "s" or player == "s" and computer == "r":
print("computer wins!")
computer_counter += 1
computer = random.choice("rps")
print(computer)
print("Your score is:", player_counter, "and the computer's score is:", computer_counter)
# player = str(input("Rock, Paper, Scissors, Shoot! "))
elif player == "r" and computer == "s" or player == "p" and computer == "r" or player == "s" and computer == "p":
print("You win!")
player_counter += 1
computer = random.choice("rps")
print(computer)
print("Your score is:", player_counter, "and the computer's score is:", computer_counter)
#player = str(input("Rock, Paper, Scissors, Shoot! "))
if player_counter == 3:
print("You win the game!")
elif computer_counter == 3:
print("You lose the game!")
There is no need to write the input and use random.choice() statement each time you run into a condition. YOu can move both the input and the random.choice() at the start of the loop. This will also solve the problem of entering input after the computer or the user wins the game.
import random
print(
"Welcome to rock, paper, scissors, where you will verse a computer, and the first one to win 3 rounds, wins!\n"
"to chose rock, enter r, to chose paper, enter p, to enter scissors enter s."
)
player_counter = 0
computer_counter = 0
while player_counter <= 2 and computer_counter <= 2:
player = str(input("Rock, Paper, Scissors, Shoot! "))
computer = random.choice("rps")
print(computer)
if (
player == "s"
and computer == "s"
or player == "p"
and computer == "p"
or player == "r"
and computer == "r"
):
print("You and the computer tied!")
computer = random.choice("rps")
print(computer)
print(
"Your score is:",
player_counter,
"and the computer's score is:",
computer_counter,
)
elif (
player == "r"
and computer == "p"
or player == "p"
and computer == "s"
or player == "s"
and computer == "r"
):
print("computer wins!")
computer_counter += 1
print(computer)
print(
"Your score is:",
player_counter,
"and the computer's score is:",
computer_counter,
)
elif (
player == "r"
and computer == "s"
or player == "p"
and computer == "r"
or player == "s"
and computer == "p"
):
print("You win!")
player_counter += 1
print(computer)
print(
"Your score is:",
player_counter,
"and the computer's score is:",
computer_counter,
)
if player_counter == 3:
print("You win the game!")
elif computer_counter == 3:
print("You lose the game!")
I'm quite new to coding, and I've been trying to make a text-based game with a menu. The game itself works fine, but once I try to incorporate a menu, i get the error "NameError: free variable 'player_one_rps' referenced before assignment in enclosing scope".
I have been googling it like a mad for some time now, but the few answers I find uses too advanced code for me to understand it yet.
(I tried changing the scopes and indents, I tried calling different functions at different indents, I tried assigning an argument to the functions, also, to have the main menu as the last function in the code – the list goes on..)
Here is the code for the menu and game option 1:
def main():
print("\t\t*** Welcome to this totally adequate game! ***")
def game_menu():
"""Displays game menu and prompts user for input"""
menu_choice = input("""What do you want to do?
1 - One player: rock, paper, scissor, lizard, spock
2 - Two player: rock, paper, scissor, lizard, spock
3 - Surprise! Bonus feature
4 - User guide
5 - Quit
Enter the menu number to access: """)
while True:
if menu_choice == "1":
print("One player: rock, paper, scissor, lizard, spock")
player_one_rps()
break
elif menu_choice == "2":
print("Two player: rock, paper, scissor, lizard, spock")
player_two_rps()
break
elif menu_choice == "3":
print("Surprise! Bonus feature")
dad_jokes()
break
elif menu_choice == "4":
print("User guide")
user_info()
elif menu_choice == "5":
print("Quit game")
exit()
elif menu_choice != 1 - 5:
print("Error, choose a valid number")
# print(menu_choice)
game_menu()
main()
# First game
def player_one_rps():
"""One player rock, paper, scissor, lizard, spock - game"""
import random
def instructions():
"""Displays menu and simple instructions on how to play"""
print("Welcome to rock, paper, scissor, lizard, spock!")
play = input("\nNavigate by \"yes\", \"no\", and numbers.\nNew game?:").lower()
if play == "yes":
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Lizard")
print("5. Spock")
elif play != "no":
print("an error has occured. Please type \"yes\" or \"no\":")
instructions()
def get_user_choice():
"""Prompts the player to pick a 'weapon'"""
choice = int(input("What do you choose?: "))
if choice > 5:
print("Invalid number, please try again....")
get_user_choice()
elif choice < 1:
print("Invalid number, please try again....")
get_user_choice()
elif choice == 1:
print("You chose rock")
elif choice == 2:
print("You chose paper")
elif choice == 3:
print("You chose scissor")
elif choice == 4:
print("You chose lizard")
elif choice == 5:
print("You chose spock")
return choice
def get_pc_choice():
"""The computer chooses a random weapon"""
choice = random.randint(1, 5)
if choice == 1:
print("PC chose rock")
elif choice == 2:
print("PC chose paper")
elif choice == 3:
print("PC chose scissor")
elif choice == 4:
print("PC chose lizard")
elif choice == 5:
print("PC chose spock")
return choice
def winner(user_choice, pc_choice, user_wins, pc_wins, ties):
"""Calculates if the player or computer won the match"""
if user_choice == 1 and pc_choice == 3 or pc_choice == 4:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 2 and pc_choice == 1 or pc_choice == 5:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 3 and pc_choice == 2 or pc_choice == 4:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 4 and pc_choice == 2 or pc_choice == 5:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 5 and pc_choice == 1 or pc_choice == 3:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == pc_choice:
print("\nTie")
ties = ties.append(1)
else:
print("\nPC won")
pc_wins = pc_wins.append(1)
return
def game_total(user_wins, pc_wins, ties):
"""Displays the total score"""
user_wins = sum(user_wins)
pc_wins = sum(pc_wins)
ties = sum(ties)
print("Your final score: ", user_wins)
print("PC\'s final Score: ", pc_wins)
print("Total ties: ", ties)
def main_one_p():
"""Main instructions for how the game runs"""
user_choice = 0
user_wins = []
pc_choice = 0
pc_wins = []
ties = []
final_user_wins = 0
final_pc_wins = 0
final_ties = 0
Continue = "yes"
instructions()
while Continue == "yes":
user_choice = get_user_choice()
pc_choice = get_pc_choice()
winner(user_choice, pc_choice, user_wins, pc_wins, ties)
Continue = input("Would you like to play again: ").lower()
if Continue == "no":
print("This is the final scores.")
break
game_total(user_wins, pc_wins, ties)
main_one_p()
player_one_rps()
game_menu() # Returns player to the main menu
(sorry if it is quite long)
Could anyone help point me in the direction of my mistake? Explanations and tips on how to fix it would also be greatly appreciated :)
In general, I'm thankful for all feedback, as i really want to become better at coding.
The global function must have a higher declarative code than where it is called. Simply reposition the function. The function game_menu must be below the function play_one_rps. The other functions are the same.
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")
So, I've made a rock paper scissors program, and it works like a charm. The only gripe I have with it is that the scores in the output do not carry over afterwards. This is written in Python- and forgive me if the code in the box below is formatted wrong, I'm new to stack overflow.
ties = ties + 1, for example, will print properly, but then when the program is run again, if I get another tie, it won't say ties = 2, it'll keep saying Ties: 1. Or if I get a tie and a loss, it'll say Ties: 1 Loses: 0 and then it'll print Ties: 0 Loses: 1
import random
def main():
playRPS = str.lower(input("Play a game or rock paper scissors? Yes or no. "))
if(playRPS == "no"):
print("Well, why did you run the program them?")
while(playRPS == "yes"):
human = int(input("Welcome to rock paper scissors! Type 1 for rock, 2 for paper, or 3 for scissors"))
cpu = random.randint(1,3)
ties = 0
wins = 0
loses = 0
if(human == cpu):
print("It's a tie!")
ties = ties + 1
playRPS = input("Play again?")
elif(human == 1 and cpu == 2):
print("The computer picked paper, you picked rock, CPU wins!")
loses = loses + 1
playRPS = input("Play again?")
elif(human == 1 and cpu == 3):
print("The computer picked scissors, you picked rock, You win!")
wins = wins + 1
playRPS = input("Play again?")
elif(human == 2 and cpu == 1):
print("You picked paper, the computer picked rock, You win!")
wins = wins + 1
playRPS = input("Play again?")
elif(human == 2 and cpu == 3):
print("You picked paper, the computer picked scissors, CPU wins!")
loses = loses + 1
playRPS = input("Play again?")
elif(human == 3 and cpu == 1):
print("You picked scissors, the computer picked rock, CPU wins!")
loses = loses + 1
playRPS = input("Play again?")
elif(human == 3 and cpu == 2):
print("You picked scissors, the computer picked paper, You win!")
wins = wins + 1
playRPS = input("Play again?")
else:
print("An error occured, maybe you typed 4, or 5, or maybe you made a typo.")
playRPS = str.lower(input("Another game? Yes or no."))
print("Wins: " + str(wins))
print("Ties: " + str(ties))
print("Loses " + str(loses))
main()
As your code is written, each time the while loop runs, it resets ties, wins, and losses back to zero. Move those expressions outside the while loop, and the values won't be reset with each new game.
I am having trouble with this part of my assignment. I have to declare a winner of the game and then input into a function. Once I have entered all the if statements I then have to create a function def playGame(). This has to include:
showRules()
user = getUserChoice()
computer = getComputerChoice()
declareWinner(user, computer)
I am not too sure how to do this. Please help.
Below is the code that I have completed so far: (Would I need to do an if statement for scissors as well?)
#Display game rules
print("Rules: Each player chooses either Rock, Paper, or Scissors.")
print("\tThe winner is determined by the following rules:")
print("\t\tScissors cuts Paper --> Scissors wins")
print("\t\tPaper covers Rock --> Paper wins")
print("\t\tRock smashes Scissors --> Rock Wins")
def userchoice():
choice = (input("Make your selection (Rock, Paper, or Scissors). ")).lower()
return choice
#obtain computer input
def getComputerchoice():
import random
rnum = random.randint(1,3)
if rnum == 1:
print("The computer has chosen Rock.")
if rnum == 2:
print("The computer has chosen Paper.")
if rnum == 3:
print("The computer has chosen Scissors.")
return rnum
#Declare winner
def declarewinner (user, rnum):
if userchoice == 1:
print("You have chosen rock.")
if getComputerchoice == 1:
print("Computer has chose rock as well.")
return 0
else:
print("The computer has chosen scissors. Rock breaks scissors. You WIN!")
return 1
if userchoice == 2:
print("You have chosen paper.")
if getComputerchoice == 1:
print("The computer has chosen rock. Paper covers rock. You WIN!")
return 1
elif getComputerchoice == 2:
print("The computer has chosen paper as well.")
return 0
else:
print("The computer has chosen scissors. Scissors cut paper. You LOSE!")
return 1
if userchoice == 3:
print("You have chosen scissors")
if getComputerchoice == 1:
print("The computer has chosen rock. Rock breaks scissors. You LOSE!")
return 1
elif getComputerchoice == 2:
print("The computer has chosen paper. Scissors cut paper. You WIN!")
return 1
how bout
class hand:
def __init__(self,rps):
self.rps = ["rock","paper","scissors"].index(rps.lower())
def __cmp__(self,other): #take advantage of pythons __cmp__ and override it
#this is the magic
wins_against = {0:2,1:0,2:1}
#if their equal return 0
if self.rps == other.rps: return 0
#if this hand wins return 1
if wins_against[self.rps] == other.rps:return 1
#else (This hand loses) return -1
return -1
def __str__(self):
return ["rock","paper","scissors"][self.rps]
print( hand("rock") > hand("paper") )
print( hand("scissors") > hand("paper") )
print( hand("rock") > hand("scissors") )
granted its probably overkill for this but it s a cool technique ... and if you can get it down now it may help you with future assignments
def get_cpu_pick():
return random.choice(["rock", "paper", "scissors"])
def get_player_pick():
valid_inputs = {
'r':'rock','p':'paper','s':'scissors'
}
user_choice = input("Select RPS:")
while user_choice.lower() not in valid_inputs:
user_choice = input("Select RPS:")
return valid_inputs.get(user_choice.lower())
def play():
user_hand = hand(get_player_pick())
cpu_hand = hand(get_cpu_pick())
if user_hand > cpu_hand:
print ("User Wins {0} v. {1}".format(user_hand,cpu_hand))
elif user_hand < cpu_hand:
print ("CPU Wins {0} v. {1}".format(user_hand,cpu_hand))
else:
print("TIE!!!")