Pickle 用户输入 - Python 3

Pickle user inputs - Python 3

我很绝望,因为我已经尝试了很长时间才能使它正常工作。

我正在制作一个文字冒险,其中一些用户输入选择玩家的生命值、伤害,随便你怎么说。

我想做一个保存功能,但是每次加载时,播放器都有默认参数。

示例:

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.

以下运行良好。使用大写首字母重命名 Player class 以避免名称冲突。我在最后添加了一些测试调用,播放器加载了预期的(非默认)统计数据。

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