[英]Having trouble with functions calling other functions through dictionaries: could someone please explain this code to me?
在基於文本的游戲中使用它來確定是否已輸入其他房間以運行功能。 這是學習練習,因此我確定代碼不是最佳的。 整個過程從最后一行運行代碼開始。
def runner(map, start):
next = start
while True:
room = map[next]
print "\n--------"
next = room()
runner(ROOMS, 'central_corridor')
這是在運行程序函數中用作參數的ROOMS詞典:
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
因此,更具體地說,我的問題是,如果在游戲中輸入了下一個房間,則如何使用while循環來運行下一個房間的功能? 我感覺答案在於while循環中包含的下一個迭代器。
如果我們重命名變量,代碼將更容易理解。 永遠不要命名變量map
或next
變量,因為這樣做會遮蓋相同名稱的內置變量。
重命名map
和next
之后,這是相同的代碼:
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
def runner(visit, start):
room = start
while True:
action = visit[room]
print "\n--------"
room = action()
runner(ROOMS, 'central_corridor')
visit
變量是將房間映射到動作(即功能)的字典。 動作的返回值為房間。 所以
action = visit[room]
查找您訪問房間時發生的操作,然后
room = action()
在執行action
后將room
設置為下一個房間的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.