Search code examples
netlogoagent

Can't run Netlogo code - asking turtles to look around themselves and select the lowest patch variable


I am trying to get my turtles to look around themselves in netlogo and select a patch with the lowest slope variable in radius 2 - and if there isn't one to just select any patch.

I check my code, and it says everything is fine, but when I run it I keep getting this error: this code can't be run by a patch - error while patch X X running ifelse - called by procedure move - called by procedure go - called by button "go"

This is my move code:

    to move
    ask turtles [ask patches in-radius 2 
    [ifelse slope < 5 
       [fd 1] 
       [move-to one-of patches in-radius 2]
    ]
   ]

    end

I have already tried downhill and downhill4 but my agents seemed to get stuck at the bottom of the slope and couldn't move anywhere.

Thank you for any help and advice!

Thank you - my code now works!


Solution

  • Because you are asking turtles to ask patches, the code inside the ask patches is run by the patch! A patch can’t use turtle variables, and doesn’t know that you mean to refer to the variables of the turtle that asked the patch.

    This is what “of myself” is for. It lets an agent (self) talk to the agent that is telling it what to do. You’ll see stuff like “set heading [heading] of myself” But that’s not what you need here.

    we could use an ask patches like you are doing here, but we really don’t want them to do anything, and it’s going to make the code much more complex looking. Anyway, We just want to find a patch that meets the turtle’s needs and move to it.

    So instead. We can query the nearby patches using a WITH and store the set of patches found in a “patch set” variable.

    If there are any, we can move to one of them.

    Else, we can just move forward.

    So

    To move
    Ask turtles
    [
      ;; here the turtle tells patches to test the patch’s own slope
      Let good-spots patches in-radius 2 with [ slope < 5 ]
      ;; are there some patches that pass the test?
      If-else  any? Good-spots
      [ ;; Yes, pick one and go there
        move-to one-of good-spots
      ]
      [ ;; No, just move forward
        Fd 1
      ]
    ]
    End
    

    Edit to add : Matteo’s answer correctly identifies the actual requirement, based on the question: move directly to the flattest patch, versus what the code above does, move to one of the flatter patches, if there is one.

    Move-to min-one-of patches in-radius 2 [ slope ] 
    

    As you noted, This is similar but not identical to

    Downhill slope
    

    And neither of these may prevent turtles from getting stuck in a pit. You may need more code to detect pits and jump out of them.