Menu
CoddyTech

A Level in Text

Part of the Worlds section of Coddy's Pygame journey. Lesson 1 of 36.

Drawing a level wall by wall with numbers is slow to write and hard to change. Instead, type the level as text: a list of strings, one string per row of tiles, one character per tile.

LEVEL = [
    "################",
    "#..............#",
    "#....####......#",
    "#..............#",
    "#.........##...#",
    "#..##.....##...#",
    "#..##..........#",
    "#.........###..#",
    "#..............#",
    "####..####..####",
]

Here # is a wall and . is empty space. LEVEL[9] is the bottom row, a string, and LEVEL[9][4] is its fifth character. Rows count from the top, columns from the left, both from 0.

With tiles TILE = 36 pixels wide, the tile in column col and row row starts at x = col * TILE, y = row * TILE. To walk over one row, enumerate gives each character with its index:

for col, char in enumerate(LEVEL[9]):
    if char == "#":
        pygame.draw.rect(screen, WALL, (col * TILE, 9 * TILE, TILE, TILE))

Two gaps in the bottom row stay empty, because only a # draws a tile.

Leave the map as it is. The green square moves with the arrow keys and passes through everything for now: walls that stop it come later in this section.

challenge icon

Challenge

Easy

Draw the bottom row of the level from the map.

  1. Remove the line that draws the brown bar.
  2. Loop over LEVEL[9] with enumerate.
  3. For each #, draw a WALL rectangle at (col * TILE, 9 * TILE, TILE, TILE).

Press Play: the bottom row has two gaps. Then Check.

Try it yourself

import pygame

TILE = 36
WALL = (120, 90, 60)
PLAYER = (80, 200, 120)

LEVEL = [
    "################",
    "#..............#",
    "#....####......#",
    "#..............#",
    "#.........##...#",
    "#..##.....##...#",
    "#..##..........#",
    "#.........###..#",
    "#..............#",
    "####..####..####",
]

pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Map from Text")
clock = pygame.time.Clock()

player = pygame.Rect(40, 40, 28, 28)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.x -= 4
    if keys[pygame.K_RIGHT]:
        player.x += 4
    if keys[pygame.K_UP]:
        player.y -= 4
    if keys[pygame.K_DOWN]:
        player.y += 4

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, WALL, (0, 324, 576, 36))
    pygame.draw.rect(screen, PLAYER, player)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Worlds

Practice on your own: Pygame playground