2017-10-05 24 views
-2

因此,我正在研究一個基於文本的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 

如果你需要更多我的代碼來幫助我才問。

+0

請包含一個[MCVE](https://stackoverflow.com/help/mcve),它重現了一些您想修復的錯誤。你可能應該使用* instance *屬性來代替* class *屬性,就像你現在正在做的那樣。 –

+1

我們不需要更多的代碼,我們需要更少的代碼。暴露您的問題的最少量的代碼。它也將幫助你澄清你的問題是什麼,也許(可能在這種情況下)自己解決它。 –

回答

3

你誤解了班級的工作方式。您正在使用類級別的屬性,而不是實例級別的屬性,這會導致它們無法正確使用。你基本上把一個類看作是一本字典,而這根本不是它們的工作方式。

當你創建一個類,它就像一個藍圖。一輛汽車的藍圖可以用來創造許多汽車「實例」,但藍圖不是汽車本身。

所以爲了從你的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是一個明確的指示符,表示您正在與實例交談,而不是類本身。

相關問題