Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Functions: There’s a Name for That 147

sitting on the (x, y) location, so picture moving this smiley face
template around by placing its origin (0, 0) over any other point
(x, y) on the screen. Let’s figure out how to draw each smiley face
starting from a given point.


Drawing a head


Each smiley face has a yellow circle for the head, two small blue
circles for eyes, and some black lines for the mouth. Given a point
on the screen, our draw_smiley() function will need to draw a head,
eyes, and a mouth at the correct positions relative to the given
point. To figure out the code that will go in our function definition,
let’s plan the head, eyes, and mouth separately, starting with the
head. We’ll draw the head first so that it doesn’t cover the eyes and
mouth we’ll draw next.
We’ll count each grid line in Figure 7-1 as 10 pixels, so the
smiley we’ve drawn would measure 100 pixels tall; that will equal
around an inch, give or take, on most computer screens. Since
the diameter, or height and width, of the circle is 100 pixels, that
means it has a radius (one-half the diameter) of 50 pixels. We
need the radius because the turtle module’s circle() command
takes the radius as its parameter. The command to draw a circle
with a radius of 50 (which makes a diameter of 100) is t.circle(50).
The circle() function draws a circle directly above the turtle’s cur-
rent (x, y) location. We’ll need to know this to correctly place the
eyes and mouth, so I’ve drawn my smiley face with the bottom
edge resting on the origin, (0, 0). We can figure out where we
need to draw everything else by adding the coordinates of each
part to that starting (x, y) location of (0, 0).
To draw the big yellow head, we’ll make the pen color yellow,
make the fill color yellow, turn on the paint fill for our shape, draw
the circle (which gets filled with yellow because we turned on the
paint fill), and turn off the paint fill when we’re done. Assuming
we have a turtle pen named t defined earlier in the program, the
code to draw the yellow circle as the head of our smiley face at the
current (x, y) location looks like this:


Head


t.pencolor("yellow")
t.fillcolor("yellow")
t.begin_fill()
t.circle(50)
t.end_fill()

Free download pdf