如何在NetLogo中所有斑块被着色时让海龟停止运行?
需求:NetLogo实现海龟完成斑块覆盖后停止并记录tick数
需要实现的功能:当海龟把所有红色斑块都改成蓝色后,停在最后一个被着色的斑块处,同时记录运行所用的tick数。
现有代码
turtles-own [time-since-last-found]
to setup ca ask n-of num-clusters patches [ ask n-of 20 patches in-radius 5 [ set pcolor red ] ] crt 1 [ set shape "person" set color yellow set size 2 set time-since-last-found 999 pen-down ] reset-ticks end
to go ask turtles [search] tick end
to search ifelse time-since-last-found < 20 [ right (random 181) - 90 ] [ right (random 21) - 10 ] fd 1 ifelse pcolor = red [ set time-since-last-found 0 set pcolor blue ] [ set time-since-last-found time-since-last-found + 1 ] end
修改方案
核心思路是跟踪剩余未着色的红色斑块数量,当数量归0时停止海龟行动。具体修改步骤如下:
- 添加全局变量跟踪剩余红色斑块
在代码最顶部添加全局变量,用来记录还未被改成蓝色的红色斑块数:
globals [ remaining-red-patches ]
- 初始化剩余斑块数
修改setup过程,在最后加入计算初始红色斑块数量的代码:
to setup ca ask n-of num-clusters patches [ ask n-of 20 patches in-radius 5 [ set pcolor red ] ] crt 1 [ set shape "person" set color yellow set size 2 set time-since-last-found 999 pen-down ] ; 初始化剩余红色斑块数量 set remaining-red-patches count patches with [pcolor = red] reset-ticks end
- 更新剩余斑块数并添加停止判断
修改search过程,每次把红色斑块改成蓝色时同步减少剩余斑块数,且提前判断是否已完成所有着色:
to search ; 如果所有斑块都已着色,直接停止行动 if remaining-red-patches = 0 [ stop ] ifelse time-since-last-found < 20 [ right (random 181) - 90 ] [ right (random 21) - 10 ] fd 1 ifelse pcolor = red [ set time-since-last-found 0 set pcolor blue ; 剩余红色斑块数减1 set remaining-red-patches remaining-red-patches - 1 ] [ set time-since-last-found time-since-last-found + 1 ] end
- 控制go循环停止
修改go过程,当剩余红色斑块为0时,不再执行海龟行动和tick计数:
to go if remaining-red-patches > 0 [ ask turtles [search] tick ] end
修改完成后,当最后一个红色斑块被改成蓝色时,remaining-red-patches会变为0,海龟在下一次执行search时会直接停止,go循环也会终止,此时界面显示的ticks数值就是整个过程所用的时间。
内容的提问来源于stack exchange,提问作者echakee
相关产品推荐
相关产品推荐

