Search code examples
netlogoagentmulti-agent

How to make turtle go back to specific coordination without getting stuck there?


I am trying to make turtles walk back to a specific coordination (center of the world) after going on patches with a certain color (yellow here), I wrote the following code and my turtle walks back but then it keeps going back to that coordination after moving 1 step forward. There must be sth wrong with my code.

I don't want turtles to jump, I need them to walk back for further procedures.

breed [miners miner]
breed [bases base]

to setup
  clear-all
  reset-ticks
  create-miners 1
  create-bases 1
  ask bases
  [set size 1]
  ask miners
  [set size 1
    set heading random 360]
  ask patches
  [set pcolor green]
  place-golds
end

to go
  ask miners
  [right random 360
    forward random 4
    get-gold]
  tick
end
to place-golds
  ask n-of 10 patches [ set pcolor yellow ]
end

to get-gold
  ask miners
  [if pcolor = yellow
    [set pcolor green
      back-to-base]
  ]    
end

to back-to-base  
  loop [
    ifelse  on-base?  [ stop ]
    [
     facexy 0 0
     fd 1
    ]
  ]
end
to-report on-base?
  report (xcor = 0 AND ycor = 0)
end

I also tried this for back-to-base procedure using while loop, but the problem remains unsolved.

to back-to-base1
 while [xcor != 0 AND ycor != 0]
      [
        facexy 0 0
        fd 1
        if xcor = 0 AND ycor = 0 
          [stop] 
    ]
end

Solution

  • Your basic issue is that you are using a while loop, which will run until it's satisfied. This means that once you have a turtle going back to base, it will appear to jump because it keeps moving until it's there. The easiest way to handle this sort of situation is to have a variable for each turtle that tracks whether it is going for gold, going for home or something else.

    So, first you need to create the variable for whether gold already found and set it to false when the miner is created:

    miners-own [gold-done?]
    
    to setup
      clear-all
      reset-ticks
      create-miners 1
      [ set size 1
        set heading random 360
        set gold-done? false        ; new line here
      ]
      create-bases 1 
      [ set size 1
      ]
      ask patches [set pcolor green]
      place-golds
    end
    

    Then you can modify your procedure where gold is found to trigger the return:

    to get-gold
      ask miners
      [ if pcolor = yellow
        [ set pcolor green
          set gold-done? true     ; new line here
        ]
      ]    
    end
    

    And your go procedure (which is what happens each unit of time) has the miners moving:

    to go
      ask miners with [ not gold-done? ]
      [ right random 360
        forward random 4
        get-gold
      ]
      ask miners with [ gold-done? ]
      [ face patch 0 0
        forward 1
      ]
      tick
    end
    

    You'll also need to do some code to check whether the destination is reached and what to do next.