Python: Sample Platform game

Return to Python resources

import pygame, sys, random
from pygame.locals import *

pygame.init()
fps = pygame.time.Clock()
window = pygame.display.set_mode((800,700))
pygame.display.set_caption("Platformer")

# Create colours
cRed = pygame.Color(255,0,0)
cGreen = pygame.Color(0,255,0)
cBlue = pygame.Color(0,0,255)
cYellow = pygame.Color(255,255,0)
cBlack = pygame.Color(0,0,0)
cWhite = pygame.Color(255,255,255)

# Create platform rectangles
platforms = []
for i in range(0,30):
    platforms.append( Rect( random.randint(0,39)*20, random.randint(2,34)*20, random.randint(1,10)*20, 20 ) )
gameRunning = True
onGround = False
gravity = 0.5
me = Rect( 0, 0, 10, 20 )
dX = 0
dY = 0
holdLeft = False
holdRight = False

while gameRunning:
    # Events
    for event in pygame.event.get():
        if event.type == QUIT:
            gameRunning = False
        elif event.type == KEYDOWN:
            if event.key == K_LEFT:
                holdLeft = True
            elif event.key == K_RIGHT:
                holdRight = True
            elif event.key == K_UP:
                if onGround:
                    dY = -10
        elif event.type == KEYUP:
            if event.key == K_LEFT:
                holdLeft = False
            elif event.key == K_RIGHT:
                holdRight = False
            elif event.key == K_UP:
                if dY < -3:
                    dY = -3

    # Calculations
    onGround = False
    if me.collidelist( platforms ) >= 0:
        onGround = True
    if holdLeft:
        dX -= 2
    if holdRight:
        dX += 2
    if onGround:
        dX *= 0.8 # We move a bit slower on the ground
        if dY > 0:
            dY = 0
    else:
        dY += gravity
    me.move_ip( dX, dY )

    # Draw graphics
    window.fill( cBlack )
    for platform in platforms:
        pygame.draw.rect( window, cWhite, platform )
    pygame.draw.rect( window, cYellow, me )
    pygame.display.update()
    fps.tick(10)

pygame.quit()
print("Good bye!")