diff --git a/src/assets/js/games/space-invaders.js b/src/assets/js/games/space-invaders.js index 580f1efc..82d96625 100644 --- a/src/assets/js/games/space-invaders.js +++ b/src/assets/js/games/space-invaders.js @@ -1,3 +1,4 @@ +/* global GameManager, Phaser, XP_SPACE_INVADERS_WIN */ /** * space-invaders.js — The classic Space Invaders Easter Egg game. * @@ -41,7 +42,6 @@ const SpaceInvaders = (() => { pointerEvents: "auto", background: "#000000", }); - document.body.appendChild(canvas); const config = { type: Phaser.CANVAS, @@ -62,6 +62,8 @@ const SpaceInvaders = (() => { }; GameManager.create(GAME_ID, config); + // create() removes the previous canvas; attach the new one afterwards. + document.body.appendChild(canvas); } // ─── Scene callbacks ───────────────────────────────────────────────────── @@ -85,8 +87,20 @@ const SpaceInvaders = (() => { } function _onUpdate() { - if (!this.si_player?.body) return; - + if (!this.si_player?.body || this.si_finished) return; + + if ( + this.si_aliens + .getChildren() + .some( + (alien) => + alien.active && + alien.getBounds().bottom >= this.si_player.getBounds().top, + ) + ) { + _onDefeat(this); + return; + } _updatePlayerVelocity(this); if (this.si_cursors.space.isDown) { _fireBullet(this); @@ -108,6 +122,13 @@ const SpaceInvaders = (() => { // ─── Game setup ────────────────────────────────────────────────────────── function _setupGame(scene) { + scene.si_finished = false; + scene.si_score = 0; + scene.si_scoreText = scene.add.text(20, 20, "SCORE 0", { + fontSize: "24px", + fill: "#ffffff", + }); + // Player rocket scene.si_player = scene.add.text( window.innerWidth / 2, @@ -147,7 +168,7 @@ const SpaceInvaders = (() => { // Alien movement timer scene.si_alienDirection = 1; - scene.time.addEvent({ + scene.si_movementTimer = scene.time.addEvent({ delay: 800, callback: _moveAliens, callbackScope: scene, @@ -159,8 +180,11 @@ const SpaceInvaders = (() => { scene.si_bullets, scene.si_aliens, (bullet, alien) => { + if (scene.si_finished || !bullet.active || !alien.active) return; bullet.destroy(); alien.destroy(); + scene.si_score += 10; + scene.si_scoreText.setText(`SCORE ${scene.si_score}`); _playInvaderHitSound(); if (scene.si_aliens.countActive() === 0) { @@ -191,6 +215,7 @@ const SpaceInvaders = (() => { /** Called with `callbackScope: scene` so `this` = scene. */ function _moveAliens() { + if (this.si_finished) return; const padding = 60; let hitEdge = false; const children = this.si_aliens.getChildren(); @@ -215,6 +240,7 @@ const SpaceInvaders = (() => { } function _fireBullet(scene) { + if (scene.si_finished) return; const now = scene.time.now; if (now - scene.si_lastFired < 400) return; @@ -271,6 +297,7 @@ const SpaceInvaders = (() => { // ─── Victory / cleanup ──────────────────────────────────────────────────── function _onVictory(scene) { + if (!_finishRound(scene)) return; const w = scene.scale.width; const h = scene.scale.height; @@ -281,9 +308,6 @@ const SpaceInvaders = (() => { const wins = GameManager.incrementStat("space_invaders_wins"); if (wins === 1) GameManager.grantAchievement("first_blood"); - // Update high score (score = wins × 100) - GameManager.setHighScore(GAME_ID, wins * 100); - // Victory overlay scene.add .text(w / 2, h / 2 - 60, "🎉 INVADERS REPELLED! 🎉", { @@ -305,7 +329,7 @@ const SpaceInvaders = (() => { .setOrigin(0.5); scene.add - .text(w / 2, h / 2 + 70, "Click anywhere to continue", { + .text(w / 2, h / 2 + 70, "R RESTART ESC QUIT CLICK TO CLOSE", { fontSize: "16px", fill: "#ffffff", alpha: 0.7, @@ -313,6 +337,36 @@ const SpaceInvaders = (() => { .setOrigin(0.5); scene.input.once("pointerdown", _cleanup); + scene.input.keyboard.once("keydown-R", () => scene.scene.restart()); + } + + function _finishRound(scene) { + if (scene.si_finished) return false; + scene.si_finished = true; + scene.si_player.body.setVelocityX(0); + scene.si_movementTimer.remove(false); + scene.physics.pause(); + GameManager.setHighScore(GAME_ID, scene.si_score); + return true; + } + + function _onDefeat(scene) { + if (!_finishRound(scene)) return; + scene.add + .text( + scene.scale.width / 2, + scene.scale.height / 2, + `GAME OVER\nSCORE ${scene.si_score}\nR RESTART ESC QUIT`, + { + fontSize: "24px", + fill: "#ffffff", + align: "center", + backgroundColor: "#000000", + padding: { x: 20, y: 20 }, + }, + ) + .setOrigin(0.5); + scene.input.keyboard.once("keydown-R", () => scene.scene.restart()); } function _cleanup() { diff --git a/tests/space-invaders.test.cjs b/tests/space-invaders.test.cjs new file mode 100644 index 00000000..0dafed71 --- /dev/null +++ b/tests/space-invaders.test.cjs @@ -0,0 +1,87 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); + +const game = () => { + let config = null; + const rewards = []; + const scores = []; + const context = vm.createContext({ + window: { innerWidth: 1000, innerHeight: 800 }, + document: { createElement: () => ({ style: {} }), body: { appendChild() { /* Unused renderer hook in this scene test double. */ } } }, + Phaser: { CANVAS: 1 }, XP_SPACE_INVADERS_WIN: 100, + GameManager: { + loadPhaser: fn => fn(), create: (_, c) => { config = c; }, + awardXP: xp => rewards.push(xp), incrementStat: () => 1, + grantAchievement() { /* Unused renderer hook in this scene test double. */ }, setHighScore: (_, score) => scores.push(score), destroy() { /* Unused renderer hook in this scene test double. */ }, + }, + }); + vm.runInContext(`${fs.readFileSync('src/assets/js/games/space-invaders.js', 'utf8')}\nSpaceInvaders.launch();`, context); + const handlers = {}; + const group = () => ({ children: [], add(x) { this.children.push(x); }, getChildren() { return this.children.filter(x => x.active); }, countActive() { return this.getChildren().length; } }); + const scene = { + scale: { width: 1000, height: 800 }, + add: { text(x,y,text) { return { x,y,text,width:24,active:true, setOrigin() { return this; },setText(t) { this.text=t; },getBounds() { return {top:this.y,bottom:this.y+24}; },destroy() { this.active=false; } }; } }, + physics: { pause() { scene.paused=true; }, add: { + existing(x) { x.body={setCollideWorldBounds(){ /* Unused physics hook in this scene test double. */ },setAllowGravity(){ /* Unused physics hook in this scene test double. */ },setSize(){ /* Unused physics hook in this scene test double. */ },setVelocityX(v){this.vx=v;},setVelocityY(){ /* Unused physics hook in this scene test double. */ }}; }, + group, overlap(a,b,fn) { scene.hit=fn; }, + } }, + time: { now:1000,addEvent(c) { scene.move=c.callback; return {remove() { scene.timerRemoved=true; }}; } }, + input: { once() { /* Unused renderer hook in this scene test double. */ },keyboard: {createCursorKeys:()=>({left:{},right:{},space:{}}),once(k,fn){handlers[k]=fn;} } }, + scene: { restart() { config.scene.create.call(scene); } }, + }; + config.scene.create.call(scene); + return { scene, handlers, rewards, scores, update:()=>config.scene.update.call(scene) }; +}; + +test('hits update HUD; duplicate collision cannot score twice',()=>{ + const {scene}=game(); const bullet={active:true,destroy(){this.active=false;}}; + const alien=scene.si_aliens.getChildren()[0]; + scene.hit(bullet,alien); scene.hit(bullet,alien); + assert.equal(scene.si_score,10);assert.equal(scene.si_scoreText.text,'SCORE 10'); +}); + +test('invasion ends round, freezes input, awards no XP; restart resets round',()=>{ + const {scene,update,handlers,rewards,scores}=game(); + scene.si_aliens.getChildren()[0].y=scene.si_player.y; + update(); update(); + assert.equal(scene.si_finished,true);assert.equal(scene.timerRemoved,true); + assert.equal(scene.paused,true);assert.deepEqual(rewards,[]);assert.deepEqual(scores,[0]); + scene.si_cursors.space.isDown=true; update();assert.equal(scene.si_bullets.countActive(),0); + handlers['keydown-R']();assert.equal(scene.si_finished,false);assert.equal(scene.si_score,0); + assert.equal(scene.si_aliens.countActive(),50); +}); + +test('victory awards once, stores round score, and supports restart',()=>{ + const {scene,rewards,scores,handlers}=game(); + for(const alien of [...scene.si_aliens.getChildren()]) scene.hit({active:true,destroy(){this.active=false;}},alien); + assert.equal(scene.si_finished,true);assert.equal(scene.si_score,500); + assert.deepEqual(rewards,[100]);assert.deepEqual(scores,[500]); + scene.hit({active:true},{active:true});assert.deepEqual(rewards,[100]); + handlers['keydown-R']();assert.equal(scene.si_scoreText.text,'SCORE 0'); +}); + +test('launch attaches the new canvas after manager cleanup, including relaunch', () => { + const canvases = []; + const context = vm.createContext({ + window: { innerWidth: 1000, innerHeight: 800 }, + document: { + createElement: () => ({ style: {}, remove() { canvases.splice(canvases.indexOf(this), 1); } }), + getElementById: id => canvases.find(canvas => canvas.id === id), + body: { appendChild: canvas => canvases.push(canvas) }, + }, + Phaser: { CANVAS: 1, Game: class { + constructor(config) { this.canvas = config.canvas; } + destroy() { this.canvas.remove(); } + } }, + }); + vm.runInContext(fs.readFileSync('src/assets/js/games/game-manager.js', 'utf8'), context); + vm.runInContext(fs.readFileSync('src/assets/js/games/space-invaders.js', 'utf8'), context); + vm.runInContext('SpaceInvaders.launch()', context); + assert.equal(canvases.length, 1); + const firstCanvas = canvases[0]; + vm.runInContext('SpaceInvaders.launch()', context); + assert.equal(canvases.length, 1); + assert.notEqual(canvases[0], firstCanvas); +});