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)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am at the final steps of creating a rock, paper, scissors game for class. In our brief we must include a function for the computer's choice.
I created the function but some errors have come up where it says that 'choices' has been undefined. I am new to using functions so I am not entirely sure why these errors have come up as I thought I already defined choices.
This is the piece of code which has the error:
def aiChoice():
choices = ['r', 'p', 's']
com_choice = random.choice(choices)
# the possible choices
return choices
return com_choice
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices: **error here that says undefined name 'choices'**
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = random.choice(choices) **same error here for 'choices'**
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw
You need choices outside of the aiChoice() function.
See:
import random
win = 0
loss = 0
draw = 0
# the possible choices
choices = ['r', 'p', 's']
def aiChoice():
com_choice = random.choice(choices)
return com_choice
while True:
name = input("Enter your name: ")
# asks user for name
if name.isalpha():
break
else:
print("Please enter characters A-Z only")
# makes sure user only enters letters
# taken from Stack Overflow
# asks user how many games they want to play
while True:
games = int(input(name + ', enter in number of plays between 1 and 7: '))
if games <= 7:
break
else:
print('1 to 7 only.')
# makes sure user input doesn't exceed seven plays
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices:
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = random.choice(choices)
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw
elif user_play == 'r' and com_choice == 'p':
print('Paper beats rock.')
print('AI wins!')
loss = loss + 1
# if the user plays rock and computer plays paper, says that the computer won and puts a point in the loss category
elif user_play == 'r' and com_choice == 's':
print('Rock beats scissors.')
print(name + ' wins!')
win = win + 1
# if the user plays rock and computer plays scissors, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 'r':
print('Paper beats rock.')
print(name + ' wins!')
win = win + 1
# if the user plays paper and computer plays rock, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 's':
print('Scissors beats paper.')
print('AI wins!')
loss = loss + 1
# if the user playspaper and scissors plays paper, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'r':
print('Rock beats scissors.')
print('AI wins!')
loss = loss + 1
# if the user plays scissors and computer plays rock, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'p':
print('Scissors beats paper.')
print(name + ' wins!')
win = win + 1
# if the user plays scissors and computer plays paper, says that the person won and puts a point in the win category
print(name + "'s final score:")
print('Wins: ' + str(win))
print('Loss: ' + str(loss))
print('Draws: ' + str(draw))
# prints the final score after all games are finished.
At the moment you're also not calling the aiChoice() function.
Do this instead:
import random
win = 0
loss = 0
draw = 0
# the possible choices
choices = ['r', 'p', 's']
def aiChoice():
com_choice = random.choice(choices)
return com_choice
while True:
name = input("Enter your name: ")
# asks user for name
if name.isalpha():
break
else:
print("Please enter characters A-Z only")
# makes sure user only enters letters
# taken from Stack Overflow
# asks user how many games they want to play
while True:
games = int(input(name + ', enter in number of plays between 1 and 7: '))
if games <= 7:
break
else:
print('1 to 7 only.')
# makes sure user input doesn't exceed seven plays
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices:
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = aiChoice()
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw
elif user_play == 'r' and com_choice == 'p':
print('Paper beats rock.')
print('AI wins!')
loss = loss + 1
# if the user plays rock and computer plays paper, says that the computer won and puts a point in the loss category
elif user_play == 'r' and com_choice == 's':
print('Rock beats scissors.')
print(name + ' wins!')
win = win + 1
# if the user plays rock and computer plays scissors, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 'r':
print('Paper beats rock.')
print(name + ' wins!')
win = win + 1
# if the user plays paper and computer plays rock, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 's':
print('Scissors beats paper.')
print('AI wins!')
loss = loss + 1
# if the user playspaper and scissors plays paper, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'r':
print('Rock beats scissors.')
print('AI wins!')
loss = loss + 1
# if the user plays scissors and computer plays rock, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'p':
print('Scissors beats paper.')
print(name + ' wins!')
win = win + 1
# if the user plays scissors and computer plays paper, says that the person won and puts a point in the win category
print(name + "'s final score:")
print('Wins: ' + str(win))
print('Loss: ' + str(loss))
print('Draws: ' + str(draw))
# prints the final score after all games are finished.
I am working on Rock, Paper, Scissors in Python 3. I need help trying to implement where the computer keeps track of the users choices so it can tell what the player favors and have an advantage over the player. I also have the computer choosing random using an integer but I need to make the players choice a lowercase 'r' 'p' 's' and a 'q' to quit so it can check for invalid entry and display message and ask again. I don't want to use integers for the player.
Here is what I have:
import os
import random
import time
#global variable
#0 is a placeholder and will not be used
choices = [0, 'rock', 'paper', 'scissors']
player_wins = 0
computer_wins = 0
tie_count = 0
round_number = 1
keep_playing = True
# sets cls() to clear screen
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
# function to display stats
def stats():
print("Current Statistics:")
print("Player Wins: {}".format(player_wins))
print("Computer Wins: {}".format(computer_wins))
print("Tied Games: {}\n".format(tie_count))
# function to check outcome
def game_outcome(player, computer):
#this makes the variables global, else you'll get error
global player_wins, tie_count, computer_wins
if computer == player:
print("It's a tie!\n\n")
tie_count += 1 # incraments tie
# checks all possible win conditions for player. and if met, declares player a winner. If not, declares compute the winner.
elif (player == "rock" and computer == "scissors") or (player == "paper" and computer == "rock") or (player == "scissors" and computer == "paper"):
print("Player wins\n\n")
player_wins += 1 # incraments player's wins
else:
print("Computer wins!\n\n")
computer_wins += 1 # incraments computer's wins
# clears screen
cls()
print("Let's play Rock Paper Scissors!")
# 3-second time out before clearing and asking for input
time.sleep(3)
while keep_playing == True:
# make computer choice random from defined list. Only selects a range of 1-3 ignoring the "0" placeholder
# this is because the user selects a number, instead of typing the weapon, and that number pulls the weapon from the list
computer = random.choice(choices[1:4])
cls()
# prints starting of round and shows stats
print("+++++++++++++[Starting Round {}]+++++++++++++\n".format(round_number))
stats()
# ask for player input
player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
player = choices[int(player)]
cls()
print("\n\nThe player's choice: [{}]\n".format(player))
print("The computer's choice: [{}]\n\n".format(computer))
game_outcome(player, computer)
round_number += 1
# ask if player wants to play again. If not, stop
play_again = input('Would you like to play again [y/n]? ')
if play_again.lower() == 'n':
break
print("Thanks for playing!")
Try using a dictionary:
# put this with the imports at the top
import sys
# replace `choices` at the top
choices = {'r': 'rock', 'p': 'paper', 's': 'scissors', 'q': 'quit'}
# get computer choice
# replaces `computer = random.choice(choices[1:4])`
computer = random.choice(['rock', 'paper', 'scissors'])
# ask for player input
# replace these two lines of code:
# player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
# player = choices[int(player)]
while True:
try:
player = choices[input("What is your choice?\n(r) Rock\n(p) Paper\n(s) Scissors?\n(q) to quit.\n\nEnter the letter before the weapon of choice: ")]
if player == 'quit':
sys.exit(0)
break
except KeyError:
print('Please try again.')
Problems:
Program does not seem to accept the integers entered. Won't add to win/loss/draw count and does not display computer choice in debug mode
Basics Design of the Program:
Write a program that lets the user play the game of Rock, Paper, Scissors against the computer.
The program should work as follows.
A menu is displayed:
Score: 0 wins, 0 draws, 0 losses
(D)ebug to show computer's choice
(N)ew game
(Q)uit
If the user enters "Q" or "q" the program would end. "N" or "n" for a new game, "D" or "d" for debug mode, anything else would cause an error message to be displayed.
When a game begins, a random number in the range of 1 through 3 is generated. If the number is 1, then the computer has chosen rock. If the number is 2, then the computer has chosen paper. If the number is 3, then the computer has chosen scissors. (Don't display the computer's choice yet unless we are in "D"ebug mode.)
The user enters his or her choice of “1-rock”, “2-paper”, or “3-scissors” at the keyboard.
The computer's choice is displayed.
A winner is selected according to the following rules:
• If one player chooses rock and the other player chooses scissors, then rock wins.
(The rock smashes the scissors.)
• If one player chooses scissors and the other player chooses paper, then scissors wins.(Scissors cuts paper.)
• If one player chooses paper and the other player chooses rock, then paper wins.
(Paper wraps rock.)
• If both players make the same choice, the game is a draw.
Your program would keep a running total of the number of wins, loses and draws.
Re-display the menu and repeat the game loop.
My Program:
import random
def main():
continuing = "y"
win = 0
lose = 0
draw = 0
while continuing == "y":
print("Score:", win,"wins,", draw, "draws,", lose,"losses")
print("(D)ebug to show computer's choice")
print("(N)ew game")
print("(Q)uit")
choice = input(" ")
if choice == "n" or choice == "N":
win, draw, lose = playgame(win, draw, lose)
elif choice == "d" or choice == "D":
win, draw, lose = playgame2(win, draw, lose)
elif choice == "q" or choice == "Q":
break
def playgame(win, draw, lose):
computer = random.randint(1,3)
player = input("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ")
if computer == 1 and player == 2:
Score = "You won"
win += 1
elif computer == 1 and player == 3:
Score = "You lost"
lose += 1
elif computer == 2 and player == 1:
Score = "You lost"
lose += 1
elif computer == 2 and player == 3:
Score = "You won"
win += 1
elif computer == 3 and player == 1:
Score = "You won"
win += 1
elif computer == 3 and player == 2:
Score = "You lost"
lose += 1
elif computer == player:
Score = "Draw"
draw += 1
return (win, draw, lose)
def playgame2(win, draw, lose):
computer = random.randint(1, 3)
player = input("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ")
if computer == 1 and player == 2:
Score = "You won"
print("Computer chose rock")
win += 1
elif computer == 1 and player == 3:
Score = "You lost"
print("Computer chose rock")
lose += 1
elif computer == 2 and player == 1:
Score = "You lost"
print("Computer chose paper")
lose += 1
elif computer == 2 and player == 3:
Score = "You won"
print("Computer chose paper")
win += 1
elif computer == 3 and player == 1:
Score = "You won"
print("Computer chose scissors")
win += 1
elif computer == 3 and player == 2:
Score = "You lost"
print("Computer chose scissors")
lose += 1
elif computer == player:
Score = "Draw"
print("Computer chose the same as you")
draw += 1
return (win, draw, lose)
main()
I'm no Pythonista, but at a guess, input returns strings, and you'll need to convert to integer before comparing to the computer's int.
I also think you are missing a trick in DRYing up your code - you should be able to have a single playgame method, which takes an additional boolean parameter debugmode, which instead of calling print directly, calls an indirection, e.g.:
def debugPrint(debugString, debugMode)
if debugMode
print(debugString)
Hope this makes sense?
This would work in Python 2.x, but, not in Python 3.x
In Python 3.x, input() returns strings. Thus, the player's input would be of the form "1" or "2" or "3". Since 1 and "1" are different, the program will not execute any of the lines in the if and elif blocks in playgame() and playgame2().
Here is a Python 3.x example:
>>> a = input("Input = ")
Input = 1
>>> print a
SyntaxError: Missing parentheses in call to 'print'
>>> print(a)
1
>>> a
'1'
>>> type(a)
<class 'str'>
Thus, you should use i = int(input("Input = ")) wherever you want an integer input.
However, in Python 2.x, input() will take 1 as 1 itself and not as "1". But, when you want to type a string as an inpu, you will have to give the quotes also. Here is an exxample:
>>> a1 = input("Input = ")
Input = 1
>>> a1
1
>>> type(a1)
<type 'int'>
>>> #I want to input a string now:
>>> a2 = input("Input = ")
Input = string
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a2 = input("Input = ")
File "<string>", line 1, in <module>
NameError: name 'string' is not defined
>>> a2 = input("Input = ")
Input = "string"
>>> a2
'string'
>>> type(a2)
<type 'str'>
>>> a3 = raw_input("Input = ")
Input = hello
>>> a3
'hello'
>>> type(a3)
<type 'str'>
>>>
In Python 2.x, the raw_input() function takes the input as a string.
Need help on stopping the score from resetting every game,
this is my code so far and its not working.
This is part of a function that checks who's the winner etc.
def winner ():
global Win
if alist [0] == player1 and alist[1] == player1 and alist[2] ==player1:#top line horizontal
Win = 'player1'
return True
elif alist[3] == player1 and alist[4] == player1 and alist[5] ==player1:#middleline horizontal
Win = 'player1'
return True
this statement determines the score and whether to start another game.
if winner():
if Win == 'player1':
print("player1 is winner")
p1score = p1score+1
elif Win == 'player2':
print("player2 is winner")
p2score = p2score+1
print('Player1s score =', p1score,'Player2s score =', p2score)
print("Would you like to play again(yes or no)")
restart = input("")
if restart == 'yes':
return gamemode()
Ok so at the end of the game the score displays correctly, but when another game is played it resets?
def playervscomputer():
global Player1Score
Player1Score = 0
global ComputerScore
ComputerScore = 0
players = [name, 'computer']
global turn
turn = random.randint(0,1)
while True:
print('its\s %s\'s turn' % players[turn])
if winner1():
#Check if people have won
if Win == 'player1':
print("player1 is winner")
Player1Score = Player1Score+1
print("player1s score is", Player1Score, 'Computer Score=', ComputerScore)
print("would you like to play again?(yes or no)")
restart = input("")
if restart =='yes':
return main()
else:
print("Thanks for playing")
elif Win == 'Computer':
print("Computer is winner")
ComputerScore = ComputerScore+1
print('Player1s score =', Player1Score,'Computers score =', ComputerScore)
Any ideas or any help on it keeping the scores after a few games have been played.
Thanks
Looks like you're not fully understanding scope. Try changing p1score and p2score to global variables (like you did with Win).
This YouTube video helped me understand the difference between global and local variables, maybe it will help you.
https://www.youtube.com/watch?v=A054Ged9suI
A simple programm, that uses a function to increment two independent variables (in a list):
score = [0,0]
def increment(Player):
global score
if Player == 1:
score[0]+=1
elif Player ==2:
score[1]+=1
else:
print('Input not defined')
def main():
global score
print(score)
increment(1)
increment(2)
increment(2)
print(score)
I am very new to programming.
I have to write a Rock Paper Scissors game for my Intro to Programming class. I have a great start but a few issues I don't know how to solve.
I need three different menus. The main menu should ask to 1. Start new game 2. Load game or 3. Quit. Choose 1 or 2 and you input your name then play begins. You are then asked to select 1. Rock 2. Paper 3. Scissors. My game works great but after choosing Rock paper scissors I want a NEW menu to pop up: What would you like to do? 1. Play Again 2. View Statistics 3. Quit. But I have no idea where to put this. I have tried a few different places but it just by passes it and asks for rock paper scissors again.
Then my second issue is, when user selects 1. State new game needs to ask for their name and use their name to save their games to a file. Then when user chooses 2. Load Game, their name will be used to find a file "name.rps" and load their stats to continue to play (stats, round number, name).
Any help is appreciated.
import random
import pickle
tie = 0
pcWon = 0
playerWon = 0
game_round = (tie + playerWon + pcWon) + 1
# Displays program information, starts main play loop
def main():
print("Welcome to a game of Rock, Paper, Scissors!")
print("What would you like to do?")
print ("")
welcomemenu()
playGame = True
while playGame:
playGame = play()
displayScoreBoard()
prompt = input("Press enter to exit")
def welcomemenu():
print ("[1]: Start New Game")
print ("[2]: Load Game")
print ("[3]: Quit")
print("")
menuselect = int(input("Enter choice: "))
print("")
if menuselect == 1:
name = input("What is your name? ")
print("Hello", name, ".")
print("Let's play!")
elif menuselect == 2:
name = input("What is your name? ")
print("Welcome back", name, ".")
print("Let's play!")
player_file = open('name.rps', 'wb')
pickle.dump(name, player_file)
player_file.close()
elif menuselect == 3:
exit()
return menuselect
# displays the menu for user, if input ==4, playGame in the calling function (main()) is False, terminating the program.
# Generate a random int 1-3, evaluate the user input with the computer input, update globals accordingly, returning True
# to playGame, resulting in the loop in the calling function (main()) to continue.
def play():
playerChoice = int(playerMenu())
if playerChoice == 4:
return 0
else:
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome)
return 1
# prints the menu, the player selects a menu item, the input is validated, if the input is valid, returned the input, if
# the input is not valid, continue to prompt for a valid input
# 1 - rock
# 2 - paper
# 3 - scissors
def playerMenu():
print("Select a choice: \n [1]: Rock \n [2]: Paper \n [3]: Scissors")
print("")
menuSelect = input("What will it be? ")
while not validateInput(menuSelect):
invalidChoice(menuSelect)
menuSelect = input("Enter a correct value: ")
return menuSelect
# if the user doesn't input a 1-3 then return false, resulting in prompting the user for another value. If the value
# is valid, return True
# takes 1 argument
# menuSelection - value user entered prior
def validateInput(menuSelection):
if menuSelection == "1" or menuSelection == "2" or menuSelection == "3":
return True
else:
return False
# return a random integer 1-3 to determine pc selection
# 1 - rock
# 2 - paper
# 3 - scissors
def pcGenerate():
pcChoice = random.randint(1,3)
return pcChoice
# evaluate if the winner is pc or player or tie, return value accordingly
# 0 - tie
# 1 - player won
# -1 - pc won
def evaluateGame(playerChoice, pcChoice):
if playerChoice == 1:
print("You have chosen rock.")
if pcChoice == 1:
#tie
print("Computer has chose rock as well. TIE!")
return 0
elif pcChoice == 2:
#paper covers rock - pc won
print("The computer has chosen paper. Paper covers rock. You LOSE!")
return -1
else:
#rock breaks scissors - player won
print("The computer has chosen scissors. Rock breaks scissors. You WIN!")
return 1
elif playerChoice == 2:
print("You have chosen paper.")
if pcChoice == 1:
#paper covers rock - player won
print("The computer has chosen rock. Paper covers rock. You WIN!")
return 1
elif pcChoice == 2:
#tie
print("The computer has chosen paper as well. TIE!")
return 0
else:
#scissors cut paper - pc won
print("The computer has chosen scissors. Scissors cut paper. You LOSE!")
return -1
else: #plyer choice defaults to 3
print("You have chosen scissors")
if pcChoice == 1:
#rock breaks scissors - pc won
print("The computer has chosen rock. Rock breaks scissors. You LOSE!")
return -1
elif pcChoice == 2:
#scissors cut paper - player won
print("The computer has chosen paper. Scissors cut paper. You WIN!")
return 1
else: #pc defaults to scissors
#tie
print("The computer has chosen scissors as well. TIE!")
return 0
# Update track of ties, player wins, and computer wins
def updateScoreBoard(gameStatus):
global tie, playerWon, pcWon
if gameStatus == 0:
tie +=1
elif gameStatus == 1:
playerWon += 1
else:
pcWon += 1
# If user input is invalid, let them know.
def invalidChoice(menuSelect):
print(menuSelect, "is not a valid option. Please use 1-3")
# Print the scores before terminating the program.
def displayScoreBoard():
global tie, playerWon, pcWon
print("Statistics:\nTies:", tie, "\nPlayer Wins:", playerWon, "\nComputer Wins:", pcWon)
print("Win/Loss Ratio:", playerWon/pcWon)
print("Rounds:", tie + playerWon + pcWon)
main()
def play():
playerChoice = int(playerMenu())
if playerChoice == 4:
return 0
else:
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome)
return 1
This is the method we want.
So all you need to do is call the new menu method under updateScoreBoard().
Then under the new menu method.
if(playerChoice == 1)
play();
if else(playeChoice == 2)
stats();
else
quit();
Use '%s.rsp' % name, Not 'name.rsp'. open('name.rsp', 'w') will always open 'name.rsp' evn if name = 'foo'.
I made SPOILER for you!
this code work well and helpful for you. but you have to think enough before see this code
BELOW IS SPOILER CODE
import random
import pickle
#I'll use class for easy load, easy dump.
class GameStatus():
def __init__(self, name):
self.tie = 0
self.playerWon = 0
self.pcWon = 0
self.name = name
def get_round(self):
return self.tie + self.playerWon + self.pcWon + 1
# Displays program information, starts main play loop
def main():
print "Welcome to a game of Rock, Paper, Scissors!"
print "What would you like to do?"
print ""
game_status = welcomemenu()
while True:
play(game_status)
endGameSelect(game_status)
#prompt user's choice and return GameStatus instance
def welcomemenu():
#changed a logic to handle unexpected user input.
while True:
print "[1]: Start New Game"
print "[2]: Load Game"
print "[3]: Quit"
print ""
menuselect = input("Enter choice: ")
if menuselect in [1, 2, 3]:
break
else:
print "Wrong choice. select again."
if menuselect == 1:
name = raw_input("What is your name?: ") # raw_input for string
print "Hello %s." % name
print "Let's play!"
game_status = GameStatus(name) #make a new game status
elif menuselect == 2:
while True:
name = raw_input("What is your name?: ")
try:
player_file = open('%s.rsp' % name, 'r')
except IOError:
print "There's no saved file with name %s" % name
continue
break
print "Welcome back %s." % name
print "Let's play!"
game_status = pickle.load(player_file) #load game status. not dump.
displayScoreBoard(game_status)
player_file.close()
elif menuselect == 3:
print "Bye~!"
exit()
return
return game_status
# displays the menu for user, if input == 4, playGame in the calling function (main()) is False, terminating the program.
# Generate a random int 1-3, evaluate the user input with the computer input, update globals accordingly, returning True
# to playGame, resulting in the loop in the calling function (main()) to continue.
def play(game_status):
playerChoice = int(playerMenu())
#this if statement is unnecessary. playerMenu() already checked this.
#if playerChoice == 4:
# return 0
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome, game_status)
# prints the menu, the player selects a menu item, the input is validated, if the input is valid, returned the input, if
# the input is not valid, continue to prompt for a valid input
# 1 - rock
# 2 - paper
# 3 - scissors
def playerMenu():
print "Select a choice: \n [1]: Rock \n [2]: Paper \n [3]: Scissors\n"
menuSelect = input("What will it be? ")
while not validateInput(menuSelect):
invalidChoice(menuSelect) #I think this function is un necessary. just use print.
menuSelect = input("Enter a correct value: ")
return menuSelect
# if the user doesn't input a 1-3 then return false, resulting in prompting the user for another value. If the value
# is valid, return True
# takes 1 argument
# menuSelection - value user entered prior
def validateInput(menuSelection):
if menuSelection in [1, 2, 3]: # more readable.
return True
else:
return False
# return a random integer 1-3 to determine pc selection
# 1 - rock
# 2 - paper
# 3 - scissors
def pcGenerate():
pcChoice = random.randint(1,3)
return pcChoice
# evaluate if the winner is pc or player or tie, return value accordingly
# 0 - tie
# 1 - player won
# 2 - pc won
def evaluateGame(playerChoice, pcChoice):
#more readable.
rsp = ['rock', 'paper', 'scissors']
win_statement = ['Rock breaks scissors', 'Paper covers rock', 'Scissors cut paper']
# if player win, win_status = 1 (ex. rock vs scissors -> (1 - 3 == -2) -> (-2 % 3 == 1))
# if pc win, win_status = 2
# if tie, win_status = 0
win_status = (playerChoice - pcChoice) % 3
print "You have chosen %s" % rsp[playerChoice - 1]
what_to_say = "Computer has chose %s" % rsp[pcChoice - 1]
if win_status == 0:
what_to_say += " as Well. TIE!"
elif win_status == 1:
what_to_say += ". %s. You WIN!" % win_statement[playerChoice - 1]
else:
what_to_say += ". %s. You LOSE!" % win_statement[pcChoice - 1]
print what_to_say
return win_status
# Update track of ties, player wins, and computer wins
def updateScoreBoard(outcome, game_status):
if outcome == 0:
game_status.tie += 1
elif outcome == 1:
game_status.playerWon += 1
else:
game_status.pcWon += 1
# If user input is invalid, let them know.
def invalidChoice(menuSelect):
print menuSelect, "is not a valid option. Please use 1-3"
# Print the scores before terminating the program.
def displayScoreBoard(game_status):
print ""
print "Statistics:"
print "Ties: %d" % game_status.tie
print "Player Wins: %d" % game_status.playerWon
print "Computer Wins: %d" % game_status.pcWon
if game_status.pcWon > 0:
#if you don't use float, '10 / 4' will be '2', not '2.5'.
print "Win/Loss Ratio: %f" % (float(game_status.playerWon) / game_status.pcWon)
else:
print "Win/Loss Ratio: Always Win."
print "Rounds: %d" % game_status.get_round()
def endGameSelect(game_status):
print ""
print "[1]: Play again"
print "[2]: Show Statistics"
print "[3]: Save Game"
print "[4]: Quit"
print ""
while True:
menuselect = input("Enter choice: ")
if menuselect in [1, 2, 3, 4]:
break
else:
print "Wrong input."
if menuselect == 2:
displayScoreBoard(game_status)
endGameSelect(game_status)
elif menuselect == 3:
f = open("%s.rsp" % game_status.name, 'w')
pickle.dump(game_status, f)
f.close()
print "Saved."
endGameSelect(game_status)
elif menuselect == 4:
print "Bye~!"
exit()
main()
def rps(a, b):
game = { "rp" : 1, "rr" : 0, "rs" : -1,
"ps" : 1, "pp" : 0, "pr" : -1,
"sr" : 1, "ss" : 0, "sp" : -1}
return (game[a + b])
# For example:
print (rps("r", "p"))