完全迷失了如何实现保存/加载功能(初学者!!)
Posted
技术标签:
【中文标题】完全迷失了如何实现保存/加载功能(初学者!!)【英文标题】:completely lost on how to implement save/load function (beginner!!) 【发布时间】:2019-11-15 18:12:25 【问题描述】:我的完整游戏代码在下面我需要放入一个保存加载功能我知道它类似于
dct = 'hp': 0, 'gold': 100 #<- state
import json
json.dump(dct, open("savegame.json", "w"), indent=4) #SAVING
但我不知道将其放在我的代码中的哪个位置或如何执行。我的老师没有讨论这个,所以初学者的提示会很棒。请帮忙。谢谢。
__version__ = 8
# 2) print_introduction: Introduction to game
def print_introduction():
print('Welcome to The Haunted House adventure. You are locked inside this creepy old house and you need to escape!')
print('There are 6 rooms in this house for you to explore. You must find 2 key items and solve a riddle in order to be free!')
print('\n')
print('Strange noises and whispers fill the air. Will you make it out alive to tell your story?! Let us find out...')
# 3) get_initial_state: Make the initial state for your player
def get_initial_state():
'''
Dictionary tells player initial state
:
Returns:
dict: A dictionary with the player's current state field values
'''
initial_state_dict = 'game status': 'playing',
'location': 'living room',
'shiny fork': False,
'golden key': False,
'bait':False,
'life jacket':False,
'jaws': False
print('\n')
print('Now, let us begin this escape!')
return initial_state_dict
#while not done:
# 4) print_current_state:some text describing the game
def print_current_state(the_player):
'''
This function is needed to print the current location
Args:
the_player (from dict): gives current player state
'''
#print location:
print('\n_____________________________________________________')
print('Current location:', the_player['location'], '\n')
if the_player['location'] == 'living room':
print('You are in the living room and hear strange whispers as your hairs on the back of your neck stand up... What are you going to do next?')
if the_player['location'] == 'kitchen':
if the_player['shiny fork']:
print('This might help you in one of the bedrooms')
else:
print('You walk into the kitchen and looked around. As you scan the room your eyes rest on a shiny fork. What are you going to do?')
if the_player['location'] == 'bedroom 1':
if the_player['shiny fork']:
if the_player['golden key']:
print ('Now you can enter bedroom 2')
else:
print('After grabbing the shiny fork, you begin to walk down the hall when you hear a loud noise behind you! You start running and make it to the first bedroom and slam the door shut behind you... whew! Not long after that, you discover a golden key in the bedroom')
else:
print('The door is locked, it maybe jammed. You need something sharp to open it. Maybe a fork from the kitchen')
if the_player['location'] == 'bedroom 2':
if the_player['golden key'] == False:
print('You cannot open the locked closet door without the golden key.')
if the_player['golden key'] == True:
print('Aha it worked! You insert the golden key into the locked closet door and turn the knob... You brush aside the old cobwebs and make your way through the secret passage to reach the basement.')
if the_player['location'] == 'basement':
print('After making your way through the secret passage, you step into the cold, damp basement. Shivers go through your spine as you try to keep warm')
if the_player['location'] == 'garden':
print('You break free and sprint out into the garden! Taking a quick look behind you, you see nothing but whisps of air filling the void. You cannot shake the feeling that something is still after you, but never again will you go inside that haunted house!')
# 5) get_options: list of commands available
def get_options(the_player):
if the_player['location'] == 'living room':
actions_list = ['kitchen','bedroom 1', 'bedroom2', 'quit']
#print('kitchen')
#print('explore bedroom')
#print('quit')
return actions_list
if the_player['location'] == 'bedroom 1':
if the_player['shiny fork'] == True:
if the_player['golden key'] == True:
actions_list = ['kitchen','bedroom 2','quit']
return actions_list
else:
actions_list = ['kitchen', 'pick up golden key','bedroom 2','quit']
return actions_list
else:
actions_list = ['kitchen']
return actions_list
if the_player['location'] == 'bedroom 2':
actions_list = ['basement']
return actions_list
if the_player['location'] == 'basement':
actions_list = ['garden']
return actions_list
if the_player['location'] == 'garden':
actions_list = ['pier', 'harbor', 'reef', 'deep sea']
return actions_list
#If player is in the kitchen location:
elif the_player['location'] == 'kitchen':
if the_player['shiny fork']:
actions_list = ['bedroom 1','quit']
return actions_list
else:
actions_list = ['pick up shiny fork', 'bedroom 1','quit']
return actions_list
# 6) print_options: the list of commands available to player
def print_options(available_options):
print('\nChoose one of the options below. Locations and actions to choose from:')
for item in available_options:
print(item)
# 7) get_user_input: handles valid commands
def get_user_input(available_options):
command = ''
while command not in available_options:
if command == 'home':
return 'quit'
command = input('What would you like to do next? ') #user input based on the list of options provided
return command #this value is returned from the function and stored under the variable 'chosen_command' in the main function
#this variable is used as a parameter for process_command function below.
# 8) process_command: based on dictionary
def process_command(chosen_command, the_player):
if chosen_command == 'quit':
the_player['game status']= chosen_command
if chosen_command == 'pick up shiny fork':
the_player['shiny fork'] = True
if chosen_command == 'pick up golden key':
the_player['golden key'] = True
if chosen_command == 'bedroom 1':
the_player['location'] = chosen_command
if chosen_command == 'kitchen':
the_player['location'] = chosen_command
if chosen_command == 'bedroom 2':
if the_player['golden key']:
the_player['location'] = chosen_command
else:
print('Find golden key to open this room')
if chosen_command == 'basement':
the_player['location'] = chosen_command
if chosen_command == 'garden':
the_player['location'] = 'garden'
the_player['game status'] = 'win'
# 9) print_game_ending: tells the user if they won or lost, quit
def print_game_ending(the_player):
if the_player['game status'] == 'quit':
print('\nYOU QUIT.')
if the_player['game status'] == 'lose':
print('\nYOU LOSE.')
if the_player['game status'] == 'win':
print('You have succcessfully escaped and vowed to never go back to the haunted house again')
print('\n')
print('YOU WON!')
#get_initial_state() is printed here:
if the_player:
print('')
# 1) Main function that runs the game
#
def main():
# introduction to the game
print_introduction()
# the initial state for game
the_player = get_initial_state()
# sees if player won or not
while the_player['game status'] == 'playing':
# Gives players current state
print_current_state(the_player)
# this Gives options to player
available_options = get_options(the_player)
# once given input gives more options
print_options(available_options)
# this Gives Valid User Input
chosen_command = get_user_input(available_options)
# this Process Commands and change state
process_command(chosen_command, the_player)
# Give user message
print_game_ending(the_player)
# the main function
if __name__ == "__main__":
'''
the main function call each function
'''
main()
# print_introduction()
# print(get_initial_state())
【问题讨论】:
【参考方案1】:大量的代码!学习很好。
您似乎只想将“加载”和“保存”添加到 process_command()。你可能想要这样的代码:
if chosen_command == 'save':
with open('game.json', 'w') as the_file:
json.dump(the_player, the_file)
elif chosen_command == 'load':
with open('game.json', 'r') as the_file:
the_player = json.load(the_file)
继续破解!记笔记!
【讨论】:
【参考方案2】:无需尝试在很大程度上重构您的代码,这里有一些通用函数,您可以根据需要添加代码。
祝你好运。
import json
def save_state(state: dict, filename: str='save_state.json'):
"""
Given a save state as a dictionary (or list) and an OPTIONAL
`filename` the state will be saved to the current working directory.
Default filename: save_state.json
"""
with open(filename, 'w') as f:
json.dump(state, f)
def load_state(filename: str='save_state.json'):
"""
Given an OPTIONAL `filename`, the state will try to be loaded
from the current working directory.
Default filename: save_state.json
If the file cannot be found or contains malformed JSON then an empty
dictionary will be return.
"""
try:
with open(filename, 'r') as f:
result = json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
# If either the file is not found OR
# the file is empty, then this exception will be entered.
result =
return result
my_game_state =
'hp': 10
save_state(my_game_state)
loaded_state = load_state()
print(loaded_state['hp']) # 10
【讨论】:
以上是关于完全迷失了如何实现保存/加载功能(初学者!!)的主要内容,如果未能解决你的问题,请参考以下文章