Pixel Climber: a platformer
Run, jump, collect every coin and reach the flag. Levels are plain text, so designing new ones takes minutes.
- Difficulty
- Advanced
- Source size
- 253 lines, 1 file
- Requires
- Python 3.10+, pygame-ce or pygame
- Assets
- None (drawn in code)
Controls
- Left Right A D Run
- Space Up W Jump (hold for higher)
- R Restart level
On this page
What you'll learn#
- Building levels from text strings
- Axis-separated collision against solid tiles
- Coyote time, jump buffering and variable jump height
- A camera that follows the player smoothly
- Win and lose conditions
Run it on your computer#
- Install Python 3.10 or newer and Pygame:
python -m pip install pygame-ce(orpygame). See the installation guides. - Download platformer.py into any folder.
- Open a terminal in that folder and run
python platformer.py.
No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.
How it works#
The platformer tutorial walks through this code section by section. In short:
- Level turns each character of the text level into solid rectangles, coins, spikes, the flag and the start position.
- Player applies gravity, reads input, and moves and collides one axis at a time. Coyote time and jump buffering make jumps register when players expect them to.
- Game collects coins, checks spikes and the flag, and moves the camera towards the player while keeping it inside the level.
The flag only works once every coin has been collected, which is shown by its colour.
Complete source code#
platformer.pyDownloadRun online
"""Pixel Climber - a Pygame.net game project (a side-scrolling platformer).
Run, jump and collect every coin, then reach the flag. Levels are written as
plain text, so you can design new ones without touching the game code.
Run it: pip install pygame-ce (or: pip install pygame)
python platformer.py
Controls: Left/Right or A/D to run, Space/Up/W to jump, R to restart the level.
License: MIT - https://pygame.net/licenses/
"""
import asyncio
import pygame
WIDTH, HEIGHT = 640, 480
FPS = 60
TILE = 32
GRAVITY = 1800
RUN_SPEED = 230
JUMP_SPEED = 680
COYOTE_TIME = 0.1 # seconds you can still jump after walking off a ledge
JUMP_BUFFER = 0.12 # seconds a jump press is remembered before landing
SKY = (190, 220, 250)
DIRT = (150, 100, 60)
GRASS = (90, 170, 90)
BRICK = (120, 130, 160)
INK = (21, 35, 63)
COIN = (244, 197, 49)
# # = ground, B = floating block, C = coin, P = player start, F = flag, ^ = spikes
LEVELS = [
[
" ",
" ",
" C C C ",
" BBBBBBB ",
" C C ",
" BBBBBBB BB F ",
" C C BBBB ",
" BBBBB C BB ",
" C BB BBB BB ",
" P BBB ^^ C C ",
"###### ######## ########## #### ##### ###########",
"###### ######## ########## #### ##### ###########",
"######^^^^^########^^^##########^^^^####^^#####^^###########",
"############################################################",
"############################################################",
],
]
class Level:
def __init__(self, rows):
self.solids = []
self.spikes = []
self.coins = []
self.flag = None
self.start = (TILE, TILE)
self.tiles = {}
for r, row in enumerate(rows):
for c, ch in enumerate(row):
rect = pygame.Rect(c * TILE, r * TILE, TILE, TILE)
if ch in "#B":
self.solids.append(rect)
self.tiles[(c, r)] = ch
elif ch == "C":
self.coins.append(pygame.Rect(rect.x + 9, rect.y + 9, 14, 14))
elif ch == "^":
self.spikes.append(pygame.Rect(rect.x + 4, rect.y + 16, TILE - 8, TILE - 16))
elif ch == "F":
self.flag = pygame.Rect(rect.x + 10, rect.y - TILE, 12, TILE * 2)
elif ch == "P":
self.start = (rect.x, rect.y)
self.width = len(rows[0]) * TILE
self.height = len(rows) * TILE
class Player:
def __init__(self, pos):
self.rect = pygame.Rect(pos[0] + 6, pos[1] + 2, 20, 28)
self.pos = pygame.Vector2(self.rect.topleft)
self.vel = pygame.Vector2(0, 0)
self.on_ground = False
self.coyote = 0.0
self.jump_buffer = 0.0
self.facing = 1
def update(self, dt, keys, solids):
direction = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a])
self.vel.x = direction * RUN_SPEED
if direction:
self.facing = direction
self.vel.y = min(self.vel.y + GRAVITY * dt, 900)
self.coyote = COYOTE_TIME if self.on_ground else max(0.0, self.coyote - dt)
self.jump_buffer = max(0.0, self.jump_buffer - dt)
if self.jump_buffer > 0 and self.coyote > 0:
self.vel.y = -JUMP_SPEED
self.jump_buffer = 0
self.coyote = 0
# Releasing jump early gives a shorter hop (variable jump height).
if self.vel.y < 0 and not (keys[pygame.K_SPACE] or keys[pygame.K_UP] or keys[pygame.K_w]):
self.vel.y += GRAVITY * dt
# Resolve collisions one axis at a time.
self.pos.x += self.vel.x * dt
self.rect.x = round(self.pos.x)
for s in solids:
if self.rect.colliderect(s):
if self.vel.x > 0:
self.rect.right = s.left
elif self.vel.x < 0:
self.rect.left = s.right
self.pos.x = self.rect.x
self.pos.y += self.vel.y * dt
self.rect.y = round(self.pos.y)
self.on_ground = False
for s in solids:
if self.rect.colliderect(s):
if self.vel.y > 0:
self.rect.bottom = s.top
self.on_ground = True
elif self.vel.y < 0:
self.rect.top = s.bottom
self.vel.y = 0
self.pos.y = self.rect.y
# Sub-pixel moves can leave us resting exactly on a tile without overlapping it.
if not self.on_ground and self.vel.y >= 0 and self.rect.move(0, 1).collidelist(solids) != -1:
self.on_ground = True
class Game:
def __init__(self):
self.font = pygame.font.Font(None, 30)
self.big = pygame.font.Font(None, 60)
self.level_index = 0
self.load()
def load(self):
self.level = Level(LEVELS[self.level_index])
self.player = Player(self.level.start)
self.coins = list(self.level.coins)
self.total = len(self.coins)
self.camera = 0.0
self.state = "playing" # playing, dead, won
self.timer = 0.0
def handle_event(self, event):
if event.type == pygame.KEYDOWN:
if event.key in (pygame.K_SPACE, pygame.K_UP, pygame.K_w):
if self.state == "playing":
self.player.jump_buffer = JUMP_BUFFER
else:
self.load()
elif event.key == pygame.K_r:
self.load()
def update(self, dt, keys=None):
if self.state != "playing":
return
if keys is None:
keys = pygame.key.get_pressed()
self.timer += dt
p = self.player
p.update(dt, keys, self.level.solids)
p.rect.left = max(0, p.rect.left)
p.pos.x = p.rect.x
collected = [c for c in self.coins if p.rect.colliderect(c)]
for c in collected:
self.coins.remove(c)
if p.rect.collidelist(self.level.spikes) != -1 or p.rect.top > self.level.height:
self.state = "dead"
if self.level.flag and p.rect.colliderect(self.level.flag) and not self.coins:
self.state = "won"
# Camera follows the player smoothly and stays inside the level.
target = p.rect.centerx - WIDTH / 2
self.camera += (target - self.camera) * min(1.0, dt * 8)
self.camera = max(0, min(self.level.width - WIDTH, self.camera))
def draw(self, surface):
surface.fill(SKY)
cam = round(self.camera)
for x in range(-(cam // 3) % 200 - 200, WIDTH, 200): # parallax hills
pygame.draw.circle(surface, (160, 200, 235), (x + 100, HEIGHT - 40), 120)
y_off = HEIGHT - self.level.height
for (c, r), ch in self.level.tiles.items():
rect = pygame.Rect(c * TILE - cam, r * TILE + y_off, TILE, TILE)
if rect.right < 0 or rect.left > WIDTH:
continue
if ch == "#":
pygame.draw.rect(surface, DIRT, rect)
if (c, r - 1) not in self.level.tiles:
pygame.draw.rect(surface, GRASS, (rect.x, rect.y, TILE, 8))
else:
pygame.draw.rect(surface, BRICK, rect)
pygame.draw.rect(surface, INK, rect, 2)
for s in self.level.spikes:
x, y = s.x - cam, s.y + y_off
for i in range(3):
pygame.draw.polygon(surface, (200, 205, 215), [(x + i * 8, y + 16), (x + i * 8 + 4, y), (x + i * 8 + 8, y + 16)])
for c in self.coins:
pygame.draw.ellipse(surface, COIN, c.move(-cam, y_off))
pygame.draw.ellipse(surface, (200, 150, 20), c.move(-cam, y_off), 2)
if self.level.flag:
f = self.level.flag.move(-cam, y_off)
pygame.draw.rect(surface, INK, (f.x, f.y, 4, f.height))
color = (90, 170, 90) if not self.coins else (232, 93, 82)
pygame.draw.polygon(surface, color, [(f.x + 4, f.y), (f.x + 30, f.y + 10), (f.x + 4, f.y + 20)])
pr = self.player.rect.move(-cam, y_off)
pygame.draw.rect(surface, (91, 147, 230), pr, border_radius=5)
eye_x = pr.centerx + 4 * self.player.facing
pygame.draw.circle(surface, (255, 255, 255), (eye_x, pr.y + 9), 4)
pygame.draw.circle(surface, INK, (eye_x + self.player.facing, pr.y + 9), 2)
surface.blit(self.font.render(f"Coins {self.total - len(self.coins)}/{self.total}", True, INK), (14, 12))
t = self.font.render(f"Time {self.timer:5.1f}s", True, INK)
surface.blit(t, (WIDTH - t.get_width() - 14, 12))
if self.coins and self.level.flag and self.player.rect.colliderect(self.level.flag):
h = self.font.render("Collect every coin to raise the flag", True, INK)
surface.blit(h, h.get_rect(center=(WIDTH // 2, 60)))
if self.state != "playing":
msg = "Level complete!" if self.state == "won" else "Ouch!"
m = self.big.render(msg, True, INK)
surface.blit(m, m.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 30)))
h = self.font.render("Press Space to play again", True, INK)
surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 20)))
async def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pixel Climber - Pygame.net")
clock = pygame.time.Clock()
game = Game()
running = True
while running:
dt = min(clock.tick(FPS) / 1000, 0.03)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
game.handle_event(event)
game.update(dt)
game.draw(screen)
pygame.display.flip()
await asyncio.sleep(0)
pygame.quit()
if __name__ == "__main__":
asyncio.run(main())The code is released under the MIT license: use it, change it and build on it. See licenses.
Ideas to extend it#
- Add a second level and a level counter.
- Add moving platforms.
- Add enemies that patrol between two points.
- Replace rectangles with art from the pixel art editor.
- Add a double jump power-up.