21. Smarter, not harder
One of the most awesome aspects of programming is creating code that is elegant and saves you time. In our lessons so far we have created a few nifty procedures, and used a few variables. In this lesson we are going to make a procedure that is adjustable... because of those variables. Lets clear the screen and begin.
type cs (another smarter, not harder trick is using the shortcut for clearscreen)
The hard way. Lets start by doing things to old fashioned way. Make a rectangle on your screen Make a 50 by 70 rectangle using the fd and right commands on your screen
You will start with fd 50, then rt 90 (more shortcuts)
fd 50 rt 90 fd 70 rt 90 fd 50 rt 90 fd 70 rt 90
Repeat after me... Can you think of anything else we could have done to shorten the code we just used? Was anything repetitive? Lets try the command again
Remember you type repeat followed by the number of times you want it to happen, and the place the it in the square brackets. For a rectangle it should start like this. repeat 2[fd 50 rt 90.... Can you finish it?
repeat 2 [fd 50 rt 90 fd 70 rt 90]
What about those variables I mentioned? Do the words Width and Length come to mind? When we learned about variables earlier we used the make command. Lets do the same here Make a variable :W = 50 and a :L = 70
this will take 2 lines of code. first type Make "w 50 and press enter. Do the same thing for the variable "l but with 70
Make "w 50 Make "L 70
Now lets put that in our old repeat formula The only catch is we change the original numbers to variables
Start by typing repeat 2 [fd :W rt 90...
repeat 2 [fd :W rt 90 fd :L rt 90]
This is where the true power comes into play. We need to make it a procedure. I am going to choose the name rec because it is short and sweet. We want it to draw a custom rectangle each time, so we need to "ask" Create the new rec procedure
start with... to rec :W :L repeat 2 [
to rec :W :L repeat 2 [fd :W rt 90 fd :L rt 90] end
This is the fun part. You now have the ability to make any rectangle by simply calling the procedure rec and typing 2 numbers after it. See if you can draw a 60 by 10 rectangle
type rec followed by the numbers 60 and 10
rec 60 10