3. Giving Your Turtle a Mind of Its Own: Logic and Decision-Making
- Giving Your Turtle a Mind of Its Own: Logic and Decision-Making
To create truly dynamic programs, you need to give the turtle the ability to make choices. Decision-making allows a program to change its behavior based on a specific condition, leading to results that can be different every time you run the code.
Making a Simple Choice with
The if statement is the most basic form of decision-making. It works like a simple question: “If a certain condition is true, then run this specific block of commands.”
A fun way to see this in action is to create a “random walk,” where the turtle decides its path randomly at each step. The random 3 command generates a number that is either 0, 1, or 2. We can use an if statement to check that number and tell the turtle what to do.
make “r random 3
if :r = 0 [fd 20]
if :r = 1 [rt 90 fd 20]
if :r = 2 [lt 90 fd 20]
This logic works as follows:
- If the random number is 0, the turtle moves forward.
- If the random number is 1, the turtle turns right and moves forward.
- If the random number is 2, the turtle turns left and moves forward.
Key Insight: By putting this logic inside a procedure and repeating it, you give the turtle a “choice” at every step. Each time you run the program, the turtle will draw a completely unique path, all because it can make simple decisions.
Repeating with a Condition using
The repeat command is great, but it’s like telling someone to take exactly 10 steps. The while loop is different; it’s like telling them to keep walking until they reach the wall. You don’t need to know how many steps it will take, only the condition for stopping. A while loop repeats commands as long as a certain condition remains true.
Consider this procedure for drawing a spiral that grows larger with each turn:
to spiral
make “n 1
while [:n < 100] [
make “n :n + 5
fd :n
rt 90
]
end
Here is a step-by-step breakdown of the logic:
- A variable :n is created and set to an initial value of 1.
- The while loop checks its condition: is the value of :n less than 100? Since 1 is less than 100, the commands inside the brackets run.
- First, :n is increased by 5. Its value is now 6.
- Next, the turtle moves forward by the new amount in :n (6 units) and turns right.
- The loop repeats, checking the condition again. Since 6 is still less than 100, it runs again: :n becomes 11, the turtle moves forward 11 units, and so on. This continues until :n is no longer less than 100, at which point the spiral stops growing.
Key Insight: Notice how the two key actions inside the loop—moving forward by an increasing amount (fd :n) and turning by a constant amount (rt 90)—work together. The growing step length pushes the turtle further out on each pass, while the consistent turn shapes its path into an elegant spiral.