看看這個例子。我只是將最近的點追加到connected_points
列表中,並將其從openset
中刪除。當前點只是最後的附加點:current_point = connected_points[-1]
。
import math
import random
import pygame as pg
def dist(p1, p2):
return math.hypot(p2[0]-p1[0], p2[1]-p1[1])
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
points = [(random.randrange(640), random.randrange(480))
for _ in range(10)]
openset = set(points)
connected_points = [random.choice(points)]
openset.remove(connected_points[-1])
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if openset:
bestdist = math.inf
current_point = connected_points[-1]
for point in openset:
cdist = dist(current_point, point)
if cdist < bestdist:
bestdist = cdist
nearest_point = point
connected_points.append(nearest_point)
openset.remove(nearest_point)
screen.fill((30, 30, 30))
for p in points:
pg.draw.circle(screen, (100, 140, 100), p, 5)
if len(connected_points) >= 2:
pg.draw.lines(screen, (150, 50, 50), False, connected_points, 2)
pg.display.flip()
pg.time.wait(500)
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
請更全面地解釋你想要做什麼以及你的代碼應該如何工作。另外,發佈一個[最小和可運行的示例](https://stackoverflow.com/help/mcve)。 – skrx
如果你想知道你的程序出了什麼問題,你必須發佈一個完整的例子。 – skrx