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

(vip2019) #1
User Interaction: Get into the Game 217

once we write a useful class for one programming project, we can
often reuse that class in another program instead of starting from
scratch. For example, a game company can write a Card class to
represent the cards in a standard deck. Then, every time the com-
pany programs a new game—like Blackjack, War, Poker, Go Fish,
and so on—it can reuse that Card class, saving time and money by
using the same code in future apps.
The Sprite class in Pygame is a great example. The Pygame
team wrote the Sprite class to contain many of the features we
need when we program a game object, from a running character
to a spaceship to a floating smiley face. By using the Sprite class,
programmers like us no longer need to write all the basic code to
draw an object on the screen, detect when objects collide with one
another, and so on. The Sprite class handles many of those func-
tions for us, and we can focus on building the unique qualities of
our app on top of that foundation.
Another handy Pygame class we’ll use is the Group class. Group
is a container class that lets us store Sprite objects together as a
group. The Group class helps us keep all our sprites together in one
place (accessible through a single Group object), and that’s impor-
tant when we have dozens or possibly hundreds of sprites floating
around the screen. The Group class also has convenient methods
for updating all the sprites in a group (such as moving the Sprite
objects to each of their new locations each frame), adding new
Sprite objects, removing Sprite objects from the Group, and so on.
Let’s see how we can use these classes to build our smiley explo-
sion app.


Using classes to Build our app


We’re going to create Sprite objects for our smiley face balloons that
take advantage of the Sprite class’s properties to produce quick ani-
mation around the screen, even when hundreds of sprites are being
moved in the same frame. I mentioned that Pygame also has sup-
port for groups of sprites that can all be drawn and handled as a
collection; this group of sprites will be of type pygame.sprite.Group().
Let’s look at the setup section of our app:


import pygame
import random


BLACK = (0,0,0)
pygame.init()

Free download pdf