WMICraft/logic/health_bar.py

61 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.target_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, dmg_taken):
if self.target_hp > 0:
self.target_hp -= dmg_taken
elif self.target_hp < 0:
self.target_hp = 0
def heal(self, amount):
if self.target_hp < self.max_hp:
self.target_hp += amount
elif self.target_hp > self.max_hp:
self.target_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))
2022-04-28 14:13:59 +02:00
pygame.Surface.fill(self.screen, GREEN, (self.x, self.y, int(self.target_hp / self.health_ratio), self.height))
2022-04-11 17:51:46 +02:00