如何让NetLogo海龟排除曾停留斑块进行邻域检测?
解决NetLogo建造者海龟排除走过的斑块检测道路的问题
核心思路
你不需要patch-behind原语,通过给海龟添加状态变量记录走过的斑块(或上一个停留的斑块),就能实现排除已走过区域的道路检测。下面分两种场景给出解决方案:
场景1:排除所有曾停留过的斑块
如果需要排除建造者走过的所有斑块,给海龟添加列表变量记录路径:
- 定义海龟变量
在代码开头添加:
turtles-own [ target ; 建造目标斑块 previous-patches ; 记录所有停留过的斑块列表 ]
- 初始化建造者
创建建造者时初始化变量:
create-builders 1 [ set target <你的目标斑块> ; 替换为实际目标,例如 patch 10 10 set previous-patches [] ; 初始路径为空 ]
- 修改循环逻辑
更新你的循环代码,添加路径记录和排除逻辑:
loop [ ; 标记当前斑块为道路,并加入路径列表 ask patch-here [ set pcolor grey ] set previous-patches lput patch-here previous-patches ; 到达目标则停止 if patch-here = target [ die ] ; 前方无可行走斑块则停止 if patch-ahead 1 = nobody [ die ] ; 检测相邻4个斑块中,非走过区域的道路斑块 let adjacent-road-patches neighbors4 with [ pcolor = grey and not member? self previous-patches ] if any? adjacent-road-patches [ die ] ; 向前移动 fd 1 ]
场景2:仅排除上一个停留的斑块
如果只需要排除刚离开的那个斑块(而非所有走过的),用单个变量记录上一个斑块更高效:
- 定义海龟变量
turtles-own [ target ; 建造目标斑块 last-patch ; 记录上一个停留的斑块 ]
- 初始化建造者
create-builders 1 [ set target <你的目标斑块> set last-patch nobody ; 初始无前置斑块 ]
- 修改循环逻辑
loop [ ; 标记当前斑块为道路 ask patch-here [ set pcolor grey ] ; 到达目标则停止 if patch-here = target [ die ] ; 前方无可行走斑块则停止 if patch-ahead 1 = nobody [ die ] ; 检测相邻4个斑块中,排除上一个斑块后的道路斑块 let adjacent-road-patches neighbors4 with [ pcolor = grey and self != last-patch ] if any? adjacent-road-patches [ die ] ; 移动前记录当前斑块为下一次的前置斑块 set last-patch patch-here fd 1 ]
关键逻辑说明
- 两种方案都不需要
patch-behind:通过主动记录海龟的位置历史,直接排除不需要检测的斑块。 neighbors4获取四个非对角相邻斑块,结合with筛选条件,精准排除已走过的区域。- 场景2的效率更高,适合长路径的建造者,避免维护大型列表带来的性能损耗。
内容的提问来源于stack exchange,提问作者viheleha
相关产品推荐
相关产品推荐

