import pygame from common.constants import BAR_ANIMATION_SPEED, BAR_WIDTH_MULTIPLIER, BAR_HEIGHT_MULTIPLIER from common.colors import FONT_DARK, ORANGE, WHITE, RED, GREEN, BLACK class HealthBar: def __init__(self, screen, rect: pygame.rect, current_hp, max_hp, calculate_xy=False, calculate_size=False): self.health_ratio = None self.rect = rect self.screen = screen self.current_hp = current_hp self.max_hp = max_hp self.x = self.rect.x self.y = self.rect.y self.calculate_xy = calculate_xy if calculate_size: self.width = int(self.rect.width * BAR_WIDTH_MULTIPLIER) - 2 self.height = int(self.rect.width * BAR_HEIGHT_MULTIPLIER) - 2 else: self.width = self.rect.width - 2 self.height = self.rect.height - 2 self.update_stats() def update(self): self.update_stats() self.show() def update_stats(self): if self.calculate_xy: self.x = int(self.rect.width * (1 - BAR_WIDTH_MULTIPLIER)/2) + self.rect.x + 1 self.y = int(self.rect.height * BAR_HEIGHT_MULTIPLIER/2) + self.rect.y + 1 else: self.x = self.rect.x + 1 self.y = self.rect.y + 1 self.health_ratio = self.max_hp / self.width def take_dmg(self, amount): if self.current_hp - amount > 0: self.current_hp -= amount elif self.current_hp - amount <= 0: self.current_hp = 0 def heal(self, amount): if self.current_hp + amount < self.max_hp: self.current_hp += amount elif self.current_hp + amount >= self.max_hp: self.current_hp = self.max_hp def show(self): pygame.Surface.fill(self.screen, BLACK, (self.x-1, self.y-1, self.width+2, self.height+2)) pygame.Surface.fill(self.screen, RED, (self.x, self.y, self.width, self.height)) pygame.Surface.fill(self.screen, GREEN, (self.x, self.y, int(self.current_hp / self.health_ratio), self.height))