From ea9a11cbf05d35f540b39842fa14b7586f223e40 Mon Sep 17 00:00:00 2001 From: dragoncoder047 <101021094+dragoncoder047@users.noreply.github.com> Date: Mon, 18 Nov 2024 12:19:14 -0500 Subject: [PATCH] make health use getters and setters --- examples/ghosthunting.js | 2 +- examples/shooter.js | 2 +- src/components/misc/health.ts | 36 +++++++++++------------------------ 3 files changed, 13 insertions(+), 27 deletions(-) diff --git a/examples/ghosthunting.js b/examples/ghosthunting.js index 963fe143..5ca2fba9 100644 --- a/examples/ghosthunting.js +++ b/examples/ghosthunting.js @@ -198,7 +198,7 @@ function addEnemy(p) { { add() { this.onHurt(() => { - this.opacity = this.hp() / 100; + this.opacity = this.hp / 100; }); this.onDeath(() => { const rect = this.localArea(); diff --git a/examples/shooter.js b/examples/shooter.js index ce1e2e8a..58cb01fd 100644 --- a/examples/shooter.js +++ b/examples/shooter.js @@ -307,7 +307,7 @@ scene("battle", () => { }); boss.onHurt(() => { - healthbar.set(boss.hp()); + healthbar.set(boss.hp); }); boss.onDeath(() => { diff --git a/src/components/misc/health.ts b/src/components/misc/health.ts index 979efca1..f67433e5 100644 --- a/src/components/misc/health.ts +++ b/src/components/misc/health.ts @@ -18,19 +18,11 @@ export interface HealthComp extends Comp { /** * Current health points. */ - hp(): number; - /** - * Set current health points. - */ - setHP(hp: number): void; + hp: number /** * Max amount of HP. */ - maxHP(): number | null; - /** - * Set max amount of HP. - */ - setMaxHP(hp: number): void; + maxHP: number | undefined /** * Register an event that runs when hurt() is called upon the object. * @@ -62,29 +54,23 @@ export function health( return { id: "health", hurt(this: GameObj, n: number = 1) { - this.setHP(hp - n); this.trigger("hurt", n); + this.hp -= n; }, heal(this: GameObj, n: number = 1) { - const origHP = hp; - this.setHP(hp + n); - this.trigger("heal", hp - origHP); + this.trigger("heal", n); + this.hp += n; }, - hp(): number { + get hp(): number { return hp; }, - maxHP(): number | null { - return maxHP ?? null; - }, - setMaxHP(n: number): void { - maxHP = n; - }, - setHP(this: GameObj, n: number) { - hp = maxHP ? Math.min(maxHP, n) : n; + set hp(n: number) { + hp = this.maxHP ? Math.min(this.maxHP, n) : n; if (hp <= 0) { - this.trigger("death"); + (this as unknown as GameObj).trigger("death"); } }, + maxHP, onHurt( this: GameObj, action: (amount?: number) => void, @@ -101,7 +87,7 @@ export function health( return this.on("death", action); }, inspect() { - return `health: ${hp}`; + return `health: ${this.hp}` + (this.maxHP ? `/${this.maxHP}` : ""); }, }; }