I am trying to get a layout-circle
in NetLogo to have every second turtle to move one coordinate towards the centre, and the remaining ones to move away from it. I have found a way around using random
, but the result is not really tidy. What I am trying to get is turtles that are positioned in a zig-zag manner around the circle, without the random component I am getting. For instance, that all even-numbered turtles move towards the centre, and all odd-numbered ones move away.
Any thoughts, hoping this is sufficiently clear?
to setup
clear-turtles
create-turtles 100
layout-circle (sort turtles) max-pxcor - 1
ask turtles [setxy xcor (ycor + random 3 - 1)]
end
Given that your turtles are sorted, using their who
would work. Also, if you want to preserve the circle layout, you should have turtles move along the radius rather than according to the world's coordinates (and surely get rid of random
if you want no random effects).
Before we proceed, a big warning: you will read quite regularly that using agents' who
is bad NetLogo coding practice (I myself still need to understand exactly why that is dangerous).
Considering that your turtles are sorted in the layout and assuming this passage happens just upon setup, I think it is sufficiently safe to use who
in your case - however, I also include an approach that doesn't use who
, which would also be needed in case of unsorted turtles.
In both cases, the outcome is this:
(note that this perfect zigzag is possible only if turtles are created in an even number)
who
to setup
clear-turtles
create-turtles 100
layout-circle (sort turtles) max-pxcor - 1
ask turtles [
ifelse (who mod 2 = 0)
[forward 0.5]
[forward -0.5]
]
end
By doing this, every even turtle will move forwards by a bit, and every odd turtle will move backwards by the same amount.
who
This has to be more elaborated.
We take advantage of the fact that, if we make turtles move alternately forwards and backwards (achieved by ifelse (counter mod 2 = 0) [] []
) from the circle layout, then the closest turtle to the last moving turtle (the moving turtle is reference-turtle
in the code) will be the next turtle on the circle perimeter who hasn't moved yet.
At the end of every while
iteration, the current reference-turtle
will ask the closest turtle to become the new reference-turtle
.
To make this all work, we can use counter
both as the stop condition for the while
loop and as the condition based on which turtles know whether to move forwards or backwards
to setup
clear-turtles
create-turtles 100
layout-circle turtles max-pxcor - 1
let counter 0
let reference-turtle one-of turtles
while [counter < count turtles] [
ask reference-turtle [
ifelse (counter mod 2 = 0)
[forward 0.5]
[forward -0.5]
ask min-one-of other turtles [distance myself] [
set reference-turtle self
]
]
set counter counter + 1
]
end