Add video background option to Mahjong Match

- Register three looping mp4 backdrops in the asset manifest alongside the existing images.
- Add an Image | Video segmented toggle on the layout-select screen; choice persists in localStorage and defaults to Video.
- Render a muted, looping, letterboxed video behind the tiles with a scrim, falling back to image backdrops if no video is cached.
- Defer re-fitting after Phaser swaps in the real video frame so the backdrop isn't rendered ~3× zoomed against the 256×256 placeholder.
- Add tools/smokeMahjongMatchBgVideo.mjs Playwright smoke test covering toggle default/persistence, video playback/mute/loop/sizing, and image fallback.
This commit is contained in:
Brian Fertig 2026-11-26 13:21:01 -07:00
parent 14f098e3f1
commit 0223a191fc
No known key found for this signature in database
3 changed files with 237 additions and 3 deletions

View File

@ -327,6 +327,8 @@ export const MANIFEST = {
image('bg-mahjongmatch-menu', 'assets/images/background-mahjongmatch.png'),
// In-play backdrops — one is picked at random per game.
...['01', '02', '03'].map((n) => image(`bg-mm-${n}`, `assets/images/background-mm-${n}.png`)),
// Looping video versions of the same three backdrops (Background: Video).
...['01', '02', '03'].map((n) => ({ type: 'video', key: `bg-mm-video-${n}`, path: `assets/videos/mahjong/mm-background-${n}.mp4` })),
// chinese soundtrack (see services/soundtrack.js) — lazy-loaded here so
// its audio only downloads once Mahjong Match is actually entered.
(scene) => musicFrom(scene, 'chinese-music'),

View File

@ -50,6 +50,9 @@ const FREED_GOLD = 0xffd15c;
// three are brightly lit, so a dark scrim sits over it to keep the ivory tiles
// and the HUD readable — drop SCRIM_ALPHA toward 0 for more of the artwork.
const BG_KEYS = ['bg-mm-01', 'bg-mm-02', 'bg-mm-03'];
// Looping video versions of the same three backdrops (Background: Video).
const BG_VIDEO_KEYS = ['bg-mm-video-01', 'bg-mm-video-02', 'bg-mm-video-03'];
const BG_MODE_KEY = 'mahjongmatch-bg-mode';
const SCRIM = 0x06140d;
const SCRIM_ALPHA = 0.45;
@ -132,6 +135,9 @@ export default class MahjongMatchGame extends Phaser.Scene {
const totalW = 3 * CARD_W + 2 * GAP_X;
const left = cx - totalW / 2 + CARD_W / 2;
// Background toggle: right side, above the Pyramid card (3rd column).
this._addBgToggle(left + 2 * (CARD_W + GAP_X), 355);
LAYOUT_ORDER.forEach((key, i) => {
const layout = LAYOUTS[key];
const x = left + (i % 3) * (CARD_W + GAP_X);
@ -219,13 +225,109 @@ export default class MahjongMatchGame extends Phaser.Scene {
}
// Added to `this.layer` before the tiles, so insertion order keeps it behind
// them. If the texture hasn't loaded, the felt rectangle underneath shows.
// them. If the asset hasn't loaded, the felt rectangle underneath shows.
_drawBackground() {
const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2;
const scrim = () =>
this.layer.add(this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, SCRIM, SCRIM_ALPHA));
if (this._bgMode() === 'video') {
const keys = BG_VIDEO_KEYS.filter((k) => this.cache.video?.exists(k));
if (keys.length) {
const key = keys[Math.floor(Math.random() * keys.length)];
const v = this.add.video(cx, cy, key);
v.setLoop(true).setMute(true);
v.once('error', () => v.destroy());
this._fitVideo(v);
// Phaser swaps in the real 864×480 frame (setSizeToFrame, scale kept)
// when the video's texture is ready — a fit computed against the
// initial 256×256 placeholder would otherwise survive and render the
// backdrop ~3× zoomed in. Defer the re-fit one tick so it runs after
// Phaser's own sizing has settled, whichever of these two fires.
const refit = () => { if (v.active) this._fitVideo(v); };
v.once('textureready', () => this.time.delayedCall(0, refit));
v.video?.addEventListener('loadedmetadata', () => this.time.delayedCall(0, refit), { once: true });
this.layer.add(v);
v.play().catch?.(() => {});
scrim();
return;
}
// Video failed to load — fall through to the image backdrops.
}
const key = BG_KEYS[Math.floor(Math.random() * BG_KEYS.length)];
if (!this.textures.exists(key)) return;
const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2;
this.layer.add(this.add.image(cx, cy, key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT));
this.layer.add(this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, SCRIM, SCRIM_ALPHA));
scrim();
}
// Fit the video to the screen: full-screen when it fits, but never larger
// than the screen and never stretched — non-matching aspects letterbox
// over the felt backdrop instead of cropping or distorting.
_fitVideo(v) {
const el = v.video;
let srcW = el?.videoWidth, srcH = el?.videoHeight;
if (!srcW || !srcH) { srcW = 16; srcH = 9; } // all current loops are 16:9
const s = Math.min(GAME_WIDTH / srcW, GAME_HEIGHT / srcH);
v.setDisplaySize(Math.round(srcW * s), Math.round(srcH * s));
}
// ── Background toggle (Image / Video) ────────────────────────────────────────
_bgMode() {
try { return localStorage.getItem(BG_MODE_KEY) ?? 'video'; } catch (_) { return 'video'; }
}
_setBgMode(mode) {
try { localStorage.setItem(BG_MODE_KEY, mode); } catch (_) { /* private mode */ }
}
// Segmented Image | Video control, shown above the Pyramid card on the
// layout-select screen. Only affects the next game, so no redraw needed.
_addBgToggle(x, y) {
const OPTS = ['image', 'video'];
const OPT_W = 120, OPT_H = 44, GAP = 12;
const totalW = OPTS.length * OPT_W + (OPTS.length - 1) * GAP;
const cap = this.add.text(x - totalW / 2 - 20, y, 'Background', {
fontFamily: 'Righteous', fontSize: '28px', color: '#000000',
}).setOrigin(1, 0.5);
const opts = [];
let ox = x - totalW / 2;
for (const opt of OPTS) {
const rx = ox + OPT_W / 2;
const bg = this.add.rectangle(rx, y, OPT_W, OPT_H, 0x143523)
.setStrokeStyle(2, COLORS.gold, 0.7)
.setInteractive({ useHandCursor: true });
const lbl = this.add.text(rx, y, opt === 'video' ? 'Video' : 'Image', {
fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex,
}).setOrigin(0.5);
const entry = { opt, bg, lbl };
opts.push(entry);
bg.on('pointerup', () => {
this._setBgMode(opt);
for (const e of opts) this._styleBgOpt(e, e.opt === opt);
});
ox += OPT_W + GAP;
}
const apply = (mode) => { for (const e of opts) this._styleBgOpt(e, e.opt === mode); };
apply(this._bgMode());
// Retained for tests / programmatic use. Bail if the select screen is gone.
this.bgToggle = {
opts,
set: (mode) => {
if (!opts.some(({ bg }) => bg.active)) return; // destroyed with the select screen
this._setBgMode(mode);
apply(mode);
},
};
this.layer.add([cap, ...opts.flatMap(({ bg, lbl }) => [bg, lbl])]);
}
_styleBgOpt({ bg, lbl }, active) {
bg.setFillStyle(active ? COLORS.gold : 0x143523).setStrokeStyle(2, COLORS.gold, 0.7);
lbl.setColor(active ? '#231a08' : COLORS.textHex);
}
// Fit the layout into the area right of the button strip.

View File

@ -0,0 +1,130 @@
// Smoke test — Mahjong Match "Background: Image | Video" toggle.
// node tools/smokeMahjongMatchBgVideo.mjs [baseURL]
//
// Verifies:
// 1. The toggle appears on the layout-select screen and defaults to Video.
// 2. The selection persists in localStorage.
// 3. Video mode: a looping, muted backdrop video plays behind the tiles.
// 4. Image mode: the classic image backdrop is used (no video).
// Exits non-zero on any failure.
let chromium;
try { chromium = (await import('playwright')).chromium; }
catch { chromium = (await import('file:///home/brianfertig/.npm/_npx/e41f203b7505f1fb/node_modules/playwright/index.mjs')).chromium; }
const BASE = process.argv[2] || 'http://localhost:8123';
let failures = 0;
function check(ok, msg) {
console.log(` ${ok ? '✓' : '✗'} ${msg}`);
if (!ok) failures++;
}
const browser = await chromium.launch({
headless: true,
executablePath: '/home/brianfertig/.cache/ms-playwright/chromium-1208/chrome-linux64/chrome',
args: ['--no-sandbox', '--disable-gpu'],
});
const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });
const errors = [];
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
await page.goto(BASE + '/', { waitUntil: 'load', timeout: 30000 });
await page.waitForFunction(
() => window.game && (window.game.isRunning === true || window.game.isRunning === 'running'),
{ timeout: 25000 },
);
// Boot the scene directly, then load its lazy assets (videos + images).
const r = await page.evaluate(async () => {
const { ensureGameAssets } = await import('/src/services/assetLoader.js');
window.game.scene.start('MahjongMatchGame', { game: { slug: 'mahjongmatch', name: 'Mahjong Match' } });
const scene = window.game.scene.getScene('MahjongMatchGame');
await ensureGameAssets(scene, 'mahjongmatch');
const videoKeys = ['bg-mm-video-01', 'bg-mm-video-02', 'bg-mm-video-03'].filter(
(k) => scene.cache.video?.exists(k));
return { videoKeys, imageKeys: ['bg-mm-01', 'bg-mm-02', 'bg-mm-03'].filter((k) => scene.textures.exists(k)) };
});
console.log('Assets:');
check(r.videoKeys.length === 3, `video assets loaded: ${r.videoKeys.join(', ')}`);
check(r.imageKeys.length === 3, `image assets loaded: ${r.imageKeys.join(', ')}`);
console.log('Toggle:');
const t = await page.evaluate(() => {
const scene = window.game.scene.getScene('MahjongMatchGame');
return {
exists: !!scene.bgToggle,
defaultMode: scene._bgMode(),
stored: localStorage.getItem('mahjongmatch-bg-mode'),
};
});
check(t.exists, 'toggle present on layout-select screen');
check(t.defaultMode === 'video', `default mode is Video (got ${t.defaultMode})`);
await page.evaluate(() => window.game.scene.getScene('MahjongMatchGame').bgToggle.set('image'));
const stored = await page.evaluate(() => localStorage.getItem('mahjongmatch-bg-mode'));
check(stored === 'image', 'Image selection persisted to localStorage');
// ── Video mode game ───────────────────────────────────────────────────────────
await page.evaluate(() => {
const scene = window.game.scene.getScene('MahjongMatchGame');
scene.bgToggle.set('video');
scene.startGame('pyramid');
});
console.log('Video background:');
const v = await page.evaluate(async () => {
const scene = window.game.scene.getScene('MahjongMatchGame');
const vid = scene.layer.list.find((o) => o.type === 'Video');
if (!vid) return null;
const el = vid.video;
// Headless loading is slow; wait for playback to actually start.
const deadline = Date.now() + 20000;
while (Date.now() < deadline && !(el.currentTime > 0 || el.readyState >= 2)) {
await new Promise((res) => setTimeout(res, 250));
}
return {
src: el?.currentSrc?.split('/').pop() ?? null,
playing: vid.isPlaying() && !el.paused,
muted: el.muted,
loop: el?.loop === true,
readyState: el?.readyState ?? 0,
currentTime: el?.currentTime ?? 0,
// The zoom regression: a fit computed against Phaser's 256×256 placeholder
// frame survives the real 864×480 frame arriving and renders 3× too big.
display: [vid.displayWidth, vid.displayHeight],
};
});
check(!!v, 'a backdrop video is present behind the tiles');
if (v) {
check(v.src !== null && /^mm-background-0\d\.mp4$/.test(v.src), `video is one of the three mahjong loops (${v.src})`);
check(v.playing && v.currentTime > 0, 'video is actually playing (currentTime > 0)');
check(v.muted && v.loop, 'video is muted and looping');
const [dw, dh] = v.display;
check(dw <= 1921 && dh <= 1081, `video fits the screen (display ${dw}×${dh}, max 1920×1080)`);
}
// ── Image mode game ───────────────────────────────────────────────────────────
await page.evaluate(() => {
const scene = window.game.scene.getScene('MahjongMatchGame');
scene.showLayoutSelect(); // back to the select screen (toggle recreated)
scene.bgToggle.set('image');
scene.startGame('garden');
});
await page.waitForTimeout(500);
console.log('Image background:');
const i = await page.evaluate(() => {
const scene = window.game.scene.getScene('MahjongMatchGame');
return {
video: scene.layer.list.some((o) => o.type === 'Video'),
image: scene.layer.list.some((o) => o.type === 'Image' && /^bg-mm-0\d$/.test(o.texture?.key)),
};
});
check(!i.video, 'no video backdrop in Image mode');
check(i.image, 'image backdrop (bg-mm-0x) present in Image mode');
if (errors.length) console.log(errors.join('\n'));
await browser.close();
if (failures || errors.length) { console.error(`FAILED (${failures})`); process.exit(1); }
console.log('OK');