A Monster
Lesson 5 of 20 in Coddy's Pygame Project: Hold the Keep course.
A monster walks straight at the knight. pygame.Vector2 holds an x and a y that can have decimals, and you can add and subtract whole Vector2s:
step = pygame.Vector2(target) - self.pos
if step.length() > 0:
self.pos += step.normalize() * self.speed
self.rect.center = self.posstep points from the monster to the knight, however far away. normalize() keeps its direction but makes it 1 pixel long, so times self.speed the monster moves exactly its speed each frame, in any direction. A Rect holds whole numbers only, so the exact place lives in self.pos and the Rect follows it.
Each kind of monster gets one row in a table, so adding a kind later is one line:
MONSTERS = {
"slime": {"image": load("slime.png"), "speed": 1.0},
}Monsters come in from outside the window. edge_point() picks a side with random.randint(0, 3) and a random place along it, 24 pixels out.
Challenge
Mediumimport randomand add theMONSTERStable with the slime.- Write
edge_point(): side 0 is(random.randint(0, WIDTH), -24), 1 the same atHEIGHT + 24, 2 is(-24, random.randint(0, HEIGHT))and 3 the same atWIDTH + 24. - Write
class Monster(pygame.sprite.Sprite):__init__(self, kind, pos)keepskind,imageandspeedfrom the table,posas a Vector2 and a 28 by 28rectcentred on it;update(self, target)walks as above. - In
Night:self.monsters = pygame.sprite.Group()with one slime atedge_point();updatecallsself.monsters.update(self.knight.rect.center). Draw every monster withdrawbefore the knight.
Try it yourself
import pygame
WIDTH, HEIGHT = 720, 480
TILE = 48
NIGHT = 60 * 60 * 4
WHITE = (240, 240, 240)
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Hold the Keep")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 24)
def load(name):
return pygame.image.load("assets/images/" + name).convert_alpha()
floor_img = load("floor.png")
wall_img = load("wall.png")
knight_img = load("knight.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))
def draw(image, center):
screen.blit(image, image.get_rect(center=center))
def clock_text(frames):
seconds = frames // 60
return f"{seconds // 60}:{seconds % 60:02d}"
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
self.speed = 3
def move(self, keys):
if keys[pygame.K_LEFT]:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT]:
self.rect.x += self.speed
if keys[pygame.K_UP]:
self.rect.y -= self.speed
if keys[pygame.K_DOWN]:
self.rect.y += self.speed
self.rect.clamp_ip(courtyard)
class Night:
def __init__(self):
self.knight = Knight()
self.time = 0
def update(self, keys):
self.time += 1
self.knight.move(keys)
night = Night()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
night.update(pygame.key.get_pressed())
screen.blit(background, (0, 0))
knight = night.knight
draw(knight.image, knight.rect.center)
left = font.render(clock_text(max(0, NIGHT - night.time)) + " until dawn", True, WHITE)
screen.blit(left, left.get_rect(center=(WIDTH // 2, 24)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Pygame Project: Hold the Keep
Practice on your own: Pygame playground