为了提供一些背景,我正在使用Doyren库(libtcod)在Python中开发一个Roguelike游戏。我更习惯于C++,其中对象具有强类型。
我正在编写多个类,例如GameMap、GameObject等。许多这些类包含期望特定类型的方法,例如:
class GameMap:
...
def add_object(self, game_object, x, y):
...
该方法将游戏对象game_object添加到地图上的坐标(x, y)。该函数很明显会有几种被误用的情况:
- game_object传递了一个非GameObject对象
- x或y传递了一个非整数
- x或y传递了一个负整数
- x传递了一个超出地图宽度的整数
- y传递了一个超出地图高度的整数
我看到有几种可能性: 选项1:在方法开始处设置一系列断言:
def add_object(self, game_object, x, y):
assert(isinstance(game_object, GameObject)
assert(type(x) == type(y) == int)
assert(0 <= x < self.map_width and 0 <= y < self.map_height)
...
由于我需要将它们复制粘贴到GameMap中的许多方法中,因此这些断言变得非常重复,这就是为什么我还提供了第二个选项:
选项2:编写自己的函数以编写断言,并在需要时调用这些函数以防止复制和粘贴。
def check_game_object(self, game_object):
assert(isinstance(game_object, GameObject)
def check_coordinate(self, x, y):
assert(type(x) == type(y) == int)
assert(0 <= x < self.map_width and 0 <= y < self.map_height)
def add_object(self, game_object, x, y):
check_game_object(game_object)
check_coordinate(x, y)
...
选项3:在方法开头设置一系列自定义异常:
def add_object(self, game_object, x, y):
if not isinstance(game_object, GameObject):
raise InvalidParameterException("game_object not a GameObject")
elif not type(x) == type(y) == int:
raise InvalidParameterException("(x, y) not integers")
elif not (0 <= x < self.map_width and 0 <= y < map.self_height)
raise InvalidMapCell("x, y do not represent a valid map cell)
...
选项4:返回失败指示器,并在更高层面上处理问题
def add_object(self, game_object, x, y):
if not isinstance(game_object, GameObject):
return False
elif not type(x) == type(y) == int:
return False
elif not (0 <= x < self.map_width and 0 <= y < map.self_height)
return False
...
选项X:其他选择?
这里的任何建议都将非常感激!我想确保在继续进行时遵循有用和可维护的模式。