WMICraft/logic/health_bar.py

60 lines
2.0 KiB
Python
Raw Permalink Normal View History

2022-04-11 17:51:46 +02:00
import pygame
2022-04-28 14:13:59 +02:00
from common.constants import BAR_ANIMATION_SPEED, BAR_WIDTH_MULTIPLIER, BAR_HEIGHT_MULTIPLIER
from common.colors import FONT_DARK, ORANGE, WHITE, RED, GREEN, BLACK
2022-04-11 17:51:46 +02:00
class HealthBar:
def __init__(self, screen, rect: pygame.rect, current_hp, max_hp, calculate_xy=False, calculate_size=False):
self.health_ratio = None
2022-04-11 17:51:46 +02:00
self.rect = rect
self.screen = screen
2022-04-11 17:51:46 +02:00
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
2022-04-28 14:13:59 +02:00
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()
2022-04-28 14:13:59 +02:00
self.show()
def update_stats(self):
if self.calculate_xy:
2022-04-28 14:13:59 +02:00
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:
2022-04-28 14:13:59 +02:00
self.x = self.rect.x + 1
self.y = self.rect.y + 1
self.health_ratio = self.max_hp / self.width
2022-04-11 17:51:46 +02:00
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
2022-04-11 17:51:46 +02:00
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
2022-04-11 17:51:46 +02:00
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))
2022-04-11 17:51:46 +02:00