Tile maps

Build worlds from a grid of reusable tiles. Load maps from text or CSV, pre-render them for speed, collide with solid tiles and scroll a camera across levels larger than the screen.

Advanced2 min readUpdated
On this page

What you'll learn

  • Representing a level as a grid of tile IDs
  • Converting between pixel and tile coordinates
  • Pre-rendering a static map for speed
  • Scrolling a camera over a large map
  • Loading maps made in the tilemap editor

Prerequisites: Collision detection.

Why tiles?#

A tile map describes a level as a grid where each cell holds a small number: 0 for empty, 1 for grass, 2 for stone and so on. Each number refers to a small image in a tileset. A 100 × 20 level is only 2,000 numbers, yet it can look rich because tiles repeat. Tiles also make collision simple: a cell is either solid or not.

Pixel and tile coordinates#

With square tiles of size TILE:

Python
col, row = int(x // TILE), int(y // TILE)          # pixel -> tile
x, y = col * TILE, row * TILE                      # tile -> pixel (top-left of the tile)

This lets you look up what is under the player instantly, instead of testing every tile.

A scrolling tile map#

tilemap_scroll.pyDownload
"""A tile map from text, pre-rendered once, with a camera that follows the player."""
import pygame

TILE = 32
WIDTH, HEIGHT = 640, 480
LEVEL = """
##############################################
#............................................#
#.....................ooo....................#
#....................#####...........ooo.....#
#...................................#####....#
#............................................#
#..........ooo...............................#
#.........#####..........ooo......########...#
#........................###.................#
#....######..........................ooo.....#
#..........................#######..#####....#
#...........ooo......#.......................#
#..P.......#####....##..................ooo..#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
##############################################
""".strip().splitlines()
COLORS = {"#": (110, 120, 150), "~": (70, 140, 90)}


def build_level(rows):
    walls, coins, start = [], [], (TILE, TILE)
    surface = pygame.Surface((len(rows[0]) * TILE, len(rows) * TILE))
    surface.fill((24, 32, 56))
    for r, row in enumerate(rows):
        for c, ch in enumerate(row):
            rect = pygame.Rect(c * TILE, r * TILE, TILE, TILE)
            if ch in COLORS:
                walls.append(rect)
                pygame.draw.rect(surface, COLORS[ch], rect)
                pygame.draw.rect(surface, (40, 50, 80), rect, 1)
            elif ch == "o":
                coins.append(rect.inflate(-16, -16))
            elif ch == "P":
                start = rect.topleft
    return surface, walls, coins, start


pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 28)
level_surface, walls, coins, start = build_level(LEVEL)   # drawn once, blitted every frame
player = pygame.Rect(start[0] + 4, start[1] + 4, 24, 24)
camera = pygame.Vector2(0, 0)
level_rect = level_surface.get_rect()

running = True
while running:
    dt = clock.tick(60) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    keys = pygame.key.get_pressed()
    move = pygame.Vector2(keys[pygame.K_RIGHT] - keys[pygame.K_LEFT], keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 220 * dt
    # Move on each axis separately and push out of any wall we hit.
    player.x += round(move.x)
    for w in walls:
        if player.colliderect(w):
            player.right = w.left if move.x > 0 else player.right
            player.left = w.right if move.x < 0 else player.left
    player.y += round(move.y)
    for w in walls:
        if player.colliderect(w):
            player.bottom = w.top if move.y > 0 else player.bottom
            player.top = w.bottom if move.y < 0 else player.top
    coins = [c for c in coins if not player.colliderect(c)]

    # Camera: centre on the player, clamped to the level edges.
    camera.x = max(0, min(player.centerx - WIDTH / 2, level_rect.width - WIDTH))
    camera.y = max(0, min(player.centery - HEIGHT / 2, level_rect.height - HEIGHT))
    offset = (-round(camera.x), -round(camera.y))

    screen.fill((0, 0, 0))
    screen.blit(level_surface, offset)
    for c in coins:
        pygame.draw.ellipse(screen, (244, 197, 49), c.move(offset))
    pygame.draw.rect(screen, (91, 147, 230), player.move(offset), border_radius=4)
    screen.blit(font.render(f"Coins left: {len(coins)}   Arrow keys to move", True, (230, 236, 247)), (12, 10))
    pygame.display.flip()

pygame.quit()
A tile level with platforms, coins and a blue player
tilemap_scroll.py: the camera follows the player across a level wider than the window

Key ideas:

  • Pre-rendering. build_level draws every static tile once onto a big Surface. Each frame blits that single Surface instead of hundreds of tiles, which is dramatically cheaper. Only things that change (coins, the player) are drawn individually.
  • Camera offset. The camera is just a position. Everything is drawn at world position - camera, using rect.move(offset) to shift copies of rects without changing the originals.
  • Clamping the camera to the level keeps the view from showing empty space beyond the edges.

For very large maps, pre-rendering the entire level uses a lot of memory. Pre-render chunks (for example 16 × 16 tiles), or draw only the tiles inside the camera's view by looping over the visible column and row ranges.

Loading maps from the tilemap editor#

The tilemap editor exports a map.csv (one row per line, tile IDs separated by commas, 0 for empty), a tileset.png, and a ready-made loader. The core of loading a CSV map is short:

Python
import csv

def load_map(path):
    with open(path, newline="") as f:
        return [[int(v) for v in row] for row in csv.reader(f) if row]

Slicing a tileset uses subsurface, the same technique as sprite sheets:

Python
def load_tileset(path, tile):
    sheet = pygame.image.load(path).convert_alpha()
    tiles = [None]                                   # id 0 = empty
    for y in range(0, sheet.get_height(), tile):
        for x in range(0, sheet.get_width(), tile):
            tiles.append(sheet.subsurface((x, y, tile, tile)))
    return tiles

Collision with tiles#

For a handful of solid tiles, a list of Rects and collidelist is fine, as in the example. For big maps, check only the tiles around the player using tile coordinates: compute the range of columns and rows the player's rect covers and test those cells. This stays fast no matter how large the level is.

Common mistakes#

  • Off-by-one at the edges: a rect's right is one past its last pixel, so use (rect.right - 1) // TILE for the last column it covers.
  • Visible seams between tiles when the camera has fractional positions: round the offset to whole pixels before drawing.
  • Mixing up rows and columns: maps are indexed level[row][col], that is [y][x].

Practice exercises#

  1. Design a level in the tilemap editor, export the CSV and load it here.
  2. Draw only visible tiles instead of pre-rendering, and display how many tiles are drawn per frame.
  3. Add a minimap: scale the pre-rendered level down with pygame.transform.scale and draw it in a corner.
  4. Mark some tile IDs as "water" that slows the player instead of blocking them.
↑ ↓ to moveEnter to openEsc to close