Implementing Observer pattern
This commit is contained in:
parent
71aeb0057a
commit
df9229cb78
|
@ -13,12 +13,12 @@ The Gun is the mouse. To draw it, hide the cursor with the noCursor function and
|
|||
|
||||
|
||||
class Gun extends Subject {
|
||||
constructor(totalShots) {
|
||||
constructor(totShots) {
|
||||
super();
|
||||
this.cursorImg = null;
|
||||
this.shotSound = null;
|
||||
this.emptySound = null;
|
||||
this.remainingShots = totalShots;
|
||||
this.remainingShots = totShots;
|
||||
this.bullets = []; // array of Bullet objects
|
||||
}
|
||||
|
||||
|
|
|
@ -38,6 +38,16 @@ class ScoreDisplay {
|
|||
}
|
||||
|
||||
}
|
||||
|
||||
update(source, ...others) {
|
||||
if (source === 'gun') {
|
||||
const [, , remainingShots] = others;
|
||||
this.shotLeft = remainingShots;
|
||||
} else if (source === 'target-hit') {
|
||||
const [points] = others;
|
||||
this.score += points;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { ScoreDisplay };
|
||||
|
|
|
@ -1,5 +1,27 @@
|
|||
class Subject {
|
||||
// TO DO
|
||||
constructor() {
|
||||
this.observers = [];
|
||||
}
|
||||
|
||||
subscribe(observer) {
|
||||
if (!observer || typeof observer.update !== 'function') return;
|
||||
this.observers.push(observer);
|
||||
}
|
||||
|
||||
unsubscribe(observer) {
|
||||
this.observers = this.observers.filter(o => o !== observer);
|
||||
}
|
||||
|
||||
unsubscribeAll() {
|
||||
this.observers = [];
|
||||
}
|
||||
|
||||
notifySubscribers(source, ...others) {
|
||||
for (let observer of this.observers) {
|
||||
observer.update(source, ...others);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export { Subject };
|
||||
|
|
|
@ -39,6 +39,15 @@ class Target extends Subject {
|
|||
py >= this.y &&
|
||||
py <= this.y + TARGET_WIDTH;
|
||||
}
|
||||
|
||||
update(source, ...others) {
|
||||
if (source === 'gun') {
|
||||
const [x, y] = others;
|
||||
if (this.contains(x, y)) {
|
||||
this.hit();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TeddyTarget extends Target {
|
||||
|
|
|
@ -20,6 +20,14 @@ function setup() {
|
|||
// 2. Init the targets
|
||||
initTargets();
|
||||
// 3. Subscribe gun
|
||||
gun.subscribe(score);
|
||||
|
||||
// Subscribe each target to gun
|
||||
for (let target of targets) {
|
||||
gun.subscribe(target);
|
||||
target.subscribe(score);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user