import { compareGameCatalogOrder, gameGenreLabels, gameGenres, gameSettings, gameStyles, type GameBrief, type GameCard, type GameCatalog, type GameCreated, type GameGenre, type GameRemixOptions, type GameSetting, type GameStyle, type GameTrailer, type GameHandoff } from '../../../../shared/game-contract'; import { motionApi } from '../useWorkspace'; import { isLocalGamePreviewUrl } from '../../../../shared/local-game-preview'; export const genreLabels: Record = gameGenreLabels; export const styleLabels: Record = { pixel: 'Pixel art', minimal: 'Minimalist', ascii: 'ASCII art', voxel: 'Voxel', anime: 'Anime', '3d': '3D' }; export const settingLabels: Record = { medieval: 'Medieval', cyberpunk: 'Cyberpunk', retro: 'Retro', modern: 'Modern', space: 'Outer space', fantasy: 'Fantasy' }; /** Example briefs for each genre and the generic game input placeholder. */ export const genrePlaceholders: Record = { none: 'Describe the game you want to make', shooter: 'A wave shooter where you defend a space station', platformer: 'A pixel platformer with a boss fight at the end', story: 'A branching mystery told through letters', casual: 'A one-tap game you can play with one thumb', racing: 'A night-time street race with drifting', horror: 'A dark maze where something follows your torch', }; /** The brief sent to the Agent: chosen options first, then the user's words. */ export function composeBrief({ prompt, genre, style, setting, multiplayer }: GameBrief) { const parts = [style && `${styleLabels[style]} style`, multiplayer && 'with multiplayer', genre && genreLabels[genre], setting && `${settingLabels[setting]} setting`].filter(Boolean); return [parts.join(', '), prompt.trim()].filter(Boolean).join('. '); } // Bundled templates keep Explore usable while the local service is starting or older than this Studio. const bundledMeta = import.meta.glob('../../../../templates/games/*/game.json', { eager: true, import: 'default' }) as Record & { cover: string }>; const bundledPages = import.meta.glob('../../../../templates/games/*/index.html', { query: '?raw', import: 'default' }) as Record Promise>; const folder = (path: string) => path.split('/').slice(-2, -1)[0]; // Original browser games shared publicly by their creators. They open on the creator's page and are not // copied into OpenMotion; covers are frames from the creators' own posts, credited on each card. const communityCovers = import.meta.glob('./community/*.jpg', { eager: true, query: '?url', import: 'default' }) as Record; const curatedZh: Record = {"saltline": ["Saltline 盐线", "夜雨船厂里的 3D 射击,对抗机器狗和无人机;模型、音效和贴图都由 AI 从零生成。"], "shipwreck": ["安提基特拉沉船", "潜入沉船寻找安提基特拉机械,画面和声音都由一个网页文件里的代码实时生成。"], "sky-reach": ["Sky Reach 天际之旅", "驾驶飞船降落到星球表面,下船步行探索。"], "little-prince": ["小王子:星辰之旅", "把小王子的每个星球做成可探索的水彩 3D 场景,需要浏览器开启硬件加速。"], "voxel-musou": ["方块三国无双", "一个英雄对战 300 个体素士兵,有连招、闪避和无双大招。"], "turbo-kart": ["Turbo Kart 卡丁车", "卡丁车漂移竞速,可以捡道具,作者称一次生成。"]}; const community = (id: string, title: string, description: string, genre: GameGenre, external: NonNullable, createdAt: string): GameCard => ({ id: 'community-' + id, title, description, genre, style: '3d', setting: null, multiplayer: false, maxPlayers: 1, status: 'published', cover: communityCovers[`./community/${id}.jpg`] ?? null, playUrl: external.url, plays: 0, likes: 0, dislikes: 0, reaction: 0, favorite: false, source: 'community', external, remixOf: null, controls: '', createdAt, updatedAt: createdAt, i18n: curatedZh[id] ? { 'zh-CN': { title: curatedZh[id][0], description: curatedZh[id][1] } } : undefined, }); // Ordered by views on the creator's original post (2026-11-20): 4.47M, 3.92M, 424K, 400K, 380K, 170K. const viralOrder = ['saltline', 'little-prince', 'sky-reach', 'shipwreck', 'turbo-kart', 'voxel-musou']; export const communityGames: GameCard[] = [ community('saltline', 'Saltline', 'A 3D shooter in a shipyard against robot dogs and drones; models, sound and textures generated from scratch.', 'shooter', { url: 'https://claude.ai/artifact/BGY1SztrAYcJQHSsnHHGmp', author: '@felixrieseberg', postUrl: 'https://x.com/felixrieseberg/status/2119925633564463609', model: 'Fable 5.2', embeddable: false }, '2026-11-09T00:00:00.000Z'), community('shipwreck', 'Antikythera Dive', 'Dive into a wreck to find the Antikythera mechanism. Graphics and sound are generated by code in one HTML file.', 'story', { url: 'https://claude.ai/artifact/ReCBQGZ4EirKSiEmT8XXfs', author: '@edwinarbus', postUrl: 'https://x.com/edwinarbus/status/2102463453176979794', model: 'Opus 5.5', embeddable: false }, '2026-09-22T00:00:00.000Z'), community('sky-reach', 'Sky Reach', 'Fly a ship down to a planet surface, land and explore on foot.', 'casual', { url: 'https://tesana.com/game/sky-reach', author: '@jonesiller', postUrl: 'https://x.com/Rubzem/status/2104253584737230926', model: 'Opus 5.5', embeddable: false }, '2026-09-27T00:00:00.000Z'), community('little-prince', 'The Little Prince: Star Journey', 'Explore each planet of The Little Prince as a watercolour 3D scene. Needs hardware acceleration in the browser.', 'story', { url: 'https://littleprince.dev/', author: '@Saccc_c', postUrl: 'https://x.com/Saccc_c/status/2109962425512734739', model: 'Opus 5.5', embeddable: true }, '2026-10-13T00:00:00.000Z'), community('voxel-musou', 'Voxel Musou', 'One hero against 300 voxel soldiers, with combos, dodges and a special attack.', 'shooter', { url: 'https://voxel-musou.vercel.app', author: '@BubuStd', postUrl: 'https://x.com/BubuStd/status/2102991290568954264', model: 'Opus 5.5', embeddable: true }, '2026-09-24T00:00:00.000Z'), community('turbo-kart', 'Turbo Kart Rally', 'Kart racing with drifting and item pickups, generated in one pass.', 'racing', { url: 'https://bridge-mind.github.io/turbo-kart-rally/', author: '@bridgemindai', postUrl: 'https://x.com/bridgemindai/status/2102451997395866021', model: 'Opus 5.5', embeddable: true }, '2026-09-22T00:00:00.000Z'), ].sort((a, b) => viralOrder.indexOf(a.id.replace('community-', '')) - viralOrder.indexOf(b.id.replace('community-', ''))); // More viral games collected from social media (community/more-games.json), merged by view count after the curated six. type MoreGame = { id: string; title: string; description: string; genre: GameGenre; style: GameStyle | null; url: string; author: string; postUrl: string; model: string; embeddable: boolean; views?: { value: number; label: string }; ipRisk?: string; zh?: { title?: string; description?: string } }; const moreGameFiles = import.meta.glob('./community/more-games.json', { eager: true, import: 'default' }) as Record; const genreIds = new Set(gameGenres); const moreViews = new Map([['community-saltline', 4_470_000], ['community-little-prince', 3_920_000], ['community-sky-reach', 424_000], ['community-shipwreck', 400_000], ['community-turbo-kart', 380_000], ['community-voxel-musou', 170_000]]); for (const item of (Object.values(moreGameFiles)[0] ?? []).filter(item => item.url && genreIds.has(item.genre)).sort((a, b) => (b.views?.value ?? 0) - (a.views?.value ?? 0))) { if (communityGames.some(game => game.id === 'community-' + item.id)) continue; const game = community(item.id, item.title, item.description, item.genre, { url: item.url, author: item.author, postUrl: item.postUrl, model: item.model || 'Unknown', embeddable: item.embeddable }, '2026-11-20T00:00:00.000Z'); communityGames.push({ ...game, plays: 0, style: item.style ?? game.style, i18n: item.zh ? { 'zh-CN': { title: item.zh.title, description: item.zh.description } } : undefined }); moreViews.set(game.id, item.views?.value ?? 0); } // One ranking for every social-media game: views on the creator's original X post (2026-11-20). communityGames.sort((a, b) => (moreViews.get(b.id) ?? 0) - (moreViews.get(a.id) ?? 0)); // Only games that play inside OpenMotion are listed; ones that run solely on the creator's site are left out for now. for (let index = communityGames.length - 1; index >= 0; index--) if (!communityGames[index].external?.embeddable) communityGames.splice(index, 1); import communityBriefs from './community/briefs.json'; /** 做同款 for a community game: an original game built from a detailed brief (goal, controls, rules, art, assets, acceptance), never a copy. */ export function communityRemixPrompt(game: GameCard) { const brief = (communityBriefs as Record)[game.id.replace(/^community-/, '')]; const lead = `Make an original game in the spirit of "${game.title}". Use original characters, names, story and art; do not copy its code or assets.`; return brief ? `${lead}\nFollow this brief, including every acceptance check:\n${JSON.stringify(brief, null, 2)}` : `${lead} ${game.description}`; } /** Agent instructions are returned once at creation; keep them so a draft or failed game can be handed over again. */ const instructionKey = 'om-game-instructions'; export function rememberInstruction(id: string, instruction: string) { try { const all = JSON.parse(localStorage.getItem(instructionKey) || '{}'); all[id] = instruction; localStorage.setItem(instructionKey, JSON.stringify(all)); } catch { /* storage may be unavailable */ } } export function storedInstruction(id: string): string | null { try { return JSON.parse(localStorage.getItem(instructionKey) || '{}')[id] ?? null; } catch { return null; } } /** Links that only open on this computer must not be presented as shareable. */ export const isLocalOnly = (url: string) => url.startsWith('blob:') || isLocalGamePreviewUrl(url) || /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/)/.test(new URL(url, location.href).href); // Option artwork generated for OpenMotion (one consistent set for genres, styles and settings). const optionArt = import.meta.glob('./art/*.webp', { eager: true, query: '?url', import: 'default' }) as Record; const art = (name: string) => optionArt[`./art/${name}.webp`] ?? null; export const genreCovers = Object.fromEntries(gameGenres.map(genre => [genre, art('genre-' + genre)])) as Record; export const genreHomeCovers = Object.fromEntries(gameGenres.map(genre => [genre, art('genre-home-' + genre) ?? genreCovers[genre]])) as Record; export const styleCovers = Object.fromEntries(gameStyles.map(style => [style, art('style-' + style)])) as Record; export const settingCovers = Object.fromEntries(gameSettings.map(setting => [setting, art('setting-' + setting)])) as Record; // Template covers and assets stay in the template folder and are served by the local game service, so they // are not bundled twice. Without the service (the only time this list is shown), a card uses its genre artwork. export const bundledGames: GameCard[] = Object.entries(bundledMeta).map(([path, meta]): GameCard => { const id = folder(path); return { ...meta, id, cover: genreCovers[meta.genre] ?? null, playUrl: `bundled:${id}`, reaction: 0, favorite: false, source: 'template', remixOf: null }; }).sort(compareGameCatalogOrder); /** A bundled page that loads sibling files (./assets/..., ./src/..., ./app.part0.js) cannot run from a blob URL. */ export const needsGameService = (html: string) => /["'(]\.?\/?(?:assets|src)\/|["']\.\/[^"']+\.(?:js|css|json|wasm)\b|<(?:script|link)\b[^>]+(?:src|href)=["'](?!https?:|data:|blob:|#)/i.test(html); export function isIsolatedGameFrame(url: string | null): boolean { return Boolean(url && isLocalGamePreviewUrl(url) && new URL(url).origin !== window.location.origin); } export async function resolveGameFrameUrl(id: string, path: string) { try { const { url } = await motionApi<{ url: string | null }>(`/games/${encodeURIComponent(id)}/preview-url`); if (url && isIsolatedGameFrame(url)) { const preview = new URL(url); const original = new URL(path, window.location.href); preview.search = original.search; preview.hash = original.hash; return preview.href; } } catch { /* Older or offline Studio servers still have the default sandbox. */ } return path; } /** Resolve a playable URL. Service URLs go through the Studio proxy; bundled pages become blob URLs. */ export async function playableUrl(game: GameCard) { if (game.external) return game.external.url; if (game.playUrl.startsWith('bundled:')) { const load = Object.entries(bundledPages).find(([path]) => folder(path) === game.id)?.[1]; if (!load) throw new Error('Start the local game service to play this template.'); const html = await load(); if (needsGameService(html)) throw new Error('Start the local game service to play this template.'); return URL.createObjectURL(new Blob([html], { type: 'text/html' })); } const path = game.playUrl.replace(/^\/api\//, '/motion-api/'); return game.source === 'template' && !game.multiplayer ? resolveGameFrameUrl(game.id, path) : path; } /** The game's entry HTML, shown in the project view's code tab. */ export async function gameSource(game: GameCard) { if (game.playUrl.startsWith('bundled:')) { const load = Object.entries(bundledPages).find(([path]) => folder(path) === game.id)?.[1]; return load ? load() : ''; } const response = await fetch(game.playUrl.replace(/^\/api\//, '/motion-api/')); if (!response.ok) throw new Error(String(response.status)); return response.text(); } // A relative cover is a file inside the game folder, served next to the game. export const coverUrl = (game: GameCard) => game.cover && !game.cover.startsWith('/') && !/^(blob|data|https?):/.test(game.cover) ?`/motion-api/games/${encodeURIComponent(game.id)}/play/${game.cover}` : game.cover?.replace(/^\/api\//, '/motion-api/') ?? null; const json = (body: unknown): RequestInit => ({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); export const gameApi = { catalog: () => motionApi('/games'), create: (brief: GameBrief) => motionApi('/games', json(brief)), remix: (id: string, overrides?: GameRemixOptions) => motionApi(`/games/${encodeURIComponent(id)}/remix`, json(overrides ?? {})), play: (id: string) => motionApi(`/games/${encodeURIComponent(id)}/play`, json({})), react: (id: string, value: -1 | 0 | 1) => motionApi(`/games/${encodeURIComponent(id)}/reaction`, json({ value })), favorite: (id: string, favorite: boolean) => motionApi(`/games/${encodeURIComponent(id)}/favorite`, json({ favorite })), /** Start (or restart) the record-gameplay → compose → render trailer job; read its progress. */ startTrailer: (id: string) => motionApi(`/games/${encodeURIComponent(id)}/trailer`, json({})), trailer: (id: string) => motionApi(`/games/${encodeURIComponent(id)}/trailer`), /** The full instruction for the user's Agent (game id, brief and steps), for any workspace draft. */ handoff: (id: string) => motionApi(`/games/${encodeURIComponent(id)}/handoff`), }; export function formatPlays(value: number, locale: string) { return new Intl.NumberFormat(locale, { notation: value >= 10000 ? 'compact' : 'standard', maximumFractionDigits: 1 }).format(value); } /** Prominent curated badge/filter tag for high-grossing mini-game templates. */ export const TOP_EARNING_TAG = 'TOP赚钱'; /** Match both canonical `TOP赚钱` and legacy lowercase `top赚钱` tags on game cards. */ export function isTopEarningGame(game: Pick): boolean { const needle = TOP_EARNING_TAG.toLowerCase(); return Array.isArray(game.tags) && game.tags.some((tag) => tag.trim().toLowerCase() === needle); }