如何实现NetLogo中海龟穿越5个斑块后停止并变色?
解决NetLogo海龟穿越指定斑块后停止移动的问题
原逻辑下,NetLogo中的海龟会在pycor > 70时停止并变红,现在需要替换为穿越5个不同斑块后停止的判断,由于海龟孵化时间不同,无法通过tick直接实现,修改方案如下:
修改后的完整代码
breed [birds bird] birds-own [ parents? patches-crossed ; 记录已穿越的斑块数量 last-patch ; 记录上一次所在的斑块,避免同一斑块重复计数 ] to setup ca ask patches [set pcolor green] create-birds 100 [ set color blue set size 2 move-to one-of patches with [pycor < 50] set heading random 360 set parents? false set patches-crossed 0 set last-patch patch-here ; 初始化时记录当前斑块 ] ask n-of 25 birds [set parents? true] reset-ticks end to go give-birth fly-around stop-flying tick end to give-birth ask birds with [parents? = true][ hatch 1 [ set color blue set size 2 set heading random 360 set parents? false set patches-crossed 0 set last-patch patch-here ; 孵化的后代也要初始化斑块记录 ] ] end to fly-around ask birds with [patches-crossed < 5] [ ; 只让未停止的海龟移动 fd 2 if patch-here != last-patch [ ; 检查是否进入了新斑块 set patches-crossed patches-crossed + 1 set last-patch patch-here ; 更新上一个斑块记录 ] ] end to stop-flying ask birds with [patches-crossed >= 5][ set color red stop ; 停止该海龟的后续动作 ] end
关键修改说明
- 新增海龟变量
patches-crossed和last-patch:前者统计穿越的斑块数,后者用来标记上一次所在的斑块,防止在同一个斑块内移动时重复计数 - 初始化阶段(包括孵化后代):给新海龟的
patches-crossed设为0,last-patch设为当前所在斑块 - 移动逻辑优化:只有未达到穿越次数的海龟才会执行移动,每次移动后检查是否进入新斑块,是则增加计数
- 停止条件替换:不再用
pycor位置判断,改为检查patches-crossed >=5,满足条件的海龟变红并停止动作
内容的提问来源于stack exchange,提问作者sledgehammer
相关产品推荐
相关产品推荐

