Menu
CoddyTech

Tile Images

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

Brown rectangles show where the walls are. Images make the level look like a place. Load each tile image once, after set_mode:

block_img = pygame.image.load("assets/images/block.png").convert_alpha()
coin_img = pygame.image.load("assets/images/coin.png").convert_alpha()

Each tile is 36 by 36, the size of a map tile, so it fits the grid without scaling. The coin image has an empty border, so blit it at the tile's corner and the coin sits in the middle.

Keep what to draw in one list of pairs: which image, and where. tiles.append((block_img, rect)) adds a pair; the game loop blits them all:

for image, rect in tiles:
    screen.blit(image, rect)

The loop unpacks each pair into image and rect.

challenge icon

Challenge

Easy

Draw the level with pictures instead of rectangles.

  1. After set_mode, load assets/images/block.png into block_img and assets/images/coin.png into coin_img, with convert_alpha().
  2. Build a list tiles: for each #, (block_img, pygame.Rect(col * TILE, row * TILE, TILE, TILE)); for each C, (coin_img, ...) with the same Rect.
  3. Blit every pair in tiles instead of the rectangles.

Press Play: blocks and coins replace the flat colours. Then Check.

Try it yourself

import pygame

TILE = 36
WALL = (120, 90, 60)
COIN = (255, 196, 0)

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

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

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

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

    screen.fill((140, 200, 240))
    for wall in walls:
        pygame.draw.rect(screen, WALL, wall)
    for coin in coins:
        pygame.draw.rect(screen, COIN, coin)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Worlds

Practice on your own: Pygame playground