如何限制NetLogo智能体不超出gis:load-dataset加载的栅格范围?
解决智能体越界及禁止进入黑色区域的方案
1. 标记允许移动的区域
先在代码开头的patches-own声明里新增变量,用来标记可通行的地块:
patches-own [coberturas borde-negro is-allowed?]
然后修改setup-mapa代码,给每个地块标记是否允许智能体进入:
to setup-mapa set mapa-coberturas gis:load-dataset "C:\\RASCII.asc" gis:set-world-envelope gis:envelope-of mapa-coberturas ask patches [ set coberturas gis:raster-sample mapa-coberturas self ; 给允许通行的地块设颜色并标记为可通行 if coberturas >= 0 and coberturas < 1 [ set pcolor 8 set is-allowed? true ] if coberturas >= 1 and coberturas < 2 [ set pcolor 68 set is-allowed? true ] if coberturas >= 2 and coberturas < 3 [ set pcolor 49 set is-allowed? true ] if coberturas >= 3 and coberturas < 4 [ set pcolor 28 set is-allowed? true ] if coberturas >= 4 [ set pcolor 79 set is-allowed? true ] ; 禁止通行的区域(黑色/地图背景)标记为不可通行 if coberturas < 0 [ set pcolor 130 set is-allowed? false ] ] ask patches with [coberturas <= 0] [ if any? neighbors with [pcolor = black][ set borde-negro 1 set is-allowed? false ; 边缘地块也标记为不可通行 ] ]
2. 修改智能体移动逻辑
针对不同的移动方式,添加通行检查:
向前移动(
fd命令):
把原来的fd 1替换为:let target-patch patch-ahead 1 if target-patch != nobody and [is-allowed?] of target-patch [ fd 1 ]逻辑:先获取前方地块,仅当地块存在且可通行时才移动。
随机移动到邻居地块:
把随机移动的代码替换为:let valid-neighbors neighbors with [is-allowed?] if any? valid-neighbors [ move-to one-of valid-neighbors ]逻辑:只从可通行的邻居地块中选一个移动,没有可通行邻居则保持不动。
初始位置限制:
确保智能体一开始就生成在可通行区域,在setup的智能体生成代码里添加:create-turtles 10 [ ; 示例生成10个智能体 move-to one-of patches with [is-allowed?] ]
3. 额外:禁止靠近地图边缘
如果要让智能体完全避开地图最外围地块,可修改is-allowed?的判断逻辑,在标记可通行区域时额外排除边缘地块:
set is-allowed? (coberturas > 0 and pxcor != min-pxcor and pxcor != max-pxcor and pycor != min-pycor and pycor != max-pycor)
内容的提问来源于stack exchange,提问作者HeyIt'sMerley
相关产品推荐
相关产品推荐

