Letters With Meanings
Part of the Worlds section of Coddy's Pygame journey. Lesson 3 of 35.
A map can hold more than walls. Give each kind of thing its own character. Here C is a coin.
LEVEL = [
"################",
"#..............#",
"#.C..####...C..#",
...
]The loops that find the walls find the coins too: test each character with if and elif, and put each thing in its own list.
elif char == "C":
coins.append(pygame.Rect(col * TILE + 10, row * TILE + 10, 16, 16))A coin is smaller than its tile. To centre a 16 pixel coin in a 36 pixel tile, start it (36 - 16) / 2 = 10 pixels in from the tile's left and top.
Characters you do not test for make nothing, so the . tiles stay empty.
Challenge
Easy- Make a list named
coinsnext towalls. - In the map loops, for each
C, appendpygame.Rect(col * TILE + 10, row * TILE + 10, 16, 16)tocoins. - In the game loop, after the walls, draw every coin in
COINyellow,(255, 196, 0).
Try it yourself
import pygame
TILE = 36
WALL = (120, 90, 60)
PLAYER = (80, 200, 120)
LEVEL = [
"################",
"#..............#",
"#.C..####...C..#",
"#..............#",
"#....C....##...#",
"#..##.....##.C.#",
"#..##..........#",
"#.C.......###..#",
"#..............#",
"####..####..####",
]
pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Map from Text")
clock = pygame.time.Clock()
walls = []
for row, line in enumerate(LEVEL):
for col, char in enumerate(line):
if char == "#":
walls.append(pygame.Rect(col * TILE, row * TILE, TILE, TILE))
player = pygame.Rect(40, 40, 28, 28)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= 4
if keys[pygame.K_RIGHT]:
player.x += 4
if keys[pygame.K_UP]:
player.y -= 4
if keys[pygame.K_DOWN]:
player.y += 4
screen.fill((30, 30, 46))
for wall in walls:
pygame.draw.rect(screen, WALL, wall)
pygame.draw.rect(screen, PLAYER, player)
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