使用A 尋路實現吃豆子

2021-10-17 12:08:09 字數 2607 閱讀 3457

使用a*演算法必須知道的:

1.f=g+h(尋路演算法主要是一步一步在openlist中找到最小的f)

h:當前節點行、列於目的地行列差之和 * 10

g:在父節點左右上下位置的g=10,在斜上、斜下、斜左、斜右的g=14

2.openlist:用來判斷某點到目的地點第一步可能走的選項列表;(存放某點上下左右,斜上斜下斜左斜右點 ,注意:如果可選項為障礙、怪物、比自己大的其他玩家,則不能加入openlist中)每個點都有乙個openlist

closelist:用來存放可走的最優路徑

parent:父節點

3.a*尋路思想

(1)起點插入openlist中

(2)在openlist中查詢f最小的node節點

(3)從openlist中移除f最小的node,並把它加入到closelist(即,找到該點下步要走的點)

(4)node是否是終點

(5)查詢node周圍點:目的為了找node的openlist,找到可走的點加入到openlist中(從步驟2繼續尋找)

4.核心**實現:

def searchnear(minf, offsetrow, offsetcol, endpoint):

# 處理資料+21後再對移動位置取餘 重新計算offsetcol、offsetcol

rowtemp = (minf.row + offserrow + 21)%21

coltemp = (minf.col + offsetcol + 21)%21

if list_two[rowtemp][coltemp] is ghost: # ghost不能加入

return

if list_two[rowtemp][coltemp] is obstacle1: # 障礙不能加入

return

if list_two[rowtemp][coltemp] is obstacle2: # 障礙不能加入

return

if list_two[rowtemp][coltemp] is obstacle3 # 障礙不能加入

return

if list_two[rowtemp][coltemp] > list_two[mypoint.row][mypoint.col] # 大於自己的玩家

return

# 如果在關閉表中,就忽略

currentpoint = point(minf.point.row + offsetrow, minf.point.col + offsetcol)

if checkincloselist(currentpoint):

return

# 設定單位花費

if offsetrow == 0 or offsetcol == 0:

step = 10

else:

step = 14

# 如果不再openlist中,就把它加入openlist

currentnode = checkinopenlist(currentpoint)

if not currentnode:

currentnode = node(currentpoint, endpoint, g=minf.g + step)

currentnode.parent = minf

return

# 如果在openlist中,判斷minf到當前點的g是否更小

if minf.g + step < currentnode.g: # 如果更小,就重新計算g值,並且改變father

currentnode.g = minf.g + step

currentnode.parent = minf

def findpath(endpoint):

openlist.clear()   # del openlist[:]

openlist.clear()

# 1.將mypoint加入openlist

# 2.迴圈查詢路線

while true:

#3.查詢openlist中f值最小的node

minnode = findminnode()

#4.將該node新增到closelist中並從openlist中移除

openlist.remove(minnode)

#5.判斷該node是不是目的位址,是的話尋路成功,否則繼續查詢最小f

if minnode is endpoint:

#todo 存起來這條路線 並帶有路線的長度和目標值大小

return closelist[0], len(closelist), list_two[endpoint.row][endpoint.col]

#6.查詢該node上下左右的node,並把有效的node加入openlist中,用來繼續查詢最小f值

searchnear(minnode, 1, 0, endpoint) # 右

searchnear(minnode, -1, 0, endpoint) # 左

searchnear(minnode, 0, 1, endpoint) # 下

searchnear(minnode, 0, -1, endpoint) # 上

未完待續…

C 實現A 尋路

網上有關a 演算法的文章已經非常豐富了,各種語言各種思路都有,本來我實在不想再寫一篇,但因為最近工作動盪因此專門抽空又看了一下,然後就想寫個文章防止以後印象模糊,好歹看自己寫的東西可以很快回憶起來。如果是初次接觸a 演算法的朋友可以先看看這篇參考文章,我這邊只是做乙個總結,然後先貼上我之前的筆記吧 ...

js實現A 尋路演算法

onload function cc.log this.searchroad map,0,0,4,4 傳入變數屬性,起始點座標和目標的座標。整個 執行後,列印出的是起始點到目標點最近路徑的座標 其中的map.arr是二維陣列 searchroad function map,start x,start...

C 實現網路尋路

x 國的乙個網路使用若干條線路連線若干個節點。節點間的通訊是雙向的。某重要資料報,為了安全起見,必須恰好被 兩次到達目的地。該包可能在任意乙個節點產生,我們需要知道該網路中一共有多少種不同的 路徑。源位址和目標位址可以相同,但中間節點必須不同。如圖1所示的網路。1 2 3 1 是允許的 1 2 1 ...