我正在使用
netlogo
来模拟海龟随机走动,寻找东西。我有两个规则:我希望海龟在到达世界边缘时转身(或者只是稍微转动,这样它们就不会卡在边缘),并且我希望海龟互相避开。我创建了以下代码:
to setup
clear-all
let ycord one-of (list min-pycor max-pycor)
crt 3 [
setxy random-pxcor ycord
set size 4
set color yellow
pen-down
]
reset-ticks
end
to go
tick
ask turtles [search]
end
to search
(ifelse
;if at edge of world turn around
(xcor <= min-pxcor or ycor <= min-pycor or xcor >= max-pxcor or ycor >= max-pycor) [
set heading heading + 180
]
;if any other turtles are near turn away
any? other turtles in-radius 4 [
let closest min-one-of turtles [distance myself]
face closest
set heading heading + 180
]
[right (random 21) - 10]
)
;step forward
fd 1
end
边界设置为不换行。它工作正常,除了海龟被困在角落里,它们只是来回弹跳,或者它们被困在躲避另一只海龟和在边缘转身之间。我希望它们能够无缝地不会卡在任何边缘,并避免彼此,目标是最大化所有海龟覆盖的区域。如果增加背景的话,海龟也应该模拟人类。
通过将“搜索”程序更改为以下内容,实现了您所要求的目标:
to search
(ifelse
;if at edge of world turn around
xcor <= min-pxcor + 0.25 [set heading (random 180)]
ycor <= min-pycor + 0.25 [set heading one-of (list (270 + random 90)(random 90))]
xcor >= max-pxcor - 0.25 [set heading (180 + random 180)]
ycor >= max-pycor - 0.25 [set heading (90 + random 180)]
;if any other turtles are near turn away
any? other turtles in-radius 4 [
let closest min-one-of turtles [distance myself]
face closest
set heading heading + 180
]
[right (random 21) - 10]
)
;step forward
fd 1
end
这有两个方面的帮助。一方面,海龟不会那么容易被卡住,因为它们轮流的随机性有助于避免两个彼此相邻旋转,因为它们仅有的两个选择对于继续移动是无效的。另一方面,这并不能避免它们有时陷入困境,因为它们并不处于世界的确切极限内(例如,15.98...而不是 16)。距边缘 0.25 的边距避免了这种情况。
希望这能让你的海龟做你想做的事!