我非常绝望,因为我试图在很长一段时间内完成这项工作。
我正在进行文字冒险,其中一些用户输入选择了玩家的hp,dmg,你给它命名。
我想制作一个保存功能,但每次加载时,播放器都有默认参数。
示例:
class player:
def __init__(self, hp, dmg):
self.hp = hp
self.dmg = dmg
def save(obj):
save_file = open('C:\\Users\\XXXXX XXXX\\Desktop\\Game\\save.dat', 'wb')
pickle.dump(obj, save_file)
save_file.close()
def load():
load_file = open('C:\\Users\\XXXXX XXXX\\Desktop\\Game\\save.dat', 'rb')
loaded_game_data = pickle.load(load_file)
return loaded_game_data
def start():
player.hp = input('Player Hp')
player.dmg = input('Player Dmg')
player = player(0, 0)
start()
请不要只告诉我我做错了什么,还要告诉我如何正确行事。我真的需要这个 - 谢谢!
我使用以下内容加载播放器:
>>>print(player.hp) # To make sure the HP is 0
0
>>>player.hp = 100 # I now change the HP to 100
>>>save(player) # Saving the player with 800 HP and 0 DMG
# Restarting Python
>>>load() # Loading the player
>>>print(player.hp) # Check if the HP is 100 as I saved it.
0 # The HP is 0...
# I expected 100 as I saved it.
答案 0 :(得分:0)
以下运行良好。使用大写首字母重命名您的Player
类以避免名称冲突。我在最后添加了一些测试调用,并且播放器加载了预期(非默认)统计信息。
import pickle
class Player:
def __init__(self, hp, dmg):
self.hp = hp
self.dmg = dmg
def save(obj):
save_file = open('save.dat', 'wb')
pickle.dump(obj, save_file)
save_file.close()
def load():
load_file = open('save.dat', 'rb')
loaded_game_data = pickle.load(load_file)
return loaded_game_data
def start():
player.hp = input('Player Hp: ')
player.dmg = input('Player Dmg: ')
player = Player(0, 0)
start()
save(player)
loaded_player = load()
print loaded_player.hp, loaded_player.dmg