Spaces:
Sleeping
Sleeping
File size: 10,069 Bytes
2aec246 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | /**
* ๅคๆไปถไปฃ็ ็ๆๅจ
*
* ็ปๅ GDDใAsset Pack ๅ่ๆๆถๆจกๆฟๆบ็ ๏ผ่ฐ็จ LLM ็ๆ
* ๆจกๅๅ็ๅคๆไปถๆธธๆไปฃ็ ใ
*
* ๆ ธๅฟ็บฆๆ๏ผ
* - ๆจกๆฟๅ
ๅฎนๅฟ
้กปๆณจๅ
ฅ system prompt ไฝไธบๅ่
* - LLM ่พๅบๅฟ
้กปไธบ JSON ๆฐ็ป [{ path, content }]
* - ้ฒๅพกๆง่งฃๆ๏ผๅคๅฑๅ้ๅบๅฏน LLM ่ฝฌไน้่ฏฏ/ๆชๆญ
*/
import { callLLM, resolveModel, type UserTier } from './llm-proxy';
import type { GameDesignDocument } from './gdd-generator';
import type { AssetPack } from './asset-generator';
import type { GameArchetype } from './game-classifier';
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ็ฑปๅๅฎไน
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/** ็ๆ็ไปฃ็ ๆไปถ */
export interface GeneratedCodeFile {
path: string;
content: string;
}
/** ไปฃ็ ็ๆ็ปๆ */
export interface GeneratedCode {
files: GeneratedCodeFile[];
entryPoint: string;
}
/** ไปฃ็ ็ๆๅๆฐ */
export interface GenerateCodeParams {
gdd: GameDesignDocument;
assetPack: AssetPack;
templateFiles: Array<{ path: string; content: string }>;
archetype: GameArchetype;
tier?: UserTier;
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๆ ธๅฟ้ป่พ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/**
* ็ๆๅฎๆด็ๆธธๆไปฃ็
*
* @param params - ็ๆๅๆฐ๏ผGDD + AssetPack + ๆจกๆฟ + ๅๅ + ๅฑ็บง๏ผ
* @returns ็ๆ็ไปฃ็ ๆไปถๅ่กจๅๅ
ฅๅฃ็น
*/
export async function generateGameCode(params: GenerateCodeParams): Promise<GeneratedCode> {
const { gdd, assetPack, templateFiles, archetype, tier } = params;
const model = resolveModel(tier);
const systemPrompt = buildSystemPrompt(archetype, templateFiles);
const userPrompt = buildUserPrompt(gdd, assetPack);
const raw = await callLLM(
[
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt },
],
model,
);
const files = parseCodeOutput(raw);
const entryPoint = resolveEntryPoint(files, archetype);
return { files, entryPoint };
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Prompt ็ป่ฃ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function buildSystemPrompt(
archetype: GameArchetype,
templateFiles: Array<{ path: string; content: string }>,
): string {
const templateSection = templateFiles
.map(f => `// === ${f.path} ===\n${f.content}`)
.join('\n\n');
return `You are an expert game developer generating modular game code.
ARCHETYPE: ${archetype}
REFERENCE TEMPLATES (use as structural guide, adapt to GDD requirements):
${templateSection}
OUTPUT FORMAT:
You MUST output a JSON array of file objects. Each object has:
- "path": relative file path (e.g. "src/scenes/MainScene.ts")
- "content": complete file content as a string
Example:
[
{ "path": "src/main.ts", "content": "import Phaser from 'phaser';\\n..." },
{ "path": "src/scenes/MainScene.ts", "content": "export class MainScene extends Phaser.Scene {\\n..." }
]
RULES:
1. Output ONLY the JSON array, no explanations before or after.
2. Do NOT invent new hooks, lifecycle methods, or APIs not in the templates.
3. Do NOT use placeholders like "// TODO" or "..." โ every file must be complete.
4. Escape all special characters in JSON strings properly (\\n, \\t, \\", \\\\).
5. Each file must be syntactically valid TypeScript.
6. Use the asset keys from the Asset Pack for loading resources.
7. Match the GDD's entity definitions, game config, and level specifications exactly.`;
}
function buildUserPrompt(gdd: GameDesignDocument, assetPack: AssetPack): string {
return `Generate the complete game code based on this Game Design Document and Asset Pack.
GAME DESIGN DOCUMENT:
${JSON.stringify(gdd, null, 2)}
ASSET PACK:
${JSON.stringify(assetPack, null, 2)}
Generate all files needed to run this game. Output the JSON array now.`;
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ้ฒๅพกๆงไปฃ็ ่งฃๆๅจ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/**
* ่งฃๆ LLM ่พๅบ็ไปฃ็ ๆไปถๅ่กจ
*
* ้ฒๅพกๆง่งฃๆ็ญ็ฅ๏ผ
* 1. ็ดๆฅ JSON.parse
* 2. ๅป้ค Markdown ไปฃ็ ๅๅ่งฃๆ
* 3. ๆๅ JSON ๆฐ็ป๏ผๅค็ๅๅ้ขๅคๆๆฌ๏ผ
* 4. ไฟฎๅคๅธธ่งๆชๆญ๏ผ่กฅๅ
จๅฐพ้จๆฌๅท๏ผ
* 5. ๅ
จ้จๅคฑ่ดฅๅๆๅบ่ฏฆ็ป้่ฏฏ
*/
export function parseCodeOutput(raw: string): GeneratedCodeFile[] {
const trimmed = raw.trim();
if (!trimmed) {
throw new Error('[CodeGenerator] LLM returned empty output');
}
// ็ญ็ฅ 1: ็ดๆฅ่งฃๆ
const directResult = tryParse(trimmed);
if (directResult) return directResult;
// ็ญ็ฅ 2: ๅป้ค Markdown ไปฃ็ ๅ
const stripped = stripMarkdown(trimmed);
const strippedResult = tryParse(stripped);
if (strippedResult) return strippedResult;
// ็ญ็ฅ 3: ๆๅ JSON ๆฐ็ป๏ผๅค็ๅๅ้ขๅคๆๆฌ๏ผ
const extracted = extractJSONArray(stripped);
if (extracted) {
const extractedResult = tryParse(extracted);
if (extractedResult) return extractedResult;
// ็ญ็ฅ 4: ไฟฎๅคๆชๆญ
const fixed = fixTruncation(extracted);
if (fixed) {
const fixedResult = tryParse(fixed);
if (fixedResult) return fixedResult;
}
}
// ๅ
จ้จๅคฑ่ดฅ
const preview = trimmed.slice(0, 500);
throw new Error(
`[CodeGenerator] Failed to parse LLM code output. Preview:\n${preview}`,
);
}
/** ๅฐ่ฏ่งฃๆ JSON ๆฐ็ปๅนถๆ ก้ชๆ ผๅผ */
function tryParse(text: string): GeneratedCodeFile[] | null {
try {
const parsed = JSON.parse(text);
if (!Array.isArray(parsed)) return null;
// ๆ ก้ชๆฏไธชๅ
็ด ็็ปๆ
for (const item of parsed) {
if (typeof item !== 'object' || item === null) return null;
if (typeof item.path !== 'string' || typeof item.content !== 'string') return null;
}
return parsed as GeneratedCodeFile[];
} catch {
return null;
}
}
/** ๅป้ค Markdown ไปฃ็ ๅๆ ่ฎฐ */
function stripMarkdown(text: string): string {
// ๅน้
```json ... ``` ๆ ``` ... ```
const match = text.match(/```(?:json|typescript|ts|javascript|js)?\s*\n?([\s\S]*?)```/);
if (match) return match[1].trim();
return text;
}
/**
* ไปๆๆฌไธญๆๅ็ฌฌไธไธช JSON ๆฐ็ป
* ๅค็ LLM ๅจ JSON ๅๅ่พๅบ้ขๅคๆๆฌ็ๆ
ๅต
*/
function extractJSONArray(text: string): string | null {
const start = text.indexOf('[');
if (start === -1) return null;
let depth = 0;
let inString = false;
let escape = false;
for (let i = start; i < text.length; i++) {
const ch = text[i];
if (escape) {
escape = false;
continue;
}
if (ch === '\\' && inString) {
escape = true;
continue;
}
if (ch === '"') {
inString = !inString;
continue;
}
if (inString) continue;
if (ch === '[') depth++;
if (ch === ']') {
depth--;
if (depth === 0) {
return text.slice(start, i + 1);
}
}
}
// ๆชๆพๅฐๅน้
็ ] โ ่ฟๅๅฐๆซๅฐพ๏ผๅฏ่ฝ่ขซๆชๆญ๏ผ
return text.slice(start);
}
/**
* ไฟฎๅคๅธธ่งๆชๆญ๏ผๅฐ่ฏ่กฅๅ
จ็ผบๅคฑ็ๅฐพ้จๆฌๅท
* ๅค็ LLM ่พๅบ่ขซ token limit ๆชๆญ็ๆ
ๅต
*/
function fixTruncation(text: string): string | null {
// ่ฎก็ฎๆช้ญๅ็ๆฌๅท
let braces = 0;
let brackets = 0;
let inString = false;
let escape = false;
for (const ch of text) {
if (escape) { escape = false; continue; }
if (ch === '\\' && inString) { escape = true; continue; }
if (ch === '"') { inString = !inString; continue; }
if (inString) continue;
if (ch === '{') braces++;
if (ch === '}') braces--;
if (ch === '[') brackets++;
if (ch === ']') brackets--;
}
if (braces === 0 && brackets === 0) return null;
// ๅฐ่ฏ่กฅๅ
จ๏ผๅ
ๅ
ณ้ญๆๅไธไธชๆชๅฎๆ็ๅฏน่ฑกๅญ็ฌฆไธฒ๏ผๅๅ
ณ้ญๅฏน่ฑกๅๆฐ็ป
let fix = text;
// ๅฆๆๅจๅญ็ฌฆไธฒไธญ้ดๆชๆญ๏ผๅฐ่ฏๅ
ณ้ญๅฎ
if (inString) {
fix += '"}';
}
// ่กฅๅ
จๆช้ญๅ็ }
for (let i = 0; i < braces; i++) {
fix += '}';
}
// ่กฅๅ
จๆช้ญๅ็ ]
for (let i = 0; i < brackets; i++) {
fix += ']';
}
return fix;
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๅ
ฅๅฃ็น่งฃๆ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/** ไป็ๆ็ๆไปถๅ่กจไธญ็กฎๅฎๅ
ฅๅฃๆไปถ */
function resolveEntryPoint(files: GeneratedCodeFile[], archetype: GameArchetype): string {
// ไผๅ
ๆฅๆพ main.ts
const mainFile = files.find(f => f.path.endsWith('main.ts') || f.path.endsWith('main.js'));
if (mainFile) return mainFile.path;
// ๅ
ถๆฌกๆฅๆพ index.ts
const indexFile = files.find(f => f.path.endsWith('index.ts') || f.path.endsWith('index.js'));
if (indexFile) return indexFile.path;
// ๅ้ๅฐ็ฌฌไธไธชๆไปถ
return files[0]?.path ?? `src/main.ts`;
}
|