2016-06-27 23 views
1

我一直在努力讓我的文字遊戲更逼真,我希望實現的一個設計是確保房間保持「靜態」到某個點(即玩家在房間中使用藥水,如果他們回到那個房間,藥水不應該在那裏。)更好的方式在類中創建我的列表?

這就是我的代碼基本上是如何設置的(我一直在使用Zed Shaw的「Learn Python The Hard Way」,所以我的代碼設置了很多以同樣的方式):

class Scene(object): 

    def enter(self): 
     print "This scene is not yet configured. Subclass it and implement enter()." 

class Room(Scene): 
    potions = [] 
    for i in range(3): 
     potions.append(Potion()) 

    def enter(self): 
     ... 

當我運行它,我得到一個NameError: global name 'potions' is not defined。我知道我可以通過兩種方式解決這個問題:1.讓藥劑成爲一個全局變量,但是我必須爲每個包含藥劑的房間創建一個新的列表(總共有36個房間,設置爲6x6格子) OR 2.將這一行代碼放在回車函數中,但每當用戶進入房間時會導致列表重置爲3個藥水。

potions = [] 
for i in range(3): 
    potions.append(Potion()) 

如果沒有其他辦法,我想爲所有包含藥劑的房間聲明一個新的變量(只有5個)。但我的問題是,如果還有其他方式讓這項工作沒有成爲全球性的話。 感謝您的幫助!

回答

4

首先,讓我們看看你的榜樣(我將簡化它):

class Room(Scene): 
    potions = [Potion() for x in range(3)] 

你做了什麼有創建一個類屬性potions被中Room所有實例共享。例如,你會看到我的每個房間裏的藥水都是同一種藥水(十六進制數字相同!)。如果我修改在一種情況下potions列表,它會修改所有Room實例相同的列表:

>>> room1.potions 
[<__main__.Potion instance at 0x7f63552cfb00>, <__main__.Potion instance at 0x7f63552cfb48>, <__main__.Potion instance at 0x7f63552cfb90>] 
>>> room2.potions 
[<__main__.Potion instance at 0x7f63552cfb00>, <__main__.Potion instance at 0x7f63552cfb48>, <__main__.Potion instance at 0x7f63552cfb90>] 
>>> 

這聽起來像你想potions成爲Room的每個實例的獨特屬性。

某處您將實例化一個房間,例如room = Room()。你需要寫你的構造爲您Room,以自定義您的實例:

class Room(Scene): 
    def __init__(self): # your constructor, self refers to the Room instance. 
     self.potions = [Potion() for x in range(3)] 

現在,當你創建你的房間的實例,它包含3點藥水。

您現在需要考慮如何讓您的房間實例在角色入口之間持續存在。這需要成爲整個遊戲中持續存在的某種變量。

對象構圖的這種想法將延伸到你的遊戲。也許你有一個Dungeon類中有您的36間客房:

class Dungeon(object): 
    def __init__(self): 
     self.rooms = [[Room() for x in range(6)] for x in range(6)] 

或者,也許你的房間有四個門,你將它們鏈接起來到的東西可能少方:

class Room(Scene): 
    def __init__(self, north_room, east_room, south_room, west_room): 
     self.north_door = north_room 
     self.east_door = east_room 
     [... and so on ...] 
     # Note: You could pass `None` for doors that don't exist. 

甚至更​​多創造性,

class Room(Scene): 
    def __init__(self, connecting_rooms): # connecting_rooms is a dict 
     self.connecting_rooms = connecting_rooms 

除了這兩個例子將讓你連接的房間是一個雞和蛋的問題,所以最好是添加一個方法來增加每個房間的連接:

class Room(Scene): 
    def __init__(self): 
     self.rooms = {} 
     # ... initialize your potions ... 
    def connect_room(self, description, room): 
     self.rooms[description] = room 

然後,你可以這樣做:

room = Room() 
room.connect_room("rusty metal door", room1) 
room.connect_room("wooden red door", room2) 
room.connect_room("large hole in the wall", room3) 

那麼也許你的地牢看起來是這樣的:

class Dungeon(Scene): 
    def __init__(self, initial_room): 
     self.entrance = initial_room 

現在到底,你只需要守住你的dungeon實例Dungeon在遊戲期間。

順便說一句,這個由「路徑」連接的「房間」的結構被稱爲Graph

相關問題