Search code examples
performancenetlogopatchagent

How to make turtles / agents go faster or slower when being on a certain patch?


I have to make turtles go faster when being on a green patch, and when they are on a blue patch the speed should go down. I added part of the code that I tried, but it doesn't work. Could someone please help me? Thanks in advance!!

turtles-own [speed]

to go                                                                                   
ask turtles [

left 60                                                                             
right random 60                                                                     
forward 1                                                                                                                 

  

if any? neighbors with [pcolor = green]
    [
      set speed speed + 1
       ]

    
if any? neighbors with [pcolor = blue]
    [
      set speed speed + 0.1
        ]

 ]

reset-ticks

Solution

  • I think what user2901351 was getting at was that you are using neighbors in your example code. If you look at the dictionary entry for neighbors, you'll see that it references the 8 patches around the current patch. If you instead want the turtle to check the patch it's currently on, you can use the patch-here primitive or, as a shortcut, just ask the turtle to check a patch-owned variable directly. Below is a toy example that shows an example of this at work- more details in the comments.

    turtles-own [speed]
    
    to setup 
      ca
      crt 5 [ set speed 1 ]
      ask n-of 20 patches [ 
        ifelse random-float 1 < 0.5 
        [ set pcolor green ]
        [ set pcolor blue ]
      ]
      reset-ticks
    end
    
    to go                                                                                   
      ask turtles [
        ; Since 'pcolor' is a patch variable, if the turtle queries pcolor
        ; it will check the patch's variable directly.
        if pcolor = green [ set speed speed + 0.5 ]
        if pcolor = blue [ set speed speed - 0.5 ]
        ; Make sure that the turtles are moving forward by their speed value, 
        ; rather than the hard-coded value of "1" in the example code. Also,
        ; I've included a check here so the turtles don't either stop moving
        ; or start moving backwards.
        if speed < 1 [ set speed 1 ]
        rt random-float 60 - 30
        fd speed
        show speed
      ]
      tick
    end