|
Variables are places to store values (such as numbers). A variable can be a global variable, a turtle variable, or a patch variable.
If a variable is a global variable, there is only one value for the variable, and every agent can access it. But each turtle has its own value for every turtle variable, and each patch has its own value for every patch variable.
Some variables are built into NetLogo. For example, all turtles have a color variable, and all patches have a pcolor variable. (The patch variable begins with "p" so you won't get it confused with the turtle variable.) If you set the variable, the turtle or patch changes color. (See next section for details.)
Other predefined turtle variables including xcor,ycor, and heading. Other predefined patch variables include pxcor and pycor. (There is a complete list here.)
You can also define your own variables. You can make a global variable by adding a switch or a slider to your model, or by using the globals keyword at the beginning of your code, like this:
globals [ clock ]
You can also define new turtle and patch variables using the turtles-own and patches-own keywords, like this:
turtles-own [ energy speed ] patches-own [ friction ]
These variables can then be used freely in your model. Use the set command to set them. (If you don't set them, they'll start out storing a value of zero.)
Global variables can by read and set at any time by any agent. As well, a turtle can read and set patch variables of the patch it is standing on. For example, this code:
ask turtles [ set pcolor red ]
causes every turtle to make the patch it is standing on red.
In other situations where you want an agent to read or set a different agent's variable, you put -of after the variable name and then specify which agent you mean. Examples:
set color-of turtle 5 red ;; turtle with ID number 5 turns red set pcolor-of patch 2 3 green ;; patch with pxcor of 2 and pycor of 3 turns green ask turtles [ set pcolor-of patch-at 1 0 blue ] ;; every turtle turns the patch to its east blue ask patches with [any turtles-here] [ set color-of random-one-of turtles-here yellow ] ;; on every patch, a random turtle turns yellow
|