Skip to article frontmatterSkip to article content

Creating and Controlling Turtles (20 min)

Let’s learn how to bring agents to life and give them instructions.

Bringing Agents to Life: create-turtles

The most basic command for creating a population:

create-turtles 100

This creates 100 turtles, each with:

Create specific numbers:

create-turtles 50    ; Create 50 turtles
create-turtles 200   ; Create 200 turtles

Giving Instructions to All or Some Agents: ask turtles

The ask command lets you give instructions to turtles:

Ask all turtles to do something:

ask turtles [
  forward 1           ; Every turtle moves forward
  set color red       ; Every turtle turns red
]

Ask specific turtles to do something:

ask turtle 0 [         ; Ask turtle #0 specifically
  set color blue
  set size 3
]

ask turtles with [color = red] [    ; Ask only red turtles
  forward 2
]

ask n-of 10 turtles [  ; Ask 10 randomly chosen turtles
  set color green
]

Basic Turtle Commands

Movement commands:

Property commands:

Try it yourself:

create-turtles 20 [
  setxy random-xcor random-ycor    ; Random position
  set color one-of [red blue green yellow]  ; Random color
]

ask turtles [
  right random 360    ; Turn random direction
  forward 3           ; Move forward
]

Activity 1: Build a Flock

Goal: Create turtles that move in the same direction

Step 1: Create the turtles

create-turtles 50 [
  setxy random-xcor random-ycor
  set color yellow
  set heading 90  ; All face east
]

Step 2: Make them move together

ask turtles [
  forward 1
]

Step 3: Run this repeatedly and watch your flock move across the screen!