這樣做的最有效方法是什麼?我目前的實施非常混亂:給定一個元組座標列表,找到最近的座標到指定的座標系
def distanceTo(self, start, end):
"""Distance from cell A to cell B. Look at me, using PYTHAGORUS like a real man."""
startx, starty = start
endx, endy = end
return math.sqrt(math.pow(math.fabs(endx - startx), 2)
+ math.pow(math.fabs(endy - starty), 2))
def findNearestBuildings(self, myCoords, buildingGroup):
"""Returns a list of buildings specified, in ascending order of distance"""
if len(buildingGroup.sprites()) == 0:
return None
buildings = []
distances = []
for building in buildingGroup.sprites():
distance = self.distanceTo(myCoords, building.coords)
for i in range(len(buildings)):
if distances[i] < distance:
if i == len(buildings):
buildings.append(building)
distances.append(distance)
elif distances[i] >= distance:
buildings.insert(i, building)
distances.insert(i, distance)
if len(buildings) == 0:
buildings.append(building)
distances.append(distance)
return buildings
什麼是更有效的方法來做到這一點?我使用PyGame,但這應該是一個相當普遍適用的問題。所有座標都是整數值。
我認爲[代碼審查]這將永遠是真(HTTP://代碼審查.stackexchange.com)更適合您的問題。 –
我想在同一距離可能會碰到2個coords,對吧? – Agostino
對不起@Michal我不知道這件事。將在未來發布。 – jellyberg