168 Chapter 7
Whatever kinds of apps you want to build, you’re probably going
to rely on user interaction to drive the experience. Think of the
games or other apps that you spend the most time playing: what
they all have in common is that you have some kind of control over
what happens and when. Whether you’re moving a paddle to hit a
ball; pressing the mouse button or touching and dragging to fire
something through the air; or clicking, swiping, and tapping to clear
a screen, you’re generating user events—and the programs you love
handle those events by doing something cool. Let’s build one more
interactive app for practice, and then we’ll build even more of the
kinds of apps we play with every day.
c ickKaleidoscopel
Let’s combine our ability to create functions and our ability to
handle interactive clicks to create an interactive kaleidoscope.
The user will be able to click anywhere on the screen, and four
reflected spirals of a random shape and color will be drawn start-
ing from the point where the user clicked. The result will look like
our Kaleidoscope.py program from page 134, but the user will be
able to create their own unique patterns using this kaleidoscope.
The draw_kaleido() Function
Let’s talk about the challenges in building a customized kalei-
doscope program. We know we want to allow the user to click
the screen to begin the drawing process, so we’ll use the turtle
.onscreenclick() function from the previous section. We know that
this function will give us an (x, y) location on the screen that we
can use in our callback function. And we can look back at our orig-
inal kaleidoscope program to see that all we have to do is draw a
spiral at each of the four points (x, y), (–x, y), (–x, –y), and (x, –y) to
achieve the desired reflection effect.
Each of our four reflected spirals should be the same color and
size to create the mirror illusion. We will call our function draw_
kaleido() and define it as follows:
u def draw_kaleido(x,y):
v t.pencolor(random.choice(colors))
w size = random.randint(10,40)
draw_spiral(x,y, size)