Skip to content

Commit

Permalink
Multiple score handlers per PlayerState (#1436) (#1452)
Browse files Browse the repository at this point in the history
Co-authored-by: Ben Villalobos <4691428+BenVillalobos@users.noreply.github.com>
  • Loading branch information
jwunderl and benvillalobos authored Jun 29, 2023
1 parent ca1117f commit 64f00b8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
26 changes: 18 additions & 8 deletions libs/game/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ namespace info {
// null: reached 0 and callback was invoked
public life: number;
public lifeZeroHandler: () => void;
public scoreReachedHandler: ScoreReachedHandler
public scoreReachedHandlers: ScoreReachedHandler[];

public showScore?: boolean;
public showLife?: boolean;
Expand All @@ -45,6 +45,7 @@ namespace info {
this.showScore = undefined;
this.showLife = undefined;
this.showPlayer = undefined;
this.scoreReachedHandlers = [];
}
}

Expand Down Expand Up @@ -711,12 +712,12 @@ namespace info {
const oldScore = state.score || 0;
state.score = (value | 0);

if (state.scoreReachedHandler && (
(oldScore < state.scoreReachedHandler.score && state.score >= state.scoreReachedHandler.score) ||
(oldScore > state.scoreReachedHandler.score && state.score <= state.scoreReachedHandler.score)
)) {
state.scoreReachedHandler.handler();
}
state.scoreReachedHandlers.forEach(srh => {
if ((oldScore < srh.score && state.score >= srh.score) ||
(oldScore > srh.score && state.score <= srh.score)) {
srh.handler();
}
});
}

changeScoreBy(value: number): void {
Expand Down Expand Up @@ -766,7 +767,16 @@ namespace info {

onScore(score: number, handler: () => void) {
const state = this.getState();
state.scoreReachedHandler = new ScoreReachedHandler(score, handler);

for (const element of state.scoreReachedHandlers) {
if (element.score === score) {
// Score handlers are implemented as "last one wins."
element.handler = handler;
return;
}
}

state.scoreReachedHandlers.push(new ScoreReachedHandler(score, handler));
}

raiseLifeZero(gameOver: boolean) {
Expand Down
1 change: 1 addition & 0 deletions libs/multiplayer/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ namespace mp {
onReachedScore(score: number, handler: (player: Player) => void) {
const existing = this.getScoreHandler(score);

// Overwrite the existing handler for this score. Last one wins.
if (existing) {
existing.handler = handler;
return;
Expand Down

0 comments on commit 64f00b8

Please sign in to comment.