我是编程新手。 我必须为我的编程类编写一个Rock Paper Scissors游戏。我有一个很好的开始,但有些问题我不知道如何解决。
我需要三种不同的菜单。主菜单应询问1.开始新游戏2.加载游戏或3.退出。选择1或2,然后输入您的姓名,然后开始播放。然后要求您选择1. Rock 2. Paper 3. Scissors。我的游戏效果很好但是在选择了Rock paper剪刀后我想要一个新的菜单弹出:你想做什么? 1.再次播放2.查看统计数据3.退出。但我不知道在哪里放这个。我尝试了几个不同的地方,但它只是通过它并再次要求石头剪刀。
然后我的第二个问题是,当用户选择1.状态新游戏需要询问他们的名字并使用他们的名字将他们的游戏保存到文件中。然后,当用户选择2.加载游戏时,他们的名字将用于查找文件“name.rps”并加载他们的统计数据以继续播放(统计数据,轮数,名称)。
感谢任何帮助。
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()
答案 0 :(得分:0)
def play():
playerChoice = int(playerMenu())
if playerChoice == 4:
return 0
else:
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome)
return 1
这是我们想要的方法。
所以你需要做的就是调用updateScoreBoard()
下的新菜单方法。
然后在新的菜单方法下。
if(playerChoice == 1)
play();
if else(playeChoice == 2)
stats();
else
quit();
答案 1 :(得分:0)
使用'%s.rsp' % name
,而不是'name.rsp'
。 open('name.rsp', 'w')
将永远打开“name.rsp' evn如果名字=' foo'。
答案 2 :(得分:0)
我为你做了 SPOILER ! 这段代码很有用,对你有帮助。但是在看到这段代码之前你必须要充分思考
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()
答案 3 :(得分:0)
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"))