Where the Player Starts
Part of the Worlds section of Coddy's Pygame journey. Lesson 4 of 35.
A level decides where the player starts, so put that in the map too: one P. While the loops read the map, the P tile gives the player's first position.
elif char == "P":
player = pygame.Rect(col * TILE + 4, row * TILE + 4, 28, 28)The player is a 28 pixel square, so it starts (36 - 28) / 2 = 4 pixels in from the tile's corner, in the middle of the tile. Now moving the P in the text moves the start: no numbers to work out.
The loop runs before the game loop, so player exists by the time the game loop moves it. Make sure nothing after the loops sets player again, or that later line wins.
Challenge
EasyThe map now has a P. The starter puts the player at a fixed (40, 40).
- In the map loops, for
P, makeplayer = pygame.Rect(col * TILE + 4, row * TILE + 4, 28, 28). - Remove the line that puts the player at
(40, 40).
Try it yourself
import pygame
TILE = 36
WALL = (120, 90, 60)
COIN = (255, 196, 0)
PLAYER = (80, 200, 120)
LEVEL = [
"################",
"#..............#",
"#.C..####...C..#",
"#..............#",
"#....C....##...#",
"#..##.....##.C.#",
"#..##..P.......#",
"#.C.......###..#",
"#..............#",
"####..####..####",
]
pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Map from Text")
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))
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)
for coin in coins:
pygame.draw.rect(screen, COIN, coin)
pygame.draw.rect(screen, PLAYER, player)
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