Menu
CoddyTech

Rows and Columns

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

One loop walks along a row. A second loop around it walks down the rows, so together they visit every tile of the map. The outer loop gives each string of LEVEL as line, with its row number; the inner loop walks the characters of that line.

walls = []
for row, line in enumerate(LEVEL):
    for col, char in enumerate(line):
        if char == "#":
            walls.append(pygame.Rect(col * TILE, row * TILE, TILE, TILE))

Build the walls once, before the game loop, as a list of Rects. The map does not change while you play, and a Rect is what you will later test collisions with. In the game loop, draw each wall:

for wall in walls:
    pygame.draw.rect(screen, WALL, wall)

row comes from the outer loop, so it picks the y of the tile; col from the inner loop picks the x. Mixing them up turns the level on its side.

challenge icon

Challenge

Medium

Build every wall of the map, not only the bottom row.

  1. Before the game loop, make a list named walls.
  2. With two enumerate loops, append pygame.Rect(col * TILE, row * TILE, TILE, TILE) to walls for each # of LEVEL.
  3. Draw every Rect in walls in WALL brown instead of the bottom row.

Press Play: the whole map shows. 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))
    for col, char in enumerate(LEVEL[9]):
        if char == "#":
            pygame.draw.rect(screen, WALL, (col * TILE, 9 * TILE, TILE, TILE))
    pygame.draw.rect(screen, PLAYER, player)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Worlds

Practice on your own: Pygame playground