Menu
CoddyTech

Letters With Meanings

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

A map can hold more than walls. Give each kind of thing its own character. Here C is a coin.

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

The loops that find the walls find the coins too: test each character with if and elif, and put each thing in its own list.

elif char == "C":
    coins.append(pygame.Rect(col * TILE + 10, row * TILE + 10, 16, 16))

A coin is smaller than its tile. To centre a 16 pixel coin in a 36 pixel tile, start it (36 - 16) / 2 = 10 pixels in from the tile's left and top.

Characters you do not test for make nothing, so the . tiles stay empty.

challenge icon

Challenge

Easy
  1. Make a list named coins next to walls.
  2. In the map loops, for each C, append pygame.Rect(col * TILE + 10, row * TILE + 10, 16, 16) to coins.
  3. In the game loop, after the walls, draw every coin in COIN yellow, (255, 196, 0).

Try it yourself

import pygame

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

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

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

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))
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 wall in walls:
        pygame.draw.rect(screen, WALL, wall)
    pygame.draw.rect(screen, PLAYER, player)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Worlds

Practice on your own: Pygame playground