Reset this lesson?

Your edits to this lesson are deleted and its starting files load again.

Zelda-7 finishes the template. Link’s hearts appear in a HUD that updates through the Observer pattern, the game gains a title screen and a game-over screen, and music arrives. This is the code your assignment starts from.

The Observer Pattern

The HUD needs to show Link’s health. The obvious way is for UserInterface.render() to read player.health every frame. That works, but it ties the HUD to Player’s fields, and every new thing the HUD shows (rupees, keys, a boss’s health) means another value polled 60 times a second whether it changed or not.

The Observer pattern flips it around. The HUD subscribes to Link, and Link notifies his subscribers only when something changes:

src/objects/Player.js
100
subscribe(observer) {
101
this.observers.add(observer);
102
}
103
104
/**
105
* Stops sending notifications to an observer.
106
*
107
* @param {PlayerObserver} observer Health observer.
108
* @returns {void}
109
*/
110
unsubscribe(observer) {
111
this.observers.delete(observer);
112
}
113
114
/**
115
* Emits a changed player value to every observer.
116
*
117
* @param {PlayerNotification} notification Changed value.
118
* @returns {void}
119
*/
120
notify(notification) {
121
this.observers.forEach((observer) => {
122
observer.update(notification);
123
});
124
}

takeDamage() sends a notification right after it lowers Link’s health:

src/objects/Player.js
148
this.health = nextHealth;
149
this.damageCooldown = PLAYER_DAMAGE_COOLDOWN;
150
this.notify({ type: "health", value: this.health, max: this.maxHealth });

An observer is anything with an update(notification) method. PlayerNotification and PlayerObserver in globals.d.ts describe the shapes.

The HUD

PlayState creates the HUD and subscribes it to Link:

src/states/PlayState.js
46
this.userInterface = new UserInterface(game, this.player);
47
this.player.subscribe(this.userInterface);

UserInterface copies Link’s starting values once, in its constructor. After that it only learns about changes through update():

src/services/UserInterface.js
48
update(notification) {
49
switch (notification.type) {
50
case "health":
51
this.health = notification.value;
52
this.maxHealth = notification.max;
53
break;

Its render() never touches Player. It draws from its own copies.

Here it is running. Each hit makes Link call notify(), which calls update() on every observer in his set. UserInterface is one; LowHealthWarning is a second, made up for the demo, to show that Link doesn’t care how many there are or what they do. The hearts in the HUD are drawn from UserInterface’s copy, so they only change when a notification arrives:

The notifications are slowed down so you can watch them travel. In the game, update() is an ordinary method call and the HUD changes the same frame Link is hit. The demo refills Link’s health at one heart so it keeps going.

Making Room

The canvas grows by HUD_HEIGHT, one tile, so the HUD has a strip of its own below the room:

src/config/game.js
6
export const HUD_HEIGHT = TILE_SIZE;
7
export const CANVAS_WIDTH = ROOM_WIDTH;
8
export const CANVAS_HEIGHT = ROOM_HEIGHT + HUD_HEIGHT;

Rooms still draw at the top, so nothing else moved.

Hearts

Each heart holds two health, so Link’s 6 health is three hearts. The heart sprites are loaded empty, half, then full, so a heart’s fill (0, 1, or 2) is also its index:

src/services/UserInterface.js
86
for (let index = 0; index < heartCount; index += 1) {
87
const healthInThisHeart = this.health - index * 2;
88
const fill = Math.max(0, Math.min(2, healthInThisHeart));
89
90
this.heartSprites[fill]?.render(context, 4 + index * 10, HUD_Y + 4);
91
}

With 3 health, the first heart has 3 left over (clamped to 2, full), the second has 1 (half), and the third has −1 (clamped to 0, empty).

Title and Game Over

main.js now registers three states and starts on the title screen:

src/main.js
32
game.addState(StateName.TitleScreen, TitleScreenState);
33
game.addState(StateName.Play, PlayState);
34
game.addState(StateName.GameOver, GameOverState);
35
36
game.services.stateMachine.change(StateName.TitleScreen);

TitleScreenState draws title.png and starts the theme. Any key starts the game:

src/states/TitleScreenState.js
18
update(_dt) {
19
if (this.game.input.isAnyKeyPressed()) {
20
this.game.stateMachine.change(StateName.Play);
21
}
22
}

isAnyKeyPressed() is new in lib/Input.js. Like isKeyPressed(), it consumes what it reads, but it clears every key. If it only cleared the first one it found, pressing Z to start would also swing the sword on the first frame of play.

Dying now goes to GameOverState instead of straight back into the dungeon. PlayerDeathState changes to it after the white fade, and the game-over screen restarts the same way Zelda-6 did, by building a new PlayState:

src/states/GameOverState.js
27
if (this.game.input.isKeyPressed(Input.KEYS.ENTER)) {
28
this.game.stateMachine.add(StateName.Play, new PlayState(this.game));
29
this.game.stateMachine.change(StateName.Play);
30
}

Music

Each screen now has its own track. src/config/music.js lists the tracks in Track, and this.game.music plays one looping track at a time. Every state calls this.game.music.play() in enter() and this.game.music.stop() in exit(), so nothing from one screen keeps playing under the next:

  • TitleScreenState plays the theme.
  • PlayState loops the Tail Cave dungeon music.
  • GameOverState plays the game-over music.

PlayerDeathState stops the dungeon music as Link falls, so the death sound plays on its own.

Notify the observers

Link takes damage, but the hearts in the HUD never change, because notify() in src/objects/Player.js is empty.

The finished method is the first code block under The Observer Pattern above. Copy the forEach loop from it into notify().

Then let a Moblin hurt Link and watch the hearts drop. The Challenge tab gets a ✓ once you’ve seen it work in the game.

📚 References

Powered by WebContainers
Files
Preparing Environment