Advancers – Recursion (Broccolli!)

Introduction

This week we created another drawing program using recursion, code that calls itself.

This drawing program will draw a Tree with 2 number of Branches, each Branch will split in 2 and be a little smaller than the previous Branches, The Branches will split X number of times. The finished picture will look something like this when X = 5:

Tree5

 

You can see that each branch splits into 2 new branches which are a little thinner and a little shorter than the previous branches, just like a real tree.

 

 

The Plan

Very simple plan for this one, we wanted to be able to control:

  1. the amount of branches
  2. how many degrees the split should be
  3. and what size the first branch would be

So we created a variable for each of these and left them on the Screen as a Slider. We set some minimum and Maximum values as well.

  1. Branches (1-10)
  2. Degrees (0-180)
  3. Size (30-100)

Sliders

The Code

As always we have some code that initialises everything when the Green Flag is clicked.

GreenFlag

 

We point upwards, we go to the middle of the bottom of the screen, clear everything, set the Pen colour and then call our code with the values from the Sliders.

Improvement : This should be “When Spacebar Pressed”, then we could just adjust the Sliders and then click the Spacebar to see the next tree.

 

The recursive code

This is the code that calls itself, because the Branching code is just the same thing repeated over and over again, but with slightly different values (the branches are getting smaller) it is ideal to use recursive code. You just need to remember that the code next to be able to finish.

CustomBlock

The code has two values sent in the number of branches and the size of the branches.

First thing we do is check to see if the number of branches is > 0 otherwise we exit, this is our way to finish the code.

We move (draw the branch), turn and then call ourself with slightly different values.

Just for a bit of variety we change the Pen colour each time as well.


Note: The code for 2019 is slightly different, the middle “turn” code is slightly simpler, we turn anticlockwise and we multiply by 2 not -2, so like this:

Turn01
Both will work as they both do the same thing.

This results in some quite nice Trees 🙂

SampleTree

Notes

The project that we built is available on the Scratch Web Site:

User Name : cdadvancers1819
Password : advancers

Project : ClassVersionRecursion (2018) and Tree-ClassVersion (2019)

Remember, you can put your own projects up there as well if you want.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s