Drawing snowflakes with recursion
Page 20On the previous page we used recursion for the first time. Recursion is when words call themselves. On this page they will call themselves three times.
On this page we'll draw a snowflake with recursion. It's tricky, but it's a very beautiful snowflake. It will look like this:
IF :d = 0 [FD :x STOP] ; the stop condition
KOCH :x/3 :d-1 ; the call
LT 60 ; the action
KOCH :x/3 :d-1 ; the call
RT 120 ; the action
KOCH :x/3 :d-1 ; the call
LT 60 ; the action
KOCH :x/3 :d-1 ; the call
END
TO SNOWFLAKE :x :d
REPEAT 3 [KOCH :x :d RT 120]
END
There are two words: SNOWFLAKE and KOCH. SNOWFLAKE needs KOCH to work. But KOCH doesn't need SNOWFLAKE. They both need two parameters. The first is the size. The second is how detailed they should be. What does that mean? You'll see when you try them.
Try either KOCH or SNOWFLAKE first with 200 and 0 as parameters. Then with 200 and 1. Then with 200 and 2. (You can tell the turtle to CS between them.)
Try to Think Turtle with SNOWFLAKE 200 0 and SNOWFLAKE 200 1. Can you figure out how it works? It's ok if you can't. But you can try!
Why is one of these words called KOCH? We can use any name we want to. I used KOCH because there was once a man named Koch. He drew this shape before anybody else did.
These are the words we know now. They are the same as on the last page:
| Logo word | What it means |
|---|---|
| FD 100 | Walk forward 100 steps |
| BK 100 | Walk backward 100 steps |
| LT 90 | Turn left (good for drawing squares) |
| RT 90 | Turn right (good for drawing squares) |
| LT 120 | Turn left (good for drawing triangles) |
| RT 120 | Turn right (good for drawing triangles) |
| CS | Remove everything you have drawn |
| HOME | Move back to the starting point (and draw a line) |
| PU | Lift the pen so you won't draw when you walk |
| PD | Put the pen towards the screen again | REPEAT 10 [ ] | Repeat what's in the box 10 times |
| SETPC 4 | Change the pen to pen number 4 | TO ... END | Remember the word after TO in the future |
| ; | Don't listen to me now | PRINT [I'm a turtle!] | Say "I'm a turtle!" |
| RANDOM 10 | Choose a number from 0 to 9 | WAIT 60 | Wait for 1 second. |
| PRINT 2+2 | Makes the turtle say 4 | TO SQUARE :top | Put 5 in your :top pocket when I say SQUARE 5 |
| REPCOUNT | The number of the repetition | IF ( ) [ ] | Is ( ) true? Then do [ ] |
| IFELSE ( ) [ ] [ ] | Is ( ) true? Then do the first [ ]. Otherwise do the second [ ] |
These are the words we have taught the turtle. KOCH and SNOWFLAKE are new:
| New Logo word | What it means |
|---|---|
| SQUARE :top | Draw a square |
| CIRCLE :x :size | Draw a circle |
| STAR :number :length | Draw a star |
| LEAF | Draw a leaf | BLOOM | Draw a bloom |
| KOCH :x :d | Draw the strange KOCH shape | SNOWFLAKE :x :d | Draw a snowflake |
Turn page, or back to the table of contents.