Menu
CoddyTech

Grass on Top

Part of the Worlds section of Coddy's Pygame journey. Lesson 7 of 35.

Ground has grass on its surface and dirt under it. You can tell which is which from the map: a # with another # above it is under the surface.

if row == 0 or LEVEL[row - 1][col] != "#":
    image = grass_img
else:
    image = dirt_img
tiles.append((image, pygame.Rect(x, y, TILE, TILE)))

LEVEL[row - 1][col] is the tile above. Row 0 needs its own test: there row - 1 is -1, and Python reads index -1 as the last item of a list, the bottom row. Without row == 0, a tile in the top row would turn to dirt wherever the bottom row has a # under it.

challenge icon

Challenge

Easy
  1. Load assets/images/grass.png into grass_img and assets/images/dirt.png into dirt_img.
  2. For each #, pick grass_img when it is in row 0 or the tile above is not #, and dirt_img otherwise.
  3. Put the picked image in tiles instead of block_img.

Try it yourself

import pygame

TILE = 36

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

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

grass_img = pygame.image.load("assets/images/grass.png").convert_alpha()
dirt_img = pygame.image.load("assets/images/dirt.png").convert_alpha()
coin_img = pygame.image.load("assets/images/coin.png").convert_alpha()

tiles = []
for row, line in enumerate(LEVEL):
    for col, char in enumerate(line):
        x, y = col * TILE, row * TILE
        if char == "#":
            tiles.append((grass_img, pygame.Rect(x, y, TILE, TILE)))
        elif char == "C":
            tiles.append((coin_img, pygame.Rect(x, y, TILE, TILE)))

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

    screen.fill((140, 200, 240))
    for image, rect in tiles:
        screen.blit(image, rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Worlds

Practice on your own: Pygame playground