For my exercise, I have to get the computer to play against the user in RPS. However, after both the computer and I input our action, the user will always receive a 'You Lose'.
import random
def get_computer_move():
"""Deterministic 'random' move chooser"""
options = ['rock', 'paper', 'scissors']
return options[random.randint(0, 2)]
def game_result(move1, move2):
"""game_result *exactly* as defined in question one"""
options = ["rock", "paper", "scissors"]
if move1 == move2:
return 0
elif move1 == "paper" and move2 == "rock":
return 1
elif move1 == "rock" and move2 == "scissors":
return 1
elif move1 == "scissors" and move2 == "paper":
return 1
else:
return 2
def main():
"""Runs a single game of PSR"""
print("Let's Play Paper, Scissors, Rock!")
user1 = input("Player one move: ").lower()
computer1 = print("The computer plays " + get_computer_move())
game_result(computer1, user1)
if user1 == computer1:
return print("It's a draw")
elif user1 == "paper" and computer1 == "rock":
return print("You win")
elif user1 == "rock" and computer1 == "scissors":
return print("You win")
elif user1 == "scissors" and computer1 == "paper":
return print("You win")
else:
return print("You lose")
main()
Here is my code although it is quite messy.
What I want to happen is:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
It's a draw
But it will always come out as:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
You lose
Help would be appreciated.
print returns none, you want to save the computers move and then print that separately
computer1 = get_computer_move()
print("The computer plays", computer1)
This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 1 year ago.
When I run this code and input "r" "p" or "s" the first if condition within the function runs as though it is true. My goal is for the else statement to run when the user inputs a valid answer, such as "s" "p" or "r". Tried debugging, calling the global choice variable, not sure what to do here. Help would be appreciatd. This is Python 3.7.
possible_options = ["rock", "paper", "scissors"]
choice = input("Enter r for rock, p for paper, and s for scissors: ")
def game():
global choice
print(choice)
if choice != "r" or choice != "p" or choice != "s":
choice = input("Invalid choice. Must be r, p, or s: ")
game()
else:
selection = choice
if selection == "r":
if random.choice(possible_options) == "rock":
print("The computer chose rock!")
print("It was a tie!")
elif random.choice(possible_options) == "paper":
print("The computer chose paper!")
print("Paper covers rock! You lose.")
elif random.choice(possible_options) == "scissors":
print("The computer chose scissors!")
print("Rock smashes scissors! You win!")
elif selection == "p":
if random.choice(possible_options) == "rock":
print("The computer chose rock!")
print("Paper covers rock! You win!")
elif random.choice(possible_options) == "paper":
print("The computer chose paper!")
print("It was a tie!")
elif random.choice(possible_options) == "scissors":
print("The computer chose scissors!")
print("Scissors cut paper! You lose.")
elif selection == "s":
if random.choice(possible_options) == "rock":
print("The computer chose rock!")
print("Rock smashes scissors! You lose.")
elif random.choice(possible_options) == "paper":
print("The computer chose paper!")
print("Scissors cut paper! You win!")
elif random.choice(possible_options) == "scissors":
print("The computer chose scissors!")
print("It was a tie!")
game()
Replace
if choice != "r" or choice != "p" or choice != "s":
with
if choice != "r" and choice != "p" and choice != "s":
I define a variable named 'computerChoice' in a function and then attempt to use it in another variable but it says that 'computerChoice' is undefined... Being new to Python, I am not sure why this is happening so I hope that you could help answer my question!
def computerDecision():
import random
for x in range(1):
num = random.randint(1,4)
if num == 1:
computerChoice = 'rock'
elif num == 2:
computerChoice = 'paper'
elif num == 3:
computerChoice = 'scissors'
def determineWinner():
if userInput == computerChoice:
print("You both chose " + computerChoice)
print("DRAW!")
elif userInput == 'rock' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'rock' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print('USER WINS!')
elif userInput == 'paper' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("USER WINS!")
elif userInput == 'paper' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("USER WINS!")
The computerChoice variable is restricted in scope to the function in which it was defined. This is to prevent functions from interfering with one another. You can declare it to be global (accessible from anywhere) with the keyword global:
global computerChoice
This is probably not what you want, however, as your functions do not need to interact with each other. You can just make computerDecision() return its choice.
import random
def computerDecision():
for x in range(1):
num = random.randint(1,4)
if num == 1:
return 'rock'
elif num == 2:
return 'paper'
elif num == 3:
return 'scissors'
def determineWinner():
computerChoice = computerDecision()
if userInput == computerChoice:
print("You both chose " + computerChoice)
print("DRAW!")
elif userInput == 'rock' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'rock' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print('USER WINS!')
elif userInput == 'paper' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("USER WINS!")
elif userInput == 'paper' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("USER WINS!")
Also note that computerDecision() can be redefined more simply, as just return random.choice(("rock", "paper", "scissors")).
I'm very new to Python and decided to set myself a challenge of programming a Rock, Paper, Scissors game without copying someone else's code. However, I need help from a Pythonista grown-up!
I've seen many other variations on Rock, Paper, Scissors, on here but nothing to explain why my version isn't working. My program basically follows this format: set empty variables at start, define 4 functions that prints intro text, receives player input, randomly picks the computer's choice, then assesses whether its a win or a loss for the player.
This is all then stuck in a while loop that breaks once the player selects that they don't want to play anymore. (This bit is working fine)
However, whenever I run the code, it just always gives a draw and doesn't seem to store any data for the computer's choice function call. Does anybody know what I'm doing wrong?
Many thanks!
import random
playerAnswer = ''
computerAnswer = ''
winsTotal = 0
timesPlayed = 0
def showIntroText():
print('Time to play Rock, Paper, Scissors.')
print('Type in your choice below:')
def playerChoose():
playerInput = input()
return
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return
def assessResult():
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
winsTotal += 1
return
while True:
timesPlayed += 1
showIntroText()
playerAnswer = playerChoose()
computerAnswer = computerChoose()
assessResult()
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.')
You have missed returning values in most of the case.
** Add 'return playerInput ' in playerChoose() instead of only return.
** Add ' return computerPick ' in computerChoose() instead of return.
** Initialize winsTotal variable before using it as 'winsTotal = 0' in assessResult().
** Variables you have intialized at the start of program are out of scope for functions.
Please check this StackOverFlow link for understanding scope of variables in python.
** Add 'return winsTotal' in assessResult() instead of return.
import random
def showIntroText():
print('Time to play Rock, Paper, Scissors.')
print('Type in your choice below:')
def playerChoose():
playerInput = input()
return playerInput
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return computerPick
def assessResult(winsTotal):
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
winsTotal += 1
return winsTotal
total_win = 0
while True:
timesPlayed += 1
showIntroText()
playerAnswer = playerChoose()
computerAnswer = computerChoose()
total_win = assessResult(total_win)
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.' + 'Out of which you won '+ str(total_win))
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
You win!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Draw!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Paper beats Rock. You lose!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Paper beats Rock. You lose!
Do you want to play again? (y/n)
"n"
Thank you for playing! You played 4 games.Out of which you won 1
add input and return in your functions
def computerChoose And def assessResultreturn None
for Example by this code you can play this game :
import random
playerAnswer = ''
computerAnswer = ''
winsTotal = 0
timesPlayed = 0
def playerChoose():
playerInput = input("insert:")
return playerInput
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return computerPick
def assessResult(playerAnswer, computerAnswer):
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
return
while True:
timesPlayed += 1
playerAnswer = playerChoose()
computerAnswer = computerChoose()
assessResult(playerAnswer,computerAnswer)
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.')
It is always a draw because you aren't returning the answers from your function, both playerAnswer and computerAnswer return None
As some of people said playerChoose() and computerChoose() return with None
Modifidy these statement playerChoose() -> return playerInput
and computerChoose() -> return computerPick
AS well as you have to use global variable. Insert this row
global winsTotal
in the assessResult().
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm really new to coding in Python, and since I'm on basics, every code is literally a huge block full of messed up code. What I'm trying to do at the moment is a rock-paper-scissors-lizard-spock game which will be transformed into a game later on with visual, hoping to be a basic app to my phone to sharp my learning, anyway, here's the code.
What I am trying to do is, when there's a draw with the player and the computer, ask the user if he wants to play again, I can't figure it out properly, I will appreciate any help.
import random
computerChoice = random.randint(1,5)
playerChoosing = True
answer = True
if computerChoice == 1:
computerChoice = "rock"
elif computerChoice == 2:
computerChoice = "paper"
elif computerChoice == 3:
computerChoice = "scissors"
elif computerChoice == 4:
computerChoice = "spock"
elif computerChoice == 5:
computerChoice = "lizard"
while playerChoosing == True:
print("rock, paper, scissors, lizard, spock, What do you choose?")
playerChoice = input()
if playerChoice == "rock":
print("you chose rock")
playerChoosing = False
elif playerChoice == "paper":
print("you chose paper!")
playerChoice = "paper"
playerChoosing = False
elif playerChoice == "scissors":
print("you chose scissors!")
playerChoice = "scissors"
playerChoosing = False
elif playerChoice == "lizard":
print("you chose lizard!")
playerChoice = "lizard"
playerChoosing = False
elif playerChoice == "spock":
print("you chose spock!")
playerChoice = "spock"
playerChoosing = False
else:
print("this is not an option, please try again")
playerChoosing = True
input()
print("The computer chose: " +computerChoice+ "!")
input()
#lose
while answer == True:
if playerChoice == "rock" and computerChoice == "paper":
print("you lose!, the rock was covered by the paper!")
elif playerChoice == "paper" and computerChoice == "scissors":
print("you lose!, scissors cut the paper in half")
elif playerChoice == "scissors" and computerChoice == "rock":
print("you lose!, rock crushed the scissors")
elif playerChoice == "spock" and computerChoice == "lizard":
print("you lose!, lizard poisons spock")
elif playerChoice == "scissors" and computerChoice == "spock":
print("you lose!, spock smashes scissors")
elif playerChoice == "rock" and computerChoice == "spock":
print("you lose!, spock vaporizes the rock")
elif playerChoice == "paper" and computerChoice == "lizard":
print("you lose!, lizard eats paper")
elif playerChoice == "lizard" and computerChoice == "rock":
print("you lose!, rock crushes lizard")
elif playerChoice == "lizard" and computerChoice == "scissors":
print("you lose!, scissors kills lizard")
elif playerChoice == "spock" and computerChoice == "paper":
print("you lose!, paper disproves spock")
#win
elif playerChoice == "paper" and computerChoice == "rock":
print("you win!, the rock was covered by the paper!")
elif playerChoice == "scissors" and computerChoice == "paper":
print("you win!, scissors cut the paper in half!")
elif playerChoice == "rock" and computerChoice == "scissors":
print("you win!, rock crushed the scissors!")
elif playerChoice == "lizard" and computerChoice == "spock":
print("you win!, lizard poisons spock!")
elif playerChoice == "spock" and computerChoice == "scissors":
print("you win!, spock smashes scissors!")
elif playerChoice == "lizard" and computerChoice == "paper":
print("you win!, lizard eats paper!")
elif playerChoice == "rock" and computerChoice == "lizard":
print("you win!, rock crushes lizard!")
elif playerChoice == "scissors" and computerChoice == "lizard":
print("you win!, scissors kills lizard!")
elif playerChoice == "paper" and computerChoice == "spock":
print("you win!, paper disproves spock!")
elif playerChoice == "spock" and computerChoice == "rock":
print("you win!, spock vaporizes rock!")
#draw
elif playerChoice == "paper" and computerChoice == "paper":
print("It's a draw, want to try again?, please type YES or NO: ")
answer = input()
if answer == "yes":
answer = False
else:
break
elif playerChoice == "rock" and computerChoice == "rock":
print("It's a draw, want to try again?, please type YES or NO: ")
answer = input()
if answer == "yes":
answer = False
else:
break
elif playerChoice == "scissors" and computerChoice == "scissors":
print("It's a draw, want to try again?, please type YES or NO: ")
answer = input()
if answer == "yes":
answer = False
else:
break
elif playerChoice == "lizard" and computerChoice == "lizard":
print("It's a draw, want to try again?, please type YES or NO: ")
answer = input()
elif playerChoice == "spock" and computerChoice == "spock":
print("It's a draw, want to try again?, please type YES or NO: ")
answer = input()
You'll want to wrap your code in a function definition called play(), or something similar. Then near the end:
answer = True
def play():
# your code
if playerChoice == computerChoice:
print "It's a draw, want to try again?, please type YES or NO: "
# use a dictionary to convert; default answer is False
answer = {'YES' : True, 'NO' : False}.get(input(), False)
if answer:
play()
This is all strongly rooted in the idea of Control Flow. Many languages, including Python, provide functions, classes, modules, if-else, and other control structures that allow you to control which direction your code moves. Many of these structures also help you to organize your code.
If the output of your code only needed to be win, lose, or draw, then you could use more advanced structures to get rid of your if-else statement. In my opinion, it's close to the best implementation in your case, but it's quite ugly when it's not wrapped in a function.
Here's a different way to approach the problem using python's built-ins:
import random
newgame = True
choosing = False
playerchoice = ''
computerchoice = ''
options = ['rock', 'scissors', 'paper', 'lizard', 'spock']
def play():
global choosing, computerchoice, computerchoice, newgame
choosing = True
while choosing == True: # or while choosing
choose()
result = get_result(playerchoice, computerchoice)
if result[0] == 'Draw':
print "It's a draw, want to try again?", "Please type YES or NO:"
# convert input into uppercase string, use dictionary to convert to boolean
# default to False
newgame = {'YES' : True, 'NO' : False}.get(str(input()).upper(), False)
return # leave function back into 'while newgame' loop
else:
# fun code that converts the first value into the win/lose string, and combines it with the outcome of the round
# join uses the string ', ' in between the two things we print
values = [{True : 'You win!', False : 'You lose!'}[result[0]], result[1]]
string = ', '.join(values)
print string
def choose():
global playerchoice, choosing, computerchoice
print "rock, paper, scissors, lizard, spock. What do you choose?"
playerchoice = input()
if playerchoice in options: # if playerchoice == any option
print 'you chose', playerchoice
computerchoice = options[random.randint(0,4)] # take advantage of list indexes
print 'computer chose', computerchoice
choosing = False
else:
print "this is not an option, please try again"
def get_result(playerchoice, computerchoice):
results = {
'rock' : {
'rock' : ('Draw',),
'paper' : (False, 'paper covers rock!'),
'scissors' : (True, 'rock crushes scissors!'),
'lizard' : (True, 'rock crushes lizard!'),
'spock' : (False, 'spock vaporizes rock!')
},
'paper' : {
'rock' : (True, 'paper covers rock!'),
'paper' : ('Draw',),
'scissors' : (False, 'scissors cut paper!'),
'lizard' : (False, 'lizard eats paper!'),
'spock' : (True, 'paper disproves spock!')
},
'scissors' : {
'rock' : (False, 'rock crushes scissors!'),
'paper' : (True, 'scissors cut paper!'),
'scissors' : ('Draw',),
'lizard' : (True, 'scissors kills lizard!'),
'spock' : (False, 'spock smashes scissors!')
},
'lizard' : {
'rock' : (False, 'rock crushes lizard!'),
'paper' : (True, 'lizard eats paper!'),
'scissors' : (False, 'scissors kills lizard!'),
'lizard' : ('Draw',),
'spock' : (True, 'lizard poisons spock!')
},
'spock' : {
'rock' : (True, 'spock vaporizes rock!'),
'paper' : (False, 'paper disproves spock!'),
'scissors' : (True, 'spock smashes scissors!'),
'lizard' : (False, 'lizard poisons spock!'),
'spock' : ('Draw',)
},
}
return results[playerchoice][computerchoice]
while newgame == True:
play()
Python has some very powerful built-in types and functions, so I intentionally used them in the code above to the point of absurdity. Hopefully you'll look at the code and find new things to learn about Python.
When used well, if/else is sufficient, but I hope I've demonstrated a few powerful ways Python can simplify complex code. Little things like using dictionaries to convert are really useful to keep code concise. They come with a slight performance overhead, but execution speed isn't usually a priority if you use Python.
Edit: Avoid using global variables because they get really hard to debug if you forget the global keyword ^^; Another common debugging difficulty is when you have a tuple with one element ('Draw') and forget to tell python it's a tuple by adding a comma...
I think what you want to do is to make your code shorter
Maybe instead of trying to use so many if else, consider the following first:
r 0
s 1
p 2
you player 2
Win
r - s = -1
s - p = -1
p - r = 2
Lose
s - r = 1
p - s = 1
r - p = -2
Draw
s - s = 0
p - p = 0
r - r = 0
There are a set of values that you get when you subtract your choice with theirs. So winning will only result in -1 and 2.
I'm semi-new to Python compared to some other people, but I've learnt a good amount so far. So here are some tips to solve your problem and other tips to make your code better. Now, I'm not totally sure what your exact problem is, but I believe you want to know how to start the game over if it's a tie.
Put the game into a while loop that's equal to True. Then if it's a tie, use the continue statement (if you're unsure what that is look it up) to restart the while loop. At end of the while loop put break.
I'm new to Stack Overflow, otherwise I'd post the code with the revisions to make it easier to understand. Also you don't need so many elif statements to check to see if its a tie. One simple elif playerChoice == computerChoice: should do it.
If you haven't learnt how to make functions yet, you should try simplifying your code with making your own. If you haven't learnt that yet, it's not too hard to learn and it might also help with restarting the game if there's a tie.
Another tip that I'm still working on myself is to add plenty of comments to code. I can't count how many programs I've returned to after a month or so, and I look at it confused, and ask what was the purpose of some function or statement. Hopefully I was helpful (my first posting on Stack Overflow).