Custom Functions!
Goals:
- Write functions to facilitate code reuse, simplify code maintenance, and improve readability of your code
Coding Snippets:
- Coffeescript uses the syntax
()-
> to define custom functions. - Save a function by assigning it a variable name, using the assignment operator,
=
. - The function
genericHello
doesn't have any arguments. HoweverspecificHello
has the argumentname
, which is a variable that can be referenced anywhere within the body of thespecificHello
definition.
Math and Computer Concepts:
- Functions facilitate code reuse: using functions, a block of code can be used repeatedly by simply calling the function, rather than having to write all the individual lines of code over and over again.
- Variables defined outside of a custom function can be referenced in the body of that function. This includes variables that reference other functions, such as
label
, as illustrated above. - Arguments to functions are special variables that can only be referenced within the body of that particular function. For example,
name
cannot be referenced anywhere outside of the definition ofspecificHello
.
Activities:
Save each of the following in a folder called CustomFunctions.
- Squares: Define a function called
drawSquare
that draws a square centered on the current position of the turtle, oriented in the direction it is facing. The turtle should return to its original position after drawing the square. After defining and testing your function, call it repeatedly using iteration to draw a spirograph or some other design. - In a program named RandomCity, write a function
drawHouse
that instructs the turtle to draw a house based on its current location. Then add functionsdrawTower
anddrawStreet
, which should instruct the turtle to draw a simple apartment building and a horizontal street, respectively. Define arguments to provide the function caller with control over drawing features, such as number of floors, color, and size. Lastly, write a loop to create a city with at least three streets and randomly-placed buildings. - Oval: Pencil Code does not provide a function to create an oval, so we should create our own, called
drawOval
. A basic oval can be designed using quarter turns of two sizes, one with a radius twice as big as the other (as illustrated below).