In Tutorial #2, you learned how to use the command center and agent monitors to
inspect and modify agents and make them do things. Now you’re ready to learn
about the real heart of a NetLogo model: the Code tab.

You’ve seen that agents in NetLogo are divided into patches, turtles, links, and
the observer. Patches are stationary and arranged in a grid. Turtles move over
that grid. Links connect two turtles. The observer oversees everything that’s
going on and does whatever the turtles, patches and links can’t do for
themselves.

All four types of agents can run NetLogo commands. All four can also run
“procedures”. A procedure combines a series of NetLogo commands into a single
new command that you define.

You will now learn to write procedures that make turtles move, eat, reproduce,
and die. You will also learn how to make monitors, sliders, and plots. The model
we’ll build is a simple ecosystem model not unlike Wolf Sheep Predation from
Tutorial #1.

To start a new model, select “New” from the File menu. Then begin by creating a
setup button:

Click the “Add” icon in the toolbar at the top of the Interface tab.

On the menu next to Add, select Button (if it isn’t already selected).

Click wherever you want the button to appear in the empty white area of the
Interface tab.

A dialog box for editing the button opens. Type setup in the box labeled
“Commands”.

Press the OK button when you’re done; the dialog box closes.

Now you have a setup button. Pressing the button runs a procedure called
“setup”. A procedure is a sequence of NetLogo commands that we assign a new
name. We’ll define that procedure soon, but we haven’t yet. The button refers to
a procedure that doesn’t exist, so the button turns red:

If you want to see the actual error message, click the button.

Now we’ll create the “setup” procedure, so the error message will go away:

Note that some lines are indented. Most people find it helpful to indent their
code. It isn’t mandatory, but it makes the code easier to read and change.

Your procedure begins with to and ends with end. Every procedure begins
and ends with these words.

Let’s look at what you typed in and see what each line of your procedure does:

to setup begins defining a procedure named “setup”.

clear-all resets the world to an initial, empty state. All the patches
turn black and any turtles you might have created disappear. Basically, it
wipes the slate clean for a new model run.

create-turtles 100 creates 100 turtles. They start out standing at the
origin, that is, the center of patch 0,0.

After create-turtles we can put commands for the new turtles to run,
enclosed by square brackets.

setxy random-xcor random-ycor is a command using “reporters”. A reporter, as
opposed to a command, reports a result. First each turtle runs the reporter
random-xcor which will report a random number from the
allowable range of turtle coordinates along the X axis. Then each turtle runs
the reporter random-ycor, same for the Y axis. Finally each
turtle runs the setxy command with those two numbers as inputs. That makes
the turtle move to the point with those coordinates.

reset-ticks starts the tick counter, now that setup is otherwise complete.

When you’re done typing, switch to the Interface tab and press the setup button
you made before. You will see the turtles scattered around the world:

Press setup a couple more times, and see how the arrangement of turtles is
different each time. Note that some turtles may be right on top of each other.

Think a bit about what you needed to do to make this happen. You needed to make
a button in the interface and make a procedure that the button uses. The button
only worked once you completed both of these separate steps. In the remainder of
this tutorial, you will often have to complete two or more similar steps to add
another feature to the model. If something doesn’t appear to work after you
completed what you thought is the final step for that new feature, continue to
read ahead to see if there is still more to do. After reading ahead for a couple
of paragraphs, you should then go back over the directions to see if there is
any step you might have missed.

But what is move-turtles? Is it a primitive (in other words, built-in to
NetLogo)? No, it’s another procedure that you’re about to add. So far, you have
introduced two procedures that you added yourself: setup and go.

Note there are no spaces around the hyphen in move-turtles. In Tutorial #2 we
used red - 2, with spaces, in order to subtract two numbers, but here we want
move-turtles, without spaces. The “-” combines “move” and “turtles” into a
single name.

Here is what each command in the move-turtles procedure does:

ask turtles [ ... ] says that each turtle should run the commands in the
brackets.

right random 360 is another command that uses a reporter. First, each turtle
picks a random whole number between 0 and 359.
(random doesn’t include the number you give it as a possible result.) Then
the turtle turns right this number of degrees.

forward 1 makes the turtle move forward one step.

Why couldn’t we have just written all of these commands in go instead of in a
separate procedure? We could have, but during the course of building your
project, it’s likely that you’ll add many other parts. We’d like to keep go as
simple as possible, so that it is easy to understand. Eventually, it will
include many other things you want to have happen as the model runs, such as
calculating something or plotting the results. Each of these things to do will
have its own procedure and each procedure will have its own unique name.

The ‘go’ button you made in the Interface tab is a forever button, meaning that
it will continually run its commands until you shut it off (by clicking on it
again). After you have pressed ‘setup’ once, to create the turtles, press the
‘go’ button. Watch what happens. Turn it off, and you’ll see that all the
turtles stop in their tracks.

Note that if a turtle moves off the edge of the world, it “wraps”, that is, it
appears on the other side. (This is the default behavior. It can be changed; see
the Topology section of the Programming Guide for
more information.)

Type commands into the Command Center (like turtles> set color red), or add
commands to setup, go, or move-turtles.

Note that when you enter commands in the Command Center, you must choose
turtles>, patches>, links>, or observer> in the popup menu on the left,
depending on which agents are going to run the commands. It’s just like using
ask turtles or ask patches, but saves typing. You can also use the tab key
to switch agent types, which you might find more convenient than using the menu.

You might try typing turtles>pen-down into the Command Center and then
pressing the go button.

Also, inside the move-turtles procedure you can try changing
right random 360 to right random 45.

Play around. It’s easy and the results are immediate and visible – one of
NetLogo’s many strengths.

When you feel you’ve done enough experimenting for now, you’re ready to continue
improving the model you are building.

Now we’ve got 100 turtles aimlessly moving around, completely unaware of
anything else around them. Let’s make things a little more interesting by giving
these turtles a nice background against which to move.

Go back to the setup procedure. We can rewrite it as follows:

to setup
clear-all
setup-patches
setup-turtles
reset-ticks
end

The new definition of setup refers to two new procedures. To define
setup-patches, add this:

to setup-patches
ask patches [ set pcolor green ]
end

The setup-patches procedure sets the color of every patch to green to start
with. (A turtle’s color variable is color; a patch’s is pcolor.)

The only part remaining in our new ‘setup’ that is still undefined is
setup-turtles.

We are using the if command for the first time. Look at the code carefully.
Each turtle, when it runs these commands, compares the value of the patch color
it is on (pcolor) to the value for green. (A turtle has direct access to
the variables of the patch it is standing on.) If the patch color is green, the
comparison reports true, and only then will the turtle run the commands inside
the brackets (otherwise it skips them). The commands make the turtle change the
patch color to black and increase its own energy by 10. The patch turns black to
signify that the grass at that spot has been eaten. And the turtle is given more
energy, from having just eaten.

Next, let’s make the movement of turtles use up some of the turtle’s energy.

Here we’re using count again to see how many agents are in an agentset.
patches is the set of all the patches, but we don’t just want to know how
many patches there are total, we want to know how many of them are green. That’s
what with does; it makes a smaller agentset of just those agents for whom
the condition in the brackets is true. The condition is pcolor = green, so
that gives us just the green patches.

Now we have two monitors that will report how many turtles and green patches we
have, to help us track what’s going on in our model. As the model runs, the
numbers in the monitors will automatically change.

Use the setup and go buttons and watch the numbers in the monitors change.

The eat-grass procedure introduces the ifelse command. Look at the code
carefully. Each turtle, when it runs these new commands, checks the value of
show-energy? (determined by the switch). If the switch is on, comparison is
true and the turtle will run the commands inside the first set of brackets. In
this case, it assigns the value for the energy to the label of the turtle. If
the comparison is false (the switch is off) then the turtle runs the commands
inside the second set of brackets. In this case, it removes the text labels (by
setting the label of the turtle to be nothing).

(In NetLogo, a piece of text is called a “string”, short for string of
characters. A string is a sequence of letters or other characters, written
between double quotes. Here we have two double quotes right next to each other,
with nothing in between them. That’s an empty string. If a turtle’s label is an
empty string, no text is attached to the turtle.)

Test this in the Interface tab, by running the model (using the setup and go
buttons) switching the show-energy? switch back and forth.

When the switch is on, you’ll see the energy of each turtle go up each time it
eats grass. You’ll also see its energy going down whenever it moves.

Now our turtles are eating. Let’s make them reproduce and die, too. And let’s
make the grass grow back. We’ll add all three of these of these behaviors now,
by making three separate procedures, one for each behavior.

Each of these procedures uses the if command. Each turtle, when it runs
check-death it will check to see if its energy is less or equal to 0. If this
is true, then the turtle is told to die (die is a NetLogo primitive).

When each turtle runs reproduce, it checks the value of the turtle’s energy
variable. If it is greater than 50, then the turtle runs the commands inside the
first set of brackets. In this case, it decreases the turtle’s energy by 50,
then ‘hatches’ a new turtle with an energy of 50. The hatch command is a
NetLogo primitive which looks like this: hatchnumber [ commands ]. This
turtle creates number new turtles, each identical to its parent, and asks the
new turtle(s) that have been hatched to run commands. You can use the commands
to give the new turtles different colors, headings, or whatever. In our case we
run one command. We set the energy for the newly hatched turtle to be 50.

When each patch runs regrow-grass it will check to see if a random integer
from 0 to 99 is less than 3. If so, the patch color is set to green. This will
happen 3% of the time (on average) for each patch, since there are three numbers
(0, 1, and 2) out of 100 possible that are less than 3.

Switch to the Interface tab now and press the setup and go buttons.

You should see some interesting behavior in your model now. Some turtles die
off, some new turtles are created (hatched), and some grass grows back. This is
exactly what we set out to do.

If you continue to watch your monitors in your model, you will see that the
count turtles and green patches monitors both fluctuate. Is this pattern
of fluctuation predictable? Is there a relationship between the variables?

It’d be nice if we had a easier way to track the changes in the model behavior
over time. NetLogo allows us to plot data as we go along. That will be our next
step.

Note that when you create the plot you can also set the minimum and maximum
values on the X and Y axes. You’ll want to leave the “Auto Scale” checkbox
checked, so that if anything you plot exceeds the minimum and maximum values for
the axes, the axes will automatically grow so you can see all the data.

Note that we used the plot command to add the next point to a plot. This
command moves the current plot pen to the point that has an X coordinate equal
to 1 greater than the previously plotted X coordinate and a Y coordinate equal
to the value given in the plot command (in the first case, the number of
turtles, and in the second case, the number of green patches). As the pens move
they each draw a line.

Setup and run the model again.

You can now watch the plot being drawn as the model is running. Your plot should
have the general shape of the one below, though your plot might not look exactly
the same.

Remember that we left “Auto Scale?” on. This allows the plot to readjust itself
when it runs out of room.

If you forget which pen is which, you can edit the plot and check the
“Show legend?” checkbox.

You might try running the model several times to see what aspects of the plot
are the same and which are different from run to run.

To make comparisons between plots from one model run and another, it is often
useful to do the comparison for the same length of model run. Learning how to
stop or start an action at a specific time can help make this happen by stopping
the model at the same point each model run. Keeping track of how many times the
go procedure is run is a useful way to cue these actions. That’s what the tick
counter does.

You’re already using the tick counter in your model, with the reset-ticks and
tick commands, which also trigger plotting.

You can also use the tick counter for other things, such as to set a limit on
the total length of a run.

The graph and model won’t keep running forever. They should stop automatically
when the tick counter in the Interface tab’s toolbar reaches 500.

The tick command advances the tick counter by 1. ticks is a reporter
which reports the current value of the tick counter. reset-ticks, in your
setup procedure, takes care of restarting the tick counter at 0 when a new run
is set up and ready to begin.

Finally, what other slider could you add to vary how often grass grows back? Are
there rules you can add to the movement of the turtles or to the newly hatched
turtles that happen only at certain times? Try writing them.

So now you have a simple model of an ecosystem. Patches grow grass. Turtles
wander, eat the grass, reproduce, and die.

You have created an interface containing buttons, sliders, switches, monitors,
and a plot. You’ve even written a series of procedures to give the turtles
something to do.

That’s where this tutorial leaves off.

If you’d like to look at some more documentation about NetLogo, the
Interface Guide section of the manual walks you through every
element of the NetLogo interface in order and explains its function. For a
detailed description and specifics about writing procedures, refer to the
Programming Guide. All of the primitives are listed and
described in the NetLogo Dictionary.

Also, you can continue experimenting with and expanding this model if you’d
like, experimenting with different variables and behaviors for the agents.

Alternatively, you may want to revisit the first model in the tutorial, Wolf
Sheep Predation. This is the model you used in Tutorial #1. In the Wolf Sheep
Predation model, you saw sheep move around, consume resources that are
replenished occasionally (grass), reproduce under certain conditions, and die if
they ran out of resources. But that model had another type of creature moving
around – wolves. The addition of wolves requires some additional procedures and
some new primitives. Wolves and sheep are two different “breeds” of turtle. To
see how to use breeds, study Wolf Sheep Predation.

Alternatively, you can look at other models (including the many models in the
Code Examples section of the Models Library) or even go ahead and build your own
model. You don’t even have to model anything. It can be interesting just to
watch patches and turtles forming patterns, to try to create a game to play, or
whatever.

Hopefully you have learned some things, both in terms of the NetLogo language
and about how to go about building a model. The entire set of procedures that
was created above is shown below.

The complete model is also available in NetLogo’s Models Library, in the Code
Examples section. It’s called “Tutorial 3”.

Notice that this listing is full of “comments”, which begin with semicolons.
Comments let you mix an explanation the code right in with the code itself. You
might use comments to help others understand your model, or you might use them
as notes to yourself.

In the Code tab, comments are gray, so your eyes can pick them out easily.

turtles-own [energy] ;; for keeping track of when the turtle is ready
;; to reproduce and when it will die
to setup
clear-all
setup-patches
setup-turtles
reset-ticks
end
to setup-patches
ask patches [ set pcolor green ]
end
to setup-turtles
create-turtles number ;; uses the value of the number slider to create turtles
ask turtles [ setxy random-xcor random-ycor ]
end
to go
if ticks >= 500 [ stop ] ;; stop after 500 ticks
move-turtles
eat-grass
check-death
reproduce
regrow-grass
tick ;; increase the tick counter by 1 each time through
end
to move-turtles
ask turtles [
right random 360
forward 1
set energy energy - 1 ;; when the turtle moves it looses one unit of energy
]
end
to eat-grass
ask turtles [
if pcolor = green [
set pcolor black
;; the value of energy-from-grass slider is added to energy
set energy energy + energy-from-grass
]
ifelse show-energy?
[ set label energy ] ;; the label is set to be the value of the energy
[ set label "" ] ;; the label is set to an empty text value
]
end
to reproduce
ask turtles [
if energy > birth-energy [
set energy energy - birth-energy ;; take away birth-energy to give birth
hatch 1 [ set energy birth-energy ] ;; give this birth-energy to the offspring
]
]
end
to check-death
ask turtles [
if energy <= 0 [ die ] ;; removes the turtle if it has no energy left
]
end
to regrow-grass
ask patches [ ;; 3 out of 100 times, the patch color is set to green
if random 100 < 3 [ set pcolor green ]
]
end