首先,讓我們看看你的榜樣(我將簡化它):
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。