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

(vip2019) #1

116 Chapter 6


to draw each line of the spiral. For m in range(size), the turtle will
move forward a distance of m*2, drawing a line segment of length
m*2 (m is 0 , 1 , 2 , 3 , and so on, so the length of the segment is 0, 2,
4, 6, and so on). The turtle will then rotate left 91 degrees and get
ready to draw the next segment.
The turtle starts in the center of the spiral, draws a segment
(length 0), and rotates left; that’s the first time through the loop.
The next time through, m is 1 , so the turtle draws a segment of
length 2, then rotates. As Python iterates through the loop, the
turtle will move outward from the center of the spiral, drawing
longer and longer line segments. We use the randomly generated
size, an integer between 10 and 40, as the number of lines we draw
in our spiral.
After we finish drawing the current spiral, we go back to the
top of our outer for loop. We pick a new random color, size, and
location; lift the pen; move it to the new location; put down the pen;
and go through the inner for loop to draw a new spiral of some new
random size. After drawing this spiral, we go back to the outer
loop and repeat the entire process. We do this 50 times, giving us
50 spirals of assorted colors and shapes spread randomly across
the screen.

Rock-Paper-Scissors


One game that we have the skills to program now is Rock-Paper-
Scissors. Two players (or one player and the computer) each pick
one of three possible items (rock, paper, or scissors); both show
their choice; and the winner is decided by three rules: rock crushes
scissors, scissors cut paper, paper covers rock.
To simulate this game, we’ll create a list of choices (like our
colors list in RandomSpirals.py) and we’ll use random.choice() to pick
one of the three items from the list as the computer’s choice. Then,
we’ll ask the user for their choice and use a series of if statements
to determine the winner. The user will be playing against the
computer!
Let’s jump into the code. Type RockPaperScissors.py into a
new window in IDLE or download it from http://www.nostarch
.com/teachkids/.
Free download pdf