Add Interactivity to Your Animations

What’s better than animation? Interactivity!

Now that you know how to put images on the screen and move them around ( [Hack #91] ), you’re two steps away from creating games. Step 1 is to make things interactive; step 2 is to add gameplay ( [Hack #93] ). Fortunately, with PyGame, it’s easy to make your animations respond to the human touch.

Building a small program to move a robot around on the screen with the cursor keys takes only a few minutes, yet it demonstrates the larger concepts of almost any interactive and visual game.

PyGame Input

PyGame relies on SDL for its input, so to work with input in PyGame, you need to understand SDL events. Every time an input source generates input, such as a timer going off, the user pressing a key, or someone moving the mouse, SDL turns this into an event. It then puts this event in a queue for your program to handle later. Think of SDL events as an answering service; you don’t want to answer the telephone every time something happens, so you let your answering service buffer the interruptions so that you can filter through the list of messages when it’s convenient.

SDL events have one vitally important attribute, the type designator. Every possible input type SDL supports has its own type. The most important include QUIT, KEYDOWN, and KEYUP, though there are other types for mice, joysticks, and window manager events. For keyboard events, both KEYDOWN and KEYUP have a subtype that represents the actual ...

Get Gaming Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.