For background information and how to get started with Snap! (formerly known as BYOB), click here for lesson 1.
This post is a departure from previous lessons. I’m not getting into my usual level of detail, but will share the blocks that make the magic happen. You will also find a short video demonstrating the blocks in action at the bottom of this post.
I was simply curious about the newer version of Snap! so decided to import an older project of mine and tweak it a bit. I figured I’d share it here if anyone is interested.
This project is an upright tree of varying levels and size. Each branch level produces smaller branches than the last. The example below is a level 6 tree of 100 size. The tree grows exponentially and gets really big really fast!
This project uses recursion, an advanced concept in computer science/programming. So it’s a huge jump from my previous lesson. If you’re interested in learning more about recursion, click here for the Wikipedia article. (I don’t recommend jumping ahead to recursion if you’re a true beginner but it wouldn’t hurt to check it out.)
Recursion is solving a problem’s solution in term’s of itself. Basically, it’s when you have a function that calls itself until it reaches a base case (e.g. a number reaching 0, an edge being touched, etc.) then gives back all the answers that were getting built up. It can get rather complicated – and I have geology to study – so I’ll leave you with a simple example.
Starting from main, whatever is returned from the function, sayNumbers, is printed to the console. For simplicity, I hardcoded the 5 as our input which is passed into the function. In the function, number is set to 5. If the number is 0, return 0 (end the function, go back to main). If not, then print the number (5) and pass the number minus 1 back into the sayNumbers (5 – 1 = 4). That is the recursive part. It keeps happening until that if statement (our base case) is true. Then everything that built up (4, 3, 2, 1, 0) is returned to main.
You can run the newest version of Snap! from this link.
I imported my old project.
Immediately, I noticed a new feature that would have made my previous tutorials much easier to write! You can capture images of any blocks! Boy, that would have saved me a LOT of screenshot and cropping time.
The stage is cleared, pen goes up, we go to a specific location and face up, pen goes down, then we go into the block pictured below:
Levels and size are the variables that change with user input. The recursion happens after every turn _ degrees. We take 1 away from the given level, then size goes down a notch, over and over again until there are no levels to pass.