vivo's vGame Replaces Hand-Coded Ad Mini-Games with Structured Prompts and an AI Agent Pipeline
Author: vivo Internet Frontend Team - Su Ning In advertising and marketing scenarios, mini-games have an extremely short lifecycle — often only a few days from planning to launch. Under the traditional development model, every link in the chain — requirement communication, asset production, coding and integration, testing and deployment — is a bottleneck. Based on practical experience with the vGame platform, this article details how AI Agents, structured scene descriptions, and automated pipelines can improve the development efficiency of advertising mini-games by an order of magnitude.
A 1-minute visual summary of the core points👇
I. Characteristics of Advertising Mini-Games
Advertising mini-games are an increasingly common vehicle in brand marketing — users gain brand exposure through simple interactive gameplay, and enterprises gain conversion and retention. These games have several notable characteristics:
- Frequently changing requirements: The marketing pace is fast, and gameplay is often adjusted to suit different campaign themes.
- Asset-intensive: Each campaign requires a large volume of visual assets.
- Short cycle: From planning to launch is typically only 3–7 days.
- High repetitiveness: Core gameplay patterns are limited and prone to fatigue, yet developing new gameplay is costly.
When the traditional development model addresses these demands, it often faces the dilemma of "high manpower investment, long delivery cycles, and unstable quality."
II. vGame Introduction
vGame is a Web-based, AI-driven game development platform. Its core philosophy is: Replace manual coding with structured scene descriptions + AI Agents.
III. AI-Driven Core Workflow
vGame's complete development pipeline follows a closed loop of Requirements → Asset Planning → Asset Generation → Coding → Preview → Fix. AI participates deeply in every link.
3.1 Structured System Prompts: Letting AI Understand the Game Architecture
To get AI to write runnable game code, general programming ability alone is insufficient. vGame injects a complete set of game development specifications into the Agent:
// Core constraints in src-server/ai/agent/prompts.ts
export const OPENCODE_WORKFLOW_APPEND = [
'The following workflow must be followed before entering substantive coding:',
'1. First check relevant files, then create or update docs/requirements.md',
'2. Check the assets directory, create or update docs/assets-plan.json',
'3. For images that need generation, call /api/project/<id>/assets/generate for batch generation',
'4. Formal development can only begin after asset preparation is complete',
'5. If the task involves multiple sub-project interactions, split sub-problems according to .agent/agents responsibilities',
'6. After each code modification, verify with npm run build',
'7. It is strictly forbidden to start resident services like dev/watch/preview',
].join('\n');
At the same time, the system prompt mandates a game lifecycle pattern:
Each game must implement a complete lifecycle:
1. Start screen → gameStore.status controls state
2. Game in progress → core gameplay + notifyScoreUpdate reporting
3. End screen → notifyGameOver notifies the parent page
This set of constraints ensures that every game generated by the AI has standardized lifecycle management capabilities and can be directly embedded into the advertising delivery framework.
3.2 OpenCode: An Easily Extensible Agent Backend
Using off-the-shelf agent tools for extended development saves a lot of foundational work. Compared to some mainstream CLIs on the market, OpenCode is more convenient for extended development because it provides the @opencode-ai/sdk.
- Credential security management: API Keys are stored in the server-side .env; the frontend only receives a masked version.
- Session persistence: Supports session continuation, allowing the AI to continue previous context after an interruption.
- Runtime error feedback: JS exceptions during game runtime are sent back to the server via postMessage, becoming context for the AI's next fix.
3.3 Template Base: An Engineering Foundation That Lowers AI Comprehension Cost
Having AI build a complete game project from scratch faces a huge comprehension cost — it needs to simultaneously understand the engine API, project structure, build configuration, lifecycle management, and many other aspects. vGame's strategy is to provide a pre-built "game-template" base, solidifying all the "infrastructure" so that AI only needs to "fill in the blanks" on top of it.
3.3.1 What the Base Presets
When creating a new project, the backend automatically clones the game-template repository, generating an independent base copy for each project:
// routes/project.ts —— The starting point of project creation
const repoUrl =
'xxx/game-template.git'
await execa('git', ['clone', repoUrl, projDir])
// Remove the .git directory, initialize the project's own repository
await fs.remove(path.join(projDir, '.git'))
The cloned base already contains a complete, ready-to-use game skeleton:
game-template/src/
├── config/
│ ├── assets.ts # Asset manifest (lookup table for node assetRef)
│ └── runtime.ts # Runtime config like canvas size, physics backend
├── editor/
│ ├── scene.json # Scene source of truth —— AI's core modification target
│ └── generated/scene-outline.ts
├── libs/loaders/ # Galacean resource loading wrappers
├── scene/ # Scene builder, script registration, schema definition
│ ├── index.ts # Node tree → engine entity tree conversion engine
│ ├── schema.ts # Type definitions for nodes, components, script bindings
│ ├── script-registry.ts # Auto-matches script classes by scriptIds filenames
│ └── script-runtime.ts # Runtime context injection, external data bridging
├── scripts/ # AI-produced scripts go here
│ └── player.ts # ← Example: a complete, configurable script
├── store/game.ts # Game state management (Pinia)
├── utils/ # iframe communication, runtime error reporting
├── App.vue # Three-stage UI framework: Start page / HUD / End page
└── game.ts # Engine initialization and scene startup entry
The value of this base is that the AI doesn't need to start from an empty directory — it immediately faces an engineering environment with clear conventions and boundaries.
3.3.2 Preset Game Lifecycle Framework
The base manages the three-stage lifecycle through a Pinia store, so the AI doesn't need to care about state machine implementation details:
// store/game.ts —— A "standard part" the AI doesn't need to modify
export const gameStore = defineStore('game', {
state: () => ({
status: 0, // 0: Not started, 1: In progress, 2: Ended
score: 0,
countdown: 30,
gameOver: false,
isPaused: true,
}),
actions: {
startGame() { /* Switch to in-progress */ },
endGame() { /* Switch to ended state */ },
pauseGame() { /* Pause */ },
resumeGame() { /* Resume */ },
},
})
App.vue automatically renders the corresponding UI layer based on this store:
status === 0 → Start screen (game title + "Start Game" button)
status === 1 → Game HUD (score + countdown overlay)
status === 2 → End screen (score display + "Play Again" button)
AI-generated scripts only need to call gameStore.startGame() / gameStore.endGame() and notifyScoreUpdate() / notifyGameOver() — the UI layer requires zero changes.
3.3.3 Preset Engine Integration and Runtime Capabilities
The base encapsulates the complete integration chain of the Galacean Engine, giving the AI an out-of-the-box runtime:
3.3.4 Base Script Example
The base provides a Player script as a standard paradigm for writing scripts, allowing the AI to intuitively understand how scripts are written:
// src/scripts/player.ts —— Demonstration script in the base
import { ConfigurableScript } from '@/scene/script-runtime'
type PlayerScriptConfig = {
swingSpeed?: number // Configuration parameters injected from scene.json
pulseSpeed?: number
rotationAmplitude?: number
scaleAmplitude?: number
}
export class Player extends ConfigurableScript<PlayerScriptConfig> {
private elapsed = 0
onAwake(): void {
// Record initial scale, subsequent animations are calculated based on this
this.baseScaleX = this.entity.transform.scale.x
}
onUpdate(deltaTime: number): void {
this.elapsed += deltaTime
// Read parameters from scriptIds[].config in scene.json
const swingSpeed = this.scriptConfig.swingSpeed ?? 2.2
// Read runtime parameters from external data sources
const scaleMultiplier = this.externalValue?.scaleMultiplier ?? 1
// Swing + pulse animation
const swing = Math.sin(this.elapsed * swingSpeed)
const scale = 1 + Math.sin(this.elapsed * this.scriptConfig.pulseSpeed) * scaleAmplitude
this.entity.transform.rotation.set(0, 0, swing * rotationAmplitude)
this.entity.transform.scale.set(baseX * scale, baseY * scale, 1)
}
}
This example demonstrates a three-layer parameter injection mechanism that the AI can copy directly:
- scriptConfig: Static configuration injected from the scriptIds binding of a scene.json node.
- externalValue: External data injected from the parent page via postMessage (e.g., difficulty coefficient issued by the ad platform).
- this.entity: The engine entity to which the current script is attached; Transform, components, etc., can be directly manipulated.
3.3.5 The Essence of the Base
For the AI, developing an advertising mini-game is no longer "building a house from scratch," but rather "changing furniture and wallpaper in an already decorated house," better focusing the AI's attention on "differentiation."
3.4 Agent Skills System: Modular Encapsulation of Domain Knowledge
vGame encapsulates game development domain expertise into 17 Agent Skills. Each Skill is a Markdown file defining the workflow for a specific scenario:
.agent/skills/
├── start/ # Entry routing, determines task type
├── project-stage-detect/ # Identifies the current stage of the project
├── dev-story/ # Standard workflow for feature development
├── schema-sync-check/ # Scene schema consistency verification
├── runtime-fix/ # Automatic runtime error fixing
├── galacean-2d-game/ # 2D game development guide
├── galacean-init/ # Engine initialization specification
├── galacean-entity/ # Entity creation and management
├── galacean-physics/ # Physics engine configuration
├── galacean-collider/ # Collision detection
├── galacean-interaction/ # Interaction event handling
├── galacean-animation/ # Animation system
├── galacean-camera/ # Camera configuration
├── galacean-resource/ # Resource loading
├── galacean-color/ # Color and materials
├── galacean-shader-writing/ # Shader writing
└── galacean-object-pool/ # Object pool optimization
Each Skill contains:
- Trigger conditions (when to use)
- Set of allowed tools (allowed-tools)
- Step-by-step execution flow (step-by-step instructions)
- Best practices and common pitfalls
This allows even junior developers to produce code that conforms to engine specifications under the AI's guidance.
3.5 Three-Layer Governance Architecture: Agent / Rules / Hooks
vGame doesn't just rely on Skills; it also introduces a lightweight AI development governance layer:
.agent/
├── agents/ # Role division: platform coordination, AI workflow, editor contracts, runtime QA
├── rules/ # Path constraints: AI workflow, scene schema linkage, publishing pipeline
├── skills/ # Workflow entry points: standardized operation manuals for high-frequency scenarios
├── hooks/ # Session hooks: narrow reminders triggered at session start / after file changes
└── settings.json # Claude Code-style local workflow configuration
- Agents: Decompose complex tasks into four roles, with different roles focusing on different quality dimensions.
- Rules: Implement path constraints on key coupling surfaces (e.g., schema ↔ runtime) to prevent the AI from "crossing the line with modifications."
- Hooks: Trigger checks at session start and after key file changes, reminding to synchronously update highly coupled modules.
IV. Unified Game Runtime
In traditional game development, editor data and runtime data are often two separate systems, requiring manual data format conversion. vGame uses the scene node tree as the single source of truth:
// src/editor/scene.json - Scene description shared by editor and runtime
{
"designWidth": 750,
"designHeight": 1334,
"nodes": [
{
"id": "root",
"kind": "group",
"children": [
{
"id": "bg",
"kind": "sprite",
"assetRef": "background",
"transform": { "x": 0, "y": 0, "z": 0 },
"components": {
"render": { "sortingOrder": 0, "opacity": 1 }
}
},
{
"id": "player",
"kind": "sprite",
"assetRef": "player",
"scriptIds": ["PlayerController"],
"components": {
"interaction": { "shape": "circle", "radius": 40 }
}
}
]
}
]
}
The AI's code output only needs to modify scene.json and the corresponding scripts/ files, without needing to care about engine details. The runtime workflow is as follows:
- The entry point loads src/editor/scene.json, reads the design dimensions and node tree.
- Preloads only the assets actually referenced by assetRef (not full loading).
- src/scene/index.ts creates an entity tree based on kind / parentId / transform.
- scriptIds are automatically matched to scripts in src/scripts/ via src/scene/script-registry.ts.
- Runtime errors are reported to the parent page via postMessage.
In this way, the AI only needs to understand the two concepts of "scene nodes + scripts" to produce a complete, runnable game.
V. Automated Pipeline for Asset Generation
Asset production for advertising mini-games is the most time-consuming link. vGame also incorporates asset generation into the AI pipeline:
5.1 AI Asset Generation
The platform integrates three core capabilities: image generation, sprite animation generation, and 3D model generation.
1. Image Generation
The platform has multiple built-in optimized prompt templates adapted to different business scenarios, and also opens image editing interfaces supporting basic image processing operations like cropping, scaling, and rotation.
To address the problem that AI image generation cannot produce transparent backgrounds by default, the platform adds a one-click background removal feature. We integrate all capabilities into system prompts, and the intelligent Agent autonomously determines and calls the corresponding capability before generating an image.
After image generation is complete, the system enforces a size check through hook functions, automatically compressing images that exceed size limits.
2. Sprite Animation Generation
This solution does not adopt a direct AI animation generation model, but instead uses a workflow of video generation → frame extraction → background removal → sprite sheet compositing. The actions produced by this method are smooth and natural, with stronger controllability.
Current mainstream video generation models already support advanced capabilities like start/end frame guidance and reference image generation, further enhancing the controllability of animation generation effects.
3. 3D Model Generation
At the current stage, 3D generation models can output high-quality static model assets. The industry's main pain point is concentrated in the model animation production phase.
For this, the platform integrates multiple pre-made skeletal animation resources. After 3D model generation is complete, a large model automatically completes skeleton mapping, enabling rapid reuse of skeletal animations.
5.2 Mandatory Asset Planning Process
The AI is forced to follow an asset-first principle:
Whenever a task requires visual assets, docs/assets-plan.json must not use
procedural, codegen, placeholder images, or other methods to bypass the image generation process;
unless the user explicitly requests procedural textures, real image files must be generated and saved to the public directory.
This ensures that the AI-produced game is "directly launchable," not a semi-finished product that "still needs a designer to supplement assets."
VI. Chat-Based Development Experience
6.1 ChatPanel
ChatPanel.vue is the core interactive entry point of the entire platform. It is not just a chat box, but a complete development collaboration panel:
- Streaming response: SSE implements a typewriter effect, allowing users to see the AI's coding process in real time.
- Multimodal input: Supports image attachments, allowing direct upload of reference images for the AI to imitate.
- Step cards: Each AI operation (reading files, writing files, executing commands, generating assets) is rendered as an expandable status card.
- Round change tracking: File change summaries for each conversation round are displayed, supporting version control operations of "keep/revert this round."
- Message edit replay: Supports modifying sent messages for re-execution, suitable for requirement iteration scenarios.
<!-- Round change tracking in ChatPanel -->
<div v-if="msg.roundChange?.files?.length" class="...">
<div class="flex items-center gap-2">
<span>This round modified {{ msg.roundChange.fileCount }} files</span>
<span :class="getRoundChangeStatusClass(msg.roundChange.status)">
{{ statusLabel }}
</span>
</div>
<div v-for="file in msg.roundChange.files" :key="file.path">
<span :class="getRoundChangeTypeClass(file.changeType)">
{{ changeTypeLabel }} <!-- Added / Modified / Deleted -->
</span>
<span>{{ file.path }}</span>
</div>
<!-- Keep / Revert this round action buttons -->
</div>
6.2 Integrated Development Environment
In addition to the chat panel, the frontend also provides complete visual editing capabilities:
VII. Runtime Error Feedback Loop
A unique design is the automatic reporting and fixing of runtime errors:
User Preview → Runtime Error
↓
postMessage reports to parent page (runtime-bridge)
↓
Server records to .runtime-errors.json
↓
Next AI conversation, error context is automatically injected
↓
AI analyzes stack trace, locates source code, generates fix plan
↓
After user confirmation, fix is automatically applied
Error information injected into the AI context:
// Implementation in opencode.ts
const MAX_RUNTIME_ERRORS_IN_PROMPT = 5
function buildRuntimeErrorContext(errors: RuntimeErrorLogEntry[]): string {
const recent = errors.slice(0, MAX_RUNTIME_ERRORS_IN_PROMPT)
return recent.map(e => `
Type: ${e.kind}
Message: ${e.message}
File: ${e.filename}:${e.lineno}:${e.colno}
${e.stack ? `Stack: ${e.stack}` : ''}
`).join('\n---\n')
}
This makes debugging no longer the long chain of "user describes problem → developer reproduces → fix → redeploy," but a real-time closed loop.
VIII. Conclusion & Future Outlook
AI-empowered advertising mini-game development essentially transforms "game development" from a craft into a standardizable process. It can not only be used for rapid realization of ideas but also enables quick reskinning for deploying the same gameplay in different scenarios.
As agent tools continue to improve, there are many more scenarios that can be optimized:
- Templated gameplay library: Currently the template base is a single code source; different repositories can be loaded according to different gameplay types, while accumulating more Skill templates to enrich the AI's "experience."
- Enhanced multimodal understanding: Support direct upload of competitor game screenshots, with AI automatically identifying gameplay and generating similar games.
- A/B testing integration: AI automatically generates multiple asset variants for effect comparison in conjunction with ad platforms.
- Performance self-optimization: AI automatically applies optimization strategies like object pooling, frustum culling, and texture compression when generating code.