我是python的新手,不得不用菜单创建一个石头剪刀游戏,还可以保存游戏的数据。我在尝试运行代码时收到以下错误 -
Traceback (most recent call last):
File "/Users/meganeifert/Desktop/EifertMeganRPS/rps.py", line 186, in <module>
main()
File "/Users/meganeifert/Desktop/EifertMeganRPS/rps.py", line 20, in main
welcomemenu()
File "/Users/meganeifert/Desktop/EifertMeganRPS/rps.py", line 65, in welcomemenu
return game_status
UnboundLocalError: local variable 'game_status' referenced before assignment
任何帮助修复此错误并查看我的代码以查看是否存在任何其他明显错误都会有所帮助!
import random
import pickle
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 ("")
welcomemenu()
playGame=True
while playGame:
playGame=play()
displayScoreBoard()
prompt = input("Press enter to exit")
#prompt user's choice and return GameStatus instance
def welcomemenu():
while True:
print ("[1]: Start New Game")
print ("[2]: Load Game")
print ("[3]: Quit")
print ("")
menuselect = input("Enter choice: ")
if menuselect in str([1, 2, 3]):
break
else:
print ("Wrong choice. select again.")
if menuselect == 1:
name = input("What is your name?: ")
print ("Hello %s." % name)
print ("Let's play!")
game_status = GameStatus(name)
elif menuselect == 2:
while True:
name = input("What is your name?: ")
try:
player_file = open('%s.rsp' % name, 'r')
except IOError:
print ("name %s, your game could not be found") % name
continue
break
print ("Welcome back %s.") % name
print ("Let's play!")
game_status = pickle.load(player_file)
displayScoreBoard(game_status)
player_file.close()
elif menuselect == 3:
print ("Bye~!")
exit()
return
return game_status
# displays the menu for user
def play():
playerChoice=int(playerMenu())
if playerChoice ==4:
return 0
else:
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)
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]:
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):
rsp = ['rock', 'paper', 'scissors']
win_statement = ['Rock breaks scissors', 'Paper covers rock', 'Scissors cut paper']
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:
print ("Win/Loss Ratio: %f") % (float(game_status.playerWon) / game_status.pcWon)
else:
print ("Win/Loss Ratio: ")
print ("Rounds: %d") % game_status.get_round()
def endGameSelect(game_status):
print ("")
print ("[1]: Play again")
print ("[2]: Statistics")
print ("[3]: Quit")
print ("")
while True:
menuselect = input("Enter choice: ")
if menuselect in [1, 2, 3]:
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 ("Bye!")
endGameSelect(game_status)
exit()
main()
答案 0 :(得分:0)
问题是,menuselect
永远不会与if
中的任何welcomemenu
条件相匹配,因为您要将数组转换为此行中的字符串
if menuselect in str([1, 2, 3]):
因为它永远不会匹配,所以game_status
永远不会被声明,但您会在welcomemenu
函数的末尾尝试返回它。而是将其改为此
menuselect = input("Enter choice: ")
if menuselect in [1, 2, 3]:
break
else:
print ("Wrong choice. select again.")