diff --git a/src/Gun.js b/src/Gun.js index 5f7287a..729820f 100644 --- a/src/Gun.js +++ b/src/Gun.js @@ -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 } diff --git a/src/ScoreDisplay.js b/src/ScoreDisplay.js index ae804a2..7cffb31 100644 --- a/src/ScoreDisplay.js +++ b/src/ScoreDisplay.js @@ -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 }; diff --git a/src/Subject.js b/src/Subject.js index 746a9ff..4defcce 100644 --- a/src/Subject.js +++ b/src/Subject.js @@ -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 }; diff --git a/src/Target.js b/src/Target.js index 833c72a..ac723e8 100644 --- a/src/Target.js +++ b/src/Target.js @@ -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 { diff --git a/src/main.js b/src/main.js index 43a5273..fdfc9ac 100644 --- a/src/main.js +++ b/src/main.js @@ -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); + } + }