我这里有一个 python 类方法的怪物。我能想到的唯一方法是一个巨大而丑陋的 if / elif / else 块。你们中的任何人都可以提出任何想法来使它变得更好吗?
对于上下文,这是 pygame 的网格制作库的一部分,并且是一个函数,它获取网格中的一个图块并返回周围的图块。如果 "horizontal" 设置为 false,它只返回与瓷砖垂直相邻的瓷砖,反之亦然。
def getSurroundingTiles(self, tile, horizontal = True, vertical = True):
index = list(self.getTiles()).index(tile)
maxtile = self.sqrtnum - 1 # Offset for 0 indexing
i = int(math.floor(index / self.sqrtnum))
j = int(index % self.sqrtnum)
surroundingTiles = []
if i == 0 and j == 0:
#Top left corner
if horizontal:
surroundingTiles.extend((self[i + 1][j], self[i][j + 1]))
if vertical:
surroundingTiles.append(self[i + 1][j + 1])
elif i >= maxtile and j == 0:
#Top right corner
if horizontal:
surroundingTiles.extend((self[i - 1][j], self[i][j + 1]))
if vertical:
surroundingTiles.append(self[i - 1][j + 1])
elif i == 0 and j >= maxtile:
#Bottom left corner
if horizontal:
surroundingTiles.extend((self[i + 1][j], self[i][j - 1]))
if vertical:
surroundingTiles.append(self[i + 1][j - 1])
elif i >= maxtile and j >= maxtile:
#Bottom right corner
if horizontal:
surroundingTiles.extend((self[i - 1][j], self[i][j - 1]))
if vertical:
surroundingTiles.append(self[i - 1][j - 1])
elif i == 0:
#Top border
if horizontal:
surroundingTiles.extend((self[i + 1][j], self[i][j + 1],
self[i][j - 1]))
if vertical:
surroundingTiles.extend((self[i + 1][j + 1],
self[i + 1][j - 1]))
elif i >= maxtile:
#Bottom border
if horizontal:
surroundingTiles.extend((self[i - 1][j], self[i][j + 1],
self[i][j - 1]))
if vertical:
surroundingTiles.extend((self[i - 1][j + 1],
self[i - 1][j - 1]))
elif j == 0:
#Left border
if horizontal:
surroundingTiles.extend((self[i + 1][j], self[i - 1][j],
self[i][j + 1]))
if vertical:
surroundingTiles.extend((self[i + 1][j + 1],
self[i - 1][j + 1]))
elif j >= maxtile:
#Right border
if horizontal:
surroundingTiles.extend((self[i + 1][j], self[i - 1][j],
self[i][j - 1]))
if vertical:
surroundingTiles.extend((self[i + 1][j - 1],
self[i - 1][j - 1]))
else:
if horizontal:
surroundingTiles.extend((self[i + 1][j], self[i - 1][j],
self[i][j + 1], self[i][j - 1]))
if vertical:
surroundingTiles.extend((self[i + 1][j + 1], self[i + 1][j - 1],
self[i - 1][j + 1], self[i - 1][j - 1]))
return surroundingTiles