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

(vip2019) #1
Timers and Animation: What Would Disney Do? 205

#3: Raining Dots


Finally, let’s take RandomDots.py one step further by pro-
gramming the dots to “rain” off the bottom and right sides
of the screen and reappear along the top and left. You’ve
learned in this chapter that we create animation by chang-
ing the location of an object over time. We have the location
of each dot in an array called locations, so if we change each
dot’s x- and y-coordinates, we can animate our dots. Change
the for loop from RandomDots.py to calculate a new x- and
y-coordinates for each dot based on the previous value,
like this:


for n in range(100):
pygame.draw.circle(screen, colors[n], locations[n],
sizes[n])
new_x = locations[n][0] + 1
new_y = locations[n][1] + 1
locations[n] = (new_x, new_y)


This change calculates new x- and y-coordinates (new_x
and new_y) for each dot every pass through the game loop,
but it lets the dots fall off the right and bottom edges of the
screen. Let’s fix this by checking whether each dot’s new_x or
new_y is beyond the right or bottom edges of the screen and,
if so, move the dot back up or back to the left before we store
the new location:


if new_x > 800:
new_x -= 800
if new_y > 600:
new_y -= 600
locations[n] = (new_x, new_y)


The combined effect of these changes will be a steady
flow of random dots “raining” down and to the right, disap-
pearing off the bottom right of the screen and popping back
up on the top or left edge. Four frames in this sequence are
shown in Figure 8-10; you can follow groups of dots as they
move down and to the right across the three images.
Save your new app as RainingDots.py.
continued

Free download pdf