-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
1606 lines (1425 loc) · 49.8 KB
/
Copy pathserver.js
File metadata and controls
1606 lines (1425 loc) · 49.8 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from "express"
import cors from "cors"
import dotenv from "dotenv"
import fs from "fs-extra"
import chalk from "chalk"
import { v4 as uuidv4 } from "uuid"
import swaggerJsdoc from "swagger-jsdoc"
import swaggerUi from "swagger-ui-express"
import TracedLLMProvider from "./lib/llm-providers.js"
import { spawn } from "child_process"
import path from "path"
import { fileURLToPath } from "url"
import net from "net"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
dotenv.config()
const app = express()
const PORT = process.env.PORT || 3005
const GENERATED_PROJECTS_PATH = process.env.GENERATED_PROJECTS_PATH || "generated-projects2"
const NGINX_PROJECTS_PATH = process.env.NGINX_PROJECTS_PATH || "nginx-projects"
const DEPLOY_LOG_PATH = process.env.DEPLOY_LOG_PATH || "deploy-log.txt"
app.use(cors())
app.use(express.json())
app.use(express.static("public"))
const PROJECTS_DIR = "generated-projects"
const CHAT_HISTORY_DIR = "chat-history"
await fs.ensureDir(PROJECTS_DIR)
await fs.ensureDir(CHAT_HISTORY_DIR)
let chatCounter = 1
const conversationContexts = new Map()
// Initialize traced LLM provider
const llmProvider = new TracedLLMProvider()
// ============================================================================
// SWAGGER CONFIGURATION
// ============================================================================
const swaggerOptions = {
definition: {
openapi: "3.0.0",
info: {
title: "Web Game AI Generator API",
version: "2.0.0",
description: "Streaming API for generating HTML5 Canvas web games using AI chains",
contact: {
name: "Web Game AI Generator",
email: "support@webgameai.com",
},
},
servers: [
{
url: `http://localhost:${PORT}`,
description: "Development server",
},
],
components: {
schemas: {
GamePrompt: {
type: "object",
required: ["prompt"],
properties: {
prompt: {
type: "string",
description: "Description of the web game to generate",
example: "Create a Snake game with HTML5 Canvas, smooth movement, score system, and mobile controls",
minLength: 10,
maxLength: 1000,
},
},
},
StreamEvent: {
type: "object",
properties: {
event: {
type: "string",
enum: ["progress", "step_complete", "file_generated", "complete", "error"],
description: "Type of stream event",
},
data: {
type: "object",
description: "Event data payload",
},
timestamp: {
type: "string",
format: "date-time",
description: "Event timestamp",
},
},
},
ProgressEvent: {
type: "object",
properties: {
event: {
type: "string",
enum: ["progress"],
},
data: {
type: "object",
properties: {
step: {
type: "integer",
description: "Current step number",
},
totalSteps: {
type: "integer",
description: "Total number of steps",
},
stepName: {
type: "string",
description: "Name of current step",
},
progress: {
type: "integer",
minimum: 0,
maximum: 100,
description: "Progress percentage",
},
message: {
type: "string",
description: "Progress message",
},
},
},
},
},
FileEvent: {
type: "object",
properties: {
event: {
type: "string",
enum: ["file_generated"],
},
data: {
type: "object",
properties: {
fileName: {
type: "string",
description: "Name of the generated file",
},
fileType: {
type: "string",
enum: ["html", "js"],
description: "Type of the file",
},
content: {
type: "string",
description: "Clean file content without generation comments",
},
size: {
type: "integer",
description: "File size in characters",
},
},
},
},
},
CompleteEvent: {
type: "object",
properties: {
event: {
type: "string",
enum: ["complete"],
},
data: {
type: "object",
properties: {
chatId: {
type: "integer",
description: "Chat session ID",
},
projectId: {
type: "string",
description: "Generated project UUID",
},
totalFiles: {
type: "integer",
description: "Total number of files generated",
},
aiGeneratedFiles: {
type: "integer",
description: "Number of files generated by AI",
},
chainUsed: {
type: "string",
enum: ["simple", "full"],
description: "AI chain type used",
},
setupInstructions: {
type: "object",
properties: {
npmInstall: {
type: "string",
example: "npm install",
},
startCommand: {
type: "string",
example: "npm start",
},
url: {
type: "string",
example: "http://localhost:3000",
},
},
},
},
},
},
},
ErrorEvent: {
type: "object",
properties: {
event: {
type: "string",
enum: ["error"],
},
data: {
type: "object",
properties: {
error: {
type: "string",
description: "Error message",
},
details: {
type: "string",
description: "Detailed error information",
},
chatId: {
type: "integer",
description: "Chat session ID",
},
},
},
},
},
},
},
},
apis: ["./server.js"], // Path to the API docs
}
const swaggerSpec = swaggerJsdoc(swaggerOptions)
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec))
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
// Find available port
// Find available port - Fixed version
async function findAvailablePort(startPort = 8100) {
const checkPort = (port) => {
return new Promise((resolve) => {
const server = net.createServer()
server.once("error", (err) => {
if (err.code === "EADDRINUSE") {
// Port is in use
resolve(false)
} else {
// Some other error
resolve(false)
}
})
server.once("listening", () => {
server.close(() => {
// Port is available
resolve(true)
})
})
server.listen(port, "127.0.0.1")
})
}
for (let port = startPort; port <= startPort + 100; port++) {
const isAvailable = await checkPort(port)
if (isAvailable) {
console.log(chalk.green(`✅ Found available port: ${port}`))
return port
} else {
console.log(chalk.yellow(`⚠️ Port ${port} is in use, trying next...`))
}
}
throw new Error("No available port found in range " + startPort + "-" + (startPort + 100))
}
// Save generated files to disk
async function saveGeneratedFiles(projectId, files) {
const projectPath = path.join(PROJECTS_DIR, projectId)
await fs.ensureDir(projectPath)
// Save each file
for (const file of files) {
const filePath = path.join(projectPath, file.name)
await fs.writeFile(filePath, file.content)
console.log(chalk.green(`✅ Saved ${file.name} to ${filePath}`))
}
// Create package.json
const packageJson = {
name: `web-game-${projectId}`,
version: "1.0.0",
description: "AI Generated Web Game",
main: "main.js",
scripts: {
start: "npx serve . -p 8080",
dev: "npx serve . -p 8080",
},
keywords: ["game", "html5", "canvas"],
author: "AI Generator",
license: "MIT",
}
await fs.writeFile(path.join(projectPath, "package.json"), JSON.stringify(packageJson, null, 2))
return projectPath
}
// Run npm install and start server
// Replace the setupAndRunProject function with this improved version:
async function setupAndRunProject(projectPath) {
return new Promise(async (resolve, reject) => {
try {
console.log(chalk.cyan(`📦 Running npm install in ${projectPath}...`))
// Run npm install
const npmInstall = spawn("npm", ["install"], {
cwd: projectPath,
shell: true,
stdio: "pipe",
})
npmInstall.on("close", async (code) => {
if (code !== 0) {
console.log(chalk.yellow("npm install skipped or had issues (continuing anyway)"))
}
// Find available port
const port = await findAvailablePort(8000)
console.log(chalk.cyan(`🚀 Starting server on port ${port}...`))
// Start the server
const serverProcess = spawn("npx", ["serve", ".", "-p", port.toString()], {
cwd: projectPath,
shell: true,
stdio: "pipe",
detached: false,
})
// Check if server started successfully
let serverStarted = false
serverProcess.stdout.on("data", (data) => {
const output = data.toString()
console.log(chalk.gray(`Server output: ${output}`))
// Regex to extract port from Serve's standard message
const match = output.match(/http:\/\/localhost:(\d+)/)
if (match && !serverStarted) {
serverStarted = true
const realPort = match[1]
const serverUrl = `http://localhost:${realPort}`
console.log(chalk.green(`✅ Server running at ${serverUrl}`))
resolve({
url: serverUrl,
port: Number.parseInt(realPort),
process: serverProcess,
})
} else if (!serverStarted && (output.includes("localhost") || output.includes("Listening"))) {
// Fallback: if regex doesn't work but message looks server-like
setTimeout(() => {
if (!serverStarted) {
const serverUrl = `http://localhost:${port}`
console.log(chalk.yellow(`⚠️ Fall back to assumed URL: ${serverUrl}`))
resolve({
url: serverUrl,
port: port,
process: serverProcess,
})
}
}, 1000)
}
})
serverProcess.stderr.on("data", (data) => {
console.log(chalk.gray(`Server stderr: ${data.toString()}`))
})
// Fallback: resolve after a timeout even if we don't see server messages
setTimeout(() => {
if (!serverStarted) {
const serverUrl = `http://localhost:${port}`
console.log(chalk.yellow(`⚠️ Server may be running at ${serverUrl} (timeout reached)`))
resolve({
url: serverUrl,
port: port,
process: serverProcess,
})
}
}, 5000)
serverProcess.on("error", (error) => {
console.error(chalk.red("Server error:", error))
if (!serverStarted) {
reject(error)
}
})
})
npmInstall.on("error", (error) => {
console.error(chalk.red("npm install error:", error))
reject(error)
})
} catch (error) {
reject(error)
}
})
}
// Enhanced file validation and parsing with code cleanup
function validateAndParseWebGameFiles(webGameCode, chatId) {
console.log(chalk.cyan("Validating and parsing web game files with cleanup..."))
if (!webGameCode || typeof webGameCode !== "string") {
console.log(chalk.yellow("No web game code provided, using default structure..."))
webGameCode = "// Default web game structure"
}
const files = []
const missingFiles = []
const requiredFiles = [
"index.html",
"gameManager.js",
"audioManager.js",
"main.js",
"uiManager.js",
"inputManager.js",
"renderer.js",
"gameObjects.js",
"utils.js",
"config.js",
]
const fileSeparators = [
{ pattern: /\/\/ === index\.html ===([\s\S]*?)(?=\/\/ === |$)/g, name: "index.html", type: "html" },
{ pattern: /\/\/ === gameManager\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "gameManager.js", type: "js" },
{ pattern: /\/\/ === audioManager\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "audioManager.js", type: "js" },
{ pattern: /\/\/ === main\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "main.js", type: "js" },
{ pattern: /\/\/ === uiManager\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "uiManager.js", type: "js" },
{ pattern: /\/\/ === inputManager\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "inputManager.js", type: "js" },
{ pattern: /\/\/ === renderer\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "renderer.js", type: "js" },
{ pattern: /\/\/ === gameObjects\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "gameObjects.js", type: "js" },
{ pattern: /\/\/ === utils\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "utils.js", type: "js" },
{ pattern: /\/\/ === config\.js ===([\s\S]*?)(?=\/\/ === |$)/g, name: "config.js", type: "js" },
]
// Parse files using separators
fileSeparators.forEach(({ pattern, name, type }) => {
const matches = [...webGameCode.matchAll(pattern)]
if (matches.length > 0) {
let content = matches[0][1].trim()
// Clean up the content
content = cleanupGeneratedCode(content, name)
if (content) {
files.push({
name: name,
content: content,
type: type,
})
console.log(chalk.green(`✅ Found and cleaned ${name} (${content.length} chars)`))
}
} else {
missingFiles.push(name)
}
})
// Check for missing required files
requiredFiles.forEach((fileName) => {
if (!files.find((f) => f.name === fileName)) {
missingFiles.push(fileName)
}
})
const validationResult = {
files,
missingFiles: [...new Set(missingFiles)],
isComplete: missingFiles.length === 0,
totalFiles: files.length,
requiredFiles: requiredFiles.length,
}
console.log(chalk.green(`Parsed and cleaned ${files.length}/${requiredFiles.length} files`))
if (missingFiles.length > 0) {
console.log(chalk.red(`Missing files: ${missingFiles.join(", ")}`))
}
return validationResult
}
// Function to clean up generated code
function cleanupGeneratedCode(content, fileName) {
// Remove markdown code blocks
content = content.replace(/```javascript\s*/g, "")
content = content.replace(/```html\s*/g, "")
content = content.replace(/```\s*/g, "")
// Remove generation comments
content = content.replace(/\/\/ Generated by.*?\n/g, "")
content = content.replace(/\/\* Generated by.*?\*\//g, "")
content = content.replace(/<!-- Generated by.*?-->/g, "")
// Remove AI chain comments
content = content.replace(/\/\/ Enhanced Chain V2.*?\n/g, "")
content = content.replace(/\/\/ Chat ID:.*?\n/g, "")
// Remove extra whitespace and normalize
content = content.replace(/\n\s*\n\s*\n/g, "\n\n")
content = content.trim()
return content
}
// Create complete file structure with templates
function createCompleteFileStructure(existingFiles, missingFiles, gamePrompt) {
const completeFiles = [...existingFiles]
const fileTemplates = {
"index.html": `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Game - ${gamePrompt}</title>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; text-align: center; background: #1a1a2e; color: white; }
canvas { border: 2px solid #fff; background: #000; margin: 20px 0; }
.controls { margin: 20px 0; }
.control-btn { margin: 5px; padding: 10px 20px; font-size: 16px; cursor: pointer; background: #333; color: white; border: none; border-radius: 5px; }
.control-btn:hover { background: #555; }
.score { font-size: 18px; margin: 10px 0; }
</style>
</head>
<body>
<h1>Web Game - AI Generated</h1>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div class="controls">
<button class="control-btn" data-direction="up">↑</button><br>
<button class="control-btn" data-direction="left">←</button>
<button class="control-btn" data-direction="down">↓</button>
<button class="control-btn" data-direction="right">→</button>
</div>
<div class="score">Score: <span id="score">0</span></div>
<script src="config.js"></script>
<script src="utils.js"></script>
<script src="audioManager.js"></script>
<script src="inputManager.js"></script>
<script src="renderer.js"></script>
<script src="gameObjects.js"></script>
<script src="uiManager.js"></script>
<script src="gameManager.js"></script>
<script src="main.js"></script>
</body>
</html>`,
"config.js": `const GameConfig = {
CANVAS_WIDTH: 400,
CANVAS_HEIGHT: 400,
GRID_SIZE: 20,
INITIAL_SPEED: 150,
COLORS: {
BACKGROUND: '#000000',
PRIMARY: '#00ff00',
SECONDARY: '#ff0000',
UI_TEXT: '#ffffff'
}
};
window.GameConfig = GameConfig;`,
"utils.js": `const Utils = {
randomInt: (min, max) => Math.floor(Math.random() * (max - min + 1)) + min,
clamp: (value, min, max) => Math.max(min, Math.min(max, value)),
distance: (x1, y1, x2, y2) => Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
};
window.Utils = Utils;`,
"gameManager.js": `class GameManager {
constructor(canvas, audioManager, uiManager, inputManager, renderer) {
this.canvas = canvas;
this.audioManager = audioManager;
this.uiManager = uiManager;
this.inputManager = inputManager;
this.renderer = renderer;
this.score = 0;
this.gameActive = false;
this.gameSpeed = GameConfig.INITIAL_SPEED;
this.setupGame();
}
setupGame() {
this.score = 0;
this.gameActive = true;
this.uiManager.updateScore(this.score);
this.gameLoop();
}
gameLoop() {
if (this.gameActive) {
setTimeout(() => {
this.update();
this.render();
this.gameLoop();
}, this.gameSpeed);
}
}
update() {
const input = this.inputManager.getInput();
if (input) {
console.log('Input received:', input);
}
}
render() {
this.renderer.clear();
this.renderer.drawText('Game Running!', this.canvas.width / 2, this.canvas.height / 2);
this.renderer.drawText('Score: ' + this.score, this.canvas.width / 2, 50);
}
addScore(points = 10) {
this.score += points;
this.uiManager.updateScore(this.score);
this.audioManager.playSound('score');
}
gameOver() {
this.gameActive = false;
this.audioManager.playSound('gameOver');
this.uiManager.showGameOver(this.score);
}
restart() {
this.setupGame();
}
}
window.GameManager = GameManager;`,
"audioManager.js": `class AudioManager {
constructor() {
this.audioContext = null;
this.sounds = {};
this.enabled = true;
this.volume = 0.3;
this.initAudio();
}
initAudio() {
try {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
this.createSounds();
} catch (error) {
console.warn('Audio not supported:', error);
this.enabled = false;
}
}
createSounds() {
this.sounds.score = () => this.createBeep(800, 0.1);
this.sounds.gameOver = () => this.createBeep(200, 0.5);
this.sounds.move = () => this.createBeep(400, 0.05);
}
createBeep(frequency, duration) {
if (!this.enabled || !this.audioContext) return;
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.audioContext.destination);
oscillator.frequency.value = frequency;
oscillator.type = 'sine';
gainNode.gain.setValueAtTime(this.volume, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + duration);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + duration);
}
playSound(soundName) {
if (this.sounds[soundName]) {
this.sounds[soundName]();
}
}
}
window.AudioManager = AudioManager;`,
"uiManager.js": `class UIManager {
constructor() {
this.scoreElement = document.getElementById('score');
this.setupEventListeners();
}
setupEventListeners() {
// UI event listeners can be added here
}
updateScore(score) {
if (this.scoreElement) {
this.scoreElement.textContent = score;
}
}
showGameOver(finalScore) {
setTimeout(() => {
alert(\`Game Over! Final Score: \${finalScore}\\nClick Restart to play again.\`);
}, 100);
}
showMessage(message, duration = 3000) {
const messageDiv = document.createElement('div');
messageDiv.textContent = message;
messageDiv.style.cssText = \`
position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
background: rgba(0,0,0,0.9); color: white; padding: 15px 25px;
border-radius: 8px; z-index: 1000; font-size: 18px;
\`;
document.body.appendChild(messageDiv);
setTimeout(() => messageDiv.remove(), duration);
}
}
window.UIManager = UIManager;`,
"inputManager.js": `class InputManager {
constructor() {
this.keys = {};
this.currentInput = null;
this.lastInput = null;
this.setupEventListeners();
}
setupEventListeners() {
document.addEventListener('keydown', (e) => this.handleKeyDown(e));
document.addEventListener('keyup', (e) => this.handleKeyUp(e));
const controlBtns = document.querySelectorAll('.control-btn[data-direction]');
controlBtns.forEach(btn => {
btn.addEventListener('click', (e) => this.handleControlButton(e));
btn.addEventListener('touchstart', (e) => {
e.preventDefault();
this.handleControlButton(e);
});
});
}
handleKeyDown(event) {
const key = event.key.toLowerCase();
this.keys[key] = true;
if (key === 'w' || key === 'arrowup') this.setInput('up');
else if (key === 's' || key === 'arrowdown') this.setInput('down');
else if (key === 'a' || key === 'arrowleft') this.setInput('left');
else if (key === 'd' || key === 'arrowright') this.setInput('right');
else if (key === ' ') this.setInput('space');
}
handleKeyUp(event) {
const key = event.key.toLowerCase();
this.keys[key] = false;
}
handleControlButton(event) {
const direction = event.target.dataset.direction;
if (direction) this.setInput(direction);
}
setInput(input) {
if (input !== this.lastInput) {
this.currentInput = input;
this.lastInput = input;
}
}
getInput() {
const input = this.currentInput;
this.currentInput = null;
return input;
}
isKeyPressed(key) {
return this.keys[key.toLowerCase()] || false;
}
}
window.InputManager = InputManager;`,
"renderer.js": `class Renderer {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.width = canvas.width;
this.height = canvas.height;
}
clear() {
this.ctx.fillStyle = GameConfig.COLORS.BACKGROUND;
this.ctx.fillRect(0, 0, this.width, this.height);
}
drawRect(x, y, width, height, color = GameConfig.COLORS.PRIMARY) {
this.ctx.fillStyle = color;
this.ctx.fillRect(x, y, width, height);
}
drawCircle(x, y, radius, color = GameConfig.COLORS.PRIMARY) {
this.ctx.fillStyle = color;
this.ctx.beginPath();
this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx.fill();
}
drawText(text, x, y, color = GameConfig.COLORS.UI_TEXT, font = '20px Arial') {
this.ctx.fillStyle = color;
this.ctx.font = font;
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
this.ctx.fillText(text, x, y);
}
drawLine(x1, y1, x2, y2, color = '#333333', width = 1) {
this.ctx.strokeStyle = color;
this.ctx.lineWidth = width;
this.ctx.beginPath();
this.ctx.moveTo(x1, y1);
this.ctx.lineTo(x2, y2);
this.ctx.stroke();
}
}
window.Renderer = Renderer;`,
"gameObjects.js": `class GameObject {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
this.active = true;
this.width = GameConfig.GRID_SIZE;
this.height = GameConfig.GRID_SIZE;
}
update() {
// Override in subclasses
}
render(renderer) {
// Override in subclasses
renderer.drawRect(this.x, this.y, this.width, this.height);
}
destroy() {
this.active = false;
}
getBounds() {
return {
left: this.x,
right: this.x + this.width,
top: this.y,
bottom: this.y + this.height
};
}
collidesWith(other) {
const a = this.getBounds();
const b = other.getBounds();
return !(a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom);
}
}
class Player extends GameObject {
constructor(x, y) {
super(x, y);
this.color = GameConfig.COLORS.PRIMARY;
this.speed = GameConfig.GRID_SIZE;
this.direction = { x: 1, y: 0 };
}
update(input) {
if (input) {
switch (input) {
case 'up': this.direction = { x: 0, y: -1 }; break;
case 'down': this.direction = { x: 0, y: 1 }; break;
case 'left': this.direction = { x: -1, y: 0 }; break;
case 'right': this.direction = { x: 1, y: 0 }; break;
}
}
}
move() {
this.x += this.direction.x * this.speed;
this.y += this.direction.y * this.speed;
}
render(renderer) {
renderer.drawRect(this.x, this.y, this.width, this.height, this.color);
}
}
window.GameObject = GameObject;
window.Player = Player;`,
"main.js": `document.addEventListener('DOMContentLoaded', () => {
console.log('Initializing game...');
const canvas = document.getElementById('gameCanvas');
if (!canvas) {
console.error('Canvas element not found');
return;
}
function resizeCanvas() {
const container = canvas.parentElement;
const maxWidth = Math.min(container.clientWidth - 40, 600);
const maxHeight = Math.min(container.clientHeight - 200, 600);
const size = Math.min(maxWidth, maxHeight);
canvas.style.width = size + 'px';
canvas.style.height = size + 'px';
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
try {
const audioManager = new AudioManager();
const uiManager = new UIManager();
const inputManager = new InputManager();
const renderer = new Renderer(canvas);
const game = new GameManager(canvas, audioManager, uiManager, inputManager, renderer);
window.game = game;
console.log('Game initialized successfully!');
uiManager.showMessage('Game Ready! Use arrow keys or buttons to play.', 3000);
} catch (error) {
console.error('Failed to initialize game:', error);
alert('Failed to initialize game. Please refresh the page.');
}
});`,
}
// Add missing files using templates
missingFiles.forEach((fileName) => {
if (fileTemplates[fileName]) {
completeFiles.push({
name: fileName,
content: fileTemplates[fileName],
type: fileName.endsWith(".html") ? "html" : "js",
})
console.log(chalk.yellow(`🔧 Auto-generated ${fileName}`))
}
})
return completeFiles
}
// Nginx deployment function
async function deployToNginx(subdomain, files, prompt, chatId, sendEvent) {
const { exec } = await import("child_process");
const util = await import("util");
const execAsync = util.promisify(exec);
try {
// Sanitize subdomain
const sanitizedSubdomain = subdomain
.toLowerCase()
.replace(/[^a-z0-9-]/g, "")
.substring(0, 63);
if (!sanitizedSubdomain) throw new Error("Invalid subdomain");
// Create generated project directory
const generatedPath = path.isAbsolute(GENERATED_PROJECTS_PATH)
? path.join(GENERATED_PROJECTS_PATH, sanitizedSubdomain)
: path.join(__dirname, GENERATED_PROJECTS_PATH, sanitizedSubdomain);