Menu
CoddyTech

Tile a Background

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 4 of 39.

A plain colour is a dull sky. assets/backgrounds/sky.png is a 72 by 72 picture made to repeat: put copies side by side and the edges join with no seam. Covering the window with copies of one small picture is called tiling.

Two loops give every top left corner, one row of the grid at a time:

for x in range(0, 640, 72):
    for y in range(0, 480, 72):
        screen.blit(tile, (x, y))

range(0, 640, 72) is 0, 72, 144 and so on up to 576. The copy at 576 reaches 648, past the edge: pygame draws the part inside the window and skips the rest, so the last column is cut off cleanly.

The tiles cover the whole window, so they replace screen.fill: draw them first, then everything else on top. This picture has no see-through pixels, so load it with .convert(), the version of convert_alpha() for solid images.

challenge icon

Challenge

Easy

Cover the window with sky tiles.

  1. After set_mode, load assets/backgrounds/sky.png with .convert() into tile.
  2. Replace screen.fill(...) with two loops that blit tile at every (x, y), x in range(0, 640, 72) and y in range(0, 480, 72).
  3. Keep drawing the ship after the tiles.

Press Play: a tiled sky behind the ship. Then Check.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Sky Tiles")
clock = pygame.time.Clock()

ship = pygame.image.load("assets/images/ship.png").convert_alpha()

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

    screen.fill((20, 22, 40))
    screen.blit(ship, (288, 360))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground