Skip to content Skip to sidebar Skip to footer

Pickle User Inputs - Python 3

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

Solution 1:

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

Post a Comment for "Pickle User Inputs - Python 3"