Your First Object

Okay, we're in control, but so what? This is boring! So, let's start blitting a few more things on here.

Open the third file. Near line 71, you'll see a line like this:

class PlayerSprite( pygame.sprite.Sprite ):

This is a class, the chief concept in object-oriented programming. DO NOT PANIC! Object-oriented code is designed to make your life easier, not harder. This class is a sprite, and you can think of it like a sticker or one of those animated Monty-Python characters. All a class does is define what makes a sticker a sticker. In this case, the sticker represents a player on the screen.

In python, every class starts off with a __init__ function. That's just an ugly way of stating what every sticker will look like once we start it up. In this case, all it says is that each sticker will load up the "lincoln.png" image and will start at the bottom middle of the screen.

The other function is called update, and it runs at every frame. This update function is really just how we ask the sticker to animate itself. Depending on a couple of the sticker's properties (its x and y velocity,) the sticker will move in a particular direction (or not) every frame.

That's the beauty of object-oriented code--we leave each object, like this sprite, to define what itself does. That keeps things nice and neat. So don't sweat object-oriented--it's a harsh-sounding buzzword that just means being tidy.

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