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

(vip2019) #1

152 Chapter 7


# Right eye
t.setpos(x+15, y+60)
t.begin_fill()
t.circle(10)
t.end_fill()
# Mouth
t.setpos(x-25, y+40)
t.pencolor("black")
t.width(10)
t.goto(x-10, y+20)
t.goto(x+10, y+20)
t.goto(x+25, y+40)
t.width(1)
v for n in range(50):
x = random.randrange(-turtle.window_width()//2,
turtle.window_width()//2)
y = random.randrange(-turtle.window_height()//2,
turtle.window_height()//2)
draw_smiley(x,y)

As usual, we import the modules we need and set up our turtle,
setting its speed to 0 (the fastest). We use hideturtle() so the turtle
itself doesn’t show up on the screen; this speeds up drawing too.
At u, we define our draw_smiley() function so that its job is to
draw the smiley’s face, left eye, right eye, and smile, using all that
code we wrote before. All it needs to do its job is an x-coordinate
and a y-coordinate.
In our for loop at v, a random x and y are chosen and passed
to draw_smiley(), which then draws a smiley with all features in the
correct locations relative to that random point.
The RandomSmileys.py program will draw 50 smiley faces at
random positions on the drawing screen, as shown in Figure 7-2.
You can customize the program to draw just about any shape
you want, as long as you design a function to draw that shape
starting from any (x, y) location. Start with graph paper like we
did in this example to make it easier to find the important points.
If it bothers you that some of the smiley faces are halfway off the
screen on the left and right, or almost all the way off the screen
at the top, you can use a bit of math in the x and y randrange()
statements to keep your smileys completely on the screen. Go to
http://www.nostarch.com/teachkids/ for a sample answer to this
challenge.
Free download pdf