日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Pygame 使用Djkstra广度搜索寻找迷宫(相对)最短路径

發布時間:2023/12/15 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Pygame 使用Djkstra广度搜索寻找迷宫(相对)最短路径 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

基于之前寫的迷宮生成器實現了Djkstra算法搜索路徑。

https://blog.csdn.net/ChillingKangaroo/article/details/122800431


Djkstra基于廣度優先算法,與簡單搜索不同的是Djkstra在訪問每一個節點的時候會計算到該節點的最短路徑以及上一個節點,如果有新的路徑比之前的路徑更短,儲存的上一個路徑點則會被替換掉。在完成計算之后只需要取終點的數據然后就可以沿記錄找到已搜索范圍中最短的路徑。
因為我之前迷宮基于深度優先生成,另外因為路徑沒有權重(走一格的距離都是相同的)所以其實Djkstra不太能發揮出來,實現中沒有使用優先級序列,不過算法還是有效的。

實現用了python的鏈表,動態添加很方便,在沒有找到終點的時候循環,每次循環查找列表中節點的四個方向,如果沒有訪問過則添加到新列表中,循環結尾再把新列表值給查找列表,在查找到終點時就停止。

實現效果如下,綠色表示djkstra查找范圍,藍色表示最短路徑,使用40x40矩陣測試

import pygame as pg import time import randomclass Tile(): #Tile is for generating mazedef __init__(self,grid_size,screen_size,x,y):self.x,self.y = x,yself.connected = [0,0,0,0] # up,right,down,left 0 for not connectedself.grid_size = grid_sizeself.tile_size = [(screen_size[0]-100)/grid_size[0],(screen_size[1]-100)/grid_size[1]]self.rectangle = (self.x*self.tile_size[0]+50,self.y*self.tile_size[1]+50,self.tile_size[0],self.tile_size[1])self.points = [ [self.x*self.tile_size[0]+50,self.y*self.tile_size[1]+50], #uppper left[self.x*self.tile_size[0]+50+self.tile_size[0],self.y*self.tile_size[1]+50], #upper right[self.x*self.tile_size[0]+50+self.tile_size[0],self.y*self.tile_size[1]+50+self.tile_size[1]], #lower right[self.x*self.tile_size[0]+50,self.y*self.tile_size[1]+50+self.tile_size[1]], #lower left] self.visited = Falseself.color = (255,253,150)def draw(self,color = None): #x,y represents the tile coordinates color = self.color if not color else colorpg.draw.rect(screen,color,self.rectangle)for i in range(4):if not self.connected[i]:pg.draw.line(screen,(150,175,255),(self.points[i]),(self.points[((i+1)%4)]),5)class Node():def __init__(self):self.visited = Falseself.last_node = Noneself.steps = Nonedef maze_gen(path):global tile_coveredx,y = path[-1]if x < 0 or x >= grid_size[0] or y < 0 or y >= grid_size[1]:print(f'index out of range at {x,y}')returnif matrix[y][x].visited:print(f'node already visited at {x,y}')returnelif tile_covered <= grid_size[0]*grid_size[1]:tile_covered += 1print(x,y)matrix[y][x].visited = Truepath_choice = [0,1,2,3]random.shuffle(path_choice)for i in path_choice:x_,y_ = x+directions[i][0],y+directions[i][1]path.append([x_,y_])if maze_gen(path): # tile is not visitedmatrix[y][x].connected[i] = 1 #walls of current nodematrix[y_][x_].connected[(i+2)%4] = 1#reverse the vector directionmatrix[y][x].draw()matrix[y_][x_].draw()pg.display.update()path.pop(-1)return Trueelse:print('all node visited')returndef djkstra():end_point = (grid_size[0]-1,grid_size[1]-1)x,y = start_pointmatrix[y][x].draw((255,0,0))matrix[end_point[0]][end_point[1]].draw((255,0,0))pg.display.update()border = [[0,0]]steps = 0while True:steps += 1new_border = []for x,y in border:if (x,y) == end_point:print('exit found')return end_pointfor i in range(4):if matrix[y][x].connected[i]: #if there is a waynext_x,next_y = directions[i][0]+x,directions[i][1]+yif found_path[next_y][next_x].visited == False:new_border.append([next_x,next_y])matrix[next_y][next_x].draw((0,255,0))pg.display.update()if found_path[next_y][next_x].last_node == None:found_path[next_y][next_x].last_node = (x,y)elif steps < found_path[next_y][next_x].steps:found_path[next_y][next_x].last_node = (x,y)print(f'setting {x,y} to visited')found_path[y][x].visited = Trueborder = new_borderif new_border == []:print('No exit point found')returndef draw_path(end_point):if not end_point:returnelse:x,y = end_pointwhile [x,y] != start_point:print(f'going though node {x,y}')matrix[y][x].draw((0,0,255))print(f'{(x,y)} == {start_point}:')print((x,y) == start_point)x,y = found_path[y][x].last_nodepg.display.update()screen_size = [800,800] grid_size = [40,40]tile_covered = 0 run = Truescreen = pg.display.set_mode(screen_size)matrix = [] directions = [[0,-1],[1,0],[0,1],[-1,0]] # up,right,down,left 0 for not connected found_path = [[Node() for x in range(grid_size[0])] for y in range(grid_size[1])]for y in range(grid_size[1]):temp = []for x in range(grid_size[0]):tile = Tile(grid_size,screen_size,x,y)temp.append(tile)matrix.append(temp)pg.init() path = [[0,0]] start_point = [0,0]screen.fill((255,255,255)) maze_gen(path)pg.display.update()print('======== Generation Finished ========')end_point = djkstra() draw_path(end_point)while run:for event in pg.event.get():if event.type == pg.QUIT:run = Falsepg.quit()

總結

以上是生活随笔為你收集整理的Pygame 使用Djkstra广度搜索寻找迷宫(相对)最短路径的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。