我正在尝试做一些非常简单的事情,但由于某种原因我无法让它发挥作用。
我的设置函数创建了一个从 (-20, 20) 到 (20, 20) 的方形墙,并在墙内生成了一个大小为 3 的圆形海龟。方形的墙壁只是由蓝色的补丁组成。
现在我有一个 go 函数,它告诉乌龟旋转 -90 到 90 度之间的任何位置,并向前移动 0.5 步。不准“走进”墙;当它撞到墙壁时,它只是选择另一个方向移动。乌龟在真正走进墙壁之前无法“感知”墙壁。
我一直使用的代码如下:
ask turtle 0 [
let invalid true
let turn-degree (random(180) - 90)
rt turn-degree
let next-patch patch-ahead 1 ;; Declare next-patch before moving
while [invalid] [ ;; While invalid condition
ask next-patch [
;; Neighbors of the next patch are counted, because turtle is size 3
if ( count neighbors with [pcolor = blue] = 0 ) [
set invalid false
]
]
if (invalid) [
lt turn-degree ;; Turn the turtle back to the original direction
set turn-degree (random(180) - 90) ;; Randomize turn degree again
set next-patch patch-ahead 1 ;; Declare next-patch before moving again
]
]
;; Finally, jump 0.5 steps ahead in the chosen direction
jump 0.5
]
Run Code Online (Sandbox Code Playgroud)
我很遗憾地说上面的代码不起作用,因为乌龟仍然以某种方式设法将自己与蓝色的墙重叠,这是不应该发生的。我怀疑是因为两个原因:
1) 0.5 步破坏了“提前修补”条件。但是,我尝试过使用 patch-ahead 0.5,但没有效果。2)随机转弯程度导致蓝墙距离乌龟略大于0.5,但我没有解决方法......
有什么建议么?
问题是,当海龟移动到更靠近接触墙的补丁的边缘时,neighbors海龟的补丁不是墙的一部分,但海龟距离墙的距离仍然小于 1.5墙。尝试这个:
ask turtle 0 [
rt (random 180) - 90
fd .5
while [ any? patches in-radius 2 with [ pcolor = blue ] ] [
bk .5
rt (random 180) - 90
fd .5
]
]
Run Code Online (Sandbox Code Playgroud)