Home Python Page 2 - A PyGame Working Example, continued

# Setting Things Up - Python

In this fourth article in our series covering the creation of a video game using Python and PyGame, we will code the internals of our game.

Rating:  / 9
February 14, 2006

SEARCH DEV SHED

TOOLS YOU CAN USE

Before our game is allowed to work, we must initialize PyGame and create the necessary Sprite objects. The first function we'll define is the setup function, which simply initializes PyGame and creates a screen for us to work with:

def setup():

global screen
pygame.init()
screen = pygame.display.set_mode((background.get_rect().width,
background.get_rect().height))

Now that we have a Surface object to draw on, we must blit the background image onto the Surface object. As you know already, this isn't rocket science:

screen.blit(background, background.get_rect())
pygame.display.update()

Finally, we have to create our game's Sprite objects. The first Sprite object we'll have to create is the player's sprite. We'll position the sprite in the bottom left of the player's screen to begin with, which will require a few calculations based on the data we retrieved when loading the level. The player Sprite should also be added to its own group:

global player, playerSprite

# Find the position of the player
colWidth = background.get_rect().width / columns
xPlayer = colWidth / 2
rowHeight = background.get_rect().height / rows
yPlayer = (rowHeight * (rows - 1)) + (rowHeight / 2)

playerSprite = gamesprites.Player(player, xPlayer, yPlayer)

# Create a player sprite group

Next come the object sprites. Each non-zero position in the layout list will need to be converted into a sprite, and we'll need to calculate the exact x-position of each object:

...

for y in xrange(len(layout)):
for x in xrange(len(layout[y])):
if layout[y][x]:
layout[y][x] = gamesprites.Object(objects[layout[y]
[x] - 1], (colWidth * (x)) + (colWidth / 2))

In the above code section, we simply iterate through the list and replace every non-zero element with a corresponding Sprite object. We'll also need to convert each row in the layout list to a group. This way, we can move an entire row of objects at once:

...

# Turn each layout row into a sprite group
for y in xrange(len(layout)):
for x in xrange(len(layout[y])):
if layout[y][x]: