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
Easy- Load
assets/images/grass.pngintograss_imgandassets/images/dirt.pngintodirt_img. - For each
#, pickgrass_imgwhen it is in row 0 or the tile above is not#, anddirt_imgotherwise. - Put the picked image in
tilesinstead ofblock_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
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