Un monstruo
Lección 5 de 20 del curso Proyecto con Pygame: Defiende la fortaleza de Coddy.
Un monstruo camina en línea recta hacia el caballero. pygame.Vector2 almacena una x y una y que pueden tener decimales, y puedes sumar y restar objetos Vector2 completos:
step = pygame.Vector2(target) - self.pos
if step.length() > 0:
self.pos += step.normalize() * self.speed
self.rect.center = self.posstep apunta desde el monstruo hacia el caballero, sin importar lo lejos que esté. normalize() mantiene su dirección, pero hace que mida 1 píxel, así que al multiplicarlo por self.speed, el monstruo se mueve exactamente a su velocidad en cada fotograma, en cualquier dirección. Un Rect solo almacena números enteros, así que la posición exacta se guarda en self.pos y el Rect la sigue.
Cada tipo de monstruo ocupa una fila en una tabla, así que añadir un tipo más adelante requiere una sola línea:
MONSTERS = {
"slime": {"image": load("slime.png"), "speed": 1.0},
}Los monstruos aparecen desde fuera de la ventana. edge_point() elige un lado con random.randint(0, 3) y un punto aleatorio a lo largo de ese lado, a 24 píxeles de distancia.
Desafío
Intermedioimport randomy añade la tablaMONSTERScon el slime.- Escribe
edge_point(): el lado 0 es(random.randint(0, WIDTH), -24), el 1 es igual, pero enHEIGHT + 24, el 2 es(-24, random.randint(0, HEIGHT))y el 3 es igual, pero enWIDTH + 24. - Escribe
class Monster(pygame.sprite.Sprite):__init__(self, kind, pos)conservakind,imageyspeedde la tabla,poscomo Vector2 y unrectde 28 por 28 centrado en él;update(self, target)se desplaza como antes. - En
Night:self.monsters = pygame.sprite.Group()con un slime enedge_point();updatellama aself.monsters.update(self.knight.rect.center). Dibuja cada monstruo condrawantes que al caballero.
Pruébalo tú mismo
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()
Todas las lecciones de Proyecto con Pygame: Defiende la fortaleza
Practica por tu cuenta: Playground de Pygame