BlueGit

timfa questward

Files

questward / client / src / play / health.js

health.js

health.js 1.4 KiB Download Raw
1export function initHealth ()
2{
3 let vitals = document.getElementById("vitals");
4 if (!vitals)
5 {
6 vitals = document.createElement("div");
7 vitals.id = "vitals";
8 vitals.hidden = true;
9 document.body.append(vitals);
10 }
11 let bar = document.getElementById("health-bar");
12 if (!bar)
13 {
14 bar = document.createElement("div");
15 bar.id = "health-bar";
16 bar.innerHTML = '<div id="health-bar-fill"></div><span id="health-bar-label" class="health-bar-label"></span>';
17 vitals.prepend(bar);
18 }
19 else if (bar.parentElement !== vitals)
20 { vitals.prepend(bar); }
21 const fill = document.getElementById("health-bar-fill");
22 const label = document.getElementById("health-bar-label");
23
24 let current = 1;
25 let max = 1;
26
27 function render ()
28 {
29 const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0;
30 fill.style.transform = `scaleY(${ratio})`;
31 label.textContent = `${Math.ceil(current)}/${max | 0}`;
32 bar.classList.toggle("empty", current <= 0);
33 bar.classList.toggle("low", current > 0 && current / max <= 0.25);
34 }
35
36 return {
37 show ()
38 {
39 vitals.hidden = false;
40 bar.hidden = false;
41 render();
42 },
43 hide ()
44 {
45 bar.hidden = true;
46 },
47 apply (message)
48 {
49 if (message?.max != null)
50 { max = Math.max(1, message.max | 0); }
51 if (message?.current != null)
52 { current = Math.max(0, Number(message.current) || 0); }
53 render();
54 },
55 getCurrent ()
56 { return current; },
57 getMax ()
58 { return max; }
59 };
60}