Menu
CoddyTech

The Knight

Lesson 2 of 20 in Coddy's Pygame Project: Hold the Keep course.

The knight is a sprite: a class built on pygame.sprite.Sprite that keeps its picture in self.image and its place in self.rect.

class Knight(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = knight_img
        self.rect = pygame.Rect(0, 0, 24, 24)
        self.rect.center = courtyard.center

The picture is 48 pixels square but the Rect is only 24. The Rect is what monsters will collide with, so a monster has to reach the knight's body, not a corner of empty space around it. A small hitbox feels fair to the player.

Since the picture and the Rect have different sizes, draw the picture centred on the Rect's centre. image.get_rect(center=point) gives a Rect of the picture's size centred on a point, and blit accepts it as the place to draw:

def draw(image, center):
    screen.blit(image, image.get_rect(center=center))
challenge icon

Challenge

Easy
  1. Load the knight's picture: knight_img = load("knight.png").
  2. Write the Knight class above: picture knight_img, a 24 by 24 rect centred on courtyard.center.
  3. Write the draw(image, center) function.
  4. Before the loop make knight = Knight(), and after the background draw it with draw(knight.image, knight.rect.center).

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))
for row in range(HEIGHT // TILE):
    for col in range(WIDTH // TILE):
        x = col * TILE
        y = row * TILE
        if courtyard.collidepoint(x, y):
            background.blit(floor_img, (x, y))
        else:
            background.blit(wall_img, (x, y))



running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.blit(background, (0, 0))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Pygame Project: Hold the Keep

Practice on your own: Pygame playground