pyinvaders and a Pygame cheat sheet

Recently I had a bit of a blast from the past when I found an old Pygame project. If you’ve not used Pygame before;

Pygame is a set of Python modules designed for writing games. Pygame
adds functionality on top of the excellent SDL library. This allows you to create
fully featured games and multimedia programs in the python language. Pygame is highly portable and runs on nearly every platform
and operating system. Pygame itself has been downloaded millions of times, and has had millions of visits to its website.

The game itself is available here it’s a simple copy of Space invaders I created to learn Pygame itself. Unfortunately the image and sounds were taken out because I couldn’t honestly source them but if you substitute your own, it should work fine!

However this isn’t the point of the post, what I wanted to share was a cheat sheet I created whilst working on this project!

Pygame Cheat Sheet

Load and Launch Pygame:

import pygame
pygame.init()

Display

screen = pygame.display.set_mode((width, height)) Initializes and creates the window where your game will run.
pygame.display.update() Redraws the main display surface if argument list is empty.
pygame.display.get_surface() Returns a reference to the Surface instantiated with the set_mode() function.

Rects

pygame.image.load('myImage') Load new image from a file.
image.get_rect() Get the rectangular area of the Surface.
Rect.move(x, y) Returns a Rect moved x pixels horizontally and y pixels vertically.

Time

pygame.time.Clock() Creates a Clock object (assign this to a name), which you can then call the tick() method on to find out how much time
has passed since the last time you called tick().
clock.tick(time) Used to set the frame rate.

Events

pygame.event.get() Call once per frame to get a list of events that occurred since the last time pygame.event.get.

Sprites, Groups, and Collision Detection

class Monster(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(“monster.png”)
self.rect = self.image.get_rect()
...
monsters = pygame.sprite.RenderPlain((monster1, monster2, monster3))
monsters.update()
monsters.draw()
Rect.contains(Rect): return True or False
Rect.collidepoint(x, y): return True or False
Rect.colliderect(Rect): return True or False
Rect.collidelist(list): return index
pygame.sprite.spritecollide(sprite, group, dokill):
return Sprite_list
pygame.sprite.groupcollide(group1, group2, dokill1,dokill2):
return Sprite_dict

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s