每当我尝试在该程序上加载以前的游戏时,都会出现错误。菜单中的保存功能旨在在游戏中加载诸如黄金量,胸部数量和土匪数量之类的值,然后在会话中将其用作“加载”先前游戏的原因。我也不确定泡菜模块是否适合于此,因为应该有另一种方法来做泡菜,但是我想尝试泡菜,因为它被推荐用于这种功能。
import random
import sys
import time
import os
import pickle #module used to serielize objects
boardeasy=[]
boardmed=[]
boardhard=[]
current=[0,0]
treasures = [(random.randint(0,8), random.randint(0,8)) for i in range(12)]
bandits = [(random.randint(0,8), random.randint(0,8)) for i in range(12)]
Coins = 0
Chest = 10
Bandit1 = 5
Bandit2 = 7
Bandit3 = 10
class user():
def __init__(self, username, userscore, usertime):
self.username = username
self.userscore = userscore
self.usertime = usertime
#For loop prints a new 8*8 grid after every move
boardeasy = [[' ' for j in range(8)] for i in range(8)]
def table_game_easy():
print(" 1 2 3 4 5 6 7 8")
print("---------------------------------")
for row in range(8):
print ('| ' + ' | '.join(boardeasy[row][:8]) + ' | ' + str(row + 1))
print("---------------------------------")
treasures_row = [random.randint(0,8) for i in range(10)]
treasures_col = [random.randint(0,8) for i in range(10)]
bandits_row = [random.randint(0,8) for i in range(5)]
bandits_col = [random.randint(0,8) for i in range(5)]
# For loop prints a new 10*10 grid after every move
boardmed = [[' ' for j in range(10)] for i in range(10)]
def table_game_meduim():
print(" 1 2 3 4 5 6 7 8 9 10")
print("------------------------------------------")
for row in range(10):
print ('| ' + ' | '.join(boardmed[row][:10]) + ' | ' + str(row + 1))
print("------------------------------------------")
treasures_row = [random.randint(0,10) for i in range(10)]
treasures_col = [random.randint(0,10) for i in range(10)]
bandits_row = [random.randint(0,10) for i in range(7)]
bandits_col = [random.randint(0,10) for i in range(7)]
# For loop prints a new 12*12 grid after every move
boardhard = [[' ' for j in range(12)] for i in range(12)]
def table_game_hard():
print(" 1 2 3 4 5 6 7 8 9 10 11 12")
print("----------------------------------------------------")
for row in range(12):
print ('| ' + ' | '.join(boardhard[row][:12]) + ' | ' + str(row + 1))
print("----------------------------------------------------")
treasures_row = [random.randint(0,10) for i in range(10)]
treasures_col = [random.randint(0,10) for i in range(10)]
bandits_row = [random.randint(0,10) for i in range(10)]
bandits_col = [random.randint(0,10) for i in range(10)]
#this function is in charge of downwards movement
def down(num,lev):
num=(num+current[0])%lev#The % formats this equation
current[0]=num
#this function is in charge of downwards movement
def right(num,lev):
num=(num+current[1])%lev #The % formats this equation
current[1]=num
#this function is in charge of downwards movement
def left(num,lev):
if current[1]-num>=0:
current[1]=current[1]-num
else:
current[1]=current[1]-num+lev
#this function is in charge of downwards movement
def up(num,lev):
if current[0]-num>=0:
current[0]=current[0]-num
else:
current[0]=current[0]-num+lev
def easy_level(Coins, Chest, Bandit1):
#This function is for the movement of the game in easy difficulty
while True and Chest > 0:
oldcurrent=current
boardeasy[oldcurrent[0]][oldcurrent[1]]='*'
table_game_easy()
boardeasy[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 8 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:#Validates input
print('Wrong command, please input again')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),8)#Boundary is set to 8 as the 'easy' grid is a 8^8
elif n[0].lower()=='down':
down(int(n[1].lower()),8)
elif n[0].lower()=='left':
left(int(n[1].lower()),8)
elif n[0].lower()=='right':
right(int(n[1].lower()),8)
print(Chest,"chests left")
print(Bandit1,"bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if (current[0], current[1]) in treasures[:8]:
Chest = Chest - 1
print("Hooray! You have found booty! +10 gold")
Coins = Coins + 10 #Adds an additional 10 points
print("Coins:",Coins)
if (current[0], current[1]) in bandits[:8]:
Bandit1 = Bandit1 - 1
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardeasy[current[0]][current[1]]='*'#sets value to players position
username = input("Please enter a username:")
with open("high_scores.txt","a") as f:
f.write(str(Coins)+ os.linesep)
f.write(username + os.linesep)
f.close()
def med_level(Coins, Chest, Bandit2):
#This function is for the movement of the game in medium difficulty
while True:
oldcurrent=current
boardmed[oldcurrent[0]][oldcurrent[1]]='*'
table_game_meduim()
boardmed[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 10 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:
print('wrong command')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),10)#Boundary is set to 10 as the 'easy' grid is a 10^10
elif n[0].lower()=='down':
down(int(n[1].lower()),10)
elif n[0].lower()=='left':
left(int(n[1].lower()),10)
elif n[0].lower()=='right':
right(int(n[1].lower()),10)
print(Chest,"chests left")
print(Bandit2,"bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if (current[0], current[1]) in treasures[:10]:
Chest = Chest - 1
print("Hooray! You have found booty! +10 gold")
Coins = Coins+10 #Adds an additional 10 points
print("Coins:",Coins)
if (current[0], current[1]) in bandits[:10]:
Bandit2 = Bandit2 - 1
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardmed[current[0]][current[1]]='*'
def hard_level(Coins, Chest, Bandit3):
#This function is for the movement of the game in hard difficulty
while True:
oldcurrent=current
boardhard[oldcurrent[0]][oldcurrent[1]]='*'
table_game_hard()
boardhard[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 12 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:
print('wrong command')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),12)#Boundary is set to 12 as the 'hard' grid is a 12^12
elif n[0].lower()=='down':
down(int(n[1].lower()),12)
elif n[0].lower()=='left':
left(int(n[1].lower()),12)
elif n[0].lower()=='right':
right(int(n[1].lower()),12)
print(Chest,"chests left")
print(Bandit3,"bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if (current[0], current[1]) in treasures[:12]:
Chest = Chest - 1
print("Hooray! You have found booty! +10 gold")
Coins = Coins+10 #Adds an additional 10 points
print("Coins:",Coins)
if (current[0], current[1]) in bandits[:12]:
Bandit2 = Bandit2 - 1
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardhard[current[0]][current[1]]='*'
def instruct():
difficulty = input("""Before the game starts, please consider what difficulty
would you like to play in, easy, medium or (if you're brave) hard.
""")
if difficulty == "easy":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
time.sleep(1)
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
easy_level(Coins, Chest, Bandit1)
elif difficulty == "medium":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
time.sleep(1)
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
med_level(Coins, Chest, Bandit2)
elif difficulty == "hard":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
time.sleep(1)
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
hard_level(Coins, Chest, Bandit3)
else:
print("Sorry, that is an invalid answer. Please restart the programme")
def menu():
#This function lets the user quit the application or progress to playing.
print("")
print ("Are you sure you wish to play this game? Please answer either yes or no.")
choice1 = input() # Sets variable to user input
if choice1.lower().startswith('y'):
print("Okay lets continue then!")
print("")
print("")
print("""~~~~~~~~~~MENU~~~~~~~~~~
1). Load a previous game
2). Display the high score table
3). Continue
""")
choice2 = input(">")
while choice2 != '3':
print("")
print("")
print("""~~~~~~~~~~MENU~~~~~~~~~~
1). Load a previous game
2). Display the high score table
3). Continue
""")
choice2 = input(">")
if choice2 == "1":
with open('savefile.dat', 'rb') as f:
(Coins, Chest, Bandit1) = pickle.load(f)
elif choice2 == "2":
with open("high_scores.txt") as f:
for line in f:
print(line)
print("")
elif choice1.lower().startswith('n'):
print("Thank you, I hope you will play next time!")
print("")
quit("Thank you for playing!")#Terminates the programme
else:
print("Sorry, that is an invalid answer. Please restart the programme")
print("")
quit()
instruct()
def showInstructions():
time.sleep(1.0)
print("Instructions of the game:")
time.sleep(1.0)
print("""
You are a treasure hunter, your goal is to collect atleast 100 gold by the end
of the game from treasure chests randomly scattered across the grid. There are
10 chests within a grid (this can be changed based on difficulty) and each
treasure chest is worth 10 gold but can only be reclaimed 3 times before it is
replaced by a bandit. Landing on a bandit will cause you to lose all of your
gold and if all the chests have been replaced by bandits and you have less then
100 gold this means you lose!
Press enter to continue...""")
input()
print("""
At the start of the game, you always begin at the top right of the grid.
Below is a representation of the game:
* 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Press enter to continue...""")
input()
print("""
When deciding where to move, you should input the direct co-ordinates of your
desired location. For instance:
Enter the direction followed by the number Ex: Up 5 , Number should be < 8
right 3
0 0 0 * 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Unlucky move! You have found nothing!
If nothing on the grid changes , this means that your move was a bust! Landing
on nothing isn't displayed on the grid.
Press enter to continue...""")
input()
print("""
Enter the direction followed by the number Ex: Up 5 , Number should be < 8
down 4
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Hooray! You have found booty! +10 gold
Here you can see that the use has landed on a chest!
As you land on chest, they get replaced by bandits. Be sure to remember the
previous locations so you don't accidently land on a bandit and lose all
your gold!
Press enter to continue...""")
input()
#Introduces the user
print('Welcome to the Treasure hunt!')
time.sleep(0.3)
print()
time.sleep(0.3)
print('Would you like to see the instructions? (yes/no)')
if input().lower().startswith('y'):#If function checks for the first letter
showInstructions()
elif input == 'no' or 'No':
print("Lets continue then!")#Calls the function which displays instructions
else:
print("Please check your input and try again.")
menu()
答案 0 :(得分:1)
pickle
并非最佳格式。我建议使用流行的json
格式。
要保存文件:
with open('somefile.sav', 'w') as f:
json.dump([coins, chests, bandits], f)
要重新加载:
with open('somefile.sav') as f:
coins, chests, bandits = json.load(f)