NetLogo 5.1.0转6.3.0:A*算法代码兼容问题求助
NetLogo 6.x 兼容A*算法排序问题的解决方法
核心问题原因
NetLogo 6.x 对匿名函数语法做了重大调整,旧版本(5.x)中使用?1、?2指代参数的写法已被弃用,sort-by要求传入接收两个参数的二元箭头函数,用于判断元素的排序规则。
正确的排序代码替换
将原代码中的错误排序行:
; set open sort-by [[f] of ?1 < [f] of ?2] open set open sort-by < [] open
替换为以下两种兼容写法之一:
写法1(显式变量访问,更直观):
set open sort-by [ [a b] -> [f] of a < [f] of b ] open
写法2(NetLogo 6.x 简化语法,更简洁):
set open sort-by [ [a b] -> a.f < b.f ] open
修正后的完整A*路径查找代码
to-report find-a-path [ source-patch destination-patch] ; initialize all variables to default values let search-done? false let search-path [] let current-patch 0 set open [] set closed [] ; add source patch in the open list set open lput source-patch open ; loop until we reach the destination or the open list becomes empty while [ not search-done? ] [ ifelse length open != 0 [ ; sort the patches in open list in increasing order of their f() values ; 替换为NetLogo 6.x兼容的排序写法 set open sort-by [ [a b] -> a.f < b.f ] open ; take the first patch in the open list ; as the current patch (which is currently being explored (n)) ; and remove it from the open list set current-patch item 0 open set open remove-item 0 open ; add the current patch to the closed list set closed lput current-patch closed ; explore the Von Neumann (left, right, top and bottom) neighbors of the current patch ask current-patch [ ; if any of the neighbors is the destination stop the search process ifelse any? neighbors4 with [ pxcor = [pxcor] of destination-patch and pycor = [pycor] of destination-patch ] [ set search-done? true ] [ ; the neighbors should not be obstacles or already explored patches (part of the closed list) ask neighbors4 with [ pcolor != black and not member? self closed and self != parent-patch ] [ ; the neighbors to be explored should also not be the source or ; destination patches or already a part of the open list (unexplored patches list) if not member? self open and self != source-patch and self != destination-patch [ ;set pcolor 45 ; add the eligible patch to the open list set open lput self open ; update the path finding variables of the eligible patch set parent-patch current-patch set g [g] of parent-patch + 1 set h distance destination-patch set f (g + h) ] ] ] ] ] ; 补充原代码缺失的else分支(处理open列表为空的情况) [ set search-done? true ; 可选:添加路径查找失败的提示 ; print "No path found!" ] ] ; 补充原代码缺失的report语句(回溯生成路径) if search-done? and current-patch != 0 [ set search-path lput current-patch search-path while [ [parent-patch] of last search-path != source-patch ] [ set search-path lput [parent-patch] of last search-path search-path ] set search-path lput source-patch search-path ] report search-path end
额外注意事项
- 必须在代码开头定义patch的私有变量,否则会报错:
patches-own [ parent-patch g h f ]
- 原代码缺失
while循环的else分支和最终的report语句,修正代码中已补充,保证逻辑完整性。
内容的提问来源于stack exchange,提问作者Mats Hiemink
相关产品推荐
相关产品推荐

