diff --git a/CHANGELOG b/CHANGELOG index 84646671..2f88ae0e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,7 @@ ## 0.7.1 - Unreleased * Add Wear OS watch battery indicator to the top bar and Glanceboard +* Refinements to builtin games ## 0.7.0 - 2026-09-12 diff --git a/app/apps/blocks/blocks-app.worker.ts b/app/apps/blocks/blocks-app.worker.ts index 4a5ec5f1..850eedc9 100644 --- a/app/apps/blocks/blocks-app.worker.ts +++ b/app/apps/blocks/blocks-app.worker.ts @@ -1,7 +1,9 @@ /** * Blocks app worker: a falling-blocks game. One singleton window holds the * whole game; a gravity interval drives piece descent while the window is - * foreground and the screen is on (losing either auto-pauses). + * foreground, the screen is on, and the window holds input focus (losing any + * of them auto-pauses: backgrounding, screen-off, the system menu or a + * notification modal opening over the game, focus going to the sidebar). * * Controls (in play): scroll moves the piece, click rotates, long-press hard * drops, double-click pauses. Watch swipes are spatial: left/right move, @@ -17,6 +19,7 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts"; import * as frameTimings from "../../native/frame-timings"; import { getActiveDisplay } from "../../native/active-display"; import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects"; +import { loadSoundEnabled, saveSoundEnabled } from "../../ui/sound-setting"; import { type MenuItem } from "../../ui/menu"; import { WindowMenu } from "../../ui/window-menu"; import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window"; @@ -43,11 +46,16 @@ const BOARD_X = 60; const BOARD_Y = 10; const PANEL_X = 230; -/** Gravity starts here and speeds up with score (see dropIntervalMs). */ -const BASE_DROP_MS = 1200; -const MIN_DROP_MS = 200; -/** Every this many points, gravity gets one 12% step faster. */ -const SPEED_STEP_SCORE = 300; +/** + * Gravity starts here and speeds up with score (see dropIntervalMs). Slow + * by desktop standards: the glasses round trip is ~250 ms, so a piece must + * hang around long enough to be steered through it. + */ +const BASE_DROP_MS = 1500; +const MIN_DROP_MS = 350; +/** Every this many points, gravity gets one SPEED_STEP_FACTOR step faster. */ +const SPEED_STEP_SCORE = 500; +const SPEED_STEP_FACTOR = 0.92; /** Points per cleared-line count (index = simultaneous lines), times level. */ const LINE_SCORES = [0, 100, 300, 500, 800]; const HARD_DROP_POINTS_PER_ROW = 2; @@ -201,7 +209,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { lines: 0, tickTimer: null, tickIntervalMs: BASE_DROP_MS, - soundOn: true, + soundOn: loadSoundEnabled("blocks"), lastSubmittedFingerprint: "", }; windows.set(message.windowId, window); @@ -248,6 +256,20 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { if (window.foreground) renderAndSubmit(window, 0); break; } + case "input-focus": { + const window = windows.get(message.windowId); + if (!window) break; + // Anything that takes input away from the game (the system menu, a + // notification modal, the voice dialog, focus back to the sidebar) + // pauses it: the player can't steer a piece they aren't in control of. + if (!message.focused && window.phase === "playing") { + window.phase = "paused"; + updateTickTimer(window); + // Still on screen under a shell overlay, so show the pause. + if (window.foreground) renderAndSubmit(window, 0); + } + break; + } case "screen": screenOn = message.on; for (const window of windows.values()) { @@ -296,6 +318,7 @@ function windowMenuItems(window: BlocksWindow): MenuItem[] { onSelect: (ctx) => { ctx.stack.pop(); window.soundOn = !window.soundOn; + saveSoundEnabled("blocks", window.soundOn); if (window.soundOn) playSfx(window, SFX_RESUME); }, }, @@ -547,7 +570,7 @@ function level(window: BlocksWindow): number { function dropIntervalMs(window: BlocksWindow): number { const steps = Math.floor(window.score / SPEED_STEP_SCORE); - return Math.max(MIN_DROP_MS, Math.round(BASE_DROP_MS * Math.pow(0.88, steps))); + return Math.max(MIN_DROP_MS, Math.round(BASE_DROP_MS * Math.pow(SPEED_STEP_FACTOR, steps))); } /** Keep the gravity interval running exactly when the game is live and visible. */ diff --git a/app/apps/flappy/flappy-app.worker.ts b/app/apps/flappy/flappy-app.worker.ts index 646ef0d4..b0b998db 100644 --- a/app/apps/flappy/flappy-app.worker.ts +++ b/app/apps/flappy/flappy-app.worker.ts @@ -17,10 +17,12 @@ * fall back to raster (the planner needs a non-negative origin), which is * small and rare. * - * Controls (watch swipe-up is the primary flap): swipe-up, click, or - * scroll-up flaps; double-click pauses; tap-then-hold opens the window - * menu. Ready / paused / game over: click or swipe-up starts or resumes, - * double-click yields focus. + * Controls (a watch swipe in either direction is the primary flap): + * swipe-up, swipe-down, click, or scroll-up flaps; double-click pauses; + * tap-then-hold opens the window menu. Ready / paused / game over: click or + * a swipe starts or resumes, double-click yields focus. Losing input focus + * mid-flight (a shell overlay such as the system menu or a notification, + * focus to the sidebar) pauses, as does backgrounding or screen-off. */ import "@nativescript/core/globals"; import { GrayImage } from "../../graphics/image"; @@ -32,6 +34,7 @@ import * as frameTimings from "../../native/frame-timings"; import { getActiveDisplay } from "../../native/active-display"; import { getStringSetting, setStringSetting } from "../../native/settings-store"; import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects"; +import { loadSoundEnabled, saveSoundEnabled } from "../../ui/sound-setting"; import { type MenuItem } from "../../ui/menu"; import { WindowMenu } from "../../ui/window-menu"; import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window"; @@ -198,7 +201,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { tickTimer: null, lastTickAtMs: 0, lastMinorSfxAtMs: 0, - soundOn: true, + soundOn: loadSoundEnabled("flappy"), lastSubmittedFingerprint: "", }; resetGame(window); @@ -252,6 +255,19 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { if (window.foreground) renderAndSubmit(window, 0); break; } + case "input-focus": { + const window = windows.get(message.windowId); + if (!window) break; + // Anything that takes input away (the system menu, a notification + // modal, the voice dialog, focus back to the sidebar) pauses the + // flight; a death tumble is allowed to finish. + if (!message.focused && window.phase === "playing") { + window.phase = "paused"; + syncTickTimer(window); + if (window.foreground) renderAndSubmit(window, 0); + } + break; + } case "screen": screenOn = message.on; for (const window of windows.values()) { @@ -328,6 +344,7 @@ function windowMenuItems(window: FlappyWindow): MenuItem[] { onSelect: (ctx) => { ctx.stack.pop(); window.soundOn = !window.soundOn; + saveSoundEnabled("flappy", window.soundOn); if (window.soundOn) playSfx(window, SFX_RESUME); }, }, @@ -391,7 +408,10 @@ function handleInput(window: FlappyWindow, event: InputEvent, frameId: number): /** Input while ready or flying: the flap gestures, plus pause. */ function handleFlightInput(window: FlappyWindow, event: InputEvent, frameId: number): void { switch (event.type) { + // Either swipe direction flaps: on the watch the flap is a reflex, and + // which way the thumb went shouldn't matter. case "swipe-up": + case "swipe-down": case "click": case "scroll-up": flap(window); @@ -678,7 +698,7 @@ function paintHud(image: GrayImage, window: FlappyWindow): void { if (window.highScore > 0) { drawCenteredIn(image, smallFont, 0, width, 44, `best ${window.highScore}`, 150); } - drawCenteredIn(image, smallFont, 0, width, groundTop(window) - 26, `swipe up / ${GESTURE_CLICK} flap`, 150); + drawCenteredIn(image, smallFont, 0, width, groundTop(window) - 26, `swipe / ${GESTURE_CLICK} flap`, 150); break; case "paused": paintDialog(image, window, "PAUSED", [`${GESTURE_CLICK} resume`, `${GESTURE_DOUBLE_CLICK} leave`]); diff --git a/app/apps/freecell/freecell-app.worker.ts b/app/apps/freecell/freecell-app.worker.ts index 37d12e58..070f90ae 100644 --- a/app/apps/freecell/freecell-app.worker.ts +++ b/app/apps/freecell/freecell-app.worker.ts @@ -11,6 +11,10 @@ * selection. Tap-then-hold opens the window menu (undo, new game, restart). * Watch swipes move the cursor spatially: left/right within the row, up/down * between the top row (cells + foundations) and the cascades. + * The cursor skips locations that can't take part in the move being built: + * with nothing selected, empty spots and the foundations (never a source); + * with a source selected, filled free cells and foundations that can't + * accept the card (see isCursorEligible). * Safe cards auto-play to the foundations after every move. */ import "@nativescript/core/globals"; @@ -23,6 +27,7 @@ import { TtfFont } from "../../graphics/ttf-font"; import * as frameTimings from "../../native/frame-timings"; import { getActiveDisplay } from "../../native/active-display"; import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects"; +import { loadSoundEnabled, saveSoundEnabled } from "../../ui/sound-setting"; import { WindowMenu } from "../../ui/window-menu"; import type { MenuItem } from "../../ui/menu"; import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window"; @@ -158,7 +163,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { moves: 0, cursor: LOC_CASCADE0, selected: null, - soundOn: true, + soundOn: loadSoundEnabled("freecell"), lastSubmittedFingerprint: "", }; newGame(window, false); @@ -248,6 +253,7 @@ function windowMenuItems(window: FreecellWindow): MenuItem[] { onSelect: (ctx) => { ctx.stack.pop(); window.soundOn = !window.soundOn; + saveSoundEnabled("freecell", window.soundOn); if (window.soundOn) playSfx(window, SFX_NEW_GAME); }, }, @@ -291,25 +297,25 @@ function handleInput(window: FreecellWindow, event: InputEvent, frameId: number) function handlePlayingInput(window: FreecellWindow, event: InputEvent, frameId: number): void { switch (event.type) { case "scroll-up": - window.cursor = (window.cursor + LOC_COUNT - 1) % LOC_COUNT; + moveCursor(window, -1); break; case "scroll-down": - window.cursor = (window.cursor + 1) % LOC_COUNT; + moveCursor(window, 1); break; // Watch swipes are spatial over the two rows of eight columns: up/down // switch between the top row (free cells + foundations) and the cascades - // keeping the column, left/right move within the row. + // landing on the nearest usable column, left/right move within the row. case "swipe-up": - if (window.cursor >= LOC_CASCADE0) window.cursor -= LOC_CASCADE0; + if (window.cursor >= LOC_CASCADE0) moveCursorToRow(window, LOC_CELL0); break; case "swipe-down": - if (window.cursor < LOC_CASCADE0) window.cursor += LOC_CASCADE0; + if (window.cursor < LOC_CASCADE0) moveCursorToRow(window, LOC_CASCADE0); break; case "swipe-left": - if (window.cursor % LOC_CASCADE0 > 0) window.cursor--; + moveCursorInRow(window, -1); break; case "swipe-right": - if (window.cursor % LOC_CASCADE0 < LOC_CASCADE0 - 1) window.cursor++; + moveCursorInRow(window, 1); break; case "click": if (window.selected === null) { @@ -410,6 +416,72 @@ function locationHasCard(window: FreecellWindow, location: number): boolean { return window.cascades[location - LOC_CASCADE0]!.length > 0; } +function isFoundation(location: number): boolean { + return location >= LOC_FOUNDATION0 && location < LOC_CASCADE0; +} + +/** + * Whether the cursor should stop at a location, given the move being built. + * Picking a source: it must hold a card, and foundations are never a source. + * Picking a destination: an empty free cell, a foundation that accepts the + * selected card, any cascade (a full legality check would hide the + * cascades the player wants to compare), or the source itself (clicking it + * again cancels the selection). + */ +function isCursorEligible(window: FreecellWindow, location: number): boolean { + if (window.selected === null) { + return !isFoundation(location) && locationHasCard(window, location); + } + if (location === window.selected) return true; + if (location < LOC_FOUNDATION0) return window.cells[location] === null; + if (isFoundation(location)) { + const card = topCardAt(window, window.selected); + return card !== null && foundationCanAccept(window.foundations[location - LOC_FOUNDATION0]!, card); + } + return true; +} + +/** Step the cursor through the location list (wrapping), skipping ineligible spots. */ +function moveCursor(window: FreecellWindow, step: 1 | -1): void { + let location = window.cursor; + for (let i = 0; i < LOC_COUNT; i++) { + location = (location + step + LOC_COUNT) % LOC_COUNT; + if (isCursorEligible(window, location)) { + window.cursor = location; + return; + } + } +} + +/** Step the cursor within its row (no wrapping), skipping ineligible spots. */ +function moveCursorInRow(window: FreecellWindow, step: 1 | -1): void { + const rowStart = window.cursor < LOC_CASCADE0 ? LOC_CELL0 : LOC_CASCADE0; + for (let location = window.cursor + step; location >= rowStart && location < rowStart + 8; location += step) { + if (isCursorEligible(window, location)) { + window.cursor = location; + return; + } + } +} + +/** + * Jump to the other row, keeping the column when it is eligible and + * otherwise taking the nearest eligible column; stays put when the row has + * none. + */ +function moveCursorToRow(window: FreecellWindow, rowStart: number): void { + const column = window.cursor % 8; + for (let distance = 0; distance < 8; distance++) { + for (const candidate of [column - distance, column + distance]) { + if (candidate < 0 || candidate >= 8) continue; + if (isCursorEligible(window, rowStart + candidate)) { + window.cursor = rowStart + candidate; + return; + } + } + } +} + /** True if `card` can go on `onto` in a cascade (descending, alternating color). */ function canStack(card: number, onto: number): boolean { return rankOf(onto) === rankOf(card) + 1 && isRed(onto) !== isRed(card); diff --git a/app/apps/minesweeper/minesweeper-app.worker.ts b/app/apps/minesweeper/minesweeper-app.worker.ts index 1f1b958a..2e0b5c5f 100644 --- a/app/apps/minesweeper/minesweeper-app.worker.ts +++ b/app/apps/minesweeper/minesweeper-app.worker.ts @@ -9,9 +9,13 @@ * scroll moves along the row, click reveals (or chords a satisfied number), * long-press toggles a flag, double-click returns to row-select. * Watch swipes skip the two-layer scheme and move the cell cursor in four - * directions; a watch double-click pauses directly. + * directions; a watch double-click pauses directly. Tap-then-hold opens the + * window menu in any phase, pausing a live game first. * Paused/won/lost: click resumes or starts a new game, double-click yields - * focus, long-press opens the window menu. + * focus. Losing input focus mid-game (a shell overlay such as the system + * menu or a notification, focus to the sidebar) pauses, as does + * backgrounding or screen-off. The difficulty setting persists across + * launches. */ import "@nativescript/core/globals"; import { GrayImage } from "../../graphics/image"; @@ -19,9 +23,11 @@ import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../gra import { prepareFrameDraws } from "../../graphics/glyph-wire"; import { getFont } from "../../graphics/bdffont"; import { getDefaultSmallFont } from "../../graphics/ui-fonts"; +import { getStringSetting, setStringSetting } from "../../native/settings-store"; import * as frameTimings from "../../native/frame-timings"; import { getActiveDisplay } from "../../native/active-display"; import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects"; +import { loadSoundEnabled, saveSoundEnabled } from "../../ui/sound-setting"; import { type MenuItem } from "../../ui/menu"; import { WindowMenu } from "../../ui/window-menu"; import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window"; @@ -55,6 +61,8 @@ const DIFFICULTIES = [ { name: "Medium", mines: 20 }, { name: "Hard", mines: 26 }, ] as const; +/** Persisted difficulty, stored by name so a reordering can't misfile it. */ +const DIFFICULTY_KEY = "minesweeper.difficulty"; /** Number glyph shades by adjacent-mine count; higher counts read brighter. */ const COUNT_SHADES = [0, 140, 170, 200, 220, 235, 245, 250, 250]; @@ -155,7 +163,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { focused: false, menu: null, phase: "playing", - difficultyIndex: 0, + difficultyIndex: loadDifficultyIndex(), mines: new Uint8Array(COLS * ROWS), counts: new Uint8Array(COLS * ROWS), cellState: new Uint8Array(COLS * ROWS), @@ -169,7 +177,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { elapsedMs: 0, runningSinceMs: null, tickTimer: null, - soundOn: true, + soundOn: loadSoundEnabled("minesweeper"), lastSubmittedFingerprint: "", }; windows.set(message.windowId, window); @@ -215,6 +223,19 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { if (window.foreground) renderAndSubmit(window, 0); break; } + case "input-focus": { + const window = windows.get(message.windowId); + if (!window) break; + // Anything that takes input away (the system menu, a notification + // modal, the voice dialog, focus back to the sidebar) pauses, so the + // clock stops and the board is hidden while the player can't act. + if (!message.focused && window.phase === "playing") { + window.phase = "paused"; + syncClock(window); + if (window.foreground) renderAndSubmit(window, 0); + } + break; + } case "screen": screenOn = message.on; for (const window of windows.values()) { @@ -237,6 +258,24 @@ function inferForeground(window: MinesweeperWindow, focused: boolean): void { syncClock(window); } +function loadDifficultyIndex(): number { + try { + const name = getStringSetting(DIFFICULTY_KEY, ""); + const index = DIFFICULTIES.findIndex((difficulty) => difficulty.name === name); + return index >= 0 ? index : 0; + } catch { + return 0; + } +} + +function saveDifficultyIndex(window: MinesweeperWindow): void { + try { + setStringSetting(DIFFICULTY_KEY, DIFFICULTIES[window.difficultyIndex]!.name); + } catch (error) { + console.warn(`minesweeper difficulty save failed: ${error}`); + } +} + /** * Fire a buzzer effect. Non-blocking: the firmware's sequencer plays the * steps on its own timer, and the Java call is safe from the worker thread. @@ -252,7 +291,7 @@ function playSfx(window: MinesweeperWindow, steps: Step[]): void { } } -/** The window's context menu (game actions), offered while paused or over; playing keeps long-press for flagging. */ +/** The window's context menu (game actions). Tap-then-hold reaches it in any phase; playing keeps long-press for flagging. */ function windowMenuItems(window: MinesweeperWindow): MenuItem[] { const nextDifficulty = DIFFICULTIES[(window.difficultyIndex + 1) % DIFFICULTIES.length]!; return [ @@ -269,6 +308,7 @@ function windowMenuItems(window: MinesweeperWindow): MenuItem[] { onSelect: (ctx) => { ctx.stack.pop(); window.difficultyIndex = (window.difficultyIndex + 1) % DIFFICULTIES.length; + saveDifficultyIndex(window); resetGame(window); playSfx(window, SFX_RESUME); }, @@ -278,6 +318,7 @@ function windowMenuItems(window: MinesweeperWindow): MenuItem[] { onSelect: (ctx) => { ctx.stack.pop(); window.soundOn = !window.soundOn; + saveSoundEnabled("minesweeper", window.soundOn); if (window.soundOn) playSfx(window, SFX_RESUME); }, }, @@ -290,7 +331,7 @@ function windowMenu(window: MinesweeperWindow): WindowMenu { windowId: window.windowId, post, title: () => window.title, - items: () => (window.phase === "playing" ? [] : windowMenuItems(window)), + items: () => windowMenuItems(window), claimsLongPress: () => window.phase === "playing", size: { width: window.viewportWidth, height: window.viewportHeight }, paintBase: () => paintContent(window), @@ -367,7 +408,11 @@ function handlePlayingInput(window: MinesweeperWindow, event: InputEvent, frameI toggleFlag(window); break; case "short-then-long-press": - // No context menu mid-game, so this opens the system menu instead. + // The menu's actions (new game, difficulty) all discard the board, and + // the clock must not run under it, so pause first; the board is hidden + // while paused, so the menu can't be used to study it off the clock. + window.phase = "paused"; + syncClock(window); windowMenu(window).open(); break; case "double-click": diff --git a/app/apps/pinball/pinball-app.worker.ts b/app/apps/pinball/pinball-app.worker.ts index b38b40ea..e9b375a5 100644 --- a/app/apps/pinball/pinball-app.worker.ts +++ b/app/apps/pinball/pinball-app.worker.ts @@ -13,11 +13,12 @@ * * Controls (ball ready): scroll sets launch power, click launches. In play: * click flips both flippers, scroll-up/down flips left/right individually, - * long-press nudges the table (three quick nudges tilt), double-click pauses. - * Watch swipes: left/right work the matching flipper, up nudges (or raises - * launch power at the plunger), down lowers launch power. + * double-click pauses. Watch swipes: left/right work the matching flipper, + * up/down raise and lower launch power at the plunger. * Paused/game over: click resumes or starts a new game, double-click yields - * focus, long-press opens the window menu. + * focus, long-press opens the window menu. Losing input focus mid-game (a + * shell overlay such as the system menu or a notification, focus to the + * sidebar) pauses, as does backgrounding or screen-off. */ import "@nativescript/core/globals"; import { GrayImage } from "../../graphics/image"; @@ -29,6 +30,7 @@ import * as frameTimings from "../../native/frame-timings"; import { getActiveDisplay } from "../../native/active-display"; import { getStringSetting, setStringSetting } from "../../native/settings-store"; import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects"; +import { loadSoundEnabled, saveSoundEnabled } from "../../ui/sound-setting"; import { type MenuItem } from "../../ui/menu"; import { WindowMenu } from "../../ui/window-menu"; import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window"; @@ -36,7 +38,6 @@ import { directionalFallback, GESTURE_CLICK, GESTURE_DOUBLE_CLICK, - GESTURE_LONG_PRESS, GESTURE_SCROLL, type InputEvent, } from "../../ui/gestures"; @@ -77,11 +78,6 @@ const RENDER_TICK_MS = 50; const LAUNCH_SPEEDS = [320, 380, 440, 500, 560] as const; const BUMPER_KICK = 340; const SLING_KICK = 300; -const NUDGE_KICK_UP = 70; -const NUDGE_KICK_SIDE = 45; -/** Nudges add 1 heat each and decay slowly; reaching 3 tilts the ball away. */ -const TILT_LIMIT = 3; -const TILT_HEAT_DECAY_PER_S = 0.4; const SCORE_BUMPER = 100; const SCORE_SLING = 25; @@ -208,7 +204,6 @@ const SFX_DRAIN: Step[] = [ { freq: 370, duty: 45, ms: 100 }, { freq: 247, duty: 50, ms: 200 }, ]; -const SFX_TILT: Step[] = [{ freq: 110, duty: 60, ms: 300 }]; const SFX_GAME_OVER: Step[] = [ { freq: 494, duty: 45, ms: 150 }, { freq: 440, duty: 45, ms: 150 }, @@ -269,10 +264,6 @@ type PinballWindow = { /** Debounce: a sensor re-arms only after the ball leaves its zone. */ rolloverInside: boolean[]; bumperFlashUntilMs: number[]; - tiltHeat: number; - tilted: boolean; - /** Alternates nudge direction so mashing doesn't push one way forever. */ - nudgeSign: 1 | -1; /** Transient center-table message ("BALL LOST", "+500", ...). */ toast: string; toastUntilMs: number; @@ -331,15 +322,12 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { rolloverLit: ROLLOVERS.map(() => false), rolloverInside: ROLLOVERS.map(() => false), bumperFlashUntilMs: BUMPERS.map(() => 0), - tiltHeat: 0, - tilted: false, - nudgeSign: 1, toast: "", toastUntilMs: 0, tickTimer: null, lastTickAtMs: 0, lastMinorSfxAtMs: 0, - soundOn: true, + soundOn: loadSoundEnabled("pinball"), lastSubmittedFingerprint: "", }; windows.set(message.windowId, window); @@ -385,6 +373,19 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { if (window.foreground) renderAndSubmit(window, 0); break; } + case "input-focus": { + const window = windows.get(message.windowId); + if (!window) break; + // Anything that takes input away (the system menu, a notification + // modal, the voice dialog, focus back to the sidebar) pauses: the + // ball must not drain under a menu the player can't flip through. + if (!message.focused && window.phase === "playing") { + window.phase = "paused"; + syncTickTimer(window); + if (window.foreground) renderAndSubmit(window, 0); + } + break; + } case "screen": screenOn = message.on; for (const window of windows.values()) { @@ -446,7 +447,7 @@ function playSfx(window: PinballWindow, steps: Step[], minor = false): void { } } -/** The window's context menu (game actions), offered while paused or over; playing keeps long-press for the nudge. */ +/** The window's context menu (game actions), offered while paused or over. */ function windowMenuItems(window: PinballWindow): MenuItem[] { return [ { @@ -462,6 +463,7 @@ function windowMenuItems(window: PinballWindow): MenuItem[] { onSelect: (ctx) => { ctx.stack.pop(); window.soundOn = !window.soundOn; + saveSoundEnabled("pinball", window.soundOn); if (window.soundOn) playSfx(window, SFX_RESUME); }, }, @@ -475,7 +477,6 @@ function windowMenu(window: PinballWindow): WindowMenu { post, title: () => window.title, items: () => (window.phase === "playing" ? [] : windowMenuItems(window)), - claimsLongPress: () => window.phase === "playing", size: { width: window.viewportWidth, height: window.viewportHeight }, paintBase: () => paintContent(window), isFocused: () => window.focused, @@ -519,8 +520,8 @@ function handlePlayingInput(window: PinballWindow, event: InputEvent, frameId: n flip(window, window.flippers[1]!); } break; - // Watch swipes: left/right work the matching flipper; up nudges the - // table (or raises launch power at the plunger), down lowers it. + // Watch swipes: left/right work the matching flipper; up/down set the + // launch power at the plunger. case "swipe-left": if (!ready) flip(window, window.flippers[0]!); break; @@ -530,8 +531,6 @@ function handlePlayingInput(window: PinballWindow, event: InputEvent, frameId: n case "swipe-up": if (ready) { window.launchPower = clamp(window.launchPower + 1, 1, LAUNCH_SPEEDS.length); - } else { - nudge(window); } break; case "swipe-down": @@ -547,13 +546,6 @@ function handlePlayingInput(window: PinballWindow, event: InputEvent, frameId: n flip(window, window.flippers[1]!); } break; - case "long-press": - if (ready) { - frameTimings.finishFrame(frameId, "discarded: pinball ignored input"); - return; - } - nudge(window); - break; case "short-then-long-press": // No context menu mid-game, so this opens the system menu instead. windowMenu(window).open(); @@ -606,8 +598,6 @@ function resetGame(window: PinballWindow): void { window.score = 0; window.rolloverLit = ROLLOVERS.map(() => false); window.rolloverInside = ROLLOVERS.map(() => false); - window.tiltHeat = 0; - window.tilted = false; window.toast = ""; window.toastUntilMs = 0; for (const flipper of window.flippers) { @@ -628,7 +618,6 @@ function launchBall(window: PinballWindow): void { } function flip(window: PinballWindow, flipper: Flipper): void { - if (window.tilted) return; if (flipper.state === "hold") { flipper.holdUntilMs = Date.now() + FLIPPER_HOLD_MS; return; @@ -637,25 +626,8 @@ function flip(window: PinballWindow, flipper: Flipper): void { playSfx(window, SFX_FLIPPER, true); } -function nudge(window: PinballWindow): void { - if (window.tilted) return; - window.ballVy -= NUDGE_KICK_UP; - window.ballVx += window.nudgeSign * NUDGE_KICK_SIDE; - window.nudgeSign = window.nudgeSign === 1 ? -1 : 1; - window.tiltHeat += 1; - if (window.tiltHeat >= TILT_LIMIT) { - window.tilted = true; - showToast(window, "TILT"); - // A tilt drops the flippers dead until the ball drains. - for (const flipper of window.flippers) { - if (flipper.state !== "rest") flipper.state = "falling"; - } - playSfx(window, SFX_TILT); - } -} - function addScore(window: PinballWindow, points: number): void { - if (!window.tilted) window.score += points; + window.score += points; } function showToast(window: PinballWindow, text: string, ms = 1100): void { @@ -710,7 +682,6 @@ function tick(window: PinballWindow): void { function stepPhysics(window: PinballWindow): void { const dt = PHYSICS_DT; stepFlippers(window, dt); - window.tiltHeat = Math.max(0, window.tiltHeat - TILT_HEAT_DECAY_PER_S * dt); if (window.ballState !== "live") return; window.ballVy += GRAVITY * dt; @@ -894,8 +865,6 @@ function ballDrained(window: PinballWindow): void { window.ballVx = 0; window.ballVy = 0; window.trail = []; - window.tilted = false; - window.tiltHeat = 0; window.ballsLeft--; if (window.ballsLeft <= 0) { window.phase = "game-over"; @@ -1007,9 +976,6 @@ function paintContent(window: PinballWindow): GrayImage { if (window.toastUntilMs > now && window.toast) { drawCenteredIn(image, mediumFont, LEFT, LANE_X - LEFT, 150, window.toast, 245); } - if (window.tilted) { - drawCenteredIn(image, mediumFont, LEFT, LANE_X - LEFT, 60, "TILT", 245); - } if (window.phase === "paused") { paintDialog(image, "PAUSED", [`${GESTURE_CLICK} resume`, `${GESTURE_DOUBLE_CLICK} leave`]); } else if (window.phase === "game-over") { @@ -1050,7 +1016,7 @@ function paintPanel(image: GrayImage, window: PinballWindow): void { image.drawText(smallFont, PANEL_X, 236, `${GESTURE_DOUBLE_CLICK} pause`, 115); } else { image.drawText(smallFont, PANEL_X, 216, `${GESTURE_CLICK} flip ${GESTURE_SCROLL} L/R flip`, 115); - image.drawText(smallFont, PANEL_X, 236, `${GESTURE_LONG_PRESS} nudge ${GESTURE_DOUBLE_CLICK} pause`, 115); + image.drawText(smallFont, PANEL_X, 236, `${GESTURE_DOUBLE_CLICK} pause`, 115); } } diff --git a/app/ui/shell/shell.ts b/app/ui/shell/shell.ts index 3d106809..b99b290c 100644 --- a/app/ui/shell/shell.ts +++ b/app/ui/shell/shell.ts @@ -149,6 +149,13 @@ export type ShellWindow = { onFocus?: (lastInput: InputEvent | null) => void; /** Screen turned on/off; hidden or screen-off windows should stop painting. */ setScreenOn?: (on: boolean) => void; + /** + * Input focus arrived at or left this window: it is (no longer) where + * ordinary input goes. Unlike setForeground / onFocus, this also tracks + * shell overlays (the system menu, a notification modal, the voice dialog) + * and screen-off, so a game can pause on any of them. Sent on change only. + */ + setInputFocus?: (focused: boolean) => void; }; export type ShellConfig = { @@ -300,6 +307,8 @@ class Shell { /** Window ids in most-recently-visible-first order; closing the visible window returns to the next entry. */ private mruWindowIds: string[] = []; private focus: FocusKind = "sidebar"; + /** The window last told it holds input focus (see syncInputFocus). */ + private inputFocusedWindowId: string | null = null; private screenOn = true; private lastInputAtMs = Date.now(); /** The most recent input event received, for windows gaining focus (see ShellWindow.onFocus). */ @@ -356,7 +365,15 @@ class Shell { private lastTopBarSettingsKey: string | null = null; configure(config: ShellConfig): void { - this.config = config; + // Nearly every state change ends in a shell render request, so it is + // the natural point to tell windows about input-focus changes too. + this.config = { + ...config, + requestShellRender: () => { + this.syncInputFocus(); + config.requestShellRender(); + }, + }; this.stack.setActions(config.actions); this.subscribeToTopBarSettings(); this.subscribeToAmbientCards(); @@ -537,6 +554,34 @@ class Shell { return !!window && this.focus === "window" && this.foregroundWindow() === window; } + /** + * The window ordinary input reaches right now: the foreground window with + * focus in-window, the screen on, and no shell overlay (system menu, + * notification modal, voice dialog, alert) above it. + */ + private inputTargetWindow(): ShellWindow | undefined { + if (!this.screenOn || this.focus !== "window" || !this.stack.isAtBase() || this.activeVoiceLayer) { + return undefined; + } + return this.foregroundWindow(); + } + + /** + * Tell windows when they gain or lose input focus (ShellWindow.setInputFocus). + * Called from every shell render request and the input/wake/sleep paths, + * which between them follow every focus-affecting state change; it diffs + * against the last notification, so calling it often is cheap. + */ + private syncInputFocus(): void { + const target = this.inputTargetWindow(); + const targetId = target?.windowId ?? null; + if (targetId === this.inputFocusedWindowId) return; + const previous = this.windows.find((w) => w.windowId === this.inputFocusedWindowId); + this.inputFocusedWindowId = targetId; + previous?.setInputFocus?.(false); + target?.setInputFocus?.(true); + } + /** Turn the screen on (if off) and set focus. Returns whether it was off. */ wake(focus: FocusKind, nowMs = Date.now()): boolean { this.lastInputAtMs = nowMs; @@ -544,7 +589,10 @@ class Shell { const alreadyFocused = this.isFocusTarget(gaining); this.focus = focus; if (gaining && !alreadyFocused) gaining.onFocus?.(this.lastInput); - if (this.screenOn) return false; + if (this.screenOn) { + this.syncInputFocus(); + return false; + } this.screenOn = true; this.config.onScreenStateChanged(true); for (const window of this.windows) { @@ -553,6 +601,7 @@ class Shell { // Refresh the foreground window; the compositor restored its retained // frame, but its content may be stale (e.g. a running stopwatch). this.foregroundWindow()?.requestRender(); + this.syncInputFocus(); return true; } @@ -565,6 +614,7 @@ class Shell { for (const window of this.windows) { window.setScreenOn?.(false); } + this.syncInputFocus(); this.config.onScreenStateChanged(false); } @@ -577,6 +627,7 @@ class Shell { this.setSelectedIndex(index); this.focus = "window"; if (!alreadyFocused) target?.onFocus?.(this.lastInput); + this.syncInputFocus(); } /** Idle timeout: sleep if the configured timeout elapsed. Returns whether it slept. */ @@ -655,6 +706,16 @@ class Shell { } async receiveInput(event: InputEvent, frameId = 0): Promise { + try { + return await this.routeInput(event, frameId); + } finally { + // Whatever the input did (opened an overlay, moved focus, slept the + // screen), windows learn about the resulting input-focus change. + this.syncInputFocus(); + } + } + + private async routeInput(event: InputEvent, frameId: number): Promise { const previous = this.lastInput; this.lastInput = event; // A visible window may paint a source-dependent indicator (see diff --git a/app/ui/shell/worker-window.ts b/app/ui/shell/worker-window.ts index be8c6901..cb0b340d 100644 --- a/app/ui/shell/worker-window.ts +++ b/app/ui/shell/worker-window.ts @@ -21,6 +21,12 @@ export type WorkerAppMessage = | { type: "text-input"; windowId: string; text: string } | { type: "render"; windowId: string; focused: boolean } | { type: "foreground"; windowId: string; foreground: boolean; focused: boolean } + /** + * Input focus arrived at or left the window, counting shell overlays and + * screen-off (see ShellWindow.setInputFocus). Sent on change only; the + * per-message `focused` flags above stay the source of truth for painting. + */ + | { type: "input-focus"; windowId: string; focused: boolean } | { type: "screen"; on: boolean } /** Assistant tool invocation aimed at a window; reply with tool-result. */ | { type: "tool-call"; callId: string; windowId: string; name: string; args: unknown }; @@ -421,6 +427,9 @@ export class WorkerAppHost { // uniform; the worker treats it globally. this.post({ type: "screen", on }); }, + setInputFocus: (focused) => { + this.post({ type: "input-focus", windowId: spec.windowId, focused }); + }, }; shell.registerWindow(window); // Configure the surface before any foregrounding so the worker's first diff --git a/app/ui/sound-setting.ts b/app/ui/sound-setting.ts new file mode 100644 index 00000000..043feaab --- /dev/null +++ b/app/ui/sound-setting.ts @@ -0,0 +1,26 @@ +/** + * The "Sound: on/off" entry in a game's context menu, persisted per app under + * `.soundOn` so each game remembers its own choice across launches. + * Reads default to on; storage failures fall back to on and never throw. + */ +import { getBooleanSetting, setBooleanSetting } from "../native/settings-store"; + +function soundKey(appId: string): string { + return `${appId}.soundOn`; +} + +export function loadSoundEnabled(appId: string): boolean { + try { + return getBooleanSetting(soundKey(appId), true); + } catch { + return true; + } +} + +export function saveSoundEnabled(appId: string, enabled: boolean): void { + try { + setBooleanSetting(soundKey(appId), enabled); + } catch (error) { + console.warn(`${appId} sound setting save failed: ${error}`); + } +} diff --git a/tests/fixtures/pinball-worker.cjs b/tests/fixtures/pinball-worker.cjs index a9d6e052..e0078c03 100644 --- a/tests/fixtures/pinball-worker.cjs +++ b/tests/fixtures/pinball-worker.cjs @@ -38,13 +38,14 @@ module.exports = function worker() { '../../native/active-display': {}, '../../native/settings-store': { getStringSetting: () => highScore, setStringSetting: (_, value) => { highScore = value; } }, '../../ui/sound-effects': {}, + '../../ui/sound-setting': { loadSoundEnabled: () => true, saveSoundEnabled: () => {} }, '../../ui/window-menu': { WindowMenu: class { open() {} } }, '../../ui/gestures': { directionalFallback: (event) => event, GESTURE_CLICK: '●', GESTURE_DOUBLE_CLICK: '●●', GESTURE_SCROLL: '↕', GESTURE_LONG_PRESS: '—' }, '../../util/numeric-util': { clamp: (v, lo, hi) => Math.max(lo, Math.min(hi, v)) }, }, ` renderAndSubmit = () => {}; playSfx = () => {}; - exports.api = { windows, launchBall, ballDrained, stepPhysics, tick, flip, nudge, + exports.api = { windows, launchBall, ballDrained, stepPhysics, tick, flip, checkTargets, checkRollovers, collideBumpers, resetGame, paintContent, TARGETS, ROLLOVERS }; `, { global, Date: { now: () => now }, setInterval: () => 1, clearInterval: noop }).api; const message = (data) => global.onmessage({ data }); diff --git a/tests/pinball.test.cjs b/tests/pinball.test.cjs index cb80e062..6ada5489 100644 --- a/tests/pinball.test.cjs +++ b/tests/pinball.test.cjs @@ -78,22 +78,6 @@ test('ball saver preserves objectives once, then a drain pays multiplied bonus a assert.equal(h.w.ballSaveRemaining, 8); }); -test('tilt disables awards, objective progress, saver and drain bonus', () => { - const h = worker(); - h.launchBall(h.w); target(h, 0); - h.nudge(h.w); h.nudge(h.w); h.nudge(h.w); - assert.equal(h.w.tilted, true); - lane(h, 0); target(h, 1); - h.w.ballX = 121; h.w.ballY = 110; h.collideBumpers(h.w); - assert.equal(h.w.score, 150); - assert.equal(h.w.targetsDown[1], false); - assert.ok(h.w.rolloverLit.every((value) => !value)); - h.ballDrained(h.w); - assert.equal(h.w.ballsLeft, 2); - assert.equal(h.w.lastBonus, 0); - assert.equal(h.w.score, 150); -}); - test('pause, background, screen-off and menus preserve gameplay timers', () => { for (const suspend of [ (h) => h.input('double-click'), diff --git a/tests/touch-input.test.cjs b/tests/touch-input.test.cjs index 8ddabb09..cab8e831 100644 --- a/tests/touch-input.test.cjs +++ b/tests/touch-input.test.cjs @@ -51,6 +51,7 @@ function worker() { '../../native/active-display': {}, '../../native/settings-store': { getStringSetting: () => '0', setStringSetting: noop }, '../../ui/sound-effects': {}, '../../ui/window-menu': {}, + '../../ui/sound-setting': { loadSoundEnabled: () => true, saveSoundEnabled: noop }, '../../ui/gestures': { directionalFallback: (event) => event }, '../../util/numeric-util': { clamp: (v, lo, hi) => Math.max(lo, Math.min(hi, v)) }, };