Menu
CoddyTech

Un mostro

Lezione 5 di 20 del corso Progetto Pygame: Difendi il castello di Coddy.

Un mostro cammina dritto verso il cavaliere. pygame.Vector2 contiene un valore x e un valore y che possono avere decimali, e puoi sommare e sottrarre interi Vector2:

step = pygame.Vector2(target) - self.pos
if step.length() > 0:
    self.pos += step.normalize() * self.speed
self.rect.center = self.pos

step punta dal mostro al cavaliere, a qualunque distanza si trovi. normalize() ne mantiene la direzione ma lo rende lungo 1 pixel, quindi, moltiplicato per self.speed, il mostro si muove esattamente alla sua velocità a ogni fotogramma, in qualsiasi direzione. Un Rect contiene solo numeri interi, quindi la posizione esatta è in self.pos e il Rect la segue.

Ogni tipo di mostro occupa una riga in una tabella, quindi aggiungere un tipo in seguito richiede una sola riga:

MONSTERS = {
    "slime": {"image": load("slime.png"), "speed": 1.0},
}

I mostri arrivano dall'esterno della finestra. edge_point() sceglie un lato con random.randint(0, 3) e un punto casuale lungo quel lato, a 24 pixel di distanza.

challenge icon

Sfida

Medio
  1. import random e aggiungi la tabella MONSTERS con lo slime.
  2. Scrivi edge_point(): il lato 0 è (random.randint(0, WIDTH), -24), il lato 1 è lo stesso a HEIGHT + 24, il lato 2 è (-24, random.randint(0, HEIGHT)) e il lato 3 è lo stesso a WIDTH + 24.
  3. Scrivi class Monster(pygame.sprite.Sprite): __init__(self, kind, pos) conserva kind, image e speed dalla tabella, pos come Vector2 e un rect di 28 per 28 centrato su di esso; update(self, target) si sposta come sopra.
  4. In Night: self.monsters = pygame.sprite.Group() con uno slime in edge_point(); update chiama self.monsters.update(self.knight.rect.center). Disegna ogni mostro con draw prima del cavaliere.

Provalo tu

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()

Tutte le lezioni di Progetto Pygame: Difendi il castello

Esercitati da solo: Playground Pygame