Menu
CoddyTech

The Keep's First Room

Part of the Projects section of Coddy's Pygame journey. Lesson 22 of 33.

Your next game is Rune Keep: a knight seen from above, trapped in a keep of three rooms. Each room has a key, a locked door and monsters. Find the key, open the door, reach the next room, and get out with your hearts.

A room is a text map, as in Moss Caves: 14 columns by 10 rows of 48 pixel tiles, which fills a 672 by 480 window. # is a wall. The other letters come alive in the next lessons: P the knight, K the key, D the door, S a slime, H a potion. For now they are floor.

A Room class builds everything a room holds from its map. Later the knight walks from room to room, and each new room is one line: Room(MAP2).

class Room:
    def __init__(self, lines):
        self.walls = []
        for row, line in enumerate(lines):
            for col, char in enumerate(line):
                if char == "#":
                    self.walls.append(pygame.Rect(col * TILE, row * TILE, TILE, TILE))

To draw a wall, blit its picture at its Rect: screen.blit(wall_img, wall) puts the image at the Rect's top left.

challenge icon

Challenge

Easy

Build the walls of the keep's first room.

  1. In Room.__init__, for each # in lines, add a 48 by 48 Rect at (col * TILE, row * TILE) to self.walls. The starter already makes room = Room(MAP) and loads every picture.
  2. After the floor, blit wall_img at every Rect in room.walls.

Press Play: stone walls ring the room. Then Check.

Try it yourself

import pygame

TILE = 48
MAP = [
    "##############",
    "#............#",
    "#.P......K...#",
    "#............#",
    "#....##......D",
    "#....##......#",
    "##.#######.###",
    "#............#",
    "#...S....H...#",
    "##############",
]

pygame.init()
screen = pygame.display.set_mode((672, 480))
pygame.display.set_caption("Rune Keep")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 32)


def load(name):
    return pygame.image.load("assets/images/" + name).convert_alpha()


floor_img = load("floor.png")
wall_img = load("wall.png")
knight_img = load("knight.png")
door_img = load("dungeon_door.png")
key_img = load("key.png")
slime_img = load("slime.png")
spider_img = load("spider.png")
heart_img = load("heart.png")
empty_img = load("heart_empty.png")
sword_img = load("sword.png")
potion_img = load("potion_red.png")


class Room:
    def __init__(self, lines):
        self.walls = []
        # build the walls here


room = Room(MAP)

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

    for row in range(10):
        for col in range(14):
            screen.blit(floor_img, (col * TILE, row * TILE))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Projects

Practice on your own: Pygame playground