Drawing Houses
In the last lesson we learned that functions can be used to compute values and return them in our programs. Now we'll see how to use a function to draw lots of shapes in a program. When writing a function there are three things you should decide.
- What should my function be named?
- What information does my function need to do its job?
- What type of value will my function return?
Let's consider an example. What if we want to draw a square in the graphics window. We could write this as a function called drawSquare. It would need to be given a Turtle to draw with and an (x,y) coordinate so it knew where to draw it. To make it more useful we'll also give it a scale for the square. The scale can be used to produce squares of different sizes. We could pick 100 to be a full scale (scale = 1.0) square.
This results in the program given here.
In this program the random module is used to generate random numbers. Calling random.random() produces a random number between 0 and 1. So when this program is run, 100 squares appear in the graphics window of random size and at random locations on the screen. To use random we had to import random at the top of the program.
Now You Try It
Write a program that draws houses on the screen of random size and at random locations on the screen. Use the program above as a guide. Call your function drawHouse. Be sure to give it the correct parameters so the house can be drawn. You'll need all the same parameters that drawSquare used. Use the forward, left, and right commands like drawSquare used to draw the house. Multiply each forward value by scale so your houses can be scaled. You can color your house if you like. As a bare minimum your house should have a roof, a door, and a window.