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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Game Creator</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tone@14.7.77/build/Tone.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #6e8efb, #a777e3);
        }
        .game-canvas {
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            background-color: #1a1a2e;
        }
        .prompt-input {
            transition: all 0.3s ease;
        }
        .prompt-input:focus {
            box-shadow: 0 0 0 3px rgba(167, 119, 227, 0.3);
        }
        .scaffold-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
        }
        .loading-dots::after {
            content: '.';
            animation: dots 1.5s steps(5, end) infinite;
        }
        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60% { content: '...'; }
            80%, 100% { content: ''; }
        }
        .typewriter {
            overflow: hidden;
            border-right: 3px solid #a777e3;
            white-space: nowrap;
            margin: 0 auto;
            letter-spacing: 2px;
            animation: typing 3.5s steps(40, end), blink-caret 0.75s step-end infinite;
        }
        @keyframes typing {
            from { width: 0 }
            to { width: 100% }
        }
        @keyframes blink-caret {
            from, to { border-color: transparent }
            50% { border-color: #a777e3; }
        }
        .car {
            position: absolute;
            width: 50px;
            height: 90px;
            background-color: #3498db;
            border-radius: 10px;
        }
        .opponent-car {
            position: absolute;
            width: 50px;
            height: 90px;
            background-color: #e74c3c;
            border-radius: 10px;
        }
        .road {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: #34495e;
        }
        .lane-marker {
            position: absolute;
            width: 10px;
            height: 60px;
            background-color: #f1c40f;
        }
        .adventure-tile {
            position: absolute;
            width: 60px;
            height: 60px;
            background-color: #2ecc71;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .adventure-tile:hover {
            transform: scale(1.05);
        }
        .npc {
            background-color: #9b59b6;
        }
        .item {
            background-color: #e67e22;
        }
    </style>
</head>
<body class="gradient-bg min-h-screen text-white">
    <div class="container mx-auto px-4 py-12">
        <!-- Header -->
        <header class="text-center mb-12">
            <h1 class="text-5xl font-bold mb-4 flex items-center justify-center">
                <i class="fas fa-gamepad mr-4"></i>
                <span class="typewriter">AI Game Creator</span>
            </h1>
            <p class="text-xl opacity-90 max-w-2xl mx-auto">
                Describe your dream game and watch it come to life with AI magic!
            </p>
        </header>

        <!-- Main Content -->
        <div class="flex flex-col lg:flex-row gap-8">
            <!-- Left Panel - Input & Scaffolds -->
            <div class="w-full lg:w-1/3 space-y-6">
                <!-- Prompt Input -->
                <div class="bg-white/10 backdrop-blur-sm rounded-xl p-6 shadow-lg">
                    <h2 class="text-2xl font-semibold mb-4 flex items-center">
                        <i class="fas fa-lightbulb mr-2"></i> Game Concept
                    </h2>
                    <textarea 
                        id="gamePrompt" 
                        class="w-full h-32 px-4 py-3 rounded-lg bg-white/20 border border-white/30 text-white placeholder-white/50 prompt-input focus:outline-none" 
                        placeholder="Describe your game idea... (e.g. 'A platformer where you play as a cat collecting fish while avoiding dogs')"></textarea>
                    
                    <div class="mt-4 flex justify-between items-center">
                        <button id="generateBtn" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-3 px-6 rounded-lg transition flex items-center">
                            <i class="fas fa-magic mr-2"></i> Generate Game
                        </button>
                        <div id="loadingIndicator" class="hidden items-center text-sm">
                            <span class="loading-dots">Generating</span>
                            <i class="fas fa-spinner fa-spin ml-2"></i>
                        </div>
                    </div>
                </div>

                <!-- Scaffold Selection -->
                <div class="bg-white/10 backdrop-blur-sm rounded-xl p-6 shadow-lg">
                    <h2 class="text-2xl font-semibold mb-4 flex items-center">
                        <i class="fas fa-layer-group mr-2"></i> Game Templates
                    </h2>
                    <div class="grid grid-cols-1 gap-4" id="scaffoldContainer">
                        <!-- Scaffold cards will be inserted here by JavaScript -->
                    </div>
                </div>

                <!-- Generated Code Preview -->
                <div class="bg-white/10 backdrop-blur-sm rounded-xl p-6 shadow-lg">
                    <h2 class="text-2xl font-semibold mb-4 flex items-center">
                        <i class="fas fa-code mr-2"></i> Generated Code
                    </h2>
                    <div class="bg-gray-900 rounded-lg p-4 h-64 overflow-auto">
                        <pre id="generatedCode" class="text-sm text-green-400 font-mono">// Your generated game code will appear here...</pre>
                    </div>
                </div>
            </div>

            <!-- Right Panel - Game Display -->
            <div class="w-full lg:w-2/3">
                <div class="bg-white/10 backdrop-blur-sm rounded-xl p-6 shadow-lg h-full">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-2xl font-semibold flex items-center">
                            <i class="fas fa-play-circle mr-2"></i> Game Preview
                        </h2>
                        <div class="flex space-x-2">
                            <button id="fullscreenBtn" class="bg-white/10 hover:bg-white/20 p-2 rounded-lg transition">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button id="soundToggle" class="bg-white/10 hover:bg-white/20 p-2 rounded-lg transition">
                                <i class="fas fa-volume-up"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div id="gameContainer" class="game-canvas w-full h-[500px] flex items-center justify-center relative overflow-hidden">
                        <div id="placeholderText" class="text-center p-8">
                            <i class="fas fa-gamepad text-5xl mb-4 opacity-30"></i>
                            <p class="text-xl opacity-50">Your AI-generated game will appear here</p>
                        </div>
                    </div>

                    <div class="mt-4 flex flex-wrap gap-2" id="gameControls">
                        <!-- Dynamic game controls will appear here -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Game Scaffolds Data
        const scaffolds = [
            {
                id: 'platformer',
                title: 'Platformer',
                icon: 'fas fa-running',
                description: 'Jump and run through levels with obstacles and enemies',
                keywords: ['platform', 'jump', 'run', 'side-scroller', 'mario']
            },
            {
                id: 'rhythm',
                title: 'Rhythm Game',
                icon: 'fas fa-music',
                description: 'Hit notes to the beat of the music',
                keywords: ['music', 'beat', 'dance', 'rhythm', 'sound']
            },
            {
                id: 'puzzle',
                title: 'Puzzle Game',
                icon: 'fas fa-puzzle-piece',
                description: 'Solve challenging puzzles to progress',
                keywords: ['puzzle', 'solve', 'brain', 'logic', 'challenge']
            },
            {
                id: 'shooter',
                title: 'Shooter',
                icon: 'fas fa-space-shuttle',
                description: 'Shoot enemies and avoid projectiles',
                keywords: ['shoot', 'space', 'bullet', 'enemy', 'arcade']
            },
            {
                id: 'adventure',
                title: 'Adventure',
                icon: 'fas fa-map',
                description: 'Explore a world and complete quests',
                keywords: ['explore', 'quest', 'story', 'rpg', 'world']
            },
            {
                id: 'racing',
                title: 'Racing',
                icon: 'fas fa-car',
                description: 'Race against time or opponents',
                keywords: ['race', 'speed', 'car', 'track', 'drive']
            }
        ];

        // DOM Elements
        const gamePrompt = document.getElementById('gamePrompt');
        const generateBtn = document.getElementById('generateBtn');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const scaffoldContainer = document.getElementById('scaffoldContainer');
        const gameContainer = document.getElementById('gameContainer');
        const placeholderText = document.getElementById('placeholderText');
        const gameControls = document.getElementById('gameControls');
        const generatedCode = document.getElementById('generatedCode');
        const fullscreenBtn = document.getElementById('fullscreenBtn');
        const soundToggle = document.getElementById('soundToggle');

        // Current game state
        let currentGame = null;
        let selectedScaffold = null;
        let isSoundOn = true;
        let racingInterval = null;
        let adventureState = null;

        // Initialize the app
        function init() {
            renderScaffoldCards();
            setupEventListeners();
        }

        // Render scaffold selection cards
        function renderScaffoldCards() {
            scaffoldContainer.innerHTML = '';
            
            scaffolds.forEach(scaffold => {
                const card = document.createElement('div');
                card.className = `bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg p-4 cursor-pointer transition scaffold-card ${selectedScaffold?.id === scaffold.id ? 'border-purple-500 bg-purple-500/10' : ''}`;
                card.innerHTML = `
                    <div class="flex items-center">
                        <div class="w-10 h-10 rounded-full bg-purple-600/30 flex items-center justify-center mr-3">
                            <i class="${scaffold.icon} text-purple-300"></i>
                        </div>
                        <div>
                            <h3 class="font-semibold">${scaffold.title}</h3>
                            <p class="text-sm opacity-80">${scaffold.description}</p>
                        </div>
                    </div>
                `;
                
                card.addEventListener('click', () => {
                    selectedScaffold = scaffold;
                    renderScaffoldCards();
                    updateUI();
                });
                
                scaffoldContainer.appendChild(card);
            });
        }

        // Set up event listeners
        function setupEventListeners() {
            generateBtn.addEventListener('click', generateGame);
            fullscreenBtn.addEventListener('click', toggleFullscreen);
            soundToggle.addEventListener('click', toggleSound);
            
            // Allow Enter key to trigger generation
            gamePrompt.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    generateGame();
                }
            });
        }

        // Generate game based on prompt and selected scaffold
        async function generateGame() {
            const prompt = gamePrompt.value.trim();
            
            if (!prompt) {
                showAlert('Please enter a game description', 'error');
                return;
            }
            
            if (!selectedScaffold) {
                showAlert('Please select a game template', 'error');
                return;
            }
            
            // Show loading state
            generateBtn.disabled = true;
            loadingIndicator.classList.remove('hidden');
            
            try {
                // In a real app, this would call your backend API
                // For this demo, we'll simulate the API call
                const gameData = await simulateLLMGeneration(prompt, selectedScaffold);
                
                // Create the game
                createGame(gameData);
                
                // Update the code preview
                generatedCode.textContent = gameData.code || '// No code generated';
                
                showAlert('Game generated successfully!', 'success');
            } catch (error) {
                console.error('Error generating game:', error);
                showAlert('Failed to generate game. Please try again.', 'error');
            } finally {
                // Hide loading state
                generateBtn.disabled = false;
                loadingIndicator.classList.add('hidden');
            }
        }

        // Simulate LLM generation (in a real app, this would be an API call)
        async function simulateLLMGeneration(prompt, scaffold) {
            // Simulate network delay
            await new Promise(resolve => setTimeout(resolve, 2000));
            
            // Generate mock game data based on scaffold type
            let gameData = {
                scaffold: scaffold.id,
                prompt: prompt,
                code: generateMockCode(scaffold.id, prompt),
                config: {}
            };
            
            // Add scaffold-specific config
            switch (scaffold.id) {
                case 'platformer':
                    gameData.config = {
                        player: { speed: 300, jumpForce: 600 },
                        platforms: generatePlatforms(10),
                        enemies: generateEnemies(3),
                        collectibles: generateCollectibles(5)
                    };
                    break;
                case 'rhythm':
                    gameData.config = {
                        bpm: 120,
                        notes: generateNotes(16),
                        difficulty: 'medium'
                    };
                    break;
                case 'puzzle':
                    gameData.config = {
                        gridSize: 8,
                        pieces: generatePuzzlePieces(6),
                        movesAllowed: 20
                    };
                    break;
                case 'shooter':
                    gameData.config = {
                        player: { speed: 400, fireRate: 500 },
                        enemies: generateSpaceEnemies(5),
                        powerups: generatePowerups(2)
                    };
                    break;
                case 'adventure':
                    gameData.config = {
                        worldSize: { width: 10, height: 10 },
                        npcs: generateNPCs(3),
                        items: generateAdventureItems(4)
                    };
                    break;
                case 'racing':
                    gameData.config = {
                        track: generateTrack(),
                        opponents: 3,
                        laps: 3
                    };
                    break;
            }
            
            return gameData;
        }

        // Generate mock code for preview
        function generateMockCode(scaffoldId, prompt) {
            const codeSnippets = {
                platformer: `// Platformer game based on: "${prompt}"
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    physics: {
        default: 'arcade',
        arcade: { gravity: { y: 300 }, debug: false }
    },
    scene: {
        preload: function() {
            this.load.image('sky', 'assets/sky.png');
            this.load.image('ground', 'assets/platform.png');
            this.load.image('star', 'assets/star.png');
            this.load.spritesheet('player', 'assets/player.png', {
                frameWidth: 32, frameHeight: 48
            });
        },
        create: function() {
            // Create world
            this.add.image(400, 300, 'sky');
            
            // Platforms
            const platforms = this.physics.add.staticGroup();
            platforms.create(400, 568, 'ground').setScale(2).refreshBody();
            
            // Player
            this.player = this.physics.add.sprite(100, 450, 'player');
            this.player.setBounce(0.2);
            this.player.setCollideWorldBounds(true);
            
            // Physics
            this.physics.add.collider(this.player, platforms);
            
            // Controls
            this.cursors = this.input.keyboard.createCursorKeys();
        },
        update: function() {
            // Movement logic
            if (this.cursors.left.isDown) {
                this.player.setVelocityX(-160);
            } else if (this.cursors.right.isDown) {
                this.player.setVelocityX(160);
            } else {
                this.player.setVelocityX(0);
            }
            
            if (this.cursors.up.isDown && this.player.body.touching.down) {
                this.player.setVelocityY(-330);
            }
        }
    }
};

const game = new Phaser.Game(config);`,
                rhythm: `// Rhythm game based on: "${prompt}"
const synth = new Tone.Synth().toDestination();
const notes = ['C4', 'D4', 'E4', 'F4', 'G4'];
let score = 0;

function setupGame() {
    // Create note targets
    const container = document.getElementById('gameContainer');
    notes.forEach((note, i) => {
        const noteEl = document.createElement('div');
        noteEl.className = 'note-target';
        noteEl.style.left = \`\${(i + 1) * 15}%\`;
        noteEl.dataset.note = note;
        noteEl.addEventListener('click', () => {
            synth.triggerAttackRelease(note, "8n");
            score += 10;
        });
        container.appendChild(noteEl);
    });
    
    // Start music
    Tone.Transport.bpm.value = 120;
    Tone.Transport.scheduleRepeat(time => {
        const note = notes[Math.floor(Math.random() * notes.length)];
        synth.triggerAttackRelease(note, "8n", time);
    }, "8n");
    
    Tone.Transport.start();
}`,
                puzzle: `// Puzzle game based on: "${prompt}"
class PuzzleGame {
    constructor() {
        this.gridSize = 4;
        this.pieces = [];
        this.selectedPiece = null;
        
        this.initBoard();
    }
    
    initBoard() {
        // Generate random puzzle pieces
        for (let i = 0; i < this.gridSize; i++) {
            this.pieces[i] = [];
            for (let j = 0; j < this.gridSize; j++) {
                this.pieces[i][j] = {
                    type: Math.floor(Math.random() * 6),
                    x: i,
                    y: j
                };
            }
        }
        
        this.render();
    }
    
    render() {
        const container = document.getElementById('gameContainer');
        container.innerHTML = '';
        
        this.pieces.forEach(row => {
            row.forEach(piece => {
                const pieceEl = document.createElement('div');
                pieceEl.className = 'puzzle-piece';
                pieceEl.style.backgroundColor = \`hsl(\${Math.random() * 360}, 70%, 60%)\`;
                pieceEl.addEventListener('click', () => this.handleClick(piece));
                container.appendChild(pieceEl);
            });
        });
    }
    
    handleClick(piece) {
        // Handle puzzle piece click
    }
}`,
                shooter: `// Shooter game based on: "${prompt}"
const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    physics: {
        default: 'arcade',
        arcade: { debug: false }
    },
    scene: {
        preload: function() {
            this.load.image('player', 'assets/ship.png');
            this.load.image('bullet', 'assets/bullet.png');
            this.load.image('enemy', 'assets/enemy.png');
        },
        create: function() {
            // Player
            this.player = this.physics.add.sprite(400, 500, 'player');
            this.player.setCollideWorldBounds(true);
            
            // Bullets
            this.bullets = this.physics.add.group();
            
            // Enemies
            this.enemies = this.physics.add.group();
            this.time.addEvent({
                delay: 1000,
                callback: this.spawnEnemy,
                callbackScope: this,
                loop: true
            });
            
            // Controls
            this.cursors = this.input.keyboard.createCursorKeys();
            this.input.on('pointerdown', this.shoot, this);
        },
        update: function() {
            // Movement
            if (this.cursors.left.isDown) {
                this.player.setVelocityX(-200);
            } else if (this.cursors.right.isDown) {
                this.player.setVelocityX(200);
            } else {
                this.player.setVelocityX(0);
            }
        },
        shoot: function() {
            const bullet = this.bullets.create(this.player.x, this.player.y, 'bullet');
            bullet.setVelocityY(-300);
        },
        spawnEnemy: function() {
            const x = Phaser.Math.Between(50, 750);
            const enemy = this.enemies.create(x, 0, 'enemy');
            enemy.setVelocityY(100);
        }
    }
};

const game = new Phaser.Game(config);`,
                adventure: `// Adventure game based on: "${prompt}"
class AdventureGame {
    constructor() {
        this.worldSize = { width: 10, height: 10 };
        this.playerPos = { x: 0, y: 0 };
        this.npcs = [
            { x: 3, y: 2, name: 'Wizard', dialog: 'Seek the magic orb!' },
            { x: 7, y: 5, name: 'Merchant', dialog: 'I have potions for sale.' }
        ];
        this.items = [
            { x: 5, y: 8, name: 'Magic Orb', description: 'Grants wishes' }
        ];
        
        this.renderWorld();
    }
    
    renderWorld() {
        const container = document.getElementById('gameContainer');
        container.innerHTML = '';
        
        // Render tiles
        for (let y = 0; y < this.worldSize.height; y++) {
            for (let x = 0; x < this.worldSize.width; x++) {
                const tile = document.createElement('div');
                tile.className = 'adventure-tile';
                tile.style.left = \`\${x * 7}%\`;
                tile.style.top = \`\${y * 7}%\`;
                container.appendChild(tile);
            }
        }
        
        // Render NPCs
        this.npcs.forEach(npc => {
            const npcEl = document.createElement('div');
            npcEl.className = 'adventure-tile npc';
            npcEl.style.left = \`\${npc.x * 7}%\`;
            npcEl.style.top = \`\${npc.y * 7}%\`;
            npcEl.textContent = npc.name[0];
            npcEl.title = npc.name;
            container.appendChild(npcEl);
        });
        
        // Render items
        this.items.forEach(item => {
            const itemEl = document.createElement('div');
            itemEl.className = 'adventure-tile item';
            itemEl.style.left = \`\${item.x * 7}%\`;
            itemEl.style.top = \`\${item.y * 7}%\`;
            itemEl.textContent = item.name[0];
            itemEl.title = item.name;
            container.appendChild(itemEl);
        });
    }
}`,
                racing: `// Racing game based on: "${prompt}"
class RacingGame {
    constructor() {
        this.playerCar = { x: 50, y: 400, speed: 0 };
        this.opponents = [
            { x: 150, y: 100, speed: 3 },
            { x: 250, y: 0, speed: 4 },
            { x: 350, y: -100, speed: 3.5 }
        ];
        this.road = [];
        
        this.initGame();
        this.startRace();
    }
    
    initGame() {
        const container = document.getElementById('gameContainer');
        container.innerHTML = '';
        
        // Create road
        for (let i = 0; i < 20; i++) {
            const marker = document.createElement('div');
            marker.className = 'lane-marker';
            marker.style.left = '45%';
            marker.style.top = \`\${i * 120}px\`;
            container.appendChild(marker);
        }
        
        // Create player car
        const car = document.createElement('div');
        car.className = 'car';
        car.style.left = \`\${this.playerCar.x}px\`;
        car.style.top = \`\${this.playerCar.y}px\`;
        container.appendChild(car);
        
        // Create opponent cars
        this.opponents.forEach(opp => {
            const oppCar = document.createElement('div');
            oppCar.className = 'opponent-car';
            oppCar.style.left = \`\${opp.x}px\`;
            oppCar.style.top = \`\${opp.y}px\`;
            container.appendChild(oppCar);
        });
    }
    
    startRace() {
        // Handle keyboard controls
        document.addEventListener('keydown', (e) => {
            if (e.key === 'ArrowLeft') this.playerCar.x = Math.max(50, this.playerCar.x - 20);
            if (e.key === 'ArrowRight') this.playerCar.x = Math.min(350, this.playerCar.x + 20);
            if (e.key === 'ArrowUp') this.playerCar.speed = Math.min(10, this.playerCar.speed + 0.5);
            if (e.key === 'ArrowDown') this.playerCar.speed = Math.max(0, this.playerCar.speed - 0.5);
            
            // Update player car position
            document.querySelector('.car').style.left = \`\${this.playerCar.x}px\`;
        });
        
        // Game loop
        setInterval(() => {
            // Move opponents
            this.opponents.forEach(opp => {
                opp.y += opp.speed;
                if (opp.y > 600) opp.y = -100;
                document.querySelectorAll('.opponent-car')[this.opponents.indexOf(opp)].style.top = \`\${opp.y}px\`;
            });
            
            // Move road markers
            const markers = document.querySelectorAll('.lane-marker');
            markers.forEach(marker => {
                const currentTop = parseInt(marker.style.top);
                marker.style.top = \`\${(currentTop + this.playerCar.speed) % 600}px\`;
            });
        }, 16);
    }
}`
            };
            
            return codeSnippets[scaffoldId] || '// No template found for this game type';
        }

        // Create the actual game
        function createGame(gameData) {
            // Clear previous game if exists
            if (currentGame) {
                if (currentGame instanceof Phaser.Game) {
                    currentGame.destroy(true);
                } else if (typeof currentGame.cleanup === 'function') {
                    currentGame.cleanup();
                }
                if (racingInterval) {
                    clearInterval(racingInterval);
                    racingInterval = null;
                }
                currentGame = null;
            }
            
            // Hide placeholder
            placeholderText.style.display = 'none';
            gameContainer.innerHTML = '';
            
            // Create game based on scaffold type
            switch (gameData.scaffold) {
                case 'platformer':
                    createPlatformerGame(gameData);
                    break;
                case 'rhythm':
                    createRhythmGame(gameData);
                    break;
                case 'puzzle':
                    createPuzzleGame(gameData);
                    break;
                case 'shooter':
                    createShooterGame(gameData);
                    break;
                case 'adventure':
                    createAdventureGame(gameData);
                    break;
                case 'racing':
                    createRacingGame(gameData);
                    break;
                default:
                    // Fallback
                    placeholderText.style.display = 'block';
                    placeholderText.innerHTML = `
                        <i class="fas fa-gamepad text-5xl mb-4 opacity-30"></i>
                        <p class="text-xl opacity-50">Preview not available for ${selectedScaffold.title} template</p>
                        <p class="text-sm opacity-30 mt-2">Check the code tab to see the generated code</p>
                    `;
            }
            
            // Update game controls
            updateGameControls(gameData.scaffold);
        }

        // Create a platformer game
        function createPlatformerGame(gameData) {
            const config = {
                type: Phaser.AUTO,
                width: gameContainer.clientWidth,
                height: gameContainer.clientHeight,
                physics: {
                    default: 'arcade',
                    arcade: {
                        gravity: { y: 300 },
                        debug: false
                    }
                },
                parent: 'gameContainer',
                scene: {
                    preload: preload,
                    create: create,
                    update: update
                }
            };
            
            currentGame = new Phaser.Game(config);
            
            function preload() {
                // Load assets (in a real app, these would be generated or selected based on prompt)
                this.load.image('sky', 'https://labs.phaser.io/assets/skies/space3.png');
                this.load.image('ground', 'https://labs.phaser.io/assets/platform.png');
                this.load.image('star', 'https://labs.phaser.io/assets/sprites/star.png');
                this.load.spritesheet('dude', 'https://labs.phaser.io/assets/sprites/dude.png', {
                    frameWidth: 32, frameHeight: 48
                });
            }
            
            function create() {
                // Add background
                this.add.image(400, 300, 'sky').setDisplaySize(config.width, config.height);
                
                // Platforms
                const platforms = this.physics.add.staticGroup();
                
                // Ground
                platforms.create(400, 568, 'ground').setScale(2).refreshBody();
                
                // Additional platforms
                platforms.create(600, 400, 'ground');
                platforms.create(50, 250, 'ground');
                platforms.create(750, 220, 'ground');
                
                // Player
                const player = this.physics.add.sprite(100, 450, 'dude');
                player.setBounce(0.2);
                player.setCollideWorldBounds(true);
                
                // Animation
                this.anims.create({
                    key: 'left',
                    frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
                    frameRate: 10,
                    repeat: -1
                });
                
                this.anims.create({
                    key: 'turn',
                    frames: [ { key: 'dude', frame: 4 } ],
                    frameRate: 20
                });
                
                this.anims.create({
                    key: 'right',
                    frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
                    frameRate: 10,
                    repeat: -1
                });
                
                // Stars
                const stars = this.physics.add.group({
                    key: 'star',
                    repeat: 11,
                    setXY: { x: 12, y: 0, stepX: 70 }
                });
                
                stars.children.iterate(function (child) {
                    child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
                });
                
                // Physics
                this.physics.add.collider(player, platforms);
                this.physics.add.collider(stars, platforms);
                this.physics.add.overlap(player, stars, collectStar, null, this);
                
                // Input
                this.cursors = this.input.keyboard.createCursorKeys();
                
                // Score
                this.score = 0;
                this.scoreText = this.add.text(16, 16, 'Score: 0', { 
                    fontSize: '32px', 
                    fill: '#fff',
                    fontFamily: 'Arial'
                });
                
                function collectStar(player, star) {
                    star.disableBody(true, true);
                    
                    this.score += 10;
                    this.scoreText.setText('Score: ' + this.score);
                    
                    // Play sound if enabled
                    if (isSoundOn) {
                        const synth = new Tone.Synth().toDestination();
                        synth.triggerAttackRelease("C5", "8n");
                    }
                }
            }
            
            function update() {
                const cursors = this.cursors;
                const player = this.physics.world.bodies.entries[0].gameObject;
                
                if (cursors.left.isDown) {
                    player.setVelocityX(-160);
                    player.anims.play('left', true);
                } else if (cursors.right.isDown) {
                    player.setVelocityX(160);
                    player.anims.play('right', true);
                } else {
                    player.setVelocityX(0);
                    player.anims.play('turn');
                }
                
                if (cursors.up.isDown && player.body.touching.down) {
                    player.setVelocityY(-330);
                }
            }
        }

        // Create a rhythm game
        function createRhythmGame(gameData) {
            // Clear container
            gameContainer.innerHTML = '';
            
            // Create note targets
            const notes = ['C', 'D', 'E', 'F', 'G'];
            const colors = ['#FF5252', '#FFD740', '#69F0AE', '#40C4FF', '#E040FB'];
            
            notes.forEach((note, i) => {
                const noteEl = document.createElement('div');
                noteEl.className = 'w-16 h-16 rounded-full flex items-center justify-center text-white font-bold cursor-pointer transition-transform hover:scale-110';
                noteEl.style.backgroundColor = colors[i];
                noteEl.style.position = 'absolute';
                noteEl.style.left = `${(i + 1) * 15}%`;
                noteEl.style.top = '50%';
                noteEl.style.transform = 'translate(-50%, -50%)';
                noteEl.textContent = note;
                noteEl.dataset.note = `${note}4`;
                
                noteEl.addEventListener('click', () => {
                    if (isSoundOn) {
                        const synth = new Tone.Synth().toDestination();
                        synth.triggerAttackRelease(noteEl.dataset.note, "8n");
                    }
                    noteEl.style.transform = 'translate(-50%, -50%) scale(1.2)';
                    setTimeout(() => {
                        noteEl.style.transform = 'translate(-50%, -50%) scale(1)';
                    }, 200);
                });
                
                gameContainer.appendChild(noteEl);
            });
            
            // Add visualizer
            const visualizer = document.createElement('div');
            visualizer.className = 'w-full h-2 bg-white/20 rounded-full absolute bottom-8 left-0';
            visualizer.style.overflow = 'hidden';
            
            const progress = document.createElement('div');
            progress.className = 'h-full bg-purple-500 rounded-full';
            progress.style.width = '0%';
            progress.style.transition = 'width 0.1s linear';
            visualizer.appendChild(progress);
            
            gameContainer.appendChild(visualizer);
            
            // Start music if sound is on
            if (isSoundOn) {
                const synth = new Tone.Synth().toDestination();
                const notes = ['C4', 'D4', 'E4', 'F4', 'G4'];
                let currentNote = 0;
                
                Tone.Transport.bpm.value = 120;
                Tone.Transport.scheduleRepeat(time => {
                    synth.triggerAttackRelease(notes[currentNote], "8n", time);
                    currentNote = (currentNote + 1) % notes.length;
                    
                    // Update visualizer
                    progress.style.width = `${(currentNote / notes.length) * 100}%`;
                }, "8n");
                
                Tone.Transport.start();
            }
            
            currentGame = {
                cleanup: () => {
                    Tone.Transport.cancel();
                    Tone.Transport.stop();
                }
            };
        }

        // Create a puzzle game
        function createPuzzleGame(gameData) {
            // Clear container
            gameContainer.innerHTML = '';
            
            // Create puzzle board
            const boardSize = 4;
            const pieceSize = gameContainer.clientWidth / boardSize - 10;
            
            // Create pieces
            for (let i = 0; i < boardSize * boardSize; i++) {
                const piece = document.createElement('div');
                piece.className = 'absolute bg-white/20 border border-white/30 rounded-lg cursor-pointer transition-all hover:bg-white/30';
                piece.style.width = `${pieceSize}px`;
                piece.style.height = `${pieceSize}px`;
                piece.style.left = `${(i % boardSize) * (pieceSize + 10)}px`;
                piece.style.top = `${Math.floor(i / boardSize) * (pieceSize + 10)}px`;
                
                // Random color
                const hue = Math.floor(Math.random() * 360);
                piece.style.backgroundColor = `hsla(${hue}, 80%, 60%, 0.7)`;
                
                piece.addEventListener('click', () => {
                    piece.style.transform = 'scale(0.95) rotate(5deg)';
                    setTimeout(() => {
                        piece.style.transform = '';
                    }, 200);
                    
                    if (isSoundOn) {
                        const note = ['C4', 'E4', 'G4', 'C5'][Math.floor(Math.random() * 4)];
                        const synth = new Tone.Synth().toDestination();
                        synth.triggerAttackRelease(note, "8n");
                    }
                });
                
                gameContainer.appendChild(piece);
            }
            
            currentGame = {
                cleanup: () => {
                    // No special cleanup needed
                }
            };
        }

        // Create a shooter game
        function createShooterGame(gameData) {
            const config = {
                type: Phaser.AUTO,
                width: gameContainer.clientWidth,
                height: gameContainer.clientHeight,
                physics: {
                    default: 'arcade',
                    arcade: {
                        debug: false
                    }
                },
                parent: 'gameContainer',
                scene: {
                    preload: preload,
                    create: create,
                    update: update
                }
            };
            
            currentGame = new Phaser.Game(config);
            
            function preload() {
                // Load assets
                this.load.image('ship', 'https://labs.phaser.io/assets/sprites/thrust_ship2.png');
                this.load.image('bullet', 'https://labs.phaser.io/assets/sprites/bullets/bullet6.png');
                this.load.image('enemy', 'https://labs.phaser.io/assets/sprites/asteroid.png');
            }
            
            function create() {
                // Add background
                this.add.rectangle(0, 0, config.width, config.height, 0x1a1a2e).setOrigin(0);
                
                // Player
                this.player = this.physics.add.sprite(config.width / 2, config.height - 50, 'ship');
                this.player.setCollideWorldBounds(true);
                
                // Bullets
                this.bullets = this.physics.add.group();
                
                // Enemies
                this.enemies = this.physics.add.group();
                this.time.addEvent({
                    delay: 1000,
                    callback: spawnEnemy,
                    callbackScope: this,
                    loop: true
                });
                
                // Controls
                this.cursors = this.input.keyboard.createCursorKeys();
                this.input.on('pointerdown', shoot, this);
                
                // Score
                this.score = 0;
                this.scoreText = this.add.text(16, 16, 'Score: 0', { 
                    fontSize: '24px', 
                    fill: '#fff',
                    fontFamily: 'Arial'
                });
                
                function shoot() {
                    const bullet = this.bullets.create(this.player.x, this.player.y - 20, 'bullet');
                    bullet.setVelocityY(-300);
                    
                    if (isSoundOn) {
                        const synth = new Tone.Synth().toDestination();
                        synth.triggerAttackRelease("A2", "8n");
                    }
                }
                
                function spawnEnemy() {
                    const x = Phaser.Math.Between(50, config.width - 50);
                    const enemy = this.enemies.create(x, 0, 'enemy');
                    enemy.setScale(0.5);
                    enemy.setVelocityY(Phaser.Math.Between(50, 150));
                    
                    // Collision
                    this.physics.add.collider(this.bullets, this.enemies, hitEnemy, null, this);
                    
                    function hitEnemy(bullet, enemy) {
                        bullet.destroy();
                        enemy.destroy();
                        
                        this.score += 10;
                        this.scoreText.setText('Score: ' + this.score);
                        
                        if (isSoundOn) {
                            const synth = new Tone.Synth().toDestination();
                            synth.triggerAttackRelease("C5", "8n");
                        }
                    }
                }
            }
            
            function update() {
                // Movement
                if (this.cursors.left.isDown) {
                    this.player.setVelocityX(-200);
                } else if (this.cursors.right.isDown) {
                    this.player.setVelocityX(200);
                } else {
                    this.player.setVelocityX(0);
                }
            }
        }

        // Create an adventure game
        function createAdventureGame(gameData) {
            // Clear container
            gameContainer.innerHTML = '';
            
            // Game state
            adventureState = {
                playerPos: { x: 0, y: 0 },
                inventory: [],
                npcs: [
                    { x: 3, y: 2, name: 'Wizard', dialog: 'Seek the magic orb to win the game!' },
                    { x: 7, y: 5, name: 'Merchant', dialog: 'I have potions for sale. (Coming soon!)' }
                ],
                items: [
                    { x: 5, y: 8, name: 'Magic Orb', description: 'The legendary orb that grants wishes' }
                ]
            };
            
            // Render world
            renderAdventureWorld();
            
            currentGame = {
                cleanup: () => {
                    adventureState = null;
                }
            };
            
            function renderAdventureWorld() {
                // Clear container
                gameContainer.innerHTML = '';
                
                // Create grid
                const gridSize = 10;
                const tileSize = Math.min(
                    gameContainer.clientWidth / gridSize - 2,
                    gameContainer.clientHeight / gridSize - 2
                );
                
                // Render tiles
                for (let y = 0; y < gridSize; y++) {
                    for (let x = 0; x < gridSize; x++) {
                        const tile = document.createElement('div');
                        tile.className = 'adventure-tile';
                        tile.style.width = `${tileSize}px`;
                        tile.style.height = `${tileSize}px`;
                        tile.style.left = `${x * (tileSize + 2)}px`;
                        tile.style.top = `${y * (tileSize + 2)}px`;
                        
                        // Mark player position
                        if (x === adventureState.playerPos.x && y === adventureState.playerPos.y) {
                            tile.innerHTML = '<i class="fas fa-user"></i>';
                            tile.style.backgroundColor = '#3498db';
                        }
                        
                        gameContainer.appendChild(tile);
                    }
                }
                
                // Render NPCs
                adventureState.npcs.forEach(npc => {
                    const npcEl = document.createElement('div');
                    npcEl.className = 'adventure-tile npc';
                    npcEl.style.width = `${tileSize}px`;
                    npcEl.style.height = `${tileSize}px`;
                    npcEl.style.left = `${npc.x * (tileSize + 2)}px`;
                    npcEl.style.top = `${npc.y * (tileSize + 2)}px`;
                    npcEl.innerHTML = `<i class="fas fa-hat-wizard"></i>`;
                    npcEl.title = npc.name;
                    
                    npcEl.addEventListener('click', () => {
                        alert(`${npc.name}: ${npc.dialog}`);
                    });
                    
                    gameContainer.appendChild(npcEl);
                });
                
                // Render items
                adventureState.items.forEach(item => {
                    const itemEl = document.createElement('div');
                    itemEl.className = 'adventure-tile item';
                    itemEl.style.width = `${tileSize}px`;
                    itemEl.style.height = `${tileSize}px`;
                    itemEl.style.left = `${item.x * (tileSize + 2)}px`;
                    itemEl.style.top = `${item.y * (tileSize + 2)}px`;
                    itemEl.innerHTML = `<i class="fas fa-gem"></i>`;
                    itemEl.title = item.name;
                    
                    itemEl.addEventListener('click', () => {
                        if (Math.abs(adventureState.playerPos.x - item.x) <= 1 && 
                            Math.abs(adventureState.playerPos.y - item.y) <= 1) {
                            alert(`You found the ${item.name}! ${item.description}`);
                            adventureState.items = adventureState.items.filter(i => i !== item);
                            renderAdventureWorld();
                        } else {
                            alert(`You need to get closer to the ${item.name}!`);
                        }
                    });
                    
                    gameContainer.appendChild(itemEl);
                });
                
                // Add controls
                document.addEventListener('keydown', (e) => {
                    const newPos = {...adventureState.playerPos};
                    
                    switch(e.key) {
                        case 'ArrowUp':
                            newPos.y = Math.max(0, adventureState.playerPos.y - 1);
                            break;
                        case 'ArrowDown':
                            newPos.y = Math.min(gridSize - 1, adventureState.playerPos.y + 1);
                            break;
                        case 'ArrowLeft':
                            newPos.x = Math.max(0, adventureState.playerPos.x - 1);
                            break;
                        case 'ArrowRight':
                            newPos.x = Math.min(gridSize - 1, adventureState.playerPos.x + 1);
                            break;
                    }
                    
                    if (newPos.x !== adventureState.playerPos.x || newPos.y !== adventureState.playerPos.y) {
                        adventureState.playerPos = newPos;
                        renderAdventureWorld();
                    }
                });
            }
        }

        // Create a racing game
        function createRacingGame(gameData) {
            // Clear container
            gameContainer.innerHTML = '';
            
            // Game state
            const state = {
                player: { x: 175, y: 400, speed: 0, maxSpeed: 10 },
                opponents: [
                    { x: 75, y: -100, speed: 3 },
                    { x: 175, y: -300, speed: 4 },
                    { x: 275, y: -500, speed: 3.5 }
                ],
                roadMarkers: Array.from({ length: 20 }, (_, i) => ({ y: i * 120 })),
                score: 0
            };
            
            // Create road
            const road = document.createElement('div');
            road.className = 'road';
            gameContainer.appendChild(road);
            
            // Create road markers
            state.roadMarkers.forEach(marker => {
                const markerEl = document.createElement('div');
                markerEl.className = 'lane-marker';
                markerEl.style.left = '45%';
                markerEl.style.top = `${marker.y}px`;
                gameContainer.appendChild(markerEl);
            });
            
            // Create player car
            const playerCar = document.createElement('div');
            playerCar.className = 'car';
            playerCar.style.left = `${state.player.x}px`;
            playerCar.style.top = `${state.player.y}px`;
            gameContainer.appendChild(playerCar);
            
            // Create opponent cars
            state.opponents.forEach(opp => {
                const oppCar = document.createElement('div');
                oppCar.className = 'opponent-car';
                oppCar.style.left = `${opp.x}px`;
                oppCar.style.top = `${opp.y}px`;
                gameContainer.appendChild(oppCar);
            });
            
            // Score display
            const scoreEl = document.createElement('div');
            scoreEl.className = 'absolute top-4 left-4 text-white font-bold text-xl';
            scoreEl.textContent = `Score: ${state.score}`;
            gameContainer.appendChild(scoreEl);
            
            // Controls
            document.addEventListener('keydown', (e) => {
                if (e.key === 'ArrowLeft') state.player.x = Math.max(75, state.player.x - 100);
                if (e.key === 'ArrowRight') state.player.x = Math.min(275, state.player.x + 100);
                if (e.key === 'ArrowUp') state.player.speed = Math.min(state.player.maxSpeed, state.player.speed + 0.5);
                if (e.key === 'ArrowDown') state.player.speed = Math.max(0, state.player.speed - 0.5);
                
                // Update player car position
                playerCar.style.left = `${state.player.x}px`;
            });
            
            // Game loop
            racingInterval = setInterval(() => {
                // Move opponents
                state.opponents.forEach(opp => {
                    opp.y += opp.speed;
                    if (opp.y > gameContainer.clientHeight) {
                        opp.y = -100;
                        state.score += 10;
                        scoreEl.textContent = `Score: ${state.score}`;
                    }
                    
                    // Check collision
                    if (Math.abs(opp.x - state.player.x) < 50 && 
                        Math.abs(opp.y - state.player.y) < 50) {
                        state.player.speed = Math.max(0, state.player.speed - 1);
                    }
                    
                    // Update opponent position
                    document.querySelectorAll('.opponent-car')[state.opponents.indexOf(opp)].style.top = `${opp.y}px`;
                });
                
                // Move road markers
                state.roadMarkers.forEach(marker => {
                    marker.y += state.player.speed;
                    if (marker.y > gameContainer.clientHeight) {
                        marker.y = 0;
                    }
                    
                    // Update marker position
                    const markers = document.querySelectorAll('.lane-marker');
                    markers[state.roadMarkers.indexOf(marker)].style.top = `${marker.y}px`;
                });
                
                // Update score based on speed
                state.score += Math.floor(state.player.speed / 10);
                scoreEl.textContent = `Score: ${state.score}`;
            }, 16);
            
            currentGame = {
                cleanup: () => {
                    if (racingInterval) {
                        clearInterval(racingInterval);
                        racingInterval = null;
                    }
                }
            };
        }

        // Update game controls based on game type
        function updateGameControls(gameType) {
            gameControls.innerHTML = '';
            
            const controls = {
                platformer: [
                    { label: 'Left/Right', keys: '← β†’', desc: 'Move player' },
                    { label: 'Jump', keys: '↑', desc: 'Jump' }
                ],
                rhythm: [
                    { label: 'Tap', keys: 'Click', desc: 'Hit notes' }
                ],
                puzzle: [
                    { label: 'Select', keys: 'Click', desc: 'Select pieces' }
                ],
                shooter: [
                    { label: 'Left/Right', keys: '← β†’', desc: 'Move ship' },
                    { label: 'Shoot', keys: 'Click', desc: 'Fire bullets' }
                ],
                adventure: [
                    { label: 'Move', keys: 'Arrow Keys', desc: 'Navigate the world' },
                    { label: 'Interact', keys: 'Click', desc: 'Talk to NPCs or collect items' }
                ],
                racing: [
                    { label: 'Left/Right', keys: '← β†’', desc: 'Change lanes' },
                    { label: 'Accelerate/Brake', keys: '↑ ↓', desc: 'Control speed' }
                ],
                default: [
                    { label: 'No controls', desc: 'This game type has no interactive controls' }
                ]
            };
            
            const currentControls = controls[gameType] || controls.default;
            
            currentControls.forEach(control => {
                const controlEl = document.createElement('div');
                controlEl.className = 'bg-white/10 rounded-lg px-4 py-2 flex items-center';
                
                const keysEl = document.createElement('div');
                keysEl.className = 'bg-purple-600 rounded px-2 py-1 mr-3 font-mono text-sm';
                keysEl.textContent = control.keys || '';
                
                const textEl = document.createElement('div');
                textEl.className = 'text-sm';
                textEl.innerHTML = `<span class="font-semibold">${control.label}</span>: ${control.desc}`;
                
                if (control.keys) {
                    controlEl.appendChild(keysEl);
                }
                controlEl.appendChild(textEl);
                
                gameControls.appendChild(controlEl);
            });
        }

        // Toggle fullscreen mode
        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                gameContainer.requestFullscreen().catch(err => {
                    console.error('Error attempting to enable fullscreen:', err);
                });
            } else {
                document.exitFullscreen();
            }
        }

        // Toggle sound on/off
        function toggleSound() {
            isSoundOn = !isSoundOn;
            soundToggle.innerHTML = isSoundOn ? '<i class="fas fa-volume-up"></i>' : '<i class="fas fa-volume-mute"></i>';
            
            if (isSoundOn && currentGame && selectedScaffold?.id === 'rhythm') {
                // Restart music if it's a rhythm game
                createGame({ scaffold: 'rhythm' });
            }
        }

        // Show alert message
        function showAlert(message, type) {
            const alert = document.createElement('div');
            alert.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transition-all ${
                type === 'error' ? 'bg-red-500' : 'bg-green-500'
            }`;
            alert.textContent = message;
            
            document.body.appendChild(alert);
            
            setTimeout(() => {
                alert.style.opacity = '0';
                setTimeout(() => {
                    alert.remove();
                }, 300);
            }, 3000);
        }

        // Helper functions for mock data generation
        function generatePlatforms(count) {
            return Array.from({ length: count }, (_, i) => ({
                x: Math.floor(Math.random() * 700) + 50,
                y: Math.floor(Math.random() * 400) + 100,
                width: Math.floor(Math.random() * 200) + 50
            }));
        }
        
        function generateEnemies(count) {
            return Array.from({ length: count }, (_, i) => ({
                type: ['dog', 'ghost', 'spider'][Math.floor(Math.random() * 3)],
                x: Math.floor(Math.random() * 700) + 50,
                speed: Math.floor(Math.random() * 100) + 50,
                patrol: Math.random() > 0.5 ? 'left-right' : 'up-down'
            }));
        }
        
        function generateCollectibles(count) {
            return Array.from({ length: count }, (_, i) => ({
                type: ['coin', 'gem', 'star'][Math.floor(Math.random() * 3)],
                x: Math.floor(Math.random() * 700) + 50,
                y: Math.floor(Math.random() * 500) + 50,
                value: Math.floor(Math.random() * 5) + 1
            }));
        }
        
        function generateNotes(count) {
            return Array.from({ length: count }, (_, i) => ({
                time: i * 0.5,
                note: ['C', 'D', 'E', 'F', 'G'][Math.floor(Math.random() * 5)],
                duration: 0.25
            }));
        }
        
        function generatePuzzlePieces(count) {
            return Array.from({ length: count }, (_, i) => ({
                type: i,
                color: `hsl(${Math.floor(Math.random() * 360)}, 80%, 60%)`,
                shape: ['circle', 'square', 'triangle'][Math.floor(Math.random() * 3)]
            }));
        }
        
        function generateSpaceEnemies(count) {
            return Array.from({ length: count }, (_, i) => ({
                type: ['alien', 'asteroid', 'ufo'][Math.floor(Math.random() * 3)],
                health: Math.floor(Math.random() * 3) + 1,
                speed: Math.floor(Math.random() * 150) + 50,
                pattern: ['straight', 'zigzag', 'circle'][Math.floor(Math.random() * 3)]
            }));
        }
        
        function generatePowerups(count) {
            return Array.from({ length: count }, (_, i) => ({
                type: ['shield', 'speed', 'multishot'][Math.floor(Math.random() * 3)],
                duration: Math.floor(Math.random() * 5) + 3
            }));
        }
        
        function generateNPCs(count) {
            return Array.from({ length: count }, (_, i) => ({
                name: ['Wizard', 'Merchant', 'Guard'][Math.floor(Math.random() * 3)],
                dialogue: [
                    'Hello adventurer!',
                    'Have you seen my lost treasure?',
                    'Beware of the dragon!'
                ][Math.floor(Math.random() * 3)],
                quest: Math.random() > 0.5
            }));
        }
        
        function generateAdventureItems(count) {
            return Array.from({ length: count }, (_, i) => ({
                name: ['Sword', 'Potion', 'Key', 'Map'][Math.floor(Math.random() * 4)],
                description: [
                    'A sharp blade for combat',
                    'Restores health when consumed',
                    'Opens locked doors',
                    'Shows hidden locations'
                ][Math.floor(Math.random() * 4)]
            }));
        }
        
        function generateTrack() {
            return {
                length: Math.floor(Math.random() * 5) + 3,
                turns: ['sharp', 'wide', 's-curve'][Math.floor(Math.random() * 3)],
                obstacles: Math.floor(Math.random() * 10)
            };
        }

        // Update UI based on current state
        function updateUI() {
            // Update generate button state
            generateBtn.disabled = !gamePrompt.value.trim() || !selectedScaffold;
        }

        // Initialize the app when DOM is loaded
        document.addEventListener('DOMContentLoaded', init);
        
        // Update UI when prompt changes
        gamePrompt.addEventListener('input', updateUI);
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=pysolver33/awesome-games" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>