Pickle user inputs - Python 3 [closed]

2019-09-25 08:17发布

I am pretty desperate, since I have tried to get this working in a long time.

I'm making a text adventure where some user inputs choose the player's hp, dmg, you name it.

I want to make a save function, but every time I load it, the player has default parameters.

Example:

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()

Please don't just tell me what I do wrong, but also how to do it right. I really need this out of my head - Thank you!

I load the player with the following:

>>>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.

1条回答
太酷不给撩
2楼-- · 2019-09-25 09:00

The following runs well. Rename your Player class with an uppercase initial to avoid name conflicts. I added some test calls at the end, and the player is loaded with the intended (not default) stats.

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
查看更多
登录 后发表回答