Functions: There’s a Name for That 151
The final piece will be our for loop to generate 50 random
locations for the smiley faces and call the draw_smiley() function
to draw each face. It will look like this:
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)
Our random x- and y-coordinate values are just like those we
saw in Chapter 6, generating random points from the left half to the
right half of the screen, and from the bottom half to the top half.
With draw_smiley(x,y), we’re passing these random coordinates as
arguments to the draw_smiley() function, which will draw a smiley
at that random spot.
Putting It All Together
Put the program together, and it looks something like this:
RandomSmileys.py
import random
import turtle
t = turtle.Pen()
t.speed(0)
t.hideturtle()
turtle.bgcolor("black")
u def draw_smiley(x,y):
t.penup()
t.setpos(x,y)
t.pendown()
Head
t.pencolor("yellow")
t.fillcolor("yellow")
t.begin_fill()
t.circle(50)
t.end_fill()
Left eye
t.setpos(x-15, y+60)
t.fillcolor("blue")
t.begin_fill()
t.circle(10)
t.end_fill()