Menu
CoddyTech

Rows and Columns

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

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
  1. Before the game loop, make a list named walls.
  2. Loop over every row of LEVEL and every character in it with two enumerate loops. For each #, append pygame.Rect(col * TILE, row * TILE, TILE, TILE) to walls.
  3. In the game loop, draw every Rect in walls in WALL brown, instead of the bottom row only.

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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Worlds

Practice on your own: Pygame playground