The Courtyard
Lesson 1 of 20 in Coddy's Pygame Project: Hold the Keep course.
In this course you build one whole game, a feature a lesson. A knight stands in a castle courtyard at night. Monsters come over the walls, more and more of them, and the knight's weapons fire on their own. You only move. Hold out until dawn and the keep is saved.
It starts with the courtyard: a grid of 48 pixel tiles, 15 across and 10 down, floor inside and wall around the edge. You could draw 150 tiles every frame, but they never change. Draw them once onto a Surface of the window's size, then put that one picture on the screen each frame:
background = pygame.Surface((WIDTH, HEIGHT))
for row in range(HEIGHT // TILE):
for col in range(WIDTH // TILE):
x = col * TILE
y = row * TILE
background.blit(floor_img, (x, y))courtyard is the Rect inside the walls. courtyard.collidepoint(x, y) is True when the point (x, y), here a tile's top left corner, is inside it.
Challenge
Easy- Under
# build the courtyard here, loop over every row and column of tiles. - Blit
floor_imgontobackgroundwherecourtyard.collidepoint(x, y)is True, andwall_imgeverywhere else. - In the game loop, replace
screen.fill((20, 20, 30))withscreen.blit(background, (0, 0)).
Try it yourself
import pygame
WIDTH, HEIGHT = 720, 480
TILE = 48
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Hold the Keep")
clock = pygame.time.Clock()
def load(name):
return pygame.image.load("assets/images/" + name).convert_alpha()
floor_img = load("floor.png")
wall_img = load("wall.png")
courtyard = pygame.Rect(TILE, TILE, WIDTH - 2 * TILE, HEIGHT - 2 * TILE)
background = pygame.Surface((WIDTH, HEIGHT))
# build the courtyard here
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((20, 20, 30))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Pygame Project: Hold the Keep
Practice on your own: Pygame playground