From 5033ac83838d25db52ccbf53cfd7368927a9c4c7 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:18:18 -0300 Subject: [PATCH 1/2] feat: add mobile entry point for practice mode and enhance ranked play handling - Introduced a new script for mobile entry testing to ensure proper functionality on mobile devices. - Updated the title page to include a practice option alongside the main play button for mobile users. - Enhanced the StartScene to handle practice mode initiation and integrate mobile entry checks. - Modified ranked page descriptions to clarify the availability of practice mode during ranked service failures. - Added tests to validate mobile entry behavior and ranked service failure responses. --- phaser-asteroids/docs/menus.md | 18 +- phaser-asteroids/package.json | 1 + phaser-asteroids/scripts/mobile-entry.mjs | 255 +++++++++++++++++++ phaser-asteroids/src/scenes/StartScene.ts | 22 +- phaser-asteroids/src/ui/menu/pages/ranked.ts | 24 +- phaser-asteroids/src/ui/menu/pages/title.ts | 126 ++++++--- phaser-asteroids/src/ui/menu/widgets.ts | 4 +- phaser-asteroids/tests/mobileEntry.test.ts | 38 +++ 8 files changed, 437 insertions(+), 51 deletions(-) create mode 100644 phaser-asteroids/scripts/mobile-entry.mjs create mode 100644 phaser-asteroids/tests/mobileEntry.test.ts diff --git a/phaser-asteroids/docs/menus.md b/phaser-asteroids/docs/menus.md index 714e770..97b72b1 100644 --- a/phaser-asteroids/docs/menus.md +++ b/phaser-asteroids/docs/menus.md @@ -7,7 +7,7 @@ what the pick-ups do; everything that is a setting is one step away.** Gameplay, ## Hierarchy ``` -Title Pause (during a run) +Desktop title Pause (during a run) ├── PLAY (Space; start the run) ├── RESUME (P / START; continues, cannon kept quiet) ├── RANKED (R; one player) ── RANKED PLAY page, see below ├── 1 PLAYER | 2 PLAYERS (keyboard; 1 / 2) ├── AUDIO ──┐ @@ -63,13 +63,21 @@ used by the keyboard and the controller alike. ## Ranked play and High Scores (leaderboard pass) -The title screen has a green PLAY and a gold RANKED side by side, and HIGH SCORES in the row with AUDIO and CONTROLS. They are ordinary pages of the same menu kit: +The desktop title screen keeps green PLAY (unranked) and gold RANKED side by side, with HIGH SCORES beside the player-count selector. They are ordinary pages of the same menu kit: -* `ranked` (RANKED PLAY): the rules in four lines including the time limit, the best verified score on this device, START RANKED RUN, HIGH SCORES, BACK. START asks the server for a challenge ("CONNECTING..."; BACK/Esc cancels); a failure replaces the page's content with a plain message and TRY AGAIN / PLAY NORMALLY / BACK. +* `ranked` (RANKED PLAY): the rules in four lines including the time limit, the best verified score on this device, START RANKED RUN, HIGH SCORES, BACK. START asks the server for a challenge ("CONNECTING..."; BACK/Esc cancels); a failure replaces the page's content with a plain message and RETRY / PLAY PRACTICE INSTEAD / BACK. Builds requiring an update retain the reload instruction instead of offering a futile retry. * `scores` (HIGH SCORES): board tabs (`MenuChoice`, so Left/Right switch boards on a keyboard or D-pad), ten rows, PREVIOUS / BACK / NEXT. It is also opened from the ranked result page, inside the game scene's own menu view. * `result` (game scene only, ranked runs): name field, SUBMIT SCORE, SKIP; then the verdict pages. The name field is a new widget, `MenuField`, whose text is a real DOM `` (`src/ui/nicknameInput.ts`). * With two players chosen RANKED is disabled and says `1 PLAYER ONLY`. Full description, states and tests: `docs/leaderboard-backend.md` section 15. +### Mobile solo entry + +Touch mode, or a device whose primary pointer is coarse, gets a full-width green **PLAY** for ranked gameplay. Its caption says **ONLINE LEADERBOARD / 20:00 LIMIT**. PLAY, Space and assigned-controller START all request a challenge through the existing ranked flow immediately; the request page provides CONNECTING, CANCEL and input recovery. No run begins before the challenge and input readiness checks succeed, including a second input check after the response arrives. + +**PRACTICE** (caption: NO ONLINE SCORE) and gold **HIGH SCORES** occupy the next row. AUDIO, CONTROLS and **RANKED INFO** occupy a quieter third row. RANKED INFO preserves the full explanation, time limit and device best without issuing a challenge. Practice starts the normal game, even with the development `?ranked` flag, and never requests a challenge. Server errors offer an explicit **RETRY** and **PLAY PRACTICE INSTEAD**; there is no automatic casual fallback. + +A phone with touch controls off keeps its saved preference. Both PLAY and PRACTICE first require either an assigned controller or evidence of a physical keyboard; otherwise they show the same touch recovery controls. Enabling touch is an explicit choice followed by a separate start action, preserving which run type was requested. Keyboard-mode phones retain the player-count selector at the top left; choosing two players restores the existing co-op title layout and controls. Fine-pointer desktops, including touch-capable laptops, keep their original entry behavior. + ## Where each existing setting lives now | Setting | Was | Now | @@ -101,7 +109,7 @@ Every device drives the same state machine (`menuController.ts`): ## Phones: safeguards kept -- **No tap-anywhere start.** PLAY is a button; empty space does nothing. On a phone that is in keyboard mode the PLAY button is *keys only* ("PLAY WITH KEYBOARD", tapping it does nothing). +- **No tap-anywhere start.** PLAY is a button; empty space does nothing. A phone's solo PLAY and PRACTICE actions check input readiness and explain how to recover touch controls when needed. The recovery page's START WITH KEYBOARD action is keys only; a finger cannot activate it. The existing two-player keyboard title keeps its keys-only PLAY WITH KEYBOARD button. - **Leaving touch mode takes two taps** on a deliberately plain button ("SWITCH TO KEYBOARD", then "TAP AGAIN TO SWITCH TO KEYBOARD CONTROLS"; the question lapses after 3 s; a second touch within 300 ms is not a confirmation). It exists only on the title screen's CONTROLS page: the mode cannot change during a run. - **A way back that cannot be missed.** On a touch-capable device in keyboard mode the title screen has a large green **TOUCH CONTROLS: OFF / TAP TO TURN ON** button top right, and the CONTROLS page starts with a full-width @@ -140,9 +148,11 @@ rebuilt when its content changes (player count, mode, a controller assigned) wit | Focus geometry, wrap-around, page stack | `tests/menuNav.test.ts` | | The controller: keys, pad, mouse, touch, input lock, rebuild, no build-up | `tests/menuController.test.ts` | | Power-up text from the constants, the key / pad / touch reference against the real mappings, legend widths | `tests/menuContent.test.ts` | +| Mobile entry selection from input mode, primary pointer and player count; recoverable failure wording | `tests/mobileEntry.test.ts` | | Haptics default ON, saved OFF kept, junk, blocked storage, nothing written | `tests/haptics.test.ts` | | Browser: hierarchy, keys listed are the keys that work, AUDIO / CONTROLS / CO-OP navigation and persistence, pause submenus keep the run paused, Space / A / held laser and boost never fire on resume, taps never reach the game, 25 + 20 open / close rounds leak nothing, controller navigation, **an automated layout review of every page at 5 phone and 5 desktop sizes**, reduced motion | `npm run test:menu` (`scripts/menu.mjs`, screenshots in `scripts/.smoke-output/menu-*.png`) | | Browser: ranked / High Scores / result pages with a real Worker and D1 (including gamepad and touch navigation of them) | `npm run test:ranked`, `npm run test:ranked:ui` | +| Focused production browser + real Worker/D1: mobile direct ranked PLAY, explicit PRACTICE, High Scores/settings, phone landscape layout, backend failure/retry, touch-off recovery, controller disconnect, cancellation and unchanged desktop/co-op entry | `npm run test:mobile-entry` (`scripts/mobile-entry.mjs`, screenshots in `scripts/.smoke-output/mobile-entry-*.png`) | | Browser: the touch, keyboard, controller, music and co-op suites drive the new menus through `menuSnapshot()` / `pauseMenuSnapshot()` (the scene's debug hook lists every button's id, label and rectangle) | `npm run test:touch`, `test:input`, `test:gamepad`, `test:music`, `test:coop`, `test:browser`, `test:pages` | ## Known limits diff --git a/phaser-asteroids/package.json b/phaser-asteroids/package.json index ea1b2fd..3a0d215 100644 --- a/phaser-asteroids/package.json +++ b/phaser-asteroids/package.json @@ -21,6 +21,7 @@ "test:touch": "npm run build && node scripts/touch.mjs", "test:music": "npm run build && node scripts/music.mjs", "test:menu": "npm run build && node scripts/menu.mjs", + "test:mobile-entry": "npm run build && node scripts/mobile-entry.mjs", "test:pages": "npm run build && node scripts/pages-check.mjs", "test:server": "vitest run server/tests", "test:ranked": "npm run build && node scripts/ranked-browser.mjs", diff --git a/phaser-asteroids/scripts/mobile-entry.mjs b/phaser-asteroids/scripts/mobile-entry.mjs new file mode 100644 index 0000000..8f93731 --- /dev/null +++ b/phaser-asteroids/scripts/mobile-entry.mjs @@ -0,0 +1,255 @@ +// Focused title-entry regression checks against the production build and real local Worker/D1. +// Faults are injected at the browser network boundary; no gameplay or ranked validation is bypassed. +import fs from 'node:fs'; +import { clickItem, itemPoint, makeChecker, menuItems, openTitle, requireBuild, sceneTexts, sleep, startGameAndBrowser, WorkerStack } from './lib/rankedStack.mjs'; + +const PORT = 4417; +const worker = new WorkerStack({ port: 8797, gamePort: PORT }); +const { check, state } = makeChecker(); +requireBuild(); +const migration = worker.migrate(); +if (!migration.ok) throw new Error(migration.output); +fs.mkdirSync('scripts/.smoke-output', { recursive: true }); +let game; +try { + await worker.start(); + game = await startGameAndBrowser(PORT); + const { browser, GAME } = game; + const phone = async ({ off = false, width = 844, height = 390, query = '' } = {}) => { + const ctx = await browser.newContext({ viewport: { width, height }, isMobile: true, hasTouch: true }); + await ctx.addInitScript((off) => { + if (off) localStorage.setItem('asteroids.inputMode', 'desktop'); + localStorage.setItem('asteroids.touchMovement', 'pointToFly'); + window.testPad = null; + Object.defineProperty(navigator, 'getGamepads', { value: () => [window.testPad, null, null, null] }); + }, off); + const page = await openTitle(ctx, GAME, { api: worker.API, query }); + let requests = 0; + page.on('request', (r) => { if (r.method() === 'POST' && r.url().endsWith('/api/v1/runs')) requests++; }); + return { ctx, page, requests: () => requests }; + }; + const tap = async (page, id) => { + const p = await itemPoint(page, id); + await page.touchscreen.tap(p.x, p.y); + await sleep(300); + }; + const playing = (page, ranked) => page.waitForFunction((ranked) => window.__game.scene.isActive('GameScene') && !!window.__ASTEROIDS_REPLAY__?.isVerified === ranked, ranked, { timeout: 15000 }); + const recovery = async (page) => (await sceneTexts(page, 'StartScene')).includes('TOUCH GAMEPLAY CONTROLS ARE OFF.'); + const titleActive = (page) => page.evaluate(() => window.__game.scene.isActive('StartScene')); + const prefsOff = (page) => page.evaluate(() => localStorage.getItem('asteroids.inputMode') === 'desktop' && localStorage.getItem('asteroids.touchMovement') === 'pointToFly'); + const waitError = (page) => page.waitForFunction(() => window.__game.scene.getScene('StartScene').menuSnapshot().items.some((i) => i.id === 'play-normally')); + const outage = (page) => page.route(`${worker.API}/api/v1/runs`, (route) => route.request().method() === 'POST' + ? route.fulfill({ status: 503, contentType: 'application/json', body: '{"error":{"code":"unavailable","message":"Test outage"}}' }) + : route.continue()); + const putPad = (page, pressed = false) => page.evaluate((pressed) => { + window.testPad = { index: 0, id: 'Test standard controller', mapping: 'standard', connected: true, axes: [0, 0, 0, 0], buttons: Array.from({ length: 17 }, (_, i) => ({ pressed: pressed && i === 0, value: pressed && i === 0 ? 1 : 0 })) }; + }, pressed); + const joinPad = async (page) => { await putPad(page, true); await sleep(150); await putPad(page); await sleep(300); }; + + for (const [width, height] of [[667, 375], [844, 390]]) { + const { ctx, page, requests } = await phone({ width, height }); + const snap = await menuItems(page); + const play = snap.items.find((i) => i.id === 'play'); + const practice = snap.items.find((i) => i.id === 'practice'); + const scores = snap.items.find((i) => i.id === 'scores'); + check(`${width}: PLAY dominates; PRACTICE and HIGH SCORES have their own row`, play.w === 560 && play.h > practice.h && scores.y === practice.y && scores.y > play.y); + const scale = await page.evaluate(() => document.querySelector('canvas').getBoundingClientRect().width / 1280); + check(`${width}: all targets are >=44 CSS px and fit the landscape canvas`, snap.items.every((i) => Math.min(i.w, i.h) * scale >= 44 && i.x >= 0 && i.y >= 0 && i.x + i.w <= 1280 && i.y + i.h <= 720)); + check(`${width}: no overlapping controls`, snap.items.every((a, i) => snap.items.slice(i + 1).every((b) => a.x >= b.x + b.w || b.x >= a.x + a.w || a.y >= b.y + b.h || b.y >= a.y + a.h))); + check(`${width}: PLAY explains leaderboard entry and the standard time limit`, (await sceneTexts(page, 'StartScene')).includes('ONLINE LEADERBOARD / 20:00 LIMIT')); + await page.screenshot({ path: `scripts/.smoke-output/mobile-entry-${width}.png` }); + await tap(page, 'ranked'); + check(`${width}: ranked explanation remains accessible without issuing a challenge`, (await sceneTexts(page, 'StartScene')).includes('A RANKED RUN ENDS AT 20:00.') && requests() === 0); + await tap(page, 'back'); + await tap(page, 'scores'); + check(`${width}: High Scores opens directly without starting a run`, (await menuItems(page)).page === 'scores' && requests() === 0); + await tap(page, 'back'); + for (const id of ['audio', 'controls']) { + await tap(page, id); + check(`${width}: ${id} remains one tap away`, (await menuItems(page)).page === id); + await tap(page, 'back'); + } + await tap(page, 'play'); + await playing(page, true); + check(`${width}: primary PLAY directly starts one ranked challenge with touch controls`, requests() === 1 && await page.evaluate(() => document.querySelector('.tc-root').classList.contains('tc-play'))); + check(`${width}: ranked run keeps the selected movement mode`, await page.evaluate(() => localStorage.getItem('asteroids.touchMovement') === 'pointToFly')); + await ctx.close(); + } + { + // Even the development ?ranked override must not hijack an explicit Practice action. + const { ctx, page, requests } = await phone({ query: 'ranked=1' }); + await tap(page, 'practice'); + await playing(page, false); + check('PRACTICE starts the normal game without a ranked request, including with ?ranked', requests() === 0); + await ctx.close(); + } + for (const input of ['keyboard', 'gamepad']) { + const { ctx, page, requests } = await phone(); + const press = async (key, button) => { + if (input === 'keyboard') await page.keyboard.press(key); + else { + await page.evaluate((button) => { window.testPad.buttons[button] = { pressed: true, value: 1 }; }, button); + await sleep(100); + await page.evaluate((button) => { window.testPad.buttons[button] = { pressed: false, value: 0 }; }, button); + } + await sleep(250); + }; + if (input === 'gamepad') { await putPad(page); await sleep(200); await joinPad(page); } + await press('ArrowDown', 13); + check(`mobile ${input}: Down from PLAY focuses PRACTICE`, (await menuItems(page)).focus === 'practice'); + await press('ArrowRight', 15); + await press('Enter', 0); + check(`mobile ${input}: Right and select opens HIGH SCORES`, (await menuItems(page)).page === 'scores' && requests() === 0); + await press('Escape', 1); + await press('ArrowLeft', 14); + await press('Enter', 0); + await playing(page, false); + check(`mobile ${input}: selecting PRACTICE starts unranked`, requests() === 0); + await ctx.close(); + } + { + const { ctx, page, requests } = await phone(); + await outage(page); + await tap(page, 'play'); + await waitError(page); + const snap = await menuItems(page); + check('backend failure stays on menu with a clear error, RETRY and PLAY PRACTICE INSTEAD', await titleActive(page) && (await sceneTexts(page, 'StartScene')).includes('RANKED PLAY IS TEMPORARILY UNAVAILABLE.') && snap.items.some((i) => i.label === 'RETRY') && snap.items.some((i) => i.label === 'PLAY PRACTICE INSTEAD')); + await page.screenshot({ path: 'scripts/.smoke-output/mobile-entry-error.png' }); + await tap(page, 'start'); + await waitError(page); + check('RETRY issues another request and never silently starts casual play', requests() === 2 && await titleActive(page)); + await tap(page, 'play-normally'); + await playing(page, false); + check('explicit error fallback starts Practice without another challenge', requests() === 2); + await ctx.close(); + } + { + const { ctx, page, requests } = await phone(); + await outage(page); + await tap(page, 'play'); + await waitError(page); + await page.unroute(`${worker.API}/api/v1/runs`); + await tap(page, 'start'); + await playing(page, true); + check('RETRY after service recovery starts the existing ranked flow', requests() === 2); + await ctx.close(); + } + for (const action of ['play', 'practice']) { + const { ctx, page, requests } = await phone({ off: true }); + await page.screenshot({ path: 'scripts/.smoke-output/mobile-entry-touch-off.png' }); + check(`${action}: touch-off phone retains player-count and control recovery`, (await menuItems(page)).items.filter((i) => ['players', 'touch-on'].includes(i.id)).length === 2); + await tap(page, action); + check(`${action}: touch-off phone is blocked before any challenge and keeps preferences`, await recovery(page) && requests() === 0 && await prefsOff(page)); + await tap(page, 'start'); + check(`${action}: finger cannot activate keyboard-only start`, await titleActive(page) && requests() === 0); + await tap(page, 'touch-on'); + check(`${action}: turning touch on is explicit and does not auto-start`, !(await recovery(page)) && requests() === 0 && await titleActive(page)); + await tap(page, 'start'); + await playing(page, action === 'play'); + check(`${action}: recovered start preserves the requested run type`, requests() === (action === 'play' ? 1 : 0)); + await ctx.close(); + } + { + const { ctx, page, requests } = await phone({ off: true }); + await page.keyboard.press('Space'); + await playing(page, true); + check('mobile Space matches primary PLAY with a physical keyboard and touch off', requests() === 1 && await prefsOff(page)); + await ctx.close(); + } + { + const { ctx, page, requests } = await phone({ off: true }); + await putPad(page); + await sleep(200); + await tap(page, 'play'); + check('unassigned gamepad cannot bypass readiness', await recovery(page) && requests() === 0); + await joinPad(page); + await tap(page, 'back'); + // START must have the same meaning as the mobile primary PLAY button. + await page.evaluate(() => { window.testPad.buttons[9] = { pressed: true, value: 1 }; }); + await playing(page, true); + check('assigned gamepad START matches primary PLAY without changing touch preference', requests() === 1 && await prefsOff(page)); + await ctx.close(); + } + { + const { ctx, page, requests } = await phone({ off: true }); + await putPad(page); + await sleep(200); + await joinPad(page); + let release; + const held = new Promise((r) => { release = r; }); + let received; + const responseReady = new Promise((r) => { received = r; }); + await page.route(`${worker.API}/api/v1/runs`, async (route) => { + if (route.request().method() !== 'POST') return route.continue(); + const response = await route.fetch(); + received(); + await held; + await route.fulfill({ response }); + }); + await tap(page, 'play'); + await responseReady; + await page.evaluate(() => { window.testPad = null; }); + await sleep(200); + release(); + await page.waitForFunction(() => window.__ASTEROIDS_RANKED__?.phase === 'idle'); + check('controller lost during direct PLAY request prevents an uncontrollable run', requests() === 1 && await recovery(page) && await titleActive(page) && await prefsOff(page)); + await ctx.close(); + } + { + const { ctx, page, requests } = await phone(); + let release; + const held = new Promise((r) => { release = r; }); + await page.route(`${worker.API}/api/v1/runs`, async (route) => { + if (route.request().method() !== 'POST') return route.continue(); + const response = await route.fetch(); + await held; + await route.fulfill({ response }); + }); + await tap(page, 'play'); + check('pending direct PLAY exposes CONNECTING and CANCEL', (await menuItems(page)).items.some((i) => i.label === 'CONNECTING...' && !i.enabled) && (await menuItems(page)).items.some((i) => i.label === 'CANCEL')); + await page.keyboard.press('Escape'); + release(); + await sleep(500); + check('cancelling ignores the late challenge and returns to title', requests() === 1 && await titleActive(page) && (await menuItems(page)).page === 'title'); + await ctx.close(); + } + for (const touchCapable of [false, true]) { + const ctx = await browser.newContext({ viewport: { width: 1280, height: 720 }, hasTouch: touchCapable }); + // A touch-capable laptop still has a fine primary pointer. Chromium's hasTouch alone emulates a coarse primary pointer. + if (touchCapable) await ctx.addInitScript(() => { + const nativeMatchMedia = window.matchMedia.bind(window); + window.matchMedia = (query) => query === '(pointer: coarse)' + ? Object.defineProperty(nativeMatchMedia(query), 'matches', { value: false }) + : nativeMatchMedia(query); + }); + const page = await openTitle(ctx, GAME, { api: worker.API }); + let requests = 0; + page.on('request', (r) => { if (r.method() === 'POST' && r.url().endsWith('/api/v1/runs')) requests++; }); + const snap = await menuItems(page); + check(`desktop touch-capable=${touchCapable}: original PLAY / RANKED / player selector remain`, !snap.items.some((i) => i.id === 'practice') && ['play', 'ranked', 'players', 'scores'].every((id) => snap.items.some((i) => i.id === id))); + await page.keyboard.press('Digit2'); + await sleep(200); + check('desktop two-player ranked remains disabled and Co-op is available', (await menuItems(page)).items.some((i) => i.id === 'ranked' && !i.enabled) && (await menuItems(page)).items.some((i) => i.id === 'coop')); + await page.keyboard.press('Digit1'); + await sleep(200); + await page.keyboard.press('Space'); + await playing(page, false); + check('desktop Space still starts normal unranked play', requests === 0); + await ctx.close(); + } + { + const ctx = await browser.newContext({ viewport: { width: 1280, height: 720 } }); + const page = await openTitle(ctx, GAME, { api: worker.API }); + await clickItem(page, 'ranked'); + check('desktop RANKED still opens explanation before starting', (await menuItems(page)).page === 'ranked'); + await clickItem(page, 'start'); + await playing(page, true); + check('desktop explicit ranked start still works', true); + await ctx.close(); + } +} finally { + await game?.close(); + worker.cleanup(); +} +console.log(`\n${state.total - state.failures}/${state.total} mobile entry checks passed`); +process.exit(state.failures ? 1 : 0); diff --git a/phaser-asteroids/src/scenes/StartScene.ts b/phaser-asteroids/src/scenes/StartScene.ts index 48ef8ed..3bf7217 100644 --- a/phaser-asteroids/src/scenes/StartScene.ts +++ b/phaser-asteroids/src/scenes/StartScene.ts @@ -28,7 +28,7 @@ import { buildPadLayoutPage } from '../ui/menu/pages/padLayout'; import { buildPowerupGuide } from '../ui/menu/pages/powerups'; import { buildRankedPage, type RankedMenuContext, type RankedRequestStatus } from '../ui/menu/pages/ranked'; import { buildScoresPage, type ScoresContext } from '../ui/menu/pages/scores'; -import { buildTitlePage } from '../ui/menu/pages/title'; +import { buildTitlePage, usesMobilePlayEntry } from '../ui/menu/pages/title'; import { formatClock } from '../ui/text'; import { SCENE_GAME, SCENE_START } from './keys'; @@ -116,13 +116,20 @@ export class StartScene extends Phaser.Scene { best: () => this.personalBest, }; const builders: Record = { - title: (kit) => buildTitlePage(kit, ctx, nav), + title: (kit) => buildTitlePage(kit, ctx, nav, { + practice: () => this.startPractice(), + timeLimitLabel: rankedCtx.timeLimitLabel, + }), audio: (kit) => buildAudioPage(kit, ctx, nav), controls: (kit) => buildControlsPage(kit, ctx, nav), coop: (kit) => buildCoopPage(kit, ctx, nav), powerups: (kit) => buildPowerupGuide(kit, ctx, nav), padlayout: (kit) => buildPadLayoutPage(kit, ctx, nav), ranked: (kit) => buildRankedPage(kit, rankedCtx, nav), + practice: (kit) => buildRankedPage(kit, { + ...rankedCtx, practice: true, + actions: { ...rankedCtx.actions, start: () => this.playNormally() }, + }, nav), scores: (kit) => buildScoresPage(kit, scoresCtx, nav), }; this.menu = new MenuView(this, 10, builders, 'title'); @@ -268,7 +275,7 @@ export class StartScene extends Phaser.Scene { private start(): void { if (this.starting) return; // `?ranked` (development and tests): PLAY goes through the same RANKED PLAY page a player reaches with the RANKED button. - if (this.rankedWanted()) { + if (usesMobilePlayEntry(this.makeContext()) || this.rankedWanted()) { if (this.menu.controller.currentPage !== 'ranked') this.menu.controller.open('ranked'); this.requestRanked(); return; @@ -277,6 +284,15 @@ export class StartScene extends Phaser.Scene { this.scene.start(SCENE_GAME); } + private startPractice(): void { + if (this.starting) return; + if (!this.rankedInputReady()) { + this.menu.controller.open('practice'); + return; + } + this.playNormally(); + } + /** A normal game, whatever the ranked service is doing. */ private playNormally(): void { if (this.starting) return; diff --git a/phaser-asteroids/src/ui/menu/pages/ranked.ts b/phaser-asteroids/src/ui/menu/pages/ranked.ts index 8678a5d..79a4c54 100644 --- a/phaser-asteroids/src/ui/menu/pages/ranked.ts +++ b/phaser-asteroids/src/ui/menu/pages/ranked.ts @@ -14,6 +14,8 @@ export type RankedRequestStatus = | { kind: 'error'; code: string }; export interface RankedMenuContext { + /** Reuses the same input recovery for the explicit unranked title action. */ + readonly practice?: boolean; readonly inputMode: MenuContext['inputMode']; inputAvailable(): boolean; status(): RankedRequestStatus; @@ -38,13 +40,13 @@ const WIDE = { w: 600, h: 110 }; export function describeRankedFailure(code: string): { lines: [string, string]; retry: boolean } { switch (code) { case 'unconfigured': - return { lines: ['RANKED PLAY IS NOT AVAILABLE IN THIS BUILD YET.', 'YOU CAN STILL PLAY NORMALLY.'], retry: false }; + return { lines: ['RANKED PLAY IS NOT AVAILABLE IN THIS BUILD YET.', 'YOU CAN STILL PLAY PRACTICE.'], retry: false }; case 'update_required': return { lines: ['THE GAME HAS BEEN UPDATED.', 'RELOAD THE PAGE TO PLAY RANKED.'], retry: false }; case 'rate_limited': - return { lines: ['TOO MANY RANKED RUNS STARTED RECENTLY.', 'TRY AGAIN IN A WHILE, OR PLAY NORMALLY.'], retry: true }; + return { lines: ['TOO MANY RANKED RUNS STARTED RECENTLY.', 'TRY AGAIN IN A WHILE, OR PLAY PRACTICE.'], retry: true }; default: - return { lines: ['RANKED PLAY IS TEMPORARILY UNAVAILABLE.', 'YOU CAN STILL PLAY NORMALLY.'], retry: true }; + return { lines: ['RANKED PLAY IS TEMPORARILY UNAVAILABLE.', 'YOU CAN STILL PLAY PRACTICE.'], retry: true }; } } @@ -55,7 +57,7 @@ export function describeRankedFailure(code: string): { lines: [string, string]; */ export function buildRankedPage(kit: PageKit, ctx: RankedMenuContext, nav: PageNav): PageDef { const status = ctx.status(); - pageTitle(kit, 'RANKED PLAY'); + pageTitle(kit, ctx.practice ? 'PRACTICE' : 'RANKED PLAY'); if (!ctx.inputAvailable()) { kit.text(CENTER_X, 180, 'TOUCH GAMEPLAY CONTROLS ARE OFF.', { size: TEXT.body + 2, originX: 0.5, originY: 0.5, color: '#ff9696' }); @@ -67,18 +69,24 @@ export function buildRankedPage(kit: PageKit, ctx: RankedMenuContext, nav: PageN return { defaultFocus: 'start', onBack: () => { ctx.actions.cancel(); return false; }, signature: () => `${ctx.inputAvailable()}` }; } + if (ctx.practice) { + kit.text(CENTER_X, 210, 'PRACTICE SCORES DO NOT COUNT TOWARD THE ONLINE LEADERBOARD.', { size: TEXT.body, originX: 0.5, originY: 0.5, color: COLORS.hint }); + new MenuButton(kit, { id: 'start', rect: { x: CENTER_X - WIDE.w / 2, y: 310, ...WIDE }, label: 'START PRACTICE', primary: true, onTap: ctx.actions.start, size: 38 }); + new MenuButton(kit, { id: 'back', rect: { x: CENTER_X - WIDE.w / 2, y: 436, w: WIDE.w, h: MIN_TARGET }, label: 'BACK', onTap: () => nav.back(), size: 30 }); + return { defaultFocus: 'start', signature: () => `${ctx.inputAvailable()}` }; + } + if (status.kind === 'error') { const failure = describeRankedFailure(status.code); kit.text(CENTER_X, 190, failure.lines[0], { size: TEXT.body + 2, originX: 0.5, originY: 0.5, color: '#ff9696' }); kit.text(CENTER_X, 236, failure.lines[1], { size: TEXT.body, originX: 0.5, originY: 0.5, color: COLORS.hint }); let y = 300; if (failure.retry) { - new MenuButton(kit, { id: 'start', rect: { x: CENTER_X - WIDE.w / 2, y, ...WIDE }, label: 'TRY AGAIN', primary: true, onTap: ctx.actions.start, size: 40 }); + new MenuButton(kit, { id: 'start', rect: { x: CENTER_X - WIDE.w / 2, y, ...WIDE }, label: 'RETRY', primary: true, onTap: ctx.actions.start, size: 40 }); y += WIDE.h + 16; } - const w = (WIDE.w - 16) / 2; - new MenuButton(kit, { id: 'play-normally', rect: { x: CENTER_X - WIDE.w / 2, y, w, h: MIN_TARGET }, label: 'PLAY NORMALLY', primary: !failure.retry, onTap: ctx.actions.playNormally, size: 26 }); - new MenuButton(kit, { id: 'back', rect: { x: CENTER_X - WIDE.w / 2 + w + 16, y, w, h: MIN_TARGET }, label: 'BACK', onTap: () => nav.back(), size: 30 }); + new MenuButton(kit, { id: 'play-normally', rect: { x: CENTER_X - WIDE.w / 2, y, w: WIDE.w, h: MIN_TARGET }, label: 'PLAY PRACTICE INSTEAD', primary: !failure.retry, onTap: ctx.actions.playNormally, size: 30 }); + new MenuButton(kit, { id: 'back', rect: { x: CENTER_X - WIDE.w / 2, y: y + MIN_TARGET + 16, w: WIDE.w, h: MIN_TARGET }, label: 'BACK', onTap: () => nav.back(), size: 30 }); keyHint(kit, ctx, 'UP / DOWN: CHOOSE ENTER: SELECT ESC: BACK'); return { defaultFocus: failure.retry ? 'start' : 'play-normally', signature: () => `${ctx.inputAvailable()}|${ctx.status().kind}` }; } diff --git a/phaser-asteroids/src/ui/menu/pages/title.ts b/phaser-asteroids/src/ui/menu/pages/title.ts index 20ebb7f..ff82a69 100644 --- a/phaser-asteroids/src/ui/menu/pages/title.ts +++ b/phaser-asteroids/src/ui/menu/pages/title.ts @@ -24,14 +24,25 @@ const LEGEND = { x: 40, y: 482, w: 1200, h: 224 }; const HELP_TOP = 160; const HELP_STEP = 56; +/** Keep a phone's solo entry clear even when its owner has explicitly turned touch controls off. Co-op keeps its existing menu. */ +export function usesMobilePlayEntry(ctx: Pick): boolean { + return (ctx.inputMode.isTouch || ctx.inputMode.env.coarsePrimaryPointer) && ctx.setup().game.playerCount === 1; +} + +export interface TitlePlayOptions { + practice(): void; + timeLimitLabel: string; +} + /** * The title screen: what the game is called, one big PLAY, how to steer the ship, what the pick-ups do, and quiet doors to AUDIO and * CONTROLS. Everything that is a setting lives behind those two buttons; nothing is repeated here. The reference on the left is the * controls that are active right now (touch buttons, the keys, or a controller once one is assigned), the legend below is a * tappable card that opens the full power-up guide. */ -export function buildTitlePage(kit: PageKit, ctx: MenuContext, nav: PageNav): PageDef { +export function buildTitlePage(kit: PageKit, ctx: MenuContext, nav: PageNav, play: TitlePlayOptions): PageDef { const touch = ctx.inputMode.isTouch; + const mobileEntry = usesMobilePlayEntry(ctx); const setup = ctx.setup(); const count = setup.game.playerCount; const g = kit.graphics(); @@ -54,11 +65,64 @@ export function buildTitlePage(kit: PageKit, ctx: MenuContext, nav: PageNav): Pa buildHowToPlay(kit, g, ctx, count); // A controller that has been found but not given to a player says so, in the corner, until it joins (A) or is assigned (LB / RB). - if (ctx.pads.status(count).some((s) => s.kind === 'unassigned')) { + if ((!mobileEntry || touch) && ctx.pads.status(count).some((s) => s.kind === 'unassigned')) { kit.text(LEFT_X, 30, 'CONTROLLER FOUND\nPRESS A TO JOIN', { size: TEXT.hint + 2, originX: 0, originY: 0.5, color: COLORS.heading }); } - // --- the right column: PLAY, the player count, AUDIO / CONTROLS -------------------------------------------------------- + const rankedOk = count === 1; + if (mobileEntry) { + buildMobilePlay(kit, ctx, nav, play); + // A phone using a keyboard/controller retains the player-count selector and all co-op hotkeys. + if (!touch) { + new MenuChoice(kit, { + id: 'players', label: 'PLAYERS', y: 8, + frame: { x: LEFT_X, y: 8, w: 340, h: MIN_TARGET }, + options: ['1 PLAYER', '2 PLAYERS'], + selected: () => ctx.setup().game.playerCount === 2 ? 1 : 0, + onSelect: (index) => ctx.setPlayers(index === 1 ? 2 : 1), size: 22, + }); + } + } else { + buildDesktopPlay(kit, ctx, nav, count, recover); + } + + buildLegend(kit, ctx, count, nav); + + const hotkeys: Record void> = { Space: () => ctx.actions.play() }; + if (!touch) { + if (rankedOk) hotkeys.KeyR = () => nav.open('ranked'); + hotkeys.KeyH = () => nav.open('scores'); + hotkeys.KeyC = () => nav.open('padlayout'); + const firstPad = ctx.pads.pads()[0]; + if (firstPad) hotkeys.KeyG = () => ctx.pads.cycle(firstPad.key, count); + hotkeys.Digit1 = () => ctx.setPlayers(1); + hotkeys.Numpad1 = () => ctx.setPlayers(1); + hotkeys.Digit2 = () => ctx.setPlayers(2); + hotkeys.Numpad2 = () => ctx.setPlayers(2); + if (count === 2) { + // The keys that have always changed the co-op rules from the title screen; the summary under the keys shows the result. + const coop = coopActions(ctx); + hotkeys.KeyL = coop.toggleLives; + hotkeys.KeyF = coop.toggleFire; + hotkeys.KeyK = coop.toggleP2Keys; + hotkeys.KeyS = () => coop.cycleSpeed(0); + hotkeys.KeyD = () => coop.cycleSpeed(1); + } + } + return { + hotkeys, + defaultFocus: 'play', + signature: () => { + const s = ctx.setup(); + return `${ctx.inputMode.mode}|${s.game.playerCount}|${s.p2Keys}|${s.game.livesMode}|${s.game.friendlyFire}|${s.game.speed.join(",")}|${ctx.movement.mode}|${ctx.pads.status(s.game.playerCount).map((p) => p.text).join('|')}`; + }, + }; +} + +function buildDesktopPlay(kit: PageKit, ctx: MenuContext, nav: PageNav, count: 1 | 2, recover: boolean): void { + const touch = ctx.inputMode.isTouch; + const rankedOk = count === 1; + // --- the desktop right column: PLAY, the player count, AUDIO / CONTROLS ----------------------------------------------- const playH = touch ? 150 : 110; const switchH = touch ? 0 : MIN_TARGET + 16; const block = playH + switchH + 16 + MIN_TARGET; @@ -78,7 +142,6 @@ export function buildTitlePage(kit: PageKit, ctx: MenuContext, nav: PageNav): Pa size: keyboardOnPhone ? 26 : 60, ...(touch ? {} : { hint: keyboardOnPhone ? 'PRESS SPACE ON A KEYBOARD' : 'SPACE' }), }); - const rankedOk = count === 1; new MenuButton(kit, { id: 'ranked', name: 'RANKED PLAY', @@ -126,38 +189,30 @@ export function buildTitlePage(kit: PageKit, ctx: MenuContext, nav: PageNav): Pa if (!touch) { new MenuButton(kit, { id: 'scores', rect: { x: RIGHT_X + half + 16, y: y - MIN_TARGET - 16, w: half, h: MIN_TARGET }, label: 'HIGH SCORES', onTap: openScores, size: 26 }); } +} - buildLegend(kit, ctx, count, nav); - - const hotkeys: Record void> = { Space: () => ctx.actions.play() }; - if (!touch) { - if (rankedOk) hotkeys.KeyR = () => nav.open('ranked'); - hotkeys.KeyH = () => nav.open('scores'); - hotkeys.KeyC = () => nav.open('padlayout'); - const firstPad = ctx.pads.pads()[0]; - if (firstPad) hotkeys.KeyG = () => ctx.pads.cycle(firstPad.key, count); - hotkeys.Digit1 = () => ctx.setPlayers(1); - hotkeys.Numpad1 = () => ctx.setPlayers(1); - hotkeys.Digit2 = () => ctx.setPlayers(2); - hotkeys.Numpad2 = () => ctx.setPlayers(2); - if (count === 2) { - // The keys that have always changed the co-op rules from the title screen; the summary under the keys shows the result. - const coop = coopActions(ctx); - hotkeys.KeyL = coop.toggleLives; - hotkeys.KeyF = coop.toggleFire; - hotkeys.KeyK = coop.toggleP2Keys; - hotkeys.KeyS = () => coop.cycleSpeed(0); - hotkeys.KeyD = () => coop.cycleSpeed(1); - } +function buildMobilePlay(kit: PageKit, ctx: MenuContext, nav: PageNav, play: TitlePlayOptions): void { + new MenuButton(kit, { + id: 'play', rect: { x: RIGHT_X, y: BAND_TOP, w: RIGHT_W, h: 120 }, + label: 'PLAY', primary: true, size: 60, onTap: ctx.actions.play, + hint: `ONLINE LEADERBOARD / ${play.timeLimitLabel} LIMIT`, hintSize: 24, + }); + const half = (RIGHT_W - 16) / 2; + new MenuButton(kit, { + id: 'practice', rect: { x: RIGHT_X, y: 244, w: half, h: MIN_TARGET }, + label: 'PRACTICE', hint: 'NO ONLINE SCORE', size: 32, onTap: play.practice, + }); + new MenuButton(kit, { + id: 'scores', rect: { x: RIGHT_X + half + 16, y: 244, w: half, h: MIN_TARGET }, + label: 'HIGH SCORES', size: 30, color: COLORS.heading, onTap: () => nav.open('scores'), + }); + const width = (RIGHT_W - 32) / 3; + for (const [i, [id, label]] of ([['audio', 'AUDIO'], ['controls', 'CONTROLS'], ['ranked', 'RANKED\nINFO']] as const).entries()) { + new MenuButton(kit, { + id, rect: { x: RIGHT_X + i * (width + 16), y: 346, w: width, h: MIN_TARGET }, + label, size: 26, onTap: () => nav.open(id), + }); } - return { - hotkeys, - defaultFocus: 'play', - signature: () => { - const s = ctx.setup(); - return `${ctx.inputMode.mode}|${s.game.playerCount}|${s.p2Keys}|${s.game.livesMode}|${s.game.friendlyFire}|${s.game.speed.join(",")}|${ctx.movement.mode}|${ctx.pads.status(s.game.playerCount).map((p) => p.text).join('|')}`; - }, - }; } // --- how to play ------------------------------------------------------------------------------------------------------------- @@ -184,7 +239,8 @@ function buildHowToPlay(kit: PageKit, g: ReturnType, ctx: M const { rows, usesPad } = columnFor(0); kit.text(LEFT_X + LEFT_W / 2, BAND_TOP + 22, usesPad ? 'HOW TO PLAY - CONTROLLER' : 'HOW TO PLAY', { size: TEXT.heading, originX: 0.5, originY: 0.5, color: COLORS.heading }); drawHelpRows(kit, g, LEFT_X + 30, HELP_TOP - 10, rows, { step: HELP_STEP, size: TEXT.body, compact: false }); - kit.text(LEFT_X + LEFT_W / 2, BAND_BOTTOM + 14, footnote(usesPad), { size: TEXT.hint, originX: 0.5, originY: 0.5, color: COLORS.dim, bold: false }); + const joinHint = usesMobilePlayEntry(ctx) && ctx.pads.status(count).some((s) => s.kind === 'unassigned'); + kit.text(LEFT_X + LEFT_W / 2, BAND_BOTTOM + 14, joinHint ? 'CONTROLLER FOUND - PRESS A TO JOIN' : footnote(usesPad), { size: TEXT.hint, originX: 0.5, originY: 0.5, color: COLORS.dim, bold: false }); return; } diff --git a/phaser-asteroids/src/ui/menu/widgets.ts b/phaser-asteroids/src/ui/menu/widgets.ts index ad6e5c7..f21198b 100644 --- a/phaser-asteroids/src/ui/menu/widgets.ts +++ b/phaser-asteroids/src/ui/menu/widgets.ts @@ -165,6 +165,8 @@ export interface ButtonOptions { confirm?: { armedLabel: string }; /** A tiny caption under the label (`SPACE`, a key hint). */ hint?: string; + /** A larger caption when it explains the action rather than just naming a shortcut. */ + hintSize?: number; color?: string; /** Only a key or a controller button may press it; a click or tap does nothing (PLAY on a phone that has no touch controls, where a tap would start a run nobody can steer). */ keysOnly?: boolean; @@ -195,7 +197,7 @@ export class MenuButton implements Widget { const cy = this.rect.y + this.rect.h / 2; this.text = kit.text(cx, cy - (opts.hint ? 10 : 0), '', { size: opts.size ?? TEXT.button, originX: 0.5, originY: 0.5, color: opts.color ?? COLORS.white }).setAlign('center'); if (opts.hint) { - const hint = kit.text(cx, this.rect.y + this.rect.h - 20, opts.hint, { size: TEXT.hint, originX: 0.5, originY: 0.5, color: COLORS.dim, bold: false }); + const hint = kit.text(cx, this.rect.y + this.rect.h - 20, opts.hint, { size: opts.hintSize ?? TEXT.hint, originX: 0.5, originY: 0.5, color: COLORS.dim, bold: false }); fit(hint, this.rect.w - 16); // a long hint in a narrow button shrinks instead of spilling over the edge } kit.add(this); diff --git a/phaser-asteroids/tests/mobileEntry.test.ts b/phaser-asteroids/tests/mobileEntry.test.ts new file mode 100644 index 0000000..9d43af4 --- /dev/null +++ b/phaser-asteroids/tests/mobileEntry.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_SETUP } from '../src/gameSetup'; +import { InputModeController, type InputEnvironment } from '../src/input/inputMode'; +import { describeRankedFailure } from '../src/ui/menu/pages/ranked'; +import { usesMobilePlayEntry } from '../src/ui/menu/pages/title'; + +describe('mobile play entry uses the existing input environment and preferences', () => { + const phone = { coarsePrimaryPointer: true, touchCapable: true }; + const desktop = { coarsePrimaryPointer: false, touchCapable: false }; + const laptop = { coarsePrimaryPointer: false, touchCapable: true }; + it.each<[string, InputEnvironment, string, 1 | 2, boolean]>([ + ['phone', phone, '', 1, true], + ['phone with touch explicitly off', phone, '?touch=off', 1, true], + ['phone with co-op selected', phone, '?touch=off', 2, false], + ['desktop', desktop, '', 1, false], + ['desktop co-op', desktop, '', 2, false], + ['touch laptop with a fine primary pointer', laptop, '', 1, false], + ['explicit touch override', desktop, '?touch=on', 1, true], + ])('%s', (_name, env, query, playerCount, expected) => { + const inputMode = new InputModeController(env, query, null); + const before = inputMode.mode; + expect(usesMobilePlayEntry({ inputMode, setup: () => ({ ...DEFAULT_SETUP, game: { ...DEFAULT_SETUP.game, playerCount } }) })).toBe(expected); + expect(inputMode.mode).toBe(before); + }); +}); + +describe('ranked service failures keep the choice explicit', () => { + it.each(['network', 'unavailable', 'rate_limited', 'bad_challenge'])('%s offers retry and names Practice', (code) => { + const failure = describeRankedFailure(code); + expect(failure.retry).toBe(true); + expect(failure.lines.join(' ')).toContain('PRACTICE'); + }); + it('keeps the required reload instruction for incompatible builds', () => { + expect(describeRankedFailure('update_required')).toEqual({ + lines: ['THE GAME HAS BEEN UPDATED.', 'RELOAD THE PAGE TO PLAY RANKED.'], retry: false, + }); + }); +}); From d1bedda070c6a713dafb2019935599de13f87fc1 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:24:32 -0300 Subject: [PATCH 2/2] feat: implement explicit focus neighbours for mobile menu navigation --- phaser-asteroids/docs/menus.md | 2 ++ .../src/ui/menu/menuController.ts | 7 ++++ phaser-asteroids/src/ui/menu/pages/title.ts | 11 +++++++ phaser-asteroids/tests/menuController.test.ts | 32 +++++++++++++++++++ 4 files changed, 52 insertions(+) diff --git a/phaser-asteroids/docs/menus.md b/phaser-asteroids/docs/menus.md index 97b72b1..59ebb59 100644 --- a/phaser-asteroids/docs/menus.md +++ b/phaser-asteroids/docs/menus.md @@ -76,6 +76,8 @@ Touch mode, or a device whose primary pointer is coarse, gets a full-width green **PRACTICE** (caption: NO ONLINE SCORE) and gold **HIGH SCORES** occupy the next row. AUDIO, CONTROLS and **RANKED INFO** occupy a quieter third row. RANKED INFO preserves the full explanation, time limit and device best without issuing a challenge. Practice starts the normal game, even with the development `?ranked` flag, and never requests a challenge. Server errors offer an explicit **RETRY** and **PLAY PRACTICE INSTEAD**; there is no automatic casual fallback. +The mobile title supplies explicit vertical focus neighbours so Down from the wide PLAY button reaches PRACTICE, then the settings row. Left/Right still use the existing navigation within each row. Other menus retain geometric navigation; keyboards and gamepads share the same focus links. + A phone with touch controls off keeps its saved preference. Both PLAY and PRACTICE first require either an assigned controller or evidence of a physical keyboard; otherwise they show the same touch recovery controls. Enabling touch is an explicit choice followed by a separate start action, preserving which run type was requested. Keyboard-mode phones retain the player-count selector at the top left; choosing two players restores the existing co-op title layout and controls. Fine-pointer desktops, including touch-capable laptops, keep their original entry behavior. ## Where each existing setting lives now diff --git a/phaser-asteroids/src/ui/menu/menuController.ts b/phaser-asteroids/src/ui/menu/menuController.ts index 6c05557..07e1a9c 100644 --- a/phaser-asteroids/src/ui/menu/menuController.ts +++ b/phaser-asteroids/src/ui/menu/menuController.ts @@ -31,6 +31,8 @@ export interface MenuPageSpec { readonly onBack?: () => boolean; /** The item focused when the page opens (the first one by default). */ readonly defaultFocus?: string; + /** Explicit neighbours for layouts with mixed button widths; unspecified directions keep geometric navigation. */ + readonly focusNeighbours?: Readonly>>>; /** Changes whenever the page's content must be rebuilt (the player count, a controller being assigned...). */ readonly signature?: () => string; /** Called once when the page is closed or rebuilt: removes everything it made. */ @@ -217,6 +219,11 @@ export class MenuController { return true; } if ((direction === 'left' || direction === 'right') && focused.adjust?.(direction === 'right' ? 1 : -1)) return true; + const explicit = this.page?.focusNeighbours?.[focused.id]?.[direction]; + if (explicit && items.some((i) => i.id === explicit)) { + this.focusId = explicit; + return true; + } const targets: NavTarget[] = items.map((i) => ({ id: i.id, rect: i.rect })); const next = neighbour({ id: focused.id, rect: focused.rect }, targets, direction); if (next !== null) this.focusId = next; diff --git a/phaser-asteroids/src/ui/menu/pages/title.ts b/phaser-asteroids/src/ui/menu/pages/title.ts index ff82a69..a01e514 100644 --- a/phaser-asteroids/src/ui/menu/pages/title.ts +++ b/phaser-asteroids/src/ui/menu/pages/title.ts @@ -112,6 +112,17 @@ export function buildTitlePage(kit: PageKit, ctx: MenuContext, nav: PageNav, pla return { hotkeys, defaultFocus: 'play', + ...(mobileEntry ? { focusNeighbours: { + play: { down: 'practice', up: touch ? 'powerups' : 'touch-on' }, + practice: { up: 'play', down: 'audio' }, + scores: { up: 'play', down: 'ranked' }, + audio: { up: 'practice', down: 'powerups' }, + controls: { up: 'practice', down: 'powerups' }, + ranked: { up: 'scores', down: 'powerups' }, + powerups: { up: 'audio', down: 'play' }, + players: { down: 'play' }, + 'touch-on': { down: 'play' }, + } } : {}), signature: () => { const s = ctx.setup(); return `${ctx.inputMode.mode}|${s.game.playerCount}|${s.p2Keys}|${s.game.livesMode}|${s.game.friendlyFire}|${s.game.speed.join(",")}|${ctx.movement.mode}|${ctx.pads.status(s.game.playerCount).map((p) => p.text).join('|')}`; diff --git a/phaser-asteroids/tests/menuController.test.ts b/phaser-asteroids/tests/menuController.test.ts index 42dc989..a7b3685 100644 --- a/phaser-asteroids/tests/menuController.test.ts +++ b/phaser-asteroids/tests/menuController.test.ts @@ -143,6 +143,38 @@ describe('MenuController: keyboard and controller', () => { expect(menu.currentPage).toBe('controls'); expect(menu.focusId).toBe('back'); }); + + it('uses explicit page neighbours for mixed-width rows with both keys and gamepad', () => { + const menu = new MenuController(() => ({ + id: 'mobile', + items: [ + new Item('play', { x: 680, y: 112, w: 560, h: 120 }), + new Item('practice', { x: 680, y: 244, w: 272, h: 90 }), + new Item('scores', { x: 968, y: 244, w: 272, h: 90 }), + new Item('controls', { x: 872, y: 346, w: 176, h: 90 }), + ], + focusNeighbours: { play: { down: 'practice' }, scores: { up: 'play' } }, + }), 'mobile', () => 0); + menu.start(); + menu.key('ArrowDown'); + expect(menu.focusId).toBe('practice'); + menu.pad('right'); // No override: geometric navigation still works within the row. + expect(menu.focusId).toBe('scores'); + menu.pad('up'); + expect(menu.focusId).toBe('play'); + menu.pad('down'); + expect(menu.focusId).toBe('practice'); + }); + + it('ignores an explicit neighbour missing from the current page', () => { + const menu = new MenuController(() => ({ + id: 'p', items: [new Item('a', row(0)), new Item('b', row(100))], + focusNeighbours: { a: { down: 'missing' } }, + }), 'p', () => 0); + menu.start(); + menu.key('ArrowDown'); + expect(menu.focusId).toBe('b'); + }); }); describe('MenuController: mouse and touch', () => {