我正在嘗試使用 SciPy 和 PyGame在我隨機生成的世界地圖上創建和顯示Voronoi 圖。我遇到的問題是,總有一個點有奇怪的線條,它們會忽略其他任何東西,并像星星或其他東西一樣散布在地圖上。從左上角和左下角可以看出,它們不會無限遠。我怎樣才能擺脫它?顯示內容:我的代碼:import numpyimport randomimport pygamefrom scipy.spatial import Voronoidef __generate_voronoi(): """ Randomly chooses various points within the x and y dimensions of the map. Then, uses SciPy to generate a voronoi diagram with them, and returns it. :return: SciPy voronoi diagram """ point_arr = numpy.zeros([900, 2], numpy.uint16) for i in range(900): point_arr[i][0] = numpy.uint16(random.randint(0, 1600)) point_arr[i][1] = numpy.uint16(random.randint(0, 900)) return Voronoi(point_arr)def draw_voronoi(pygame_surface): # generate voronoi diagram vor = __generate_voronoi() # draw all the edges for indx_pair in vor.ridge_vertices: start_pos = vor.vertices[indx_pair[0]] end_pos = vor.vertices[indx_pair[1]] pygame.draw.line(pygame_surface, (0, 0, 0), start_pos, end_pos)
1 回答

慕標琳琳
TA貢獻1830條經驗 獲得超9個贊
感謝這里的耐心評論者,我了解到vor.vertices對于無限大的點的第一個索引將返回 -1。這會產生一個問題,因為 python 將 -1 視為列表或數組最后一個元素的索引。
我的問題的解決方案不是從vor.vertices.
我通過用draw_voronoi()以下代碼替換函數來實現:
def draw_voronoi(pygame_surface):
# generate voronoi diagram
vor = __generate_voronoi()
# draw all the edges
for indx_pair in vor.ridge_vertices:
if -1 not in indx_pair:
start_pos = vor.vertices[indx_pair[0]]
end_pos = vor.vertices[indx_pair[1]]
pygame.draw.line(pygame_surface, (0, 0, 0), start_pos, end_pos)
這產生了這個圖像:
添加回答
舉報
0/150
提交
取消