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

(vip2019) #1

170 Chapter 7


This function takes the parameters x and y for the location to
start drawing each spiral, and the parameter size to tell us how
big to make the spiral. Inside the function, we lift the turtle’s pen
so that we can move without leaving a trail, we move the pen to
the given (x, y) location, and we put the pen back down to prepare
for the spiral. Our for loop will iterate m over the values from 0 to
size, drawing a square spiral up to that side length.
All we’ll have to do in our program, besides importing random
and turtle and setting up our screen and list of colors, is tell the
computer to listen for clicks on the turtle screen and call the draw_
kaleido() function whenever a click event happens. We can do that
with the command turtle.onscreenclick(draw_kaleido).

Putting It All Together


Here’s the full ClickKaleidoscope.py program. Type it in IDLE or
download it from http://www.nostarch.com/teachkids/ and run it.
ClickKaleidoscope.py

import random
import turtle
t = turtle.Pen()
t.speed(0)
t.hideturtle()
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green", "orange", "purple",
"white", "gray"]
def draw_kaleido(x,y):
t.pencolor(random.choice(colors))
size = random.randint(10,40)
draw_spiral(x,y, size)
draw_spiral(-x,y, size)
draw_spiral(-x,-y, size)
draw_spiral(x,-y, size)
def draw_spiral(x,y, size):
t.penup()
t.setpos(x,y)
t.pendown()
for m in range(size):
t.forward(m*2)
t.left(92)
turtle.onscreenclick(draw_kaleido)

We begin with our normal import statements and then set
up our turtle environment and list of colors. Next, we define our
Free download pdf