hi i am practicing python and doing rps game.
This is the code:
class Choices:
rock = "Rock"
paper = 'Paper'
scissors = 'Scissors'
def rps_game():
# Getting the name of the player.
name = raw_input("Welcome to Rock Paper Scissors Game!\n Enter your name:")
# The Players Choice.
while True:
player_choice = raw_input("\n1-Rock\n2-Paper\n3-Scissors\n{} choose a number:".format(name))
int(player_choice)
if player_choice == 1:
player_choice = Choices.rock
if player_choice == 2:
player_choice = Choices.paper
if player_choice == 3:
player_choice = Choices.scissors
# Getting the cpu choice.
cpu_choice = random.randint(1, 3)
if cpu_choice == 1:
cpu_choice = Choices.rock
if cpu_choice == 2:
cpu_choice = Choices.paper
if cpu_choice == 3:
cpu_choice = Choices.scissors
if player_choice == cpu_choice:
print"\n Its a Tie!/n{} you!".format(name)
if player_choice == Choices.paper and cpu_choice == Choices.rock:
print"\n Congratulations!\n{} you won!".format(name)
if player_choice == Choices.scissors and cpu_choice == Choices.paper:
print"\n Congratulations!\n{} you won!".format(name)
if player_choice == Choices.rock and cpu_choice == Choices.scissors:
print"\n Congratulations!\n{} you won!".format(name)
else:
print"\n Too Bad You Lost!".format(name)
print "\nCPU Choice: {}\n Your Choice: {}".format(cpu_choice, player_choice)
play_again = raw_input("Want to Play Again? y/n")
if play_again == 'y':
continue
else:
break
I defined only when the player is winning or its a tie and for the else i did else statement. But and a big But it will always will output always the lose output for some reason and when its print the choices for the CPU it prints a string the describes the choice(Paper Scissors ...) But for the players choice it prints the number
So Id be happy to get Your opinion what am i doing wrong and ALSO Id be happy to get some tips what are your thoughts and tips to get my code more efficient and professional
player_choice = raw_input("\n1-Rock\n2-Paper\n3-Scissors\n{} choose a number:".format(name))
int(player_choice)
This code doesn't work. player_choice is set as a string from raw_input but int(player_choice) doesn't do anything. It creates an integer and then sends it into the void. Instead, you need to reassign it to player_choice like so:
player_choice = int(player_choice)
if playerChoice == 1 and compChoice == 3:
print("You Win - Rock crushes Scissors.")
if playerChoice == 2 and compChoice == 1:
print("You Win - Paper covers Rock.")
if playerChoice == 3 and compChoice == 2:
print("You Win - Scissors cut Paper.")
if compChoice == 1 and playerChoice == 3:
print("You Lose - Rock crushes Scissors.")
if compChoice == 2 and playerChoice == 1:
print("You Lose - Paper covers Rock.")
if compChoice == 3 and playerChoice == 2:
print("You Lose - Scissors cut Paper.")
In your existing code. The else only applies to the final if statement. So if the player choice is not Rock and the cpu choice is not Scissors then the else is printed.
To resolve this use elif to make a chain of if statements. Then the else will apply only if none of the if conditions are met e.g.
if player_choice == cpu_choice:
print"\n Its a Tie!/n{} you!".format(name)
elif player_choice == Choices.paper and cpu_choice == Choices.rock:
print"\n Congratulations!\n{} you won!".format(name)
elif player_choice == Choices.scissors and cpu_choice == Choices.paper:
print"\n Congratulations!\n{} you won!".format(name)
elif player_choice == Choices.rock and cpu_choice == Choices.scissors:
print"\n Congratulations!\n{} you won!".format(name)
else:
print"\n Too Bad You Lost!".format(name)
You also need to convert the return value from raw_input to an int. Otherwise its a string and will never be equal to any of the integer values representing the choices. So use int(raw_input()) instead.
I see you tried to do this by using int(player_choice). The int constructor does not work 'in place'. i.e. it doesnt convert the variable itself to an int. It returns an integer value leaving player_choice as a string. You can see when we wrap input in the call to int we are capturing the return value and so player_choice is then an int (assuming your input was convertible to int).
Here's a that will work on python 2 and python 3.
import random
from sys import version_info
if version_info.major == 2:
try:
input = raw_input
except NameError:
pass
class Choices:
rock = "Rock"
paper = 'Paper'
scissors = 'Scissors'
def rps_game():
# Getting the name of the player.
name = input("Welcome to Rock Paper Scissors Game!\n Enter your name:")
# The Players Choice.
while True:
player_choice = int(input("\n1-Rock\n2-Paper\n3-Scissors\n{} choose a number:".format(name)))
if player_choice == 1:
player_choice = Choices.rock
elif player_choice == 2:
player_choice = Choices.paper
elif player_choice == 3:
player_choice = Choices.scissors
# Getting the cpu choice.
cpu_choice = random.randint(1, 3)
if cpu_choice == 1:
cpu_choice = Choices.rock
elif cpu_choice == 2:
cpu_choice = Choices.paper
elif cpu_choice == 3:
cpu_choice = Choices.scissors
if player_choice == cpu_choice:
print("\n Its a Tie!/n{} you!".format(name))
elif player_choice == Choices.paper and cpu_choice == Choices.rock:
print("\n Congratulations!\n{} you won!".format(name))
elif player_choice == Choices.scissors and cpu_choice == Choices.paper:
print("\n Congratulations!\n{} you won!".format(name))
elif player_choice == Choices.rock and cpu_choice == Choices.scissors:
print("\n Congratulations!\n{} you won!".format(name))
else:
print("\n Too Bad You Lost!".format(name))
print ("\nCPU Choice: {}\n Your Choice: {}".format(cpu_choice, player_choice))
play_again = input("Want to Play Again? y/n")
if play_again != 'y':
break
rps_game()
Also here's an attempt to implement it in less code.
from __future__ import print_function
import random
from sys import version_info
if version_info.major == 2:
input = raw_input
choices = ('Rock', 'Paper', 'Scissors')
winlogic = {
'Rock': 'Scissors',
'Paper': 'Rock',
'Scissors': 'Paper'
}
def calcwinner(choice1, choice2):
if choice1 == choice2: return 0
return 1 if winlogic[choice1] == choice2 else -1
name = input("Welcome to Rock Paper Scissors Game!\nEnter your name: ")
while True:
index = int(input("1-Rock\n2-Paper\n3-Scissors\n{} choose a number: ".format(name)))
try:
player_choice = choices[index - 1]
except IndexError:
print('please make a valid choice')
continue
cpu_choice = random.choice(choices)
winner = calcwinner(player_choice, cpu_choice)
print('You chose {} and computer chose {}. '.format(player_choice, cpu_choice), end='')
if winner == 0:
print('Tie')
elif winner < 0:
print('Cpu won')
else:
print('You won!')
play_again = input("Want to Play Again? y/n: ")
if play_again not in ('y', 'Y', 'yes'):
break
Related
Here is my code. I'm trying to make a rock, paper, scissors game for a school project.
import random
choices = ["Rock", "Paper", "Scissors"]
player_choice = input("Rock, Paper, Scissors?").lower()
while player_choice not in choices:
player_choice = input("Rock, Paper, Scissors?").lower()
computer_choice = random.randint(0,2)
if computer_choice == 0:
cpu_choice = choices[0]
elif computer_choice == 1:
cpu_choice = choices[1]
elif computer_choice == 2:
cpu_choice = choices[2]
print()
print("You play:", player_choice)
print("The computer plays:", cpu_choice)
print()
if player_choice == "Rock":
if cpu_choice == choices[0]:
print("Draw")
elif cpu_choice == choices[1]:
print("You Lose :((")
else:
print("You win!! :>>")
if player_choice == "Paper":
if cpu_choice == choices[0]:
print("You win!! :>>")
elif cpu_choice == choices[1]:
print("Draw")
else:
print("You Lose :((")
if player_choice == "Scissors":
if cpu_choice == choices[0]:
print("You Lose :((")
elif cpu_choice == choices[1]:
print("You Win!!! :>>")
else:
print("Draw")
The result you get is:
Rock, Paper, Scissors?rock
Rock, Paper, Scissors?Rock
Rock, Paper, Scissors?Rock
and it keeps going like this even though rock is part of choices. This also happens if I input scissors in lowercase or paper.
You can convert your input as well as the concerned comparing value into the same case whether it may be in lowercase or uppercase by using .lower() or .upper().
Or while comparing like if player_choice.lower() == 'rock',
player_choice = player_choice.lower()
Here is another approach that you could consider:
If your choices options need to be capitalized, if you capitalize the player_choice input, the user's input would then be able to match the choices options. This can be done with capitalize().
Also, instead of having to worry about perfect uppercase or lowercase matching, you could try using regular expression matching using the re module. The matching could be done using re.match() with a special flag called re.IGNORECASE that lets you ignore the case of the words that are being checked.
Additionally, it might be a good idea to use elif: statements after the first if: statement for this type of check.
I also added a space at the end of the initial input questions text for readability.
Here is an example of what these changes could look like:
import random
import re
choices = ["Rock", "Paper", "Scissors"]
player_choice = input("Rock, Paper, Scissors? ").capitalize()
while player_choice not in choices:
player_choice = input("Rock, Paper, Scissors? ").lower()
computer_choice = random.randint(0,2)
if computer_choice == 0:
cpu_choice = choices[0]
elif computer_choice == 1:
cpu_choice = choices[1]
elif computer_choice == 2:
cpu_choice = choices[2]
print()
print("You play:", player_choice)
print("The computer plays:", cpu_choice)
print()
if re.match("rock", player_choice, flags=re.IGNORECASE):
if cpu_choice == choices[0]:
print("Draw")
elif cpu_choice == choices[1]:
print("You Lose :((")
else:
print("You win!! :>>")
elif re.match("Paper", player_choice, flags=re.IGNORECASE):
if cpu_choice == choices[0]:
print("You win!! :>>")
elif cpu_choice == choices[1]:
print("Draw")
else:
print("You Lose :((")
elif re.match("Scissors", player_choice, flags=re.IGNORECASE):
if cpu_choice == choices[0]:
print("You Lose :((")
elif cpu_choice == choices[1]:
print("You Win!!! :>>")
else:
print("Draw")
Just make your condition literals to lower case:
if player_choice == 'rock':
You can do:
if player_choice.lower() == 'rock'
This will take the user input and lowercase everything in it.
A better way would be to have both player and computer choose from the same set of values. The player enters values until they enter a valid choice. The computer uses random.choice() to select one of the choices from the valid list of choices. Note that you can lower case the possible selections in the valid list:
choices = ["rock", "paper", "scissors"]
Then it is easy to compare the computer and player selections by direct comparision. Here's code for the player and computer choices:
while True:
player_choice = input("Rock, Paper, Scissors? ").lower()
if player_choice in choices:
break
print("Invalid choice, try again.")
cpu_choice = random.choice(choices)
print()
print("You play:", player_choice)
print("The computer plays:", cpu_choice)
print()
if player_choice == cpu_choice:
print("Draw")
elif player_choice == 'rock':
if cpu_choice == 'paper':
print("You Lose :((")
else:
print("You win!! :>>")
elif player_choice == 'paper':
if cpu_choice == 'scissors':
print("You Lose :((")
else:
print("You win!! :>>")
else: # player chose scissors
if cpu_choice == 'rock':
print("You Lose :((")
else:
print("You win!! :>>")
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]:
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.
I recently practiced python and I was finding myself get involved with a lot of if statements for a simple rock paper scissors game it looks like this:
and my question is how i get my code more efficient and more friendly to write and read
while True:
player_choice = raw_input("\n1-Rock\n2-Paper\n3-Scissors\n{} choose a number:".format(name))
player_choice = int(player_choice)
if player_choice == 1:
player_choice = Choices.rock
if player_choice == 2:
player_choice = Choices.paper
if player_choice == 3:
player_choice = Choices.scissors
# Getting the cpu choice.
cpu_choice = random.randint(1, 3)
if cpu_choice == 1:
cpu_choice = Choices.rock
if cpu_choice == 2:
cpu_choice = Choices.paper
if cpu_choice == 3:
cpu_choice = Choices.scissors
if player_choice == cpu_choice:
print"\n Its a Tie!\n!"
if player_choice == Choices.paper and cpu_choice == Choices.rock:
print"\n Congratulations!\n{} you won!".format(name)
if player_choice == Choices.scissors and cpu_choice == Choices.paper:
print"\n Congratulations!\n{} you won!".format(name)
if player_choice == Choices.rock and cpu_choice == Choices.scissors:
print"\n Congratulations!\n{} you won!".format(name)
if cpu_choice == Choices.scissors and player_choice == Choices.paper:
print"\n Too bad!\n{} you lost!".format(name)
if cpu_choice == Choices.paper and player_choice == Choices.rock:
print"\n Too bad!\n{} you lost!".format(name)
if cpu_choice == Choices.rock and player_choice == Choices.scissors:
print"\n Too bad!\n{} you lost!".format(name)*
Your if statements can be replaced by dictionaries. For example, mapping an integer to a specific Choices attribute can be done with a dictionary like this:
choices = {1: Choices.rock, 2: Choices.paper, 3: Choices.scissors}
Now you can use
player_choice = choices[player_choice]
and
cpu_choice = random.choice(choices.values())
From an encapsulation point of view, it should really be the responsibility of the Choices object to handle this mapping. If you were to use an actual enum.Enum object (requires Python 3 or the installation of the enum34 backport package) then you could just use:
player_choice = Choices(player_choice)
but depending on how you defined Choices, you could give it a __call__ method that basically uses the above mapping to give you the same result.
Next, you could use a dictionary to determine winners:
# if a player picks the key, and the opponent has picked the value,
# then the player wins.
wins_against = {
Choices.rock: Choices.scissors,
Choices.paper: Choices.rock,
Choices.scissors: Choices.paper,
}
then determine the winner:
if player_choice == cpu_choice:
print"\n Its a Tie!\n!"
elif wins_against[player_choice] == cpu_choice:
print"\n Congratulations!\n{} you won!".format(name)
else: # not the same, and not a win, so the player lost
print"\n Too bad!\n{} you lost!".format(name)
That mapping could also be part of your Choices enumeration objects however; give those a wins_against attribute:
if player_choice == cpu_choice:
print"\n Its a Tie!\n!"
elif player_choice.wins_against == cpu_choice:
print"\n Congratulations!\n{} you won!".format(name)
else:
print"\n Too bad!\n{} you lost!".format(name)
If you were to use the enum library, the code could become:
from enum import Enum
class Choices(Enum):
rock = 1, 'scissors'
paper = 2, 'rock'
scissors = 3, 'paper'
def __new__(cls, value, win_against):
instance = object.__new__(cls)
instance._value_ = value
instance._win_against = win_against
return instance
#property
def win_against(self):
return type(self)[self._win_against]
while True:
options = '\n'.join(['{}-{}'.format(c.value, c.name) for c in choices])
player_choice = raw_input("\n\n{} choose a number:".format(
options, name))
try:
player_choice = int(player_choice)
player_choice = Choices(player_choice)
except ValueError:
print "Not a valid option, try again"
continue
cpu_choice = random.choice(list(Choices))
if player_choice is cpu_choice:
print"\n Its a Tie!\n!"
elif player_choice.wins_against is cpu_choice:
print"\n Congratulations!\n{} you won!".format(name)
else: # not the same, and not a win, so the player lost
print"\n Too bad!\n{} you lost!".format(name)
You should use if/elif/else statements - it will only compare the conditionals until a true value occurs.
And you may want to put an error message if the user inputs some other value
if player_choice == 1:
player_choice = Choices.rock
elif player_choice == 2:
player_choice = Choices.paper
elif player_choice == 3:
player_choice = Choices.scissors
else:
print "Invalid choice"
I'm trying to write a Rock, Paper Scissors program with Python but I keep getting this error and I'm not sure how to fix it.
File "C:\Python33\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 140, in <module>
File "C:\Python33\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 34, in main
builtins.TypeError: 'tuple' object is not callable
This is my program:
import random
def main():
win = 0
lose = 0
tie = 0
ROCK_CHOICE = '1'
PAPER_CHOICE = '2'
SCISSORS_CHOICE = '3'
QUIT_CHOICE = '4'
play_again = 'y'
while play_again == 'y':
print('Welcome to the game of paper, rock, scissors!')
print('Please input the correct number according')
print('to the choices given.')
computer_choice = get_computer_choice()
player_choice = get_player_choice()
determine_winner = (computer_choice, player_choice)
print('Computer choose', computer_choice, '.')
print('You choose', player_choice, '.')
determine_winner(computer_choice, player_choice)
if result == -1:
lose += 1
elif result == 0:
tie += 1
else:
win += 1
play_again = input('Play again? Enter y for yes')
def get_computer_choice():
choice = random.randint(1,4)
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
elif choice == 3:
choice = 'SCISSORS'
else:
choice = 4
return choice
def get_player_choice():
choice = int(input('Select rock(1), paper(2), or scissors(3): '))
while choice != 1 and choice != 2 and choice != 3:
print('The valid numbers are rock choice 1), paper choice 2),')
print('or scissors choice 3).')
choice = int(input('Please a valid number: '))
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
elif choice == 3:
choice = 'SCISSORS'
else:
choice = 4
return choice
def determine_winner(computer_choice, player_choice):
if player_choice == ROCK_CHOICE and computer_choice == ROCK_CHOICE:
print('Its a tie.')
return 0
elif player_choice == PAPER_CHOICE and computer_choice == PAPER_CHOICE:
print('Its a tie.')
return 0
elif player_choice == SCISSORS_CHOICE and computer_choice == SCISSORS_CHOICE:
print('Its a tie.')
return 0
elif player_choice == ROCK_CHOICE and computer_choice == PAPER_CHOICE:
print('You lose, Rock covers Paper.')
return -1
elif player_choice == ROCK_CHOICE and computer_choice == SCISSORS_CHOICE:
print('You WIN!!! Rock smashes Scissors.')
return 1
elif player_choice == PAPER_CHOICE and computer_choice == SCISSORS_CHOICE:
print('You lose, Scissors cuts Paper.')
return -1
elif player_choice == SCISSORS_CHOICE and computer_choice == ROCK_CHOICE:
print('You lose, Rock smashes Paper.')
return -1
elif player_choice == SCISSORS_CHOICE and computer_choice == PAPER_CHOICE:
print('You WIN!!! Scissors cuts Paper.')
return 1
elif player_choice == PAPER_CHOICE and computer_choice == ROCK_CHOICE:
print('You WIN!!! Paper covers Rock.')
return 1
else:
player_choice == QUIT_CHOICE
print('Exiting the program...')
return
def display_results():
print()
print(' MENU')
print('1) Rock')
print('2) Paper')
print('3) Scissors')
print('4) Quit')
player_choice = input('Enter your choice:')
while player_choice != '1' and player_choice != '2' and \
player_choice != '3' and player_choice != '4':
print()
print('Error: invalid selection.')
player_choice = input('Please re-enter your choice:')
print('Your total wins are', win, '.')
print('Your total losses are', lose, '.')
print('Your total ties are', tie, '.')
main()
input('\nPress ENTER to continue...')
error 1:
fix line27 : result = determine_winner(computer_choice, player_choice
error 2:
if player_choice == ROCK_CHOICE and computer_choice == ROCK_CHOICE:
NameError: global name 'ROCK_CHOICE' is not defined
move:
ROCK_CHOICE = '1'
PAPER_CHOICE = '2'
SCISSORS_CHOICE = '3'
QUIT_CHOICE = '4'
outside main (to line 3)
error 3:
File "main.py", line 41, in main
play_again = input('Play again? Enter y for yes')
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
input should be raw_input line 41:
play_again = raw_input('Play again? Enter y for yes')
NB. and the input('\nPress ENTER to continue...') also needs to be a raw_input
NNBB. and if you plan to use display_results; there is errors in there too.
from random import randint
class RPS:
def __init__(self, pCh):
self.playChoice = pCh
self.compChoice = ""
self.choice = randint(0, 3)
self.winner = ""
self.uCompChoice = ""
self.uPlayChoice = ""
if self.choice == 0:
self.compChoice = "R"
elif self.choice == 1:
self.compChoice = "P"
else:
self.compChoice = "S"
if self.compChoice == "R":
self.uCompChoice = "Rock"
if self.compChoice == "P":
self.uCompChoice = "Paper"
if self.compChoice == "S":
self.uCompChoice = "Scissors"
if self.playChoice == "P" or self.playChoice == "p" or self.playChoice == "Paper" or self.playChoice == "paper" or self.playChoice == "PAPER" or self.playChoice == "2":
self.uPlayChoice = "Paper"
if self.playChoice == "S" or self.playChoice == "s" or self.playChoice == "Scissors" or self.playChoice == "scissors" or self.playChoice == "SCISSORS" or self.playChoice == "3":
self.uPlayChoice = "Scissors"
if self.playChoice == "R" or self.playChoice == "r" or self.playChoice == "Rock" or self.playChoice == "rock" or self.playChoice == "ROCK" or self.playChoice == "1":
self.uPlayChoice = "Rock"
def determineWinner(self):
if self.uCompChoice == self.uPlayChoice:
return "Draw Game!"
elif self.uCompChoice == "Rock":
if self.uPlayChoice == "Paper":
return "You won because Paper covers Rock!!"
else:
return "Computer wins because Rock breaks Scissors."
elif self.uCompChoice == "Paper":
if self.uPlayChoice == "Scissors":
return "You won because Rock cuts Paper!!"
else:
return "Computer wins because Paper covers Rock."
else:
if self.uPlayChoice == "Rock":
return "You won because Rock breaks Scissors!!"
else:
return "Computer wins because Scissors cuts Paper."
def __str__(self):
return "Your weapon: " + self.uPlayChoice + "\n" + "Computer's weapon " + self.uCompChoice + "\n" + \
self.determineWinner()
def main():
print("Welcome to RockPaperScissors.")
print("Pick your weapon: ")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("Note: If you don't pick a valid weapon the computer will pick a random weapon for you")
# input from user (weapon)
weapon = input("")
# Creating a new object
attack = RPS(weapon)
# printing the result
print(attack.__str__())
# Asking the user if he wants to play again
playagain = input("Would you like to play again: \n")
if playagain == "Yes" or playagain == "yes" or playagain == "YES" or playagain == "y" or playagain == "Y":
main()
else:
print("Thank you for playing.")
main()
don't you think, this code will be shorter this way:
print("R for rock")
print("P for paper")
print("S for scissors")
choices = ["rock", "paper", "scissor"]
while True:
choice = random.choice(choices)
player_choice = input("choose> ")
if player_choice.lower() == "r":
if choice == "rock":
print("i picked rock too!")
elif choice == 'paper':
print("YOU LOST! i picked paper")
else:
print("fine, you win")
elif player_choice.lower() == "p":
if choice == "rock":
print("You win.... Whatever!")
elif choice == 'paper':
print("haha same decisions")
else:
print("I won! You should be ashamed of losing against a bot")
elif player_choice.lower() == "s":
if choice == "rock":
print("I won! Humanity will soon be controlled by bots")
elif choice == 'paper':
print("Alright, you win")
else:
print("Draw")
else:
print("YOU WANNA PLAY GAMES WITH ME!??!?!?")