Files
mygame/game/enemy.py
2026-05-20 20:21:27 +08:00

82 lines
2.5 KiB
Python

import pygame
import math
from game.config import ENEMY_DATA, PATH_WAYPOINTS, COLOR_BLACK, COLOR_GREEN, COLOR_RED
class Enemy:
def __init__(self, enemy_type):
data = ENEMY_DATA[enemy_type]
self.type = enemy_type
self.max_hp = data["hp"]
self.hp = self.max_hp
self.base_speed = data["speed"]
self.speed = self.base_speed
self.reward = data["reward"]
self.color = data["color"]
self.size = data["size"]
self.alive = True
self.reached_end = False
self.x, self.y = PATH_WAYPOINTS[0]
self.waypoint_index = 1
self.slow_timer = 0
def apply_slow(self, factor, duration):
self.speed = self.base_speed * factor
self.slow_timer = duration
def take_damage(self, damage):
self.hp -= damage
if self.hp <= 0:
self.hp = 0
self.alive = False
def update(self, dt):
if not self.alive:
return
if self.slow_timer > 0:
self.slow_timer -= dt
if self.slow_timer <= 0:
self.speed = self.base_speed
if self.waypoint_index >= len(PATH_WAYPOINTS):
self.reached_end = True
self.alive = False
return
tx, ty = PATH_WAYPOINTS[self.waypoint_index]
dx = tx - self.x
dy = ty - self.y
dist = math.hypot(dx, dy)
move = self.speed * 60 * dt
if dist <= move:
self.x, self.y = tx, ty
self.waypoint_index += 1
else:
self.x += dx / dist * move
self.y += dy / dist * move
def draw(self, surface):
if not self.alive:
return
ix, iy = int(self.x), int(self.y)
pygame.draw.circle(surface, self.color, (ix, iy), self.size)
pygame.draw.circle(surface, COLOR_BLACK, (ix, iy), self.size, 2)
if self.type == "boss":
for offset in [(-6, -6), (6, -6)]:
pygame.draw.circle(surface, (255, 200, 0), (ix + offset[0], iy + offset[1]), 4)
pygame.draw.circle(surface, COLOR_BLACK, (ix + offset[0], iy + offset[1]), 4, 1)
bar_w = self.size * 2 + 4
if self.type == "boss":
bar_w = self.size * 3
bar_h = 4
bx = ix - bar_w // 2
by = iy - self.size - 8
ratio = self.hp / self.max_hp
pygame.draw.rect(surface, COLOR_RED, (bx, by, bar_w, bar_h))
pygame.draw.rect(surface, COLOR_GREEN, (bx, by, int(bar_w * ratio), bar_h))