为什么我只要求其中一只乌龟死亡,但我的所有乌龟都死了?

Why are all my turtles dying when I ask only one of them to?

我正在尝试制作一个程序,如果一只乌龟检测到它前面有一只乌龟,它就会死去。很简单,但出于某种原因,每当发生这种情况时,我所有的海龟都会死去,我不知道如何纠正这个问题。

这是我的代码:

to setup
  ca
  ask patches
  [ set pcolor white
  ]
end

to spawn
  crt 1
  [ set color random 140
    setxy random-xcor random-ycor
  ]
end

to wiggle
  lt 100
  rt 100
  ifelse not any? turtles-on patch-ahead 1
  [ fd 1
    set pcolor color
  ]
  [ die
  ]
end

to go
  ask turtles
  [ wiggle
  ]
end

似乎 ifelse not any? turtles-on patch-ahead 1 在某一时刻总是开始评估为 false,我不明白为什么。

我认为以下示例可能会让您对发生的事情有所了解:

to setup
  clear-all
  create-turtles 1 [
    set xcor -0.5
    set ycor -0.5
    set heading 45
    show (word "patch-here:    " patch-here)
    show (word "patch-ahead 1: " patch-ahead 1)
    show (word "patch-ahead 1: " patch-ahead 1)
    show (word 
      "not any? turtles-on patch-ahead 1:       "
      not any? turtles-on patch-ahead 1
    )
    show (word 
      "not any? other turtles-on patch-ahead 1: "
      not any? other turtles-on patch-ahead 1
    )
  ]
end

它正在创建一只乌龟,将它放在中央补丁的左下角并使其面向东北,然后再检查一些东西。如果您 运行 代码,您将得到:

observer> setup
(turtle 0): "patch-here:    (patch 0 0)"
(turtle 0): "patch-ahead 1: (patch 0 0)"
(turtle 0): "patch-ahead 1: (patch 0 0)"
(turtle 0): "not any? turtles-on patch-ahead 1:       false"
(turtle 0): "not any? other turtles-on patch-ahead 1: true"

关键是补丁的对角线比一个长(记住毕达哥拉斯定理)。这意味着 patch-ahead 1 仍然可以是乌龟所在的同一个补丁!在这种情况下,not any? turtles-on patch-ahead 1 将为假。由于您的海龟在世界各地随机移动,这最终肯定会发生。

幸运的是,有一个简单的解决方案。只需使用 other:

not any? other turtles-on patch-ahead 1