Loop Problems Rock Paper Scissors Game - python

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"))

Related

If statement only showing else portion

I'm writing code for a rock, paper, scissors game but the if statement in the function identify_winner is not running. The only thing that prints out is the else statement and it prints out for all outcomes, not just when it's a tie. I'm pretty sure it has something to do with the variables but I don't know what it is.
import random
ROCK = 1
PAPER = 2
SCISSORS = 3
def main():
user_choose(None)
comp_choose(None)
identify_winner()
def user_choose(weapon):
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
def comp_choose(choice):
if random.randint(1,3) == 1:
choice = 'Rock'
elif random.randint(1,3) == 2:
choice = 'Paper'
else:
choice = 'Scissors'
print('Your enemy has chosen',choice)
def identify_winner():
user = 0
comp = 0
while user == comp:
user_choose(user)
comp_choose(comp)
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
main()
First and foremost it is not a good practice to call main function directly as it was a script. If you plan to create not script program you should scope main function inside.
if __name__ == "__main__":
main()
Secondly, you don't need to call user_choose and comp_choose inside identify winner, you can just return those values in your main program and give them as arguments to your identify winner function. Also you should not generate two times a random number in your comp_choose() because in the second elif you could generate the previous number so comp choice most likely be Scissors. I give you one possible solution to your problem:
import random
ROCK = 1
PAPER = 2
SCISSORS = 3
def main():
identify_winner(user_choose(), comp_choose())
def user_choose():
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
return weapon
def comp_choose():
comp_weapon = random.randint(1,3)
if comp_weapon == 1:
choice = 'Rock'
elif comp_weapon == 2:
choice = 'Paper'
else:
choice = 'Scissors'
print('Your enemy has chosen',choice)
return comp_weapon
def identify_winner(user, comp):
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
if __name__ == "__main__":
main()
I made some little changes in your code. Commented the parts for explanation:
import random
# you never use those, so they are not needed here:
# ROCK = 1
# PAPER = 2
# SCISSORS = 3
def user_choose(): # no input argument needed since you define weapon in the next line anyway
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
# this part is asking for a number as long as user don't choose a valid number between 1 and 3.
# You could do even more here, check for number or letter, check if number is 0 or negative
while weapon>3:
weapon = int(input('No valid number. Please choose again: ' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
return weapon # you need to return the variable weapon, otherwise it is only in the local scope and your main function doesn't have access to it
def comp_choose(): # same as in the other function, no input argument needed
choice = random.randint(1,3) # in your code random.randint(1,3) executes twice and can have two different results. You want it once and then check on it
if choice == 1:
chose = 'Rock' # in the main() func you compare the numbers, but in your code user has numbers between 1 and 3 and comp has values with rock, paper, scissors.
elif choice == 2:
chose = 'Paper'
else:
choice = 3
chose = 'Scissors'
print('Your enemy has chosen',chose)
return choice # same as in the other function with 'weapon'
def main(): # identy_winner() isn't needed. two functions for user and comp with the main to select winner is enough
run = True
while run: # doing it like this you can make the user choose if he wants to continue or not (later at the 'continue_playing' part)
user = user_choose() # get access to the return value of the function
comp = comp_choose() # get access to the return value of the function
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
continue_playing = input('You want to play again? [y/n]: ')
if continue_playing == 'n':
run = False
main()
The code will crash if the user chooses a letter instead of numbers, and working poorly if he chooses numbers 0 or less. You may want to check for that.... I leave that up to you.

I am working on a rock, paper, scissors program using functions and it is always returning else cases

I am looking for some input on a rock, paper, scissors program that I am making where the statements in the main() and determineWinner that use playerChoice always terminate in the else: case. Each trial will output the player chooses scissors and that the game is tied. I am not sure where I went wrong here as I've printed the input to confirm it is correct before sending to it to the other functions. I cannot figure what pare of the above to function is causing the problem, if anyone could point me in the right direction here I would be grateful.
Here is the code I have so far:
import random
# define main function
def main():
# initialize playAgain to start game, set stats to 0
playAgain = 'y'
numberTied = 0
numberPlayerWon = 0
numberComputerWon = 0
print("Let's play a game of rock, paper, scissors.")
# loop back to play again if user confirms
while playAgain == 'y' or playAgain == 'Y':
computerChoice = processComputerChoice()
playerChoice = processPlayerChoice()
# display computer choice
if computerChoice == 1:
print('The computer chooses rock.')
elif computerChoice == 2:
print('The computer chooses paper.')
else:
print('The computer chooses scissors.')
# display player choice
if playerChoice == 1:
print('You choose rock.')
elif playerChoice == 2:
print('You choose paper.')
else:
print ('You choose scissors.')
# assign who won to result and add total wins/ties to accumulator
result = determineWinner(playerChoice, computerChoice)
if result == 'computer':
numberComputerWon += 1
elif result == 'player':
numberPlayerWon += 1
else:
numberTied += 1
# ask player if they would like to play again
print('')
print
playAgain = input('Do you want to play again? (Enter y or Y to start another game)')
print('')
else:
# print accumulated wins and ties for computer and player
print('There were', numberTied, 'tie games played.')
print('The computer won', numberComputerWon, 'game(s).')
print('The player won', numberPlayerWon, 'game(s).')
print('')
# define computer choice function
def processComputerChoice():
# randomly select an option for the computer to play
randomNumber = random.randint(1,3)
print(randomNumber)
return randomNumber
# define player choice function
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
# definition for the function to determine the winner
def determineWinner(playerChoice, computerChoice):
# determine player choice and compare to computer choice to determine the winner
if computerChoice == 1:
if playerChoice == 2:
print('Paper covers rock. You are victorious!')
winner = 'player'
elif playerChoice == 3:
print('Rock bashes scissors. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 1')
winner = 'tied'
if computerChoice == 2:
if playerChoice == 1:
print('Paper covers rock. The computer is victorious!')
winner = 'computer'
elif playerChoice == 3:
print('Scissors slice paper. You are victorious!')
winner = 'player'
else:
print('The game is tied. Try again 2')
winner = 'tied'
if computerChoice == 3:
if playerChoice == 1:
print('Rock bashes scissors. You are victorious!')
winner = 'player'
elif playerChoice == 2:
print('Scissors slice paper. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 3')
winner = 'tied'
return winner
main()
input("Press Enter to continue")
The return statement of your function processPlayerChoice has incorrect indentation. It should be out of while loop (unindent it one level)
At the moment, if player enters correct choice your function will return None.
If user enters incorrect choice, it will enter the while loop and will return whatever the second input from user is.
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
Make sure to align your return statements with the function body. Currently in both processPlayerChoice and determineWinner they are aligned with the conditional loops, and thus will not be reached every time.

how to use an if else statement in another while loop

I am new to coding. I want to try writing a simple rock paper scissors game. But I can't figure out how to end the game.
In the end of this program if the user input is wrong I want to go to the end variable again. I tried with the commented lines but its not working.
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
while True:
print(player1 + " What do you choose ? rock / paper / scissors : ")
a = input()
print(player2 + " What do you choose ? rock / paper / scissors : ")
b = input()
if a == "rock" and b == "scissors" :
print(player1, "won !!!")
elif a == "scissors" and b == "rock":
print(player2, "won !!!")
elif a == "paper" and b == "rock":
print(player1, "won !!!")
elif a == "rock" and b == "paper":
print(player2, "won !!!")
elif a == "scissors" and b == "paper":
print(player1, "won !!!")
elif a == "paper" and b == "scissors":
print(player2, "won !!!")
elif a == b:
print("Its a tie :-(")
elif a or b != "rock" or "paper" or "scissors":
print("Wrong input, Try again")
end = input("Do you want to play again ? yes/no ") == "yes"
if input == "yes":
continue
else:
print('''
GAME OVER''')
break
# elif input != "yes" or "no":
# print("Wrong input, Try again. yes or no ?")
I expect it to end game if the input is "no" and restart the game if input is "yes" if the input is not correct I want the prompt to appear again.
Your code has a few issues which need some addressing, and a few places where it can be streamlined. I have made a few changes to your program as well as added a few comments explaining the changes.
player1 = input("What is player 1's name ? ").title() #This uses chaining to streamline code
player2 = input("What is player 2's name ? ").title() #Same as above
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ") #no need to use a separate print statement
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
valid_entries = ["rock", "paper", "scissors"] #To check for valid inputs
if (a not in valid_entries) or (b not in valid_entries):
print("Wrong input, try again")
continue
a_number = valid_entries.index(a) #Converting it to numbers for easier comparison
b_number = valid_entries.index(b)
if(a_number == b_number):
print("Its a tie :-(")
else:
a_wins = ((a_number > b_number or (b_number == 2 and a_number == 0)) and not (a_number == 2 and b_number == 0)) #uses some number comparisons to see who wins instead of multiple if/elif checks
if(a_wins):
print(player1, "won !!!")
else:
print(player2, "won !!!")
end = input("Do you want to play again ? yes/no ")
while (end !="yes") and (end != "no"):
print("invalid input, try again")
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print("GAME OVER")
break
These changes also make the check by using another while loop to see if the input to restart the game was valid or not
*Note that I have not tested these changes and some edits may need to be be made
Just check the value of end
if end is True:
continue
else:
break
Since, you have set the value of end as a boolean by comparing the input() to "yes", it will say whether the user wants to end the game?
Also, you are not initializing the input variable, and the last elif condition will always be true as mentioned in the comment.
Well you can simplify your code using a list and then simplify your if tests. You can check the order of the options and based on it make a decision. You can also make the tests standard to minimize the number of if statements. This my suggestion to improve your code. I hope it helps:
# get playe names
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
# init vars
options = ["rock", "paper", "scissors"]
players = [player1, player2]
# start game
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check if inputs are correct
while (a not in options or b not in options):
print("Wrong input, Try again")
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check who won
if abs(options.index(a) - options.index(b)) == 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif abs(options.index(b) - options.index(a)) > 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif a == b:
print("Its a tie :-(")
# continue or drop game
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print('''
GAME OVER''')
break

Checking If a File Exists and Loading its Contents

In my programming class we are to make a Rock, Paper, Scissors Game that can load previous saves of the game, display the statistics of the game, and allow the user to continue playing if desired. I have a good chunk of the program created, I just need help with the loading of the file as I just get an endless loop of "What is your name?". My code is below and any help would be appreciated!
#Rock, Paper, Scissors Program
#A menu-based RPS program that keeps stats of wins, losses, and
ties
#12/2/18
import sys, os, random, pickle
#Functions
def print_menu():
print("\n1. Start New Game")
print("2. Load Game")
print("3. Quit")
def print_roundmenu():
print("What would you like to do?")
print("\n1. Play Again")
print("2. View Statistics")
print("3. Quit")
def start_game(username, playing):
print("Hello", username + ".", "let's play!")
playAgain = play_game()
if playAgain == True:
playing = True
elif playAgain == False:
playing = False
return playing
def play_game():
roundNo = 1
wins = 0
losses = 0
ties = 0
playing_round = True
while playing_round:
print("Round number", roundNo)
print("1. Rock")
print("2. Paper")
print("3. Scissors")
roundNo += 1
choices = ["Rock", "Paper", "Scissors"]
play = get_choice()
comp_idx = random.randrange(0,2)
comp_play = choices[comp_idx]
print("You chose", play, "the computer chose",
comp_play+".")
if (play == comp_play):
print("It's a tie!")
ties += 1
print_roundmenu()
gameFile.write(str(ties))
elif (play == "Rock" and comp_play == "Scissors" or play == "Paper" and comp_play == "Rock" or play == "Scissors" and comp_play == "Paper"):
print("You win!")
wins += 1
print_roundmenu()
gameFile.write(str(wins))
elif (play == "Scissors" and comp_play == "Rock" or play == "Rock" and comp_play == "Paper" or play == "Paper" and comp_play == "Scissors"):
print("You lose!")
losses += 1
print_roundmenu()
gameFile.write(str(losses))
response = ""
while response != 1 and response != 2 and response != 3:
try:
response = int(input("\nEnter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
continue
elif response == 2:
print(username, ", here are your game play statistics...")
print("Wins: ", wins)
print("Losses: ", losses)
print("Ties: ", ties)
print("Win/Loss Ratio: ", wins, "-", losses)
return False
elif response == 3:
return False
def get_choice():
play = ""
while play != 1 and play != 2 and play != 3:
try:
play = int(input("What will it be? "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if play == 1:
play = "Rock"
if play == 2:
play = "Paper"
if play == 3:
play = "Scissors"
return play
playing = True
print("Welcome to the Rock Paper Scissors Simulator")
print_menu()
response = ""
while playing:
while response != 1 and response != 2 and response != 3:
try:
response = int(input("Enter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
username = input("What is your name? ")
gameFile = open(username + ".rps", "w+")
playing = start_game(username, playing)
elif response == 2:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
elif response ==3:
playing = False
This code block:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
will repeat infinitely unless you set response to something other than 2. Notice here that all you're doing in this block is (1) asking for username, (2) opening the file, and (3) dumping the file contents with pickle. You're not actually starting the game, like you are in the if response == 1 block. So the same prompt keeps repeating infinitely.
A good thing to do in these situations is to manually step through your code by hand - "what did I do to get here, and what is happening as a result of that?"

Why does it skip the 'if' statements in my python 3.x code for a simple RockPaperScissors? [duplicate]

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.

Categories