Tile a Background
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 4 of 36.
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
Easy- After
set_mode, loadassets/backgrounds/sky.pngwith.convert()into a variable namedtile. - Replace
screen.fill(...)with the two loops that blittileat every(x, y), x inrange(0, 640, 72)and y inrange(0, 480, 72). - Keep drawing the ship after the tiles.
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
3Classes for Game Objects
Your First ClassMethodsSelf Is the ObjectA List of ObjectsObjects with ImagesA SubclassPractice on your own: Pygame playground