Expected an indentation block Python error - python

I've looked at the similar questions but all were either a description without indentation after an if statement, or a weird mixture of spaces and tabs. I have tried removing all of the tabs and using 4 spaces and also tried with all tabs, I'm just stuck now. I've tried retyping the whole thing but I must be missing something. Any help would be greatly appreciated
EDIT: Posting the whole thing as people are getting confused about the functions which I didn't post
from sys import exit
class player:
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 0
cave_save = False
cave_fork_save = False
dragon_save = False
def exit_beach():
print "Walking further up the beach from water, you see a cave."
print "Above the cave hangs a warning sign, it reads:\n"
print "\"DANGER: Tresspassers will be killed and eaten\""
ans = raw_input("Ignore the warning and enter the cave?\n\n1. Enter the cave\n2. Continue walking\n\n> ")
if ans == "1":
cave()
elif ans == "2":
troll()
else:
print "Error, you didn't enter 1 or 2\n"
def shadow_figure():
print "\n\nYou approach the figure, who remains silent."
print "As you get closer you realise he has bag at his feet."
print "Mysterious figure: \"You may choose only one.\""
print "You look into the bag, and see a shiny sword on top of a large steel shield."
ans = raw_input("Do you: \n1. Take the sword \n2. Take the shield \n3. Take the whole bag and run \n4. Walk away without taking anything\n> ")
if ans == "1":
print "The sword gives you an extra 3 damage"
player.wep_dam += 3
exit_beach()
elif ans == "2":
print "The shield gives you 3 armor, but it's so heavy it reduces your sneak by 1"
player.arm += 3
player.sne -= 1
exit_beach()
elif ans == "3":
dungeon("You get about 10 feet away with the bag before bony fingers grip your throat and choke you unconscious")
elif ans == "4":
exit_beach()
else:
print "Error, please enter anumber between 1 and 4"
def beach():
print "\n\nYou wake up on a beach with no idea how you got there. \nYou see a shadowy figure close to the water."
ans = raw_input("Do you: \n1. Approach him \n2. Go the other way\n> ")
if ans == "1":
shadow_figure()
elif ans == "2":
exit_beach()
else:
print "Please enter either 1 or 2"
def dungeon(why):
print why
if not player.cave_save and not player.dragon_save and not player.cave_fork_save:
print "Unfortunately you didn't get far enough to continue from a saved point, \n would you like to restart from the beginning? (Yes/No)"
ans = raw_input("> ")
ans = ans.lower()
if ans == "yes":
reset_stats()
start()
else:
end()
elif player.cave_save and not player.dragon_save and not player.cave_fork_save:
print "Would you like to continue from the cave entrance or start over?"
print "1. Cave entrance\n2. Start over\n3. Exit game"
ans = raw_input("> ")
if ans == "1":
cave()
elif ans == "2":
reset_stats()
start()
else:
end()
elif player.cave_save and player.cave_fork_save and not player.dragon_save:
print "Would you like to continue from the cave entrance, the cave fork, or start over?"
print "1. Cave entrance\n2. Cave fork\n3. Start over\n4. Exit game"
ans = raw_input("> ")
if ans == "1":
cave()
elif ans == "2":
cave_fork()
elif ans == "2":
reset_stats()
start()
else:
end()
else:
print "Havent done this part yet"
def reset_stats():
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 10
print "\n\n\n\nGame Reset\n\n\n\n"
def end():
print "Thank you for playing"
exit(0)
def start():
print "You are an adventurer, your stats are currently:"
print "Strength: %d \nCharisma: %d \n Sneak: %d" % ( player.str, player.cha, player.sne)
print "Strength determines your damage, charisma determines your chance of pursuasion, \nand sneak determines whether or not you can go get past enemies without being detected"
print "you have 10 points available to spend, to spend a point, simply type the number which corresponds\nwith the skill and hit enter"
print "\n\n1. Strength \t2. Charisma \t3. Sneak\n"
player.points_remaining = 10
while player.points_remaining > 0:
ans = raw_input("Choose a skill: ")
if ans == "1":
player.str += 1
player.points_remaining -= 1
print "Strength is now %d" % ( player.str)
print "%d points remaining\n" % ( player.points_remaining)
elif ans == "2":
player.cha += 1
player.points_remaining -= 1
print "Charisma is now %d" % ( player.cha)
print "%d points remaining\n" % ( player.points_remaining)
elif ans == "3":
player.sne += 1
player.points_remaining -= 1
print "Sneak is now %d" % ( player.sne)
print "%d points remaining\n" % (player.points_remaining)
else:
print "Error, please enter a number from 1 to 3\n"
print "Your stats are now: "
print "Strength: %d \nCharisma: %d \n Sneak: %d\n\n" % ( player.str, player.cha, player.sne)
print "Is this OK? Or would you like to restart?\n"
ans = raw_input("1. Continue \n2. Restart\n> ")
if ans == "1":
print "Game will now begin...."
beach()
elif ans == "2":
ans = raw_input("Are you sure? Yes/No\n> ")
ans = ans.lower()
if ans == "yes":
reset_stats()
start()
else:
beach()
else:
print "Error, please enter 1 or 2"
start()

Corrected code:
def shadow_figure():
print "\n\nYou approach the figure, who remains silent."
print "As you get closer you realise he has bag at his feet."
print "Mysterious figure: \"You may choose only one.\""
print "You look into the bag, and see a shiny sword on top of a large steel shield."
ans = raw_input("Do you: \n1. Take the sword \n2. Take the shield \n3. Take the whole bag and run \n4. Walk away without taking anything\n> ")
if ans == "1":
print "The sword gives you an extra 3 damage"
wep_dam += 3
exit_beach()
elif ans == "2":
print "The shield gives you 3 armor, but it's so heavy it reduces your sneak by 1"
arm += 3
sne -= 1
exit_beach()
elif ans == "3":
dungeon("You get about 10 feet away with the bag before bony fingers grip your throat and choke you unconscious") #Should dungeon() be print instead?
elif ans == "4":
exit_beach()
else:
print "Error, please enter a number between 1 and 4"
See Vaibhav Mule's answer. You were using the assignment operator on input 3 and 4, rather then the comparison operator. There might be more wrong here, but it's hard to tell without the rest of your code. Also I'm not sure what your dungeon() function does, but you probably meant print?

Please also look at elif block, where you suppose to do.
elif ans == "3": # make sure you have '==' operator here.
elif ans == "4":

The error was pointing to line 20, which in this case would be line 1.
The error was in the function exit_beach() that was being called and not actually within this function.
As soon as I added the correct indentation to function exit_beach() the error disappeared.

Related

the input is not working in the second time

when an invalid answer (a number higher than 2) is given and is sent back to the intro(name) (see the else statement at the bottom) which is the introduction, the choise1 is auto completed and is redirected to crowbar()
def intro(name):#added the whole code
print( name + " you are in a back of a car hands tied, you can't remember anything apart the cheesy pizza you had for breakfast")
time.sleep(1)
print("you can see 2 men outside the car chilling out, they haven't seen that you have waken up")
time.sleep(1)
print("you figure out that your hands are not tied hard and manages to break free")
time.sleep(1)
print("and you see a piece of paper with your adress in it on the armrest in the middle of the front seats")
time.sleep(1)
print(" you see a crowbar under the back seat ")
time.sleep(1)
print("CHOOSE WISELY")
time.sleep(1)
print("""
1)grab the crowbar
2)check to see if the door was open""")
def car():
if choise1 == 1:
crowbar()
elif choise1 == 2:
door()
else:
print("that's not a valid answer")
intro(name)
choise1 = int(input("enter 1 or 2"))
car()
you can use function with parameter in this example (x )
def car(x):
if x == 1:
print("crowbar()")
elif x == 2:
print("door()")
else:
print("that's not a valid answer")
print("intro(name)")
choise1 = int(input("enter 1 or 2"))
car(choise1)

Dice Game score and beginning doesn't work

I recently started learning python and am trying to make a simple game in python 2.7 where a computer randomly generates a number between 1 and 6 while the player enters a number between 1 and 6. The rule is that the bigger number wins except if one person has 6 and the other has 1 in which case the person with the 1 wins. The game should also ask a first question and if the player answers "yes" then the game would continue. Else it would do other processes. When I run the code however, even if the number the computer generated is higher, it doesn't add any points to the computer. Also if I enter no or something else, the code proceeds to start the game even though I am trying to get the code to print some other lines.
I have tried just using if else statements without try and except as well as changing the beginning prompt to be a boolean statement.
import random as r
score1 = 0
score2 = 0
start = raw_input("Would you like to start a new game")
if start == "yes" or " yes":
print "Choose a number between 1 and 6"
print "Enter stop to end game"
choice1 = raw_input("Pick a number")
choice2 = r.randint (1,6)
while choice1 != "stop":
try:
if choice1 > choice2:
score1 = score1 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
elif choice2 > choice1:
score2 = score2 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
except:
if choice1 == 1 and choice2 == 6:
score1 = score1 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
else:
if choice1 == 6 and choice2 == 1:
score2 = score2 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
print "Final score is: " + str(score1) + " and Computer is: " + str(score2)
elif start == "no" or " no":
print "Maybe another time"
else:
print "Please enter yes or no"
start = raw_input("Would you like to start a new game")
Program output:
Would you like to start a new game no
Choose a number between 1 and 6
Enter stop to end game
Pick a number1
The computer picked: 2
Pick a number1
The computer picked: 4
Pick a number1
The computer picked: 5
Pick a number1
The computer picked: 3
Pick a numbersotp
The computer picked: 2
Pick a numberstop
Final score is: 5 and Computer is: 0
Process finished with exit code 0
Firstly, this statement
if start == "yes" or " yes":
Is evaluated as (start == 'yes') or ('yes'). Since ' yes' is a constant and always true, it will always evaluate as true. Instead try this, it will take spaces off the front or back before evaluating.
if start.strip() == 'yes':
I would also look at the other places where you if then with multiple conditions. Consider using parens to ensure the code is evaluating as you expect. For instance,
if (choice1 == 1) and (choice2 == 6):
Also, try\expect is intended for exception logging. I'm not sure what exceptions you expect to log here. Probably better to check the user input and make sure it's a number explicitly rather than relying on try\expect

Unexpected EOF while Parsing In Russian Roulette

Im doing a little home project since I'm learning python (beginner) and I made my self a Russian roulette game and it comes up with Unexpected EOF while Parsing on the last line. So if some could help me out on whats going wrong I will be very thankful.
import random
print ("Welcome to Russian Roulette without guns :/ ")
amount = input("How many players? 2 or 3 or 4:")
if amount == ("2"):
print ("Player 1 Name")
player_1 = input(" ")
print ("Player 2 Name")
player_2 = input(" ")
print (player_1)
enter = input("Click Enter:")
if enter == (""):
number = random.randint(1, 2)
print (number)
if number == 1:
print (player_1)
print ("You dead")
print ("---------")
print (player_2)
print ("You win")
else:
print (player_2)
enter_2 = input("Click Enter:")
if enter_2 == (""):
number_2 = random.randint(1, 2)
if number_2 == 1:
print (player_2)
print ("You Lose")
print ("---------")
print (player_1)
print ("You win")
elif amount == ("3"):
print ("Player 1 Name")
player_1 = input(" ")
print ("Player 2 Name")
player_2 = input(" ")
print ("Player 3 Name ")
player_3 = input(" ")
print (player_1)
enter_3 = input("Click Enter:")
if enter_3 == (""):
number_3 = random.randint(1, 1)
print (number)
if number == 3:
print (player_1)
print ("You Dead")
print ("Your Out")
print ("-------------")
print ("{0}, {1} You are still in".format(player_1, player_2)
On the last line, you are missing a closing parenthesis. It should be:
print ("{0}, {1} You are still in".format(player_1, player_2))
EOF is end of file so it usually an an unexpected termination of the program, which is most likely caused by one of a few things, in python: if you missed closing parentheses, or a missing ; in the last line/ line before (so it runs as one line with out the ;). however i can tell you that you are missing closing parentheses at the end of the last print statement. also just a small improvement i would suggest, comment your code python is quite easy to read but its good practice for languages that are not as easy to read.

How do i fix the error in my hangman game in Python 3

This code is from a small game i've been working on over the past day or so, i know i shouldn't really post the whole code but i'm not entirely sure which part of the code is not working as intended, any help would be appreciated. the code is a hangman game and i am aware of the huge amount of repetition in the code but am unsure how to reduce it to one of every function that will work with each difficulty setting.
import random
import time
#Variables holding different words for each difficulty
def build_word_list(word_file):
words = [item.strip("\n") for item in word_file]
return words
EASYWORDS = open("Easy.txt","r+")
MEDWORDS = open("Med.txt","r+")
HARDWORDS = open("Hard.txt","r+")
INSANEWORDS = open("Insane.txt", "r+")
easy_words = build_word_list(EASYWORDS)
medium_words = build_word_list(MEDWORDS)
hard_words = build_word_list(HARDWORDS)
insane_words = build_word_list(INSANEWORDS)
#Where the user picks a difficulty
def difficulty():
print("easy\n")
print("medium\n")
print("hard\n")
print("insane\n")
menu=input("Welcome to Hangman, type in what difficulty you would like... ").lower()
if menu in ["easy", "e"]:
easy()
if menu in ["medium", "med", "m"]:
med()
if menu in ["hard", "h"]:
hard()
if menu in ["insane", "i"]:
insane()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
def difficulty2():
print("Easy\n")
print("Medium\n")
print("Hard\n")
print("Insane\n")
print("Quit\n")
menu=input("Welcome to Hangman, type in the difficulty you would like. Or would you like to quit the game?").lower()
if menu == "hard" or menu == "h":
hard()
elif menu == "medium" or menu == "m" or menu =="med":
med()
elif menu == "easy" or menu == "e":
easy()
elif menu == "insane" or menu == "i":
insane()
elif menu == "quit" or "q":
quit()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
#if the user picked easy for their difficulty
def easy():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
print ("the word was, ", word)
difficultyEASY()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyEASY()
#if the user picked medium for their difficulty
def med():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyMED()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyMED()
#if the user picked hard for their difficulty
def hard():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyHARD()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyHARD()
#if the user picked insane for their difficulty
def insane():
global score
print ("This words may contain an apostrophe. \nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyINSANE()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyINSANE()
def start():
Continue = input("Do you want to play hangman?").lower()
while Continue in ["y", "ye", "yes", "yeah"]:
name = input("What is your name? ")
print ("Hello, %s, Time to play hangman! You have ten guesses to win!" % name)
print ("\n")
time.sleep(1)
difficulty()
else:
quit
#whether they want to try a diffirent difficulty or stay on easy
def difficultyEASY():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
easy()
#whether they want to try a diffirent difficulty or stay on medium
def difficultyMED():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
med()
#whether they want to try a diffirent difficulty or stay on hard
def difficultyHARD():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
hard()
#whether they want to try a diffirent difficulty or stay on insane
def difficultyINSANE():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
insane()
score = 0
start()
When i run this code the error i get is:
Traceback (most recent call last):
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 316, in <module>
start()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 274, in start
difficulty()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 41, in difficulty
insane()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 227, in insane
word = random.choice(words).lower()
NameError: name 'words' is not defined
I'm not sure what is wrong with words or how to fix it.
Your words variable is only defined in the scope of build_word_list function.
All the other functions don't recognize it so you can't use it there.
You can have a "quickfix" by defining it as a global variable, although usually using global variables isn't the best practice and you might want to consider some other solution like passing words to your other functions that use it or use it within the confines of a class.
(If avoiding global variables interests you, maybe you would like to read this and this)
You have words defined in the method build_word_list.
You should declare words as a global variable so that it can be accessed everywhere or restructure you program into a class and use self to reference it.

Loop Problems Rock Paper Scissors Game

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

Categories