Rock Paper Scissors Keeping Score - python

I am trying to create a rock paper scissors game that keeps score but when I run this program the score resets each time. What do I need to change so that I can properly keep score?
import random
def rockPaperScissors():
playerScore = 0
computerScore = 0
print ""
p = raw_input("Type 'r' for rock, 'p' for paper or 's' for scissors: ")
choices = ['r', 'p', 's']
c = random.choice(choices)
print ""
print "Your move:", p
print "Computer's move:", c
print ""
if p == c:
print "Tie"
elif p == 'r' and c == 's':
playerScore += 1
print "You win"
elif p == 'p' and c == 'r':
playerScore += 1
print "You win"
elif p == 's' and c == 'p':
playerScore += 1
print "You win"
elif c == 'r' and p == 's':
computerScore += 1
print "You lose"
elif c == 'p' and p == 'r':
computerScore += 1
print "You lose"
elif c == 's' and p == 'p':
computerScore += 1
print "You lose"
else:
print "Try again"
print ""
print "Your score:", str(playerScore)+ ", Computer score:", str(computerScore)
while True:
rockPaperScissors()

You're calling the function in a loop. The first thing the function does is create a local variable for the score. When the function ends, that score is thrown away. It doesn't persist through multiple calls. You should return the new score and assign the new values to counters:
import random
def rockPaperScissors():
playerScore = 0
computerScore = 0
...
return playerScore, computerScore
player = 0
computer = 0
while True:
p, c = rockPaperScissors()
player += p
computer += c
print "Your score:", str(player)+ ", Computer score:", computer

Each time you run the function, you are resetting the scores. Define computerScore and playerScore outside of the function, then it will keep the values even when running the function multiple times. Use global to "import" the global variable into the function scope.
playerScore = 0
computerScore = 0
def rockPaperScissors ():
global playerScore
global computerScore
OTHER CODE

Related

NameError, variable not defined in Python

so the ultimate goal is to run best 2 out of 3 games of rock, paper, scissors, lizard, spock. i haven't added a loop yet or anything like that i'm trying to get the game itself running first but I'm coming across a NameError, it's saying the 'result' variable is undefined.
I've tried returning it but that doesn't appear to be working, but I also maybe don't know what I'm doing?
def number_to_name(number):
if number == 1:
return 'scissors'
elif number == 2:
return 'rock'
elif number == 3:
return 'paper'
elif number == 4:
return 'lizard'
elif number == 5:
return 'spock'
else:
print ("Error: Invalid number")
def name_to_number(name):
if name == 'scissors':
return 1
elif name == 'rock':
return 2
elif name == 'paper':
return 3
elif name == 'lizard':
return 4
elif name == 'spock':
return 5
else:
print ("Error: Invalid number")
def rpsls(name):
player_score, computer_score = (0, 0)
player_input = name_to_number(name)
computer_input = random.randint(1,5)
result = (player_input - computer_input) % 5
if result == 1 or result == 2:
print("player wins")
player_score += 1
print("Player {}, Computer {}". format(player_score, computer_score))
elif result == 3 or result == 4:
game = "computer wins"
computer_score += 1
print("Player {}, Computer {}". format(player_score, computer_score))
elif result == 0:
game = "it's a tie"
print("Player {}, Computer {}". format(player_score, computer_score))
else:
print("error")
rpsls("rock")
rpsls("spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
Your conditions should be inside the rpsls function.Because you result variable is local variable. You can't fetch this variable globally.
> def rpsls(name):
> player_score, computer_score = (0, 0)
> player_input = name_to_number(name)
> computer_input = random.randint(1, 5)
> result = (player_input - computer_input) % 5
>
>
> if result == 1 or result == 2:
> print("player wins")
> player_score += 1
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> elif result == 3 or result == 4:
> game = "computer wins"
> computer_score += 1
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> elif result == 0:
> game = "it's a tie"
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> else:
> print("error")
Your variable result is inside the function rpsls. So the scope of result lies to the function only.
A easy solution would be assign a 0 value to result before the function 'rpsls'
This way your updating a globally defined variable inside the function.
result = 0
def rpsls(name):
#Your code
The best way would be to write a class, have a class level variable result, and put all this code into the class.
First of all, since result is only defined in the function, it is only accessable inside that specific function, unless you choose to use the global method, which I wouldn't recommend.
Second, since you called result before you called the function that actually defines result, even if you use global, it will still not be defined for that specific line.

establishing a win streak in dice game

Hi all. Really, REALLY stuck here. I've updated my code below.
I'm trying to establish a counter to track games played, correct guesses and > incorrect guesses plus, when the number of consecutive correct guesses
= 4 or user stops playing, game summary is provided.
I cannot get the counter to work correctly.
Help appreciated!
import math
import dice
import random
# Print introduction and game explanation
print ("")
print ("")
print ("Would you like to play a game?")
print ("The game is...'Petals Around the Rose'. Cool eh?")
print ("Pay attention - the name of the game is important.")
print ("Each round, five dice are rolled and")
print ("You'll be asked for the score. (Hint? The score")
print ("will always be either 'zero' or an even number).")
print ("Your challenge is to deduce how the computer has")
print ("calculated the score.")
print ("You need to input your guess, after which")
print ("You'll learn if you were right. If not, you'll")
print ("be told the correct score & asked to roll again.")
print ("If you can guess correctly four times in a row,")
print ("You'll be declared the winner and receive the")
print ("majestic title of 'Potentate of the Rose'")
print ("")
# Define win count (four correct guesses in a row required)
win_count = 0
# Obtain input from user:
answer = input("Are you up for the challenge? Enter 'y' or 'n' : ")
# If answer = no, exit game
if answer == 'n':
print("Really? fine then. See ya!")
exit()
# If answer = yes, commence game
elif answer == 'y':
print("")
print ("Ok...here comes the first roll!")
print("")
# import dice representation
import dice
# Roll random dice x 5
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
die3 = random.randint(1, 6)
die4 = random.randint(1, 6)
die5 = random.randint(1, 6)
dice.display_dice(die1, die2, die3, die4, die5)
# Obtain player's guess for the roll
roll_guess = int(input("Enter your guess for this roll: "))
# Define die results for all dice for guess purposes to
# match the 'petals around the rose'. So, if roll a 2, 4 or 6,
# the result is zero. If return a 3, the result is 2. If
# return a 5, the result is 4.
def roll_result(die1):
if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
die1 = 0
elif die1 == 3:
die1 = 2
elif die1 == 5:
die1 = 4
return die1
def roll_result(die2):
if die2 == 1 or die2 == 2 or die2 == 4 or die2 == 6:
die2 = 0
elif die2 == 3:
die2 = 2
elif die2 == 5:
die2 = 4
return die2
def roll_result(die3):
if die3 == 1 or die3 == 2 or die3 == 4 or die3 == 6:
die3 = 0
elif die3 == 3:
die3 = 2
elif die3 == 5:
die3 = 4
return die3
def roll_result(die4):
if die4 == 1 or die4 == 2 or die4 == 4 or die4 == 6:
die4 = 0
elif die4 == 3:
die4 = 2
elif die4 == 5:
die4 = 4
return die4
def roll_result(die5):
if die5 == 1 or die5 == 2 or die5 == 4 or die5 == 6:
die5 = 0
elif die5 == 3:
die5= 2
elif die5 == 5:
die5 = 4
return die5
# tally all 5 dice rolls
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
# Compare user input to dice result
if roll_guess == total_roll_result:
print("")
print('Well done! You guessed it!')
print("")
elif guess % 2 == 0:
print("")
print("No sorry, it's", total_roll_result, "not", roll_guess)
print("")
else:
print("")
print ("No, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
# Obtain user input if continuing to play
another_attempt = input("Are you up to play again? If so, enter y or n ")
print("")
# Commence loop and win count.
while another_attempt == 'y' and win_count <4:
# Commence win count
win_count = 0
# Commence games played count
games_played = 0
# Commence incorrect guesses count
incorrect_guesses = 0
# If user has not yet gotten 4 guesses in a row:
if win_count < 4:
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
die4 = random.randint(1,6)
die5 = random.randint(1,6)
result = dice.display_dice(die1, die2, die3, die4, die5)
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
roll_guess = int(input('Enter your guess for this roll: '))
print("")
if roll_guess == total_roll_result:
# Update win count
win_count += 1
# Update games played count
games_played += 1
print("")
print('Nice work - you got it right!')
elif roll_guess %2 == 0:
# reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print("Nah, sorry, it's", total_roll_result, "not", roll_guess)
else:
# Reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print ("Nah, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
another_attempt = input("Are you up to play again? ")
# Quit loop if user no longer wishes to play
# Provide game summary
if another_attempt == 'n':
print ("")
print ("Game Summary")
print ("------------")
print ("")
print ("You played ", games_played, "games.")
print ("")
print ("You had ", correct_guesses, "overall and ")
print ("")
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
if win_count == 4:
# Inform player has correctly guessed 4 in a row
# Print congratulations message
print ("")
print ("")
print ("You've done it! You've successfully guessed")
print ("Four times in a row. Looks like you worked ")
print ("out the secret. Now, stay stum & tell no one!")
print ("")
# Provide game summary
print ("Game Summary")
print ("")
# Provide tally of games played & print:
print ("You played ", games_played, "games.")
print ("")
# Provide tally of correct guesses & print:
print ("You had ", correct_guesses, "overall and ")
print ("")
# Provide tally of total incorrect guesses & print:
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
def game_stats():
win_count
games_played
incorrect_guesses
You look very lost here. This part does not make any sense
def win_count():
win_count() == 0
correct == total_roll_result
I think you mean something like this
win_count = 0
correct = total_roll_result == roll_guess
Note
When you say
def win_count:
# some code
you are defining win_count as a function! But clearly you want win_count to be an integer counting something.

Undefined Function?

I am not sure why I am getting an error that game is not defined:
#!/usr/bin/python
# global variables
wins = 0
losses = 0
draws = 0
games = 0
# Welcome and get name of human player
print 'Welcome to Rock Paper Scissors!!'
human = raw_input('What is your name?')
print 'Hello ',human
# start game
game()
def game():
humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors, Q - Quit: ')
while humanSelect not in ['R', 'P', 'S', 'Q']:
print humanSelect, 'is not a valid selection'
humanSelect = raw_input('Enter a valid option please')
return humanSelect
main()
Because, at the time the statement game() is executed you have not yet reached the statement def game(): and game is, therefore, undefined.
If you move game() to after def game() you will then get a similar error on main() which is harder to fix as you don't appear to be defining a function called main anywhere in the code.
You have to define the function game before you can call it.
def game():
...
game()
Okay, I spent some time tinkering with this today and now have the following:
import random
import string
# global variables
global wins
wins = 0
global losses
losses = 0
global draws
draws = 0
global games
games = 0
# Welcome and get name of human player
print 'Welcome to Rock Paper Scissors!!'
human = raw_input('What is your name? ')
print 'Hello ',human
def readyToPlay():
ready = raw_input('Ready to Play? <Y> or <N> ')
ready = string.upper(ready)
if ready == 'Y':
game()
else:
if games == 0:
print 'Thanks for playing'
exit
else:
gameResults(games, wins, losses, draws)
return
def game():
global games
games += 1
human = humanChoice()
computer = computerChoice()
playResults(human, computer)
readyToPlay()
def humanChoice():
humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors: ')
while humanSelect not in ['R', 'P', 'S']:
print humanSelect, 'is not a valid selection'
humanSelect = raw_input('Enter a valid option please')
return humanSelect
def computerChoice():
computerInt = random.randint(1, 3)
if computerInt == '1':
computerSelect = 'R'
elif computerInt == '2':
computerSelect = 'P'
else:
computerSelect = 'S'
return computerSelect
def playResults(human, computer):
global draws
global wins
global losses
if human == computer:
print 'Draw'
draws += 1
elif human == 'R' and computer == 'P':
print 'My Paper wrapped your Rock, you lose.'
losses += 1
elif human == 'R' and computer == 'S':
print 'Your Rock smashed my Scissors, you win!'
wins += 1
elif human == 'P' and computer == 'S':
print 'My Scissors cut your paper, you lose.'
losses += 1
elif human == 'P' and computer == 'R':
print 'Your Paper covers my Rock, you win!'
wins += 1
elif human == 'S' and computer == 'R':
print 'My Rock smashes your Scissors, you lose.'
losses += 1
elif human == 'S' and computer == 'P':
print 'Your Scissors cut my Paper, you win!'
wins += 1
def gameResults(games, wins, losses, draws):
print 'Total games played', games
print 'Wins: ', wins, ' Losses: ',losses, ' Draws: ', draws
exit
readyToPlay()
I am going to work on the forcing the humanSelect variable to upper case in the same manner that I did with ready, ready = string.upper(ready). I ran into indentation errors earlier today, but will iron that out later tonight.
I do have a question. Is it possible to use a variable between the () of a raw_input function similar to this:
if game == 0:
greeting = 'Would you like to play Rock, Paper, Scissors?'
else:
greeting = 'Play again?'
ready = raw_input(greeting)

Rock, paper, scissors game. Writing a print statement that works

Here is my code:
from random import*
from myro import*
from math import*
def computerChoice():
computer = randint(0,2)
if (computer == 0):
choice = "rock"
elif(computer == 1):
choice = "paper"
else:
choice = "scissors"
return choice
def userGuess():
print " R = Rock"
print " P = Paper"
print " S = Scissors"
userChoice = raw_input("Enter R, P, or S: ")
return userChoice
def calculate(userChoice, choice):
userNameWins = 0
computerWins = 0
draws = 0
if(userChoice == "R" and choice == "paper"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice== "R" and choice == "scissors"):
speak( "you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "rock"):
speak("you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "scissors"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "rock"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "paper"):
speak("you win")
userNameWins = userNameWins + 1
else:
speak("Draw")
draws = draws + 1
return userNameWins, computerWins, draws
def printResults(userNameWins, computerWins, draws)
# insert code for print statement
def main():
for x in range (5):
speak("Rock Papers Scissors ")
userChoice = userGuess()
choice = computerChoice()
calculate(userChoice,choice)
printResults (userNameWins, computerWins, draws)
I get an error when I try to define some variables and I don't know why.
I need a function that properly prints the results returned by calculate()
The part you're asking for is trivial. Since you didn't give us the desired output format, I'll guess at it, and hopefully you can fix it to match the way you want it to look:
def printResults(userNameWins, computerWins, draws)
print('user won {} times, computer won {} times, and players drew {} times'
.format(userNameWins, computerWins, draws))
However, your code isn't going to work, for at least two reasons.
First, you call this:
calculate(userChoice,choice)
… which returns the 3 values you want, but you never store them anywhere. In particular, you don't store them, or anything else, in variables named userNameWins, computerWins, and draws. So, this like will get a NameError:
printResults (userNameWins, computerWins, draws)
Second, you're looping 5 times over a function that, each time, returns a full set of values, but you're only calling printResults once, not 5 times. I'm not sure what you're intending here, but most likely, either you need to move printResults into the loop, or you need to add code that sums up the results across all the loops.
sorry about the wait but hopefully this solution is of help to you.
from random import randint
#from myro import *
choice = None
userChoice = None
userNameWins = 0
computerWins = 0
draws = 0
def computerChoice():
global choice
computer = randint(0,2)
if (computer == 0):
choice = "rock"
elif(computer == 1):
choice = "paper"
else:
choice = "scissors"
print "Scribbler selected " + choice
return choice
def userGuess():
global userChoice
print " R = Rock"
print " P = Paper"
print " S = Scissors"
userChoice = raw_input("Enter R, P, or S: ")
return userChoice
def calculate(userChoice, choice):
global userNameWins
global computerWins
global draws
if(userChoice == "R" and choice == "paper"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice== "R" and choice == "scissors"):
print( "you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "rock"):
print("you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "scissors"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "rock"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "paper"):
print("you win")
userNameWins = userNameWins + 1
else:
print("Draw")
draws = draws + 1
def printResults():
print "You won " + str(userNameWins) + " times"
print "Scribbler won " + str(computerWins) + " times"
print "There were " + str(draws) + " draws"
if (userNameWins > computerWins):
print "You win overall"
elif (userNameWins < computerWins):
print "Scribbler wins overall"
else:
print "It was a dead heat"
def main():
global userChoice
global choice
for x in range (5):
print ("Rock Papers Scissors ")
userChoice = userGuess()
choice = computerChoice()
calculate(userChoice,choice)
printResults ()
main()
I didn't have myro installed so I used print instead to display the results. Before you weren't saving the variables for the results anywhere so I made a global variable so that it can store the variables. Also I completed the printResults function.

Global variable can't be modified in a separate function

I am trying to make a simple RPS game and can't see what I am doing wrong.
I declase pc_choise, player_choice and turn as global variables but I can't modify them in functions such as checkWinner().
If I print that value after the function has been called, it still has the initial value.
Code:
import random
import sys
pc_choices = ['r','p','s']
pc_choise = ''
player_choice = ''
turns = 0
print("\t\tWelcome to Rock Paper Scissors")
def getPcChoice():
return random.randint(1,3) - 1
def getUserChoice():
player_choice = input('Please choose: ')
turns = 1
if(player_choice.lower() not in pc_choices):
print('\nPlease use R, P, or S - *not case sensitive*\n')
getUserChoice()
else:
pc_choise = pc_choices[getPcChoice()]
print('\nYou picked ' + player_choice + ' and the PC picked ' +
pc_choise)
checkWinner()
def checkWinner():
if(player_choice.lower() == pc_choise.lower()):
print('Tie')
elif(player_choice.lower() == 'r' and pc_choise.lower() == 'p'
or player_choice.lower() == 'p' and pc_choise.lower() == 's'
or player_choice.lower() == 's' and pc_choise.lower() == 'r'):
print('You win! 😍')
else:
print('You lose! 🤯')
getUserChoice()
add the following code in the first line of the code:
global pc_choices and global pc_choice etc.
this is to mark the variable will use is a global variable.
You need to declare the variables as global within the function scope so that Python interpreter can interpret them accordingly, otherwise, they get the function scope by default. I also found indentation issues which I have fixed. Below is your modified code:
import random
import sys
pc_choices = ['r','p','s']
pc_choise = ''
player_choice = ''
turns = 0
print("\t\tWelcome to Rock Paper Scissors")
def getPcChoice():
return random.randint(1,3) - 1
def getUserChoice():
global pc_choise
global player_choice
player_choice = input('Please choose: ')
turns = 1
if(player_choice.lower() not in pc_choices):
print('\nPlease use R, P, or S - *not case sensitive*\n')
getUserChoice()
else:
pc_choise = pc_choices[getPcChoice()]
print('\nYou picked ' + player_choice + ' and the PC picked ' + pc_choise)
checkWinner()
def checkWinner():
global pc_choise
global player_choice
if(player_choice.lower() == pc_choise.lower()):
print('Tie')
elif(player_choice.lower() == 'r' and pc_choise.lower() == 'p'
or player_choice.lower() == 'p' and pc_choise.lower() == 's'
or player_choice.lower() == 's' and pc_choise.lower() == 'r'):
print('You win! 😍')
else:
print('You lose! 🤯')
getUserChoice()
However, as suggested by #mario_sunny in the comments, it's better to avoid using global variables.

Categories