I am new to python and I am writing a program to play Rock, Paper, Scissor. When I start to do the if else statements to compare outputs from user and the computer, my program just completely skips the if-else statements. Not sure what's going on with it.
user = input("Please enter Rock, Paper, Scissor: ")
while user not in ("Rock", "Paper", "Scissor"):
print("Try again")
user = input("Please enter Rock, Paper, Scissor: ")
if user == "Rock":
print("Your Choice is Rock")
elif user == "Scissor":
print("Your Choice is Scissor")
elif user == "Paper":
print("Your Choice is Paper")
import random
AI=["Rock", "Paper", "Scissor"]
b=random.randint(0,2)
print("The computer choice is " + AI[b])
if user == b:
print("Tie")
elif user == "Rock":
if b == "Scissor":
print("Rock Beats Scissor")
It goes through all of the code expect the last if-else statement. It just finishes the program after the computer chooses what to use.
Your issue is in the last if, you are comparing a string with a integer user == b remember that the user choice is a string but b is a random number between 0 and 2.
if user == AI[b]: # you need to compare the value with the string selection of the "AI"
print("Tie")
elif user == "Rock":
if AI[b] == "Scissor":
print("Rock Beats Scissor")
else:
# I don't remember what are the rules to win or lose LOL, but I guess there are more
# maybe you need more conditions
print("other choice...")
Related
I have this code for a beginners Rock Paper Scissors python game (I just started learning and I only know very basic stuff)
play_again = True
while (play_again):
import random
import time
rps = ("rock", "paper", "scissors")
user = None #makes it so "user" can be called in while loop
computer = random.choice(rps) #Picks 1 random option from the options variable
while user not in rps: #if user enters something other than one of the options, prompts again
user = input("Enter a choice: rock, paper, or scissors? ==> ")
#print(user)
#print(computer)
if user == computer:
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("It's a tie!")
elif (user == "rock" and computer == "scissors") or (user == "paper" and computer == "rock") or (user == "scissors" and computer == "paper"):
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("You win!")
elif (user == "scissors" and computer == "rock") or (user == "rock" and computer == "paper") or (user == "paper" and computer == "scissors"):
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("You lost ;(")
print()
question = None
play_again_options = ("yes", "no")
while question not in play_again_options:
question = input("Do you want to play again? Type 'yes' or 'no' ==> ")
if (question == "yes"):
play_again = True
print()
elif (question == "no"):
play_again = False
"while user not in rps" is supposed to re-prompt the user to input of the 3 options, rock, paper or scissors, if they enter something other than one of the options, but when I enter something that is not in options, instead of re-promting for that input, it skips it and moves down to the second while loop "while question not in play_again_options:"
everything else works fine, the game itself, the play again, its just this one thing thats been bugging me.
I know it has something to do with the second while loop at the bottom, "while question not in play_again_options:", because when I comment it out the other while loop works perfectly fine.
As noted in comments, your indentation has all code following the while user not in rps: loop inside of that loop. Rather you merely want to loop until you get valid input. This is just a matter of unindenting those lines one level.
play_again = True
while (play_again):
import random
import time
rps = ("rock", "paper", "scissors")
user = None #makes it so "user" can be called in while loop
computer = random.choice(rps) #Picks 1 random option from the options variable
while user not in rps: #if user enters something other than one of the options, prompts again
user = input("Enter a choice: rock, paper, or scissors? ==> ")
#print(user)
#print(computer)
if user == computer:
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("It's a tie!")
elif (user == "rock" and computer == "scissors") or (user == "paper" and computer == "rock") or (user == "scissors" and computer == "paper"):
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("You win!")
elif (user == "scissors" and computer == "rock") or (user == "rock" and computer == "paper") or (user == "paper" and computer == "scissors"):
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("You lost ;(")
print()
question = None
play_again_options = ("yes", "no")
while question not in play_again_options:
question = input("Do you want to play again? Type 'yes' or 'no' ==> ")
if (question == "yes"):
play_again = True
print()
elif (question == "no"):
play_again = False
Because you need to select input from a user in more than one place from a limited number of options, you may wish to create a function to handle this.
Something like the following, perhaps:
def get_input(prompt, valid_options, error_msg=None):
while True:
inp = input(f"{prompt} Type {', '.join(valid_options[:-1])} or {valid_options[-1]} ")
if inp in valid_options: return inp
if error_msg: print(error_msg)
Which we can call like so:
>>> get_input("Do you want to play again?", ('yes', 'no'))
Do you want to play again? Type yes or no jddbhf
Do you want to play again? Type yes or no dkssfd
Do you want to play again? Type yes or no no
'no'
Note that you are not handling the case when user is not in rps:
if user == computer:
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("It's a tie!")
elif (user == "rock" and computer == "scissors") or (user == "paper" and computer == "rock") or (user == "scissors" and computer == "paper"):
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("You win!")
elif (user == "scissors" and computer == "rock") or (user == "rock" and computer == "paper") or (user == "paper" and computer == "scissors"):
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("You lost ;(")
You should add an "else" case that use the instruction "continue". This instruction let you skip all the code above of it and tells the external while loop to start a new iteration. Something like this:
if user == computer:
....
else:
continue
In your current code, your getting the question to continue playing because none of the conditions of your "if - elif" structure is satisfied but there is not any instruction that tells the program to skip the rest of the code, so you only need to add the missing case with that "continue" instruction.
I made some changes and it's working. If you have any questions about what I did just send me :)
import random
import time
rps = ("rock", "paper", "scissors")
computer = random.choice(rps) # Picks 1 random option from the options variable
is_game_on = True
while is_game_on: # Now, you can use an if to change the game to of
user = input("Enter a choice: rock, paper, or scissors? ==> ")
if user not in rps:
print(f"Sorry, '{user}' is not an option. Try again...\n")
else:
if user == computer:
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("It's a tie!")
elif (user == "rock" and computer == "scissors") or (user == "paper" and computer == "rock") or (
user == "scissors" and computer == "paper"):
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("You win!")
elif (user == "scissors" and computer == "rock") or (user == "rock" and computer == "paper") or (
user == "paper" and computer == "scissors"):
print("You Chose: " + user)
print("The Computer Chose: " + computer)
print("You lost ;(")
print()
question = None
play_again_options = ("yes", "no")
while question not in play_again_options:
question = input("Do you want to play again? Type 'yes' or 'no' ==> ")
if question == "yes" or question.lower() == 'y':
print('-=' * 30)
print()
break
elif question == "no" or question.lower() == 'n':
is_game_on = False
print('-='*30)
print('END GAME')
break
else:
print(f"Sorry, '{question}' is not an option. Try again...")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 11 months ago.
I'm trying to code a Rock, Paper, Scissors game. How do I prevent them from entering random words/letters and make them reinput their choices until they hit one of the viable choice in the Rock, Paper, Scissors game? For example: "Your input is not viable. Please try again: "
import random
def play():
user = input("Choose your secret weapon! 'Rock' or 'Paper' or 'Scissors': ")
computer = random.choice(['Rock', 'Paper', 'Scissors'])
if user == computer:
return ("It's a tie! You and computer have both chosen {}.").format(user)
if win(user, computer):
return("You've won! You chose {} and computer chose {}.").format(user, computer)
return("You've lost... You chose {} and computer chose {}.").format(user, computer)
def win(user, computer):
if(user == "Scissors" and computer == "Paper") or (user == "Paper" and computer == "Rock") or (user == "Rock" and computer == "Scissors"):
return True
return False
print(play())
You could use a while loop wich chekcks if it is a valid input something like
user_input = input("Choose your secret weapon! 'Rock' or 'Paper' or 'Scissors': ")
while user_input.lower() not in ['rock', 'paper', 'scissors']:
user_input = input("Your input is not viable. Please try again: ")
#Your code
I'm trying to make a rock, paper, and scissors game that receives input from a user that plays against a robot that randomly selects rock, paper, or scissors. Here is my main() code:
"""
Name: Scott Houston
Date: January 19th, 2021
Program Description: Game of classic rock, paps
"""
import random
import gameFunctions2
def main():
while True:
computer_move = random.randint(1, 3)
print("Welcome to rock, paper, scissors! Rock beats scissors, scissors beats paper,"
" and paper beats rock. ")
user_input = input("Press 'A' for rock, 'B' for paper, and 'C' for scissors!\n"
"A. Rock\n"
"B. Paper\n"
"C. Scissors\n")
if gameFunctions2.tie(user_input, computer_move) == False:
if user_input == "A" or user_input == "a":
if computer_move == 2:
print("Your opponent has chosen paper! Paper wraps rock! You lose! ")
else:
print("Your opponent has chosen scissors! Rock breaks scissors! You win! ")
elif user_input == "B" or user_input == "b":
if computer_move == 3:
print("Your opponent has chosen scissors! Paper is cut by scissors! You lose! ")
else:
print("Your opponent has chosen rock! Paper wraps rock! You win! ")
elif user_input == "C" or user_input == "c":
if computer_move == 1:
print("Your opponent has chosen rock! Scissors loses to rock! You lose! ")
else:
print("Your opponent has chosen paper! Scissors beats paper! You win! ")
if gameFunctions2.input_detection(user_input) == True:
print()
else:
print()
user_play_again = input("Would you like to play again? Type 'y' if you'd like to play again. ")
if user_play_again == "y":
print()
else:
print("Have a great day! ")
break
# Calls the Main Function
main()
Here is my helper function (gameFunctions2):
def input_detection(user_input):
if user_input == "A" or user_input == "a" or user_input == "B" or user_input == "b" or user_input == "C" or user_input == "c":
return True
else:
print("Please enter a valid option! ")
return False
def tie(user_input, computer_move):
if user_input == user_input.lower in ["a"] and computer_move == "1":
print("It's a tie!")
return True
if user_input == user_input.lower in ["b"] and computer_move == "2":
print("It's a tie!")
return True
if user_input == user_input.lower in ["c"] and computer_move == "3":
print("It's a tie!")
return True
else:
return False
The problem that I'm facing right now is that there will never be a tie between the user and the computer. I've tried to implement the function tie(user_input, computer_move) into main(), but to no success. I have to use helper functions for this assignment, so I'm trying my best to do so. Also, if there's any place that I can make my code more efficient, it would be fantastic if you could point out where :))
Change your tie function to this:
def tie(user_input, computer_move):
if user_input.lower() == "a" and computer_move == 1:
print("It's a tie!")
return True
elif user_input.lower() == "b" and computer_move == 2:
print("It's a tie!")
return True
elif user_input.lower() == "c" and computer_move == 3:
print("It's a tie!")
return True
else:
return False
You cant compare String and Int like this: computer_move == "1" when computer_move is Int.
Simplify the user_input.lower() == "a" statement.
Here is what you can use to make your code more readable:
Use dictionary to translate users input into integers.
Then you can also easily check all the conditions.
Here is the code (I have only added the part where I have get rid of the tie function):
import random
choose = "Start"
symbols = {"rock":1, "paper":2, "scissors":3}
while True:
choose = input("Hi welcome to my game! Choose between Rock, Paper, Scissors! End the game with 'End':\n")
choose = choose.lower()
computer = random.randint(1,3)
if choose in symbols: #Check if input is in a string and if its in symbols
choose = symbols[choose]
elif choose == "end":
break
else:
print("You have written down something ... weird ... next round.")
continue
if choose == computer:
print("It's a tie!")
else:
#Choose who wins ...
pass
There are a lot of minor issues in your code that can be streamlined and a few major ones, but the one causing your issues is that you are defining computer_move as an integer in the main function (computer_move = random.randint(1, 3)), but in your tie function, you are comparing it to a string (eg, computer_move == "1") The first half of your if statement also is not doing what you want: Rewrite that function as such:
def tie(user_input, computer_move):
if user_input.lower() == "a" and computer_move == 1:
print("It's a tie!")
return True
if user_input.lower() == "b" and computer_move == 2:
print("It's a tie!")
return True
if user_input() == "c" and computer_move == 3:
print("It's a tie!")
return True
else:
return False
If you don't want to have a different if statement for each possible outcome, you can try this:
def outcomes(user_input, computer_move):
end_states = {"tie": [["a", 1], ["b",2], ["c",3]],
"user_win": ["LISTS OF USER WIN STATES"]}
if [user_input.lower(), computer_move] in end_states["tie"]:
print("tie")
if [user_input.lower(), computer_move] in end_states["user_win"]:
print("user wins")
else:
print("computer wins")
A few of the fixes:
user_input = input("Press 'A' for rock, 'B' for paper, and 'C' for scissors!\n"
"A. Rock\n"
"B. Paper\n"
C. Scissors\n")
can be changed to:
user_input = input("Press 'A' for rock, 'B' for paper, and 'C' for scissors!\n"
"A. Rock\n"
"B. Paper\n"
C. Scissors\n").lower()
so that you don't need to check for both upper and lower cases each time (you would also be able to remove .lower() from the tie function.
You should move the input_detection function to right after the user makes the input, and you can rewrite the check as such:
if not gameFunctions2.input_detection(user_input):
continue
Which roughly translates to, if it returns "False", return to the start of your while loop (You can also remove the checks for uppercase and lowercase letters, if you use the previous edit).
For checking if the player wants to play again, add .lower() to the end of the input, and you can change the last lines as such:
if user_play_again != "y":
print("Have a great day! ")
break
You don't need to have a statement that evaluates if user_play_again == "y" just to have the else statement (unless you want there to be a separate action for it). You can evaluate the opposite (if user_play_again != "y") alone.
As I began to do earlier, you can put each ending variation into dictionaries and instead of having a different line for each end state check, you can evaluate the dictionary as a whole to streamline things a bit too.
These might not be the only things, and others might disagree with my changes, but it's a start of how I would rewrite the code.
The other answers have resolved the bugs in your code. This answer is meant to give you some ideas about how you might do things differently - specifically, a more object-oriented approach, and taking advantage of the standard library a bit more.
from enum import Enum
class Move(Enum):
ROCK = 0
PAPER = 1
SCISSOR = 2
def get_user_move():
moves = dict(zip("ABC", Move))
print("Options:")
for option, move in moves.items():
print(f"{option:>5}. {move.name.title()}")
prompt = "Enter your selection: "
while True:
user_input = input(prompt).upper()
if user_input in moves:
break
prompt = "Try again: "
return moves[user_input]
def main():
from random import choice
while True:
user_move = get_user_move()
computer_move = choice(tuple(Move))
print(f"\nYou picked {user_move.name.title()}")
print(f"The computer picked {computer_move.name.title()}")
if user_move is computer_move:
print("It's a tie!\n")
else:
winner = ("The computer", "You")[(computer_move.value + 1) % len(Move) is user_move.value]
print(f"The winner is: {winner}!\n")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
:D I've make a little rock paper scissors game in Python just for fun and practice and I've been trying to implement a little scoring system that doesn't seem to want to work properly and I'm not sure how to solve the problem.
import random
import messages
def gameOn():
choice = ["rock", "paper", "scissors"]
computer_choice = random.choice(choice)
player_choice = input("Please chose Rock/Paper/Scissors: ")
player_choice = player_choice.lower()
total_score = 0
while True:
#Makes sure the user enters a valid option.
if player_choice not in("rock", "paper", "scissors"):
print("Choice is not correct!")
#Prints in case both the computer and the player chose the same option.
elif computer_choice == player_choice:
print("You chose the same.")
#Computer choses ROCK.
elif computer_choice == "rock" and player_choice == "paper":
print(messages.win[0])
total_score += 1
print(total_score)
elif computer_choice == "rock" and player_choice == "scissors":
print(messages.lose[0])
#Computer choses PAPER.
elif computer_choice == "paper" and player_choice == "rock":
print(messages.lose[1])
elif computer_choice == "paper" and player_choice == "scissors":
print(messages.win[1])
total_score += 1
print(total_score)
#Computer choses SCISSORS.
elif computer_choice == "scissors" and player_choice == "rock":
print(messages.win[2])
total_score += 1
print(total_score)
elif computer_choice == "scissors" and player_choice == "paper":
print(messages.lose[2])
#Asks the user if he/she wants to play again and restarts the loop if so.
answer = input("Would you like to play again or see your score? Yes/No/Score ")
if answer in ("yes", "Yes", "y", "Y", "yup"):
print("Game starting again!")
gameOn()
elif answer in ("Score", "score"):
print("Your total score is " + str(total_score))
answer = input("Would you like to play again or see your score? Yes/No/Score ")
print("Game starting again!")
gameOn()
else:
print("Goodbye!")
break
gameOn()
The incrementation in itself works but what I want to do is, if the player wins multiple round and at the end writes "score" he should be able to see all the points he has earned. At the moment the score variable get reset every time a new game starts so the score of the use is always either 0 or 1 if he won the round. How could I prevent this behavior?
Thank you very much :D and I hope it's not a too stupid question.
I would not advise using recursion for this. You also shouldn't need to use global variables.
I would rather just loop with while True in your gameOn function and break if the player wants to exit, so that your score is kept in scope.
Also your "Choice is not correct!" was not working because of the indentation.
import random
import messages
def gameOn():
choice = ["rock", "paper", "scissors"]
total_score = 0
while True:
computer_choice = random.choice(choice)
player_choice = input("Please chose Rock/Paper/Scissors: ")
player_choice = player_choice.lower()
while True:
#Makes sure the user enters a valid option.
if player_choice in("rock", "paper", "scissors"):
break
print("Choice is not correct!")
#Prints in case both the computer and the player chose the same option.
elif computer_choice == player_choice:
print("You chose the same.")
#Computer choses ROCK.
elif<computer_choice == "rock" and player_choice == "paper":
print(messages.win[0])
total_score += 1
print(total_score)
elif computer_choice == "rock" and player_choice == "scissors":
print(messages.lose[0])
#Computer choses PAPER.
elif computer_choice == "paper" and player_choice == "rock":
print(messages.lose[1])
elif computer_choice == "paper" and player_choice == "scissors":
print(messages.win[1])
total_score += 1
print(total_score)
#Computer choses SCISSORS.
elif computer_choice == "scissors" and player_choice == "rock":
print(messages.win[2])
total_score += 1
print(total_score)
elif computer_choice == "scissors" and player_choice == "paper":
print(messages.lose[2])
#Asks the user if he/she wants to play again and restarts the loop if so.
answer = input("Would you like to play again or see your score? Yes/No/Score ")
if answer in ("Score", "score"):
print("Your total score is " + str(total_score))
answer = input("Would you like to play again or see your score? Yes/No/Score ")
print("Game starting again!")
elif answer in ("yes", "Yes", "y", "Y", "yup"):
print("Game starting again!")
else:
print("Goodbye!")
break #this makes your game stop
gameOn()
I would suggest defining a parameter to your gameOn function, so it looks like this:
def gameOn(total_score=0):
# REMOVE this following line:
total_score = 0
# because we already defined it on parameter
# when user wins, and you call the function again,
# give current total_score to it
gameOn(total_score)
since in each function call you are giving the current score, now your app should be able to keep track of actual total score
There are 2 different ways to answer this, depending on the meaning of «every time a new game starts».
Do you want to persist the score if you call the gameOn function multiple times?
Or do you want to persist the score also if you run the program again?
Persisting the score between gameOn calls
The problem is the scope of your total_score variable, which is local. Hence it’s cleaned after each gameOn execution. The simplest way to work around this is to set it as global:
import random
import messages
# Total score is initialized outside of any game
total_score = 0
def gameOn():
choice = ["rock", "paper", "scissors"]
computer_choice = random.choice(choice)
player_choice = input("Please chose Rock/Paper/Scissors: ")
player_choice = player_choice.lower()
global total_score
# Then the rest of your existing function
# ...
Advice: With time, you’ll get better in Python, and you’ll realize such global variable is usually considered bad, because of the lack of isolation it has. For larger projects, relying on globally defined stuff makes the code more difficult to evolve, increases the cognitive load of the developer, makes it harder to test... but for such a small script it’s just perfectly fine.
My point is: it’s handy, but please keep in mind there are other ways to do it. They are more complex, and over-engineered in this case, but the key take away shouldn’t be thought as "I need to use global variable as soon as I want to persist a state" ;)
Persisting the score between runs.
If your goal is to keep the score between every time you run the script, then you need to save it "outside" of the current Python session memory.
A very simple way to do this is to save it to a file. Python’s built-in pickle library is made for that (there are many other options, depending on if you want this to be usable by other programs or not, or by humans. When it’s just for Python, pickle is super simple and fast and reliable)
In this case, what you would need is to:
load the existing score when the game starts, if an existing score exists
save it at the end of the game
import random
import messages
import pickle
import os
def gameOn():
choice = ["rock", "paper", "scissors"]
computer_choice = random.choice(choice)
player_choice = input("Please chose Rock/Paper/Scissors: ")
player_choice = player_choice.lower()
score_file = "score.dat"
# Check if an existing score existed
if os.path.isfile(score_file):
with open(score_file, "rb") as f:
total_score = pickle.load(f)
else:
total_score = 0
# Then the rest of your existing function
# ...
# and at the end of the function, we save the score to the file
with open(score_file, "wb") as f:
pickle.dump(total_score, f)
This should give you pointers to what you exactly want to achieve.
I'm trying to make a simple Rock, Paper, Scissors game in python 3.4 and it works to a certain degree but some time i get an output of "You Won Rock crushes Rock" even though i thought i have stop this from happening and only allowed certain outcomes of the code with my elif and if statements. So can anyone tell me why isn't this working sometimes. :)
import random
count = 0
OPTIONS = ['rock', 'paper', 'scissors']
# then check if the user lose's, wins ties
def computer():
return random.choice(OPTIONS)
print("\n"+"-=-"*11)
print("Welcome to ROCK, PAPER, SCISSORS")
print(" GAME")
print(" It's you Vs. the computer!")
print("-=-"*11)
while True:
user = input("What do you choose Rock, Paper, Scissors: ").lower()
if user in OPTIONS:
# Possible user time a user can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock
if user == computer():
print("tie")
elif user == 'rock' and computer() == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer().title()))
elif user == 'scissors' and computer() =='rock':
print("\nComputer Won! {} crushes {}".format(computer().title(), user.title() ))
elif user == 'scissors' and computer() == 'paper':
print("\nYou Won! {} cuts {}".format(user.title(), computer().title()))
elif user == 'paper' and computer() == 'scissors':
print("\nComputer Won! {} cuts {}".format(computer().title(), user.title()))
elif user == 'paper' and computer() == 'rock':
print("\nYou Won! {} covers {}".format(user.title(), computer().title()))
elif user == 'rock' and computer() == 'paper':
print("\nComputer Won! {} covers {}".format(computer().title(), user.title()))
else:
print("\nMake sure you choose ethier Rock, Paper or Scissors")
enter code here
elif user == 'rock' and computer() == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer().title()))
Every time you call computer(), it generates a completely new value, independent of any previous calls. For example, in the code above it's entirely possible that the first computer() call returns "scissors", and the second one returns "rock".
Call computer() only once in the loop, and store the result. Then use that value for the rest of your code.
while True:
user = input("What do you choose Rock, Paper, Scissors: ").lower()
if user in OPTIONS:
computer_move = computer()
# Possible user time a user can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock
if user == computer_move:
print("tie")
elif user == 'rock' and computer_move == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer_move.title()))
#etc
Your computer() function calls a random number. So every time you call computer() in you code you are choosing 'at random' a completely new number. Because there are only three answers, you may actually end up with the right answer quite often.
Think of calling the function as rolling a die (with 3 sides, whoa). So now your program looks like this:
def RollDice():
return random.choice(OPTIONS)
#...
while True:
user = input("What do you choose Rock, Paper, Scissors: ").lower()
if user in OPTIONS:
# Possible user time a user can succeeds rock beats scissor, scissors cuts paper, paper covers rock
if user == RollDice:
print("tie")
elif user == 'rock' and RollDice == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), RollDice.title()))
elif user == 'scissors' and RollDice =='rock':
print("\nComputer Won! {} crushes {}".format(RollDice.title(), user.title() ))
#...
Now you see what the problem is.What you really want is to save the value of 'one' random choice at the very beginning of your if statement:
if user in OPTIONS:
computerChoice = computer()
if user == computerChoice:
print("tie")
elif user == 'rock' and computerChoice == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computerChoice.title()))
elif user == 'scissors' and computerChoice =='rock':
print("\nComputer Won! {} crushes {}".format(computerChoice.title(), user.title() ))
#....
That way you have one constant choice saved in a variable to call on.
P.S. It would also be better to use raw_input instead of input so that the program will automatically change the users input into a string.
Disclaimer, the answer has been given, this is merely to peak the interest in generalizing the game.
To make any type of Rock-Paper-Scissor game you can realize that it is in fact a round-robin table of wins.
For instance if you do this:
P-R-S..P-R-S
you can see that the previous letter always wins on the next letter.
Using this approach it becomes easy to create custom rock-paper-scissor games using look-around tables:
import random
from collections import OrderedDict
# Important to retain order of "kill"
OPTIONS = OrderedDict([('P', 'Paper'),
('R', 'Rock'),
('S', 'Scissors')])
# N_KILLS determines how many letters in front it is killing
N_KILLS = 1
OPTIONS = OrderedDict([('P', 'Princess'),
('J', 'Knight'),
('W', 'Wizard'),
('D', 'Dragon'),
('K', 'King')])
N_KILLS = 2
# Create lookup table
LOOKUP = OPTIONS.keys()
# Number of items
N_ITEMS = len(LOOKUP)
# Options to choose from
STR_OPTIONS = ' ,'.join( OPTIONS.values() )
def computer():
return random.randint(0,N_ITEMS-1)
print("\n"+"-=-"*11)
print("Welcome to "+STR_OPTIONS)
print(" GAME")
print(" It's you vs. the computer!")
print("-=-"*11)
while True:
# Convert user option to integer
uidx = computer()
if uidx >= 0:
# Get computer index
cidx = computer()
d = cidx - uidx
# Correct for wrap-arounds
if d > N_KILLS:
d = d - N_ITEMS
elif d < -N_KILLS:
d = d + N_ITEMS
print(' You choose: '+OPTIONS[LOOKUP[uidx]] + ' computer chooses: '+OPTIONS[LOOKUP[cidx]])
if d == 0:
print(' Tie ...')
elif d > 0 and d <= N_KILLS:
print(' You WIN ...')
elif d < 0 and -d <= N_KILLS:
print(' You LOOSE ...')
else:
# This will only occur if N_KILLS*2+1<N_ITEMS
print(' Tie ...')
Not only is the code easier to read (in my opinion), but it becomes extremely easy to implement several new games. For instance check this amazing game out: http://www.umop.com/rps101.htm
You almost had it correct, as has been mentioned, for each game, the call to computer() should only be made once. It would also make sense to display the two player's choices. Also as you are working in title case, it would make sense to convert everything to use that to avoid needing to call .title() so many times.
import random
OPTIONS = ['Rock', 'Paper', 'Scissors']
# then check if the user lose's, wins ties
def computer():
return random.choice(OPTIONS)
print("\n"+"-=-"*11)
print("Welcome to ROCK, PAPER, SCISSORS")
print(" GAME")
print(" It's you Vs. the computer!")
print("-=-"*11)
while True:
user_choice = input("\nWhat do you choose Rock, Paper, Scissors: ").title()
computer_choice = computer()
print("User: {} Computer: {}".format(user_choice, computer_choice))
if user_choice in OPTIONS:
# Possible user_choice time a user_choice can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock
if user_choice == computer_choice:
print("tie")
elif user_choice == 'Rock' and computer_choice == 'Scissors':
print("You Won! {} crushes {}".format(user_choice, computer_choice))
elif user_choice == 'Scissors' and computer_choice == 'Rock':
print("Computer Won! {} crushes {}".format(computer_choice, user_choice ))
elif user_choice == 'Scissors' and computer_choice == 'Paper':
print("You Won! {} cuts {}".format(user_choice, computer_choice))
elif user_choice == 'Paper' and computer_choice == 'Scissors':
print("Computer Won! {} cuts {}".format(computer_choice, user_choice))
elif user_choice == 'Paper' and computer_choice == 'Rock':
print("You Won! {} covers {}".format(user_choice, computer_choice))
elif user_choice == 'Rock' and computer_choice == 'Paper':
print("Computer Won! {} covers {}".format(computer_choice, user_choice))
else:
print("Make sure you choose either Rock, Paper or Scissors")
So a game would look like:
-=--=--=--=--=--=--=--=--=--=--=-
Welcome to ROCK, PAPER, SCISSORS
GAME
It's you Vs. the computer!
-=--=--=--=--=--=--=--=--=--=--=-
What do you choose Rock, Paper, Scissors: rock
User: Rock Computer: Scissors
You Won! Rock crushes Scissors