A Level in Text
Part of the Worlds section of Coddy's Pygame journey. Lesson 1 of 35.
Drawing a level wall by wall with numbers is slow to write and hard to change. Instead, type the level as text: a list of strings, one string per row of tiles, one character per tile.
LEVEL = [
"################",
"#..............#",
"#....####......#",
"#..............#",
"#.........##...#",
"#..##.....##...#",
"#..##..........#",
"#.........###..#",
"#..............#",
"####..####..####",
]Here # is a wall and . is empty space. LEVEL[9] is the bottom row, a string, and LEVEL[9][4] is its fifth character. Rows count from the top, columns from the left, both from 0.
With tiles TILE = 36 pixels wide, the tile in column col and row row starts at x = col * TILE, y = row * TILE. To walk over one row, enumerate gives each character with its index:
for col, char in enumerate(LEVEL[9]):
if char == "#":
pygame.draw.rect(screen, WALL, (col * TILE, 9 * TILE, TILE, TILE))Two gaps in the bottom row stay empty, because only a # draws a tile.
Challenge
EasyThe starter draws the whole bottom row as one brown bar. Draw it from the map instead:
- Remove the line that draws the bar.
- Loop over
LEVEL[9]withenumerate. - For each
#, draw aWALLrectangle at(col * TILE, 9 * TILE, TILE, TILE).
Leave the map as it is. The green square moves with the arrow keys and passes through everything for now: walls that stop it come later in this section.
Try it yourself
import pygame
TILE = 36
WALL = (120, 90, 60)
PLAYER = (80, 200, 120)
LEVEL = [
"################",
"#..............#",
"#....####......#",
"#..............#",
"#.........##...#",
"#..##.....##...#",
"#..##..........#",
"#.........###..#",
"#..............#",
"####..####..####",
]
pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Map from Text")
clock = pygame.time.Clock()
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))
pygame.draw.rect(screen, WALL, (0, 324, 576, 36))
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