为什么我的腌制物不能恢复?

时间:2017-10-05 04:37:04

标签: python

所以我正在开发一个基于文本的RPG,并且在一个月前开始学习python的编码还是比较新的,所以如果有人可以提供帮助,他们就会成为救星。

当我保存并加载我的游戏时,它会加载我的默认玩家统计数据,如何使其加载统计数据增加以及我的魔药和黄金重置为默认值。

class Player:
    name = "Razor"
    atkl = 15
    atkh = 20
    magic_light_slashl = 20
    magic_light_slashh = 25
    magic_fireballl = 40
    magic_fireballh = 48
    magic_lightningl = 55
    magic_lightningh = 65
    maxhp = 50
    hp = 50
    maxap = 10
    ap = 10
    exp = 0
    level = 1
    gold = 20
    potions = 0
    great_potions = 0
    max_potions = 0
    elixers = 0
    great_elixers = 0
    max_elixers = 0

def save():
    player = Player
    level_state = Player.level
    with open('savefile', 'wb') as f:
        pickle.dump([player, level_state], f, protocol=2)
        print("Game has been saved.")
        start_up()

def load():
    if os.path.exists('savefile') == True:
        with open('savefile', 'rb') as f:
            player, level_state = pickle.load(f)
            print("Loaded save state.")
            start_up()
    else:
        print("Could not find save file.")
        main()

以下是我升级的一些方法。

def level_up():
    if Player.level == 1:
        if Player.exp >= 30 and Player.exp < 80:
            print("You are level 2")
            Player.level = 2
            Player.atkl = 17
            Player.atkh = 22
            Player.magic_light_slashl = 23
            Player.magic_light_slashh = 27
            Player.maxhp = 53
            Player.hp = 53
            Player.maxap = 12
            Player.ap = 12

如果您需要更多我的代码来帮助我问一下。

1 个答案:

答案 0 :(得分:3)

你误解了课程的运作方式。您正在使用类级属性而不是实例级属性,这会导致它们无法正确地进行pickle。你基本上把一个类看作是一个字典,而根本不是它们的工作方式。

创建类时,它就像一个蓝图。汽车的蓝图可用于创建许多汽车“实例”,但蓝图本身不是汽车。

因此,为了从Player类中获取实例,您需要“实例化”它。您可以通过在括号()之后按名称调用类来执行此操作。括号向Python表明您正在调用类的构造函数,该构造函数在类中定义为__init__()。你的类没有构造函数所以首先应该定义一个。

class Player:
    def __init__(self):
        # this is the constructor

        # let's add some instance-level properties
        self.name = 'Razor'
        # you can add the rest of your properties here as long as they being with self

        print 'I am a new instance of the player class, my name is ' + self.name

然后你可以实例化它并将实例存储在这样的变量中(注意我们的消息将在构造期间打印):

player = Player()

然后,您可以访问该实例上的属性

print player.name

或者你可以改变它们

player.name = 'Blade'
print player.name
# prints 'Blade'

此实例化有用且重要的原因是它允许您根据需要创建任意数量的“玩家”(或角色,或敌人等),并且它们都保留自己的属性。 self清楚地表明您正在与实例交谈,而不是类本身。