Tile Images
Part of the Worlds section of Coddy's Pygame journey. Lesson 6 of 35.
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
Easy- After
set_mode, loadassets/images/block.pngintoblock_imgandassets/images/coin.pngintocoin_img, each withconvert_alpha(). - Before the game loop, build a list named
tiles: for each#, the pair(block_img, pygame.Rect(col * TILE, row * TILE, TILE, TILE)); for eachC,(coin_img, ...)with the same Rect. - In the game loop, blit every pair in
tilesinstead of drawing the brown and yellow rectangles.
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()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Worlds
1Maps from Text
A Level in TextRows and ColumnsLetters With MeaningsWhere the Player StartsOne Screen at a Time3Gravity and Jumping
Falling With GravityJump From the GroundShort HopsA Top Falling SpeedJump BufferPractice on your own: Pygame playground