I am creating a rock paper scissors program in Python and that part was very easy of course. The issue lies where I need to return the score at the end in a list. I give the player the option to play as many times as they want, based on their input, and give a final score at the end, based on the number of times played. Whenever I run the code, I get the score after each game to make sure it is running correctly, but when I type '2' to exit, the score says 0 0 0. Any help would be appreciated. Here is the code.
import random as r
def main():
"""
Asks user if they want to play and keeps track of score until player exits
"""
tie_score = 0
human = 0
opponent = 0
choice = input('Enter 1 to play or 2 to exit: ')
play_again = ['1', '2']
while choice not in play_again:
# determine if user input is valid to start the game
print('Invalid choice.')
choice = input('Enter 1 to play or 2 to exit: ')
else:
while choice == '1':
play_game(tie_score, human, opponent)
choice = input('Enter 1 to play or 2 to exit: ')
def computer_choice():
"""
computer generates rock, paper, or scissors by using random module
"""
options = ['Rock', 'Paper', 'Scissors']
choice = r.choice(options)
return choice
def play_game(tie_score, human, opponent):
"""
Determines win, lose, or tie based on user input. Returns score
"""
user_options = ['Rock', 'Paper', 'Scissors']
user = input('Enter Rock, Paper, or Scissors: ')
computer = computer_choice()
while user not in user_options:
# Validates user input, allowing only rock, paper, or scissors
print('Please enter Rock, Paper, or Scissors')
user = input('Enter Rock, Paper, or Scissors: ')
else:
# determines who wins, or tie
if user == computer:
print('Computer chooses %s, tie' % computer)
tie_score = 1
elif (user == 'Rock') and (computer == 'Scissors'):
print('Computer chooses %s, win' % computer)
human = 1
elif (user == 'Paper') and (computer == 'Rock'):
print('Computer chooses %s, win' % computer)
human = 1
elif (user == 'Scissors') and (computer == 'Paper'):
print('Computer chooses %s, win' % computer)
human = 1
else:
print('Computer chooses %s, lose' % computer)
opponent = 1
return tie_score, human, opponent
main()
CodePudding user response:
The problem here is that you never actually save the scores that are returned from the play_game()
function. When you call play_game()
in your main()
function, you need to assign a variable to the result, like:
scores = play_game()
And then you can access the scores in order to add them to a list in the main function, to be printed or returned when the main while loop exits:
def main():
...
score_list = []
...
scores = play_game()
score_list.append(scores)
In general it is best not to simply dump code into the question, it is better to just give the function names and explain what they do in simplest terms. In the future, try to limit how much code you post.
CodePudding user response:
You need to store your scores. It's getting reinitialised with zero