Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 41 ยท Game Architecture

Tilemaps and Scrolling Cameras in Pygame

Build levels from tiles in Pygame: map data in text or JSON, drawing only visible tiles, tile collision, a camera that follows the player and clamps to the world.

A game world rarely fits in one screen. Platformers, top-down adventures and strategy games use worlds many screens wide, built out of repeated square tiles: grass, wall, water, spikes. Storing the world as a grid of small numbers is compact, easy to edit and wonderfully fast to collide with. A camera then decides which part of that world is visible.

This lesson covers tilemap data, drawing only what is visible, tile collision, and a smooth camera that follows the player and stops at the edges. The drawing code is read-only; the grid, collision and camera maths are runnable.

A map as data

The simplest level format is a list of strings, where each character is one tile:

Python
LEVEL = [
    "####################",
    "#..................#",
    "#...........$$.....#",
    "#.....####.........#",
    "#P.........####....#",
    "####################",
]
TILE = 32

# is a wall, . is empty space, $ is a coin and P is the player's start. You can edit this in any text editor and see the level change on the next run. For bigger worlds, use a tool such as Tiled, which exports JSON with layers (background, collision, objects) that you load with the json module. The ideas below stay the same.

flowchart LR
  F["level.txt / level.json"] --> L["load -> 2D grid"]
  L --> G["grid[row][col] = tile id"]
  G --> D["draw visible tiles only"]
  G --> C["collide: tile under a point"]
  P["player world position"] --> CAM["camera offset"]
  CAM --> D

One grid serves drawing, collision and level design.

Converting between world and grid

A tile at row r, column c occupies the pixels (c * TILE, r * TILE). The reverse mapping uses integer division:

Python
col = int(x // TILE)
row = int(y // TILE)

That one-liner gives O(1) collision against any number of tiles: to see whether a point is in a wall, look up the single tile under it instead of testing every wall rect.

Python Reading a text level

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Drawing only what you can see

A 200 by 100 tile map has 20,000 tiles. Drawing all of them every frame is wasteful when only about 30 by 17 fit the screen. Compute the range of rows and columns inside the camera's view and loop over just those:

Python
first_col = max(0, int(camera.x // TILE))
last_col = min(MAP_W, int((camera.x + WIDTH) // TILE) + 1)
first_row = max(0, int(camera.y // TILE))
last_row = min(MAP_H, int((camera.y + HEIGHT) // TILE) + 1)

for row in range(first_row, last_row):
    for col in range(first_col, last_col):
        tile = grid[row][col]
        if tile:
            screen.blit(TILE_IMAGES[tile], (col * TILE - camera.x, row * TILE - camera.y))

The + 1 includes the partly visible tile at the right and bottom edges. A world position becomes a screen position by subtracting the camera offset. Round the camera position to integers before drawing, or tiles can shimmer by one pixel.

Python How many tiles does the view really need?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Roughly 540 tiles are drawn instead of 20,000, a speed-up of about 37 times. For very large static maps you can pre-render chunks of tiles to a Surface and blit that.

Tile collision

Combine the grid with the axis-by-axis approach from Gravity and Jumping. Only the tiles touching the player's rect need checking:

Python
def solid_tiles_near(rect):
    for row in range(rect.top // TILE, rect.bottom // TILE + 1):
        for col in range(rect.left // TILE, rect.right // TILE + 1):
            if tile_at_cell(col, row) == "#":
                yield pygame.Rect(col * TILE, row * TILE, TILE, TILE)

# move horizontally, then fix
player.x += vx * dt
rect.x = round(player.x)
for wall in solid_tiles_near(rect):
    if vx > 0: rect.right = wall.left
    elif vx < 0: rect.left = wall.right
    player.x = rect.x
# then the same for y

Even with a million-tile world each frame tests only a handful of cells.

Python Wall collision against the grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The box moves right across row 1 until its right edge touches the border wall at x = 192 (column 6) and then stays put.

The camera

A camera is only an offset. To center the player, subtract half the screen size from the player's position; then clamp so the view never shows beyond the map:

Python
class Camera:
    def __init__(self, map_w, map_h, view_w, view_h):
        self.pos = pygame.Vector2(0, 0)
        self.map_w, self.map_h = map_w, map_h
        self.view_w, self.view_h = view_w, view_h

    def follow(self, target_center, dt, smooth=6.0):
        goal = pygame.Vector2(target_center) - (self.view_w / 2, self.view_h / 2)
        goal.x = max(0, min(goal.x, self.map_w - self.view_w))
        goal.y = max(0, min(goal.y, self.map_h - self.view_h))
        self.pos += (goal - self.pos) * min(1, smooth * dt)     # ease toward the goal

    def apply(self, rect):
        return rect.move(-round(self.pos.x), -round(self.pos.y))

The easing line moves a fraction of the remaining distance each frame, so the camera trails the player gently and settles. Use smooth=1000 if you want a rigid camera. If the map is smaller than the screen on some axis, center the map instead of clamping (the formula above would need max/min swapped).

Python A camera following the player and clamping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

At the far left and right the camera stops (0 and 1200) even though the player keeps moving, which keeps the empty void off screen.

Parallax backgrounds

Draw background layers with a fraction of the camera offset: far mountains at 0.2, nearer hills at 0.5, the main layer at 1.0. They scroll slower the farther they are, giving instant depth. Tile the image horizontally by drawing it at x and x + image_width, using the offset modulo the image width.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you find the tile column under the world x position 150 when tiles are 32 pixels wide?

    Integer division converts pixels to a tile index, here 4.
  2. 2. Why draw only the visible range of tiles?

    Looping over every tile in a large map wastes time; the view only needs the tiles intersecting it.
  3. 3. How is a world position converted to a screen position?

    If the camera is at x=500, a thing at world x=520 appears at screen x=20.
  4. 4. What does clamping the camera achieve?

    Limiting the offset to 0..map_size-view_size keeps the edge of the world at the edge of the screen.

Summary

  • Store levels as a grid of tile ids (text or JSON) and convert between pixels and cells with // and *.
  • Draw only the tiles in the camera's view, subtracting the camera offset.
  • Collide against the few tiles near the player, axis by axis.
  • A camera is an offset that follows the target, eases toward its goal and clamps to the map.
  • Parallax layers scroll at fractions of the camera for depth.

Next: Saving Scores and Settings