2017-08-25 57 views
1

我已經建立了一個pygame窗口,裏面有10個點,現在我正在嘗試讓每個點連接到最近連接到的點上。現在,當我運行這一點時,有些點形成了閉環,而除了那些應該包含所有點的點外,不應該有這樣的點。獲取最近的未訪問點?

What it does look like

for p in points: 
    bestdist=math.inf 
    for q in openset: 
     if(points[p]!=openset[q]): 
      cdist=dist(points[p],openset[q]) 
      if cdist<bestdist: 
       bestdist=cdist 
       b=q 
    pygame.draw.line(DISPLAYSURF, RED, points[p] ,points[b], 2) 
    openset.pop(b,None) 
    pygame.display.update() 
+0

請更全面地解釋你想要做什麼以及你的代碼應該如何工作。另外,發佈一個[最小和可運行的示例](https://stackoverflow.com/help/mcve)。 – skrx

+0

如果你想知道你的程序出了什麼問題,你必須發佈一個完整的例子。 – skrx

回答

1

看看這個例子。我只是將最近的點追加到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()