netlogo

How to Stop a simulation with a button in Netlogo


I have my go function set to forever and I want to create a button that says stop to stop the simulation as i noticed that peers running the model dont press the go button again to stop it. However, the button with the stop primitive is not stoping the run.

Is it possible to do this?


Solution

  • One way is to use a variable to store a "flag" to indicate whether running should continue. In the example below, I've called it should-stop?. You can then reference that flag somewhere in your go procedure to call stop. In the example below, I evaluate whether should-stop? is true at the start of every call to go:

    globals [ should-stop? ]
    
    to setup
      ca
      crt 20
      set should-stop? false
      reset-ticks
    end
    
    to go 
      if should-stop? [
        stop
      ]
      ask turtles [ 
        rt random 60 - 30 
        fd 1
      ]
      tick
    end
    

    Then, you can set up a stop button that has the code set should-stop? true

    Example 'Stop!' button code

    That way, when your user clicks your stop button, the condition if should-stop? will evaluate to true and the forever go button will stop.

    See the page on buttons for more information.