Sprites

Okay, keep looking at that third file. In the main function, we've added a couple new variables called player_sprite and player_sprites. player_sprite creates a new sprite, or "sticker" as we've been calling it. It does this by instatiating the PlayerSprite class. All this means is that we use the PlayerSprite class, which is just a definition, to create an actual sprite that we can move around on the screen. Since this is a one-player game, we just create one sprite and add it into the player_sprites (note the plural) group.

Now let's move it around! If you look in the event loop, you'll see we've added a few more key commands. These new commands set the velocity for the player sprite. It does not, however, move the sprite! This is important to remember. The keys are changing values of the sprite, but we leave it to the sprite to move itself! Let's see how this happens.

Below the event loop, we have a few more lines. First, we ask the player_sprites group to clear away the old "stickers" from the screen and replace them with the background image. Then we ask the group to run the update functions of the each of the sprites. Well, in this case, there's only one sprite, but it could easily do this for 100 sprites. This changes the position of where our sprite will be "stuck" on the screen.

Lastly, we ask the group to draw the sprite in its new location. See how this works? Just like a flipbook or a stop-action movie--take one position, show it screen, take it away, move it to a new position, and then show that one on screen. We do this 60 times every second, and the sticker appears to move around everytime we hit the arrow keys.

You have your first living game character!

Copyright Mike Edwards 2006-2009. All content available under the Creative Commons Attribution ShareAlike license, unless otherwise noted.