last_light/game/ui/ui_health_bar.go

108 lines
2 KiB
Go
Raw Permalink Normal View History

2024-05-30 23:39:54 +03:00
package ui
import (
"fmt"
"math"
"mvvasilev/last_light/engine"
2024-06-06 23:17:22 +03:00
"mvvasilev/last_light/game/model"
"mvvasilev/last_light/game/systems"
2024-05-30 23:39:54 +03:00
"github.com/gdamore/tcell/v2"
"github.com/gdamore/tcell/v2/views"
"github.com/google/uuid"
)
type UIHealthBar struct {
2024-06-06 23:17:22 +03:00
id uuid.UUID
2024-06-06 23:28:06 +03:00
player *model.Player
2024-05-30 23:39:54 +03:00
window *UIWindow
style tcell.Style
}
2024-06-06 23:28:06 +03:00
func CreateHealthBar(x, y, w, h int, player *model.Player, style tcell.Style) *UIHealthBar {
2024-05-30 23:39:54 +03:00
return &UIHealthBar{
2024-06-06 23:17:22 +03:00
window: CreateWindow(x, y, w, h, "HP", style),
player: player,
style: style,
2024-05-30 23:39:54 +03:00
}
}
func (uihp *UIHealthBar) MoveTo(x int, y int) {
uihp.window.MoveTo(x, y)
}
func (uihp *UIHealthBar) Position() engine.Position {
return uihp.window.Position()
}
func (uihp *UIHealthBar) Size() engine.Size {
return uihp.window.Size()
}
2024-06-06 23:17:22 +03:00
func (uihp *UIHealthBar) Input(inputAction systems.InputAction) {
2024-05-30 23:39:54 +03:00
}
func (uihp *UIHealthBar) UniqueId() uuid.UUID {
return uihp.id
}
func (uihp *UIHealthBar) Draw(v views.View) {
x, y, w, h := uihp.Position().X(), uihp.Position().Y(), uihp.Size().Width(), uihp.Size().Height()
uihp.window.Draw(v)
stages := []string{"█", "▓", "▒", "░"} // 0 = 1.0, 1 = 0.75, 2 = 0.5, 3 = 0.25
2024-05-30 23:39:54 +03:00
2024-06-06 23:17:22 +03:00
percentage := (float64(w) - 2.0) * (float64(uihp.player.HealthData().Health) / float64(uihp.player.HealthData().MaxHealth))
2024-05-30 23:39:54 +03:00
whole := math.Trunc(percentage)
last := percentage - whole
hpBar := ""
2024-05-30 23:39:54 +03:00
hpStyle := tcell.StyleDefault.Foreground(tcell.ColorIndianRed)
for range int(whole) {
hpBar += stages[0]
2024-05-30 23:39:54 +03:00
}
lastRune := func() string {
if last <= 0.0 {
return ""
}
2024-05-30 23:39:54 +03:00
if last <= 0.25 {
return stages[3]
2024-05-30 23:39:54 +03:00
}
if last <= 0.50 {
return stages[2]
2024-05-30 23:39:54 +03:00
}
if last <= 0.75 {
return stages[1]
}
if last <= 1.00 {
return stages[0]
2024-05-30 23:39:54 +03:00
}
return ""
2024-05-30 23:39:54 +03:00
}
hpBar += lastRune()
engine.DrawText(x+1, y+1, hpBar, hpStyle, v)
2024-06-06 23:17:22 +03:00
hpText := fmt.Sprintf("%v/%v", uihp.player.HealthData().Health, uihp.player.HealthData().MaxHealth)
2024-05-30 23:39:54 +03:00
engine.DrawText(
x+w/2-len(hpText)/2,
y+h-1,
hpText,
hpStyle,
v,
)
}