Agentscript is an open source javascript library for writing agent-based models. It is inspired by a programming language called Netlogo.
In Agentscript, you fill a world with three ingredients: turtles, patches, and links.
Your program describes the behavior of each of these actors and how they interact with each other. Let's see an example.
Here's an empty world to start out with:
First things first, let's make a turtle:
Click the "run once" button to execute that code once.
You'll see a turtle appear in the center of the world. It has the shape of a chevron.
This tutorial assumes you have a little familiarity with javascript. If you have never seen javascript before, or if you want a refresher, try out this interactive tutorial: Javascript in 14 Minutes.
Now that we have a turtle, we can ask it do something, like move forward:
If you are familiar with javascript, it may help to know that turtles.ask()
has the same meaning as turtles.forEach()
.
If you keep telling a turtle to move forward, it will eventually hit the edge of the world and wrap around to the other side!
We can also ask turtles to rotate:
Or both — move forward and rotate:
Try changing one of the numbers in the above code so that the turtle makes smaller steps, or bigger turns.
Instead of working one step at a time, things get really interesting when you run a behavior over and over again.
I added a "run forever" button to the code snippet above. Try it out!
How about a little randomness? Here's the same code, as before, but this time using util.randomInt()
to pick a random angle to turn to the right and to the left. The result is turtles that wander randomly around the world:
If you haven't already, try adding a bunch more turtles!
The world where the turtles live and move is divided up into a bunch of small squares called patches.
A turtle always knows what patch it's on — this is stored in turtle.patch
.
Right now, all the patches are black, which is why the world behind the turtles looks like a big black square.
Let's pretend like our turtles are ants, and they are dropping chemical pheromones everywhere they walk (this is in fact how ants communicate!)
The landscape is now filling up with pheromones!
I set up the patches ahead of time so that their color depends on how much pheromone they have. This is the color scale I'm using:
Try changing the number or names of the colors in the code block above.
The size and number of patches that make up the world can also be configured — we'll look at how to edit that later.
Now let's make the pheromone evaporate over time:
This is fun, but we're running out of room in these little code blocks. It's time for the real deal.