Implement health bar system: add HealthBar class for managing health, integrate health updates in HUDLayer, and modify enemy attack handling to reflect damage taken.

This commit is contained in:
2026-03-30 20:43:06 +00:00
parent 0369d24338
commit 32de437f86
9 changed files with 110 additions and 24 deletions
+27
View File
@@ -0,0 +1,27 @@
class HealthBar
attr_reader :health, :max_health
def initialize(max_health)
@max_health = max_health
@health = max_health
end
def take_damage(amount)
@health -= amount
@health = 0 if @health < 0
end
def heal(amount)
@health += amount
@health = @max_health if @health > @max_health
end
def draw(x, y)
# Draw the background of the health bar (red)
Gosu.draw_rect(x, y, 100, 10, Gosu::Color::RED)
# Draw the foreground of the health bar (green) based on current health
health_width = (health.to_f / max_health) * 100
Gosu.draw_rect(x, y, health_width, 10, Gosu::Color::GREEN)
end
end
+4 -1
View File
@@ -1,13 +1,15 @@
require_relative "inventory"
require_relative "health"
class HUDLayer
def initialize
@hud_bg = Gosu::Image.new("assets/images/hud.png", retro: true)
@hud_fg = Gosu::Image.new("assets/images/hud_fg.png", retro: true)
@inventory = Inventory.new
@health = HealthBar.new(100)
$bus.on(:enemy_attack) do |damage|
pp "Player takes #{damage} damage!"
@health.take_damage(damage)
end
end
@@ -15,6 +17,7 @@ class HUDLayer
@hud_bg.draw(0, 0, Float::INFINITY)
@inventory.draw
@health.draw(10, 10)
@hud_fg.draw(0, 0, Float::INFINITY)
end