Reputation: 1112
For some reason I'm failing abominably at asking turtles to go to xy coordinates in a list. I've tried several approaches and though I can see why some of them are wrong I can't identify what's right.
(foreach [ 1 2 3 4] [-16 -16 -16 -16] [12 11 10 9] [ask turtle ?1 [setxy ?2 ?3 ]])
*following this, I could set a list of commands e.g. setxy for each but that seems a waste. Additionally I'd like to call the turtle by some variable rather than an item in a list.
Ideallty, I would like to set the list as a varaiable e.g. set mylist [[0 1] [0 2]...] But I'm not sure how to go about iterating through the items.
http://ccl.northwestern.edu/netlogo/docs/dictionary.html#foreach
Upvotes: 1
Views: 3652
Reputation: 14972
Well, first of all, your example code should work, if turtles 1, 2, 3 and 4, exist. Turtles in NetLogo are indexed from 0
, so I suspect you may be doing something like:
create-turtles 4
(foreach [1 2 3 4] [-16 -16 -16 -16] [12 11 10 9] [ask turtle ?1 [setxy ?2 ?3]])
And are getting something like:
ASK expected input to be an agent or agentset but got NOBODY instead.
...because your code is trying to ask
a turtle 4
that does not exist. Changing your first list to [0 1 2 3]
would fix that.
Now is that the best way to do what you want to do? I don't have enough info to be sure, but I suspect you'd like something closer to:
clear-all
let coordinates [[-16 12] [-16 11] [-16 10] [-16 9]]
create-turtles length coordinates
(foreach (sort turtles) coordinates [
ask ?1 [ setxy item 0 ?2 item 1 ?2 ]
])
You should be able to figure out how it works if you know that sort turtles
turns your turtles
agentset into a list and item
allows you to get a specific item in a list.
Edit:
Doing create-turtles length coordinates
instead of something like create-turtles 4
will ensure that you have the same number of turtles as the number of coordinates you defined, but that's something that may or may not apply to your situation.
Edit 2:
An even simpler approach, that would only work if your turtles are not already created, would be:
clear-all
let coordinates [[-16 12] [-16 11] [-16 10] [-16 9]]
foreach coordinates [
create-turtles 1 [ setxy item 0 ? item 1 ? ]
]
Upvotes: 6