[英]How do I organize this code?
我試圖通過將函數轉換為方法來將函數分類到適當的類中(如果合適,可以將函數留在類之外)。 但我不確定如何處理這個特定的功能(如下所示)。
首先,這是我的課:
class OreBlobAction:
def __init__(self, entity, image_store):
self.entity = entity
self.image_store = image_store
def ore_blob_action(self, world, action, ticks):
entity = self.entity
entity_pt = entities.get_position(self.entity)
vein = find_nearest(world, entity_pt, entities.Vein)
(tiles, found) = blob_to_vein(world, self.entity, vein)
next_time = ticks + entities.get_rate(entity)
if found:
quake = create_quake(world, tiles[0], ticks, self.image_store)
worldmodel.add_entity(world, quake)
next_time = ticks + entities.get_rate(entity) * 2
schedule_action(world, self.entity,
OreBlobAction(self.entity, self.image_store), next_time)
return tiles
現在,這是函數:
def take_action(world, action, ticks):
entities.remove_pending_action(action.entity, action)
if isinstance(action, VeinAction):
return vein_action(world, action, ticks)
elif isinstance(action, MinerNotFullAction):
return miner_not_full_action(world, action, ticks)
elif isinstance(action, MinerFullAction):
return miner_full_action(world, action, ticks)
elif isinstance(action, OreBlobAction):
return ore_blob_action(world, action, ticks)
elif isinstance(action, OreTransformAction):
return ore_transform_action(world, action, ticks)
elif isinstance(action, EntityDeathAction):
return entity_death_action(world, action, ticks)
elif isinstance(action, WyvernSpawnAction):
return wyvern_spawn_action(world, action, ticks)
elif isinstance(action, WyvernAction):
return wyvern_action(world, action, ticks)
elif isinstance(action, VeinSpawnAction):
return vein_spawn_action(world, action, ticks)
elif isinstance(action, AnimationAction):
return animation_action(world, action, ticks)
return []
如您所見,此函數不僅考慮了 OreBlobAction 類的操作,還考慮了多個其他類的操作。 將此函數留在 OreBlobAction 類之外會更好嗎? 或者有沒有更好的方法來做到這一點?
注意:如果我將此函數排除在 OreBlobAction 類之外,並嘗試運行該程序,則會出現以下錯誤:
NameError: global name 'ore_blob_action' is not defined
你關於動作類型的大 switch 語句是重構的危險信號。 有什么可以阻止您將“采取行動”方法轉移到行動類本身中嗎? 例如
class Action(object):
""" An action that can be performed on the game world. """
def perform(self, world, ticks):
""" Perform the action. """
raise NotImplementedError()
這將是您的基本操作類,然后在每種類型的操作中,您將覆蓋perform(...)
方法,例如
class WyvernSpawnAction(Action):
""" An action that spawns a Wyvern. """
[... Some action specific initialisation code here ...]
def perform(self, world, ticks):
""" Spawn a Wyvern. """
world.spawn(Wyvern(...))
從世界中刪除動作的樣板將保留,您現在可以自由添加新類型的動作,而無需最終在您的函數中添加數百個比較。 此外,您現在可以處理操作可以繼承其他操作的行為的情況,而不必非常小心比較的順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.