From 6051a3a7fdb801c290947226ee64dd5d2b05b9cc Mon Sep 17 00:00:00 2001 From: Lili11-OSS <1599207612@qq.com> Date: Wed, 18 Nov 2026 13:27:49 +0800 Subject: [PATCH 1/6] Add scoring, defeat detection and round restart to Space Invaders --- src/assets/js/games/space-invaders.js | 66 ++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 7 deletions(-) diff --git a/src/assets/js/games/space-invaders.js b/src/assets/js/games/space-invaders.js index 580f1efc..cfc8b937 100644 --- a/src/assets/js/games/space-invaders.js +++ b/src/assets/js/games/space-invaders.js @@ -85,8 +85,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 +120,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 +166,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 +178,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 +213,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 +238,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 +295,7 @@ const SpaceInvaders = (() => { // ─── Victory / cleanup ──────────────────────────────────────────────────── function _onVictory(scene) { + if (!_finishRound(scene)) return; const w = scene.scale.width; const h = scene.scale.height; @@ -281,9 +306,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 +327,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 +335,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() { From e67b049a46606e40284306b7760f2c333ed281e5 Mon Sep 17 00:00:00 2001 From: Lili11-OSS <1599207612@qq.com> Date: Wed, 18 Nov 2026 13:27:53 +0800 Subject: [PATCH 2/6] Cover scoring, defeat, reward idempotence and restart --- tests/space-invaders.test.cjs | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 tests/space-invaders.test.cjs diff --git a/tests/space-invaders.test.cjs b/tests/space-invaders.test.cjs new file mode 100644 index 00000000..a44f9163 --- /dev/null +++ b/tests/space-invaders.test.cjs @@ -0,0 +1,63 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); + +function game() { + let config; + const rewards = []; + const scores = []; + const context = vm.createContext({ + window: { innerWidth: 1000, innerHeight: 800 }, + document: { createElement: () => ({ style: {} }), body: { appendChild() {} } }, + Phaser: { CANVAS: 1 }, XP_SPACE_INVADERS_WIN: 100, + GameManager: { + loadPhaser: fn => fn(), create: (_, c) => { config = c; }, + awardXP: xp => rewards.push(xp), incrementStat: () => 1, + grantAchievement() {}, setHighScore: (_, score) => scores.push(score), destroy() {}, + }, + }); + 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(){},setAllowGravity(){},setSize(){},setVelocityX(v){this.vx=v;},setVelocityY(){}}; }, + group, overlap(a,b,fn) { scene.hit=fn; }, + } }, + time: { now:1000,addEvent(c) { scene.move=c.callback; return {remove() { scene.timerRemoved=true; }}; } }, + input: { once() {},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'); +}); From 2cad0de2ced38baad6a04d532be87ec7dd7b2289 Mon Sep 17 00:00:00 2001 From: Lili11-OSS <1599207612@qq.com> Date: Wed, 18 Nov 2026 13:37:23 +0800 Subject: [PATCH 3/6] Address static analysis findings in Space Invaders contribution --- src/assets/js/games/space-invaders.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/assets/js/games/space-invaders.js b/src/assets/js/games/space-invaders.js index cfc8b937..68333b13 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. * @@ -182,7 +183,7 @@ const SpaceInvaders = (() => { bullet.destroy(); alien.destroy(); scene.si_score += 10; - scene.si_scoreText.setText("SCORE " + scene.si_score); + scene.si_scoreText.setText(`SCORE ${scene.si_score}`); _playInvaderHitSound(); if (scene.si_aliens.countActive() === 0) { @@ -354,7 +355,7 @@ const SpaceInvaders = (() => { .text( scene.scale.width / 2, scene.scale.height / 2, - "GAME OVER\nSCORE " + scene.si_score + "\nR RESTART ESC QUIT", + `GAME OVER\nSCORE ${scene.si_score}\nR RESTART ESC QUIT`, { fontSize: "24px", fill: "#ffffff", From 62dc09bbfd096d88df9c33afa33b890e62b9f429 Mon Sep 17 00:00:00 2001 From: Lili11-OSS <1599207612@qq.com> Date: Wed, 18 Nov 2026 13:37:28 +0800 Subject: [PATCH 4/6] Address static analysis findings in Space Invaders contribution --- tests/space-invaders.test.cjs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/space-invaders.test.cjs b/tests/space-invaders.test.cjs index a44f9163..babd6513 100644 --- a/tests/space-invaders.test.cjs +++ b/tests/space-invaders.test.cjs @@ -3,37 +3,37 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const vm = require('node:vm'); -function game() { - let config; +const game = () => { + let config = null; const rewards = []; const scores = []; const context = vm.createContext({ window: { innerWidth: 1000, innerHeight: 800 }, - document: { createElement: () => ({ style: {} }), body: { appendChild() {} } }, + 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() {}, setHighScore: (_, score) => scores.push(score), destroy() {}, + 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); + 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(){},setAllowGravity(){},setSize(){},setVelocityX(v){this.vx=v;},setVelocityY(){}}; }, + 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() {},keyboard: {createCursorKeys:()=>({left:{},right:{},space:{}}),once(k,fn){handlers[k]=fn;} } }, + 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;}}; From 592b4b6d6199a0fb64c0a7e82d39c3fea3fb2024 Mon Sep 17 00:00:00 2001 From: Lili11-OSS <1599207612@qq.com> Date: Wed, 18 Nov 2026 13:45:26 +0800 Subject: [PATCH 5/6] Keep new game canvas mounted after lifecycle cleanup --- src/assets/js/games/space-invaders.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/assets/js/games/space-invaders.js b/src/assets/js/games/space-invaders.js index 68333b13..82d96625 100644 --- a/src/assets/js/games/space-invaders.js +++ b/src/assets/js/games/space-invaders.js @@ -42,7 +42,6 @@ const SpaceInvaders = (() => { pointerEvents: "auto", background: "#000000", }); - document.body.appendChild(canvas); const config = { type: Phaser.CANVAS, @@ -63,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 ───────────────────────────────────────────────────── From eaa171a0465e6200c07c7fa19547016a8732ba40 Mon Sep 17 00:00:00 2001 From: Lili11-OSS <1599207612@qq.com> Date: Wed, 18 Nov 2026 13:45:40 +0800 Subject: [PATCH 6/6] Keep new game canvas mounted after lifecycle cleanup --- tests/space-invaders.test.cjs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/space-invaders.test.cjs b/tests/space-invaders.test.cjs index babd6513..0dafed71 100644 --- a/tests/space-invaders.test.cjs +++ b/tests/space-invaders.test.cjs @@ -61,3 +61,27 @@ test('victory awards once, stores round score, and supports restart',()=>{ 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); +});