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`;
}