Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make health use getters and setters #520

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/ghosthunting.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion examples/shooter.js
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ scene("battle", () => {
});

boss.onHurt(() => {
healthbar.set(boss.hp());
healthbar.set(boss.hp);
});

boss.onDeath(() => {
Expand Down
36 changes: 11 additions & 25 deletions src/components/misc/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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<HealthComp>).trigger("death");
}
},
maxHP,
onHurt(
this: GameObj,
action: (amount?: number) => void,
Expand All @@ -101,7 +87,7 @@ export function health(
return this.on("death", action);
},
inspect() {
return `health: ${hp}`;
return `health: ${this.hp}` + (this.maxHP ? `/${this.maxHP}` : "");
},
};
}