As usual, create a directory to hold today's files. All programs that you write today should be stored in this directory.
$ cd ~/cs120/labs $ mkdir lab6 $ cd lab6
Functions are great for code reuse. A well written function can be used in many different programs.
In Emacs, create a Python program in a file called rectangle.py. Your program should use the turtle module to draw several rectangles on the turtle window.
Your program should define the function draw_rectangle(x, y,
width, height)
. The parameters x and y specify
the location to draw the rectangle on the screen. The width
parameter specifies the size of the rectangle in the x direction,
and the height parameter specifies the size of the
rectangle in the y direction.
>>> rectangle.draw_rectangle(x=0, y=0, width=10, height=25) >>> rectangle.draw_rectangle(x=10, y=15, width=15, height=5)
up
and down
Write a function to draw an octagon. The function should have parameters to specify the location and size of the octagon to draw. Use it to draw several octagons on the turtle screen.
A benefit of writing functions is that we can use them to simplify complex programs. For example, you now have a function written to draw a square. You can use that function to create another function that draws something with multiple squares. And you can use that function to create even more complex drawings.
In Emacs, create a Python program in a file called house.py. Your program should use the turtle module to draw a house in the turtle window.
You need at least two new functions: draw_triangle(x,
y, side_length)
and draw_house(x, y)
. Both of
these functions should have parameters to make drawing with these
functions easier.
>>> house.draw_house(-100, 0) >>> house.draw_house(100, 0)
Your draw_triangle
function needs parameters
for x, y, and side_length. Recall that
you can compute the height of the triangle using the
following equation:
$$h = \frac{l \cdot \sqrt{3}}{2}$$
draw_rectangle
function is simply passing the same value as the width and
height.
draw_rectangle
function. And obviously
the roof is drawn using your draw_triangle
function.
Your drawing probably looks pretty bland as of right now. However, you can easily add color to your drawings using the turtle module. Add color to at least the door and roof of the house, and add a green rectangle to the scene to represent grass.