Gomesy72 commited on
Commit
0cb16d6
·
verified ·
1 Parent(s): 9f97f24

Upload games.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. games.js +1230 -0
games.js ADDED
@@ -0,0 +1,1230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Retro Arcade - Game Engine
2
+ let currentGame = null;
3
+ let gameLoop = null;
4
+ let canvas, ctx;
5
+ let isMobile = false;
6
+
7
+ // Detect mobile
8
+ function checkMobile() {
9
+ return (('ontouchstart' in window) ||
10
+ (navigator.maxTouchPoints > 0) ||
11
+ (navigator.msMaxTouchPoints > 0));
12
+ }
13
+
14
+ function openGame(gameName) {
15
+ const modal = document.getElementById('gameModal');
16
+ const title = document.getElementById('gameTitle');
17
+ const instructions = document.getElementById('gameInstructions');
18
+
19
+ canvas = document.getElementById('gameCanvas');
20
+ ctx = canvas.getContext('2d');
21
+
22
+ isMobile = checkMobile();
23
+
24
+ // Set canvas size based on device
25
+ if (isMobile) {
26
+ canvas.width = Math.min(window.innerWidth - 40, 400);
27
+ canvas.height = Math.min(window.innerHeight - 300, 300);
28
+ } else {
29
+ canvas.width = 600;
30
+ canvas.height = 400;
31
+ }
32
+
33
+ modal.style.display = 'flex';
34
+ currentGame = gameName;
35
+
36
+ // Show/hide mobile controls
37
+ const dpad = document.getElementById('dpad');
38
+ const actionBtn = document.getElementById('actionButtons');
39
+ const memoryTouch = document.getElementById('memoryTouch');
40
+
41
+ if (isMobile) {
42
+ document.querySelector('.mobile-controls').style.display = 'block';
43
+
44
+ // Show appropriate controls for each game
45
+ switch(gameName) {
46
+ case 'snake':
47
+ case 'tetris':
48
+ dpad.style.display = 'flex';
49
+ actionBtn.style.display = 'none';
50
+ memoryTouch.style.display = 'none';
51
+ break;
52
+ case 'dino':
53
+ dpad.style.display = 'none';
54
+ actionBtn.style.display = 'flex';
55
+ memoryTouch.style.display = 'none';
56
+ document.getElementById('btnAction').textContent = 'JUMP';
57
+ break;
58
+ case 'invaders':
59
+ title.textContent = '👾 Space Invaders';
60
+ instructions.textContent = isMobile ? 'D-Pad to move, Action to shoot' : 'Arrow keys to move, Space to shoot';
61
+ dpad.style.display = 'flex';
62
+ actionBtn.style.display = 'flex';
63
+ memoryTouch.style.display = 'none';
64
+ document.getElementById('btnAction').textContent = 'SHOOT';
65
+ initInvaders();
66
+ break;
67
+ case 'memory':
68
+ default:
69
+ dpad.style.display = 'none';
70
+ actionBtn.style.display = 'none';
71
+ memoryTouch.style.display = 'none';
72
+ }
73
+ }
74
+
75
+ switch(gameName) {
76
+ case 'snake':
77
+ title.textContent = '🐍 Snake';
78
+ instructions.textContent = isMobile ? 'Use D-Pad to move. Eat food!' : 'Use arrow keys to move. Eat food to grow!';
79
+ initSnake();
80
+ break;
81
+ case 'tetris':
82
+ title.textContent = '🧱 Tetris';
83
+ instructions.textContent = isMobile ? 'D-Pad: Left/Right/Down, Up to rotate' : 'Arrow keys to move, Up to rotate';
84
+ initTetris();
85
+ break;
86
+ case 'pong':
87
+ title.textContent = '🏓 Pong';
88
+ instructions.textContent = isMobile ? 'Touch paddle to move' : 'Mouse or arrow keys to move paddle';
89
+ initPong();
90
+ break;
91
+ case 'breakout':
92
+ title.textContent = '🧱 Breakout';
93
+ instructions.textContent = isMobile ? 'Touch to move paddle' : 'Mouse or arrow keys to move paddle';
94
+ initBreakout();
95
+ break;
96
+ case 'dino':
97
+ title.textContent = '🦕 Chrome Dino';
98
+ instructions.textContent = isMobile ? 'Tap JUMP button or tap screen' : 'Space or Up arrow to jump';
99
+ initDino();
100
+ break;
101
+ case 'invaders':
102
+ title.textContent = '👾 Space Invaders';
103
+ instructions.textContent = isMobile ? 'D-Pad to move, Action to shoot' : 'Arrow keys to move, Space to shoot';
104
+ initInvaders();
105
+ break;
106
+ case 'memory':
107
+ title.textContent = '🃏 Memory Match';
108
+ instructions.textContent = 'Tap cards to flip them';
109
+ initMemory();
110
+ break;
111
+ }
112
+
113
+ // Setup mobile controls
114
+ if (isMobile) {
115
+ setupMobileControls(gameName);
116
+ }
117
+ }
118
+
119
+ function closeGame() {
120
+ // Stop any active game loops
121
+ if (gameLoop) {
122
+ if (currentGame === 'tetris') {
123
+ clearTimeout(gameLoop);
124
+ } else {
125
+ cancelAnimationFrame(gameLoop);
126
+ }
127
+ gameLoop = null;
128
+ }
129
+
130
+ // Remove all event listeners
131
+ document.removeEventListener('keydown', handleSnakeInput);
132
+ document.removeEventListener('keydown', handleTetrisInput);
133
+
134
+ // Remove canvas event listeners by cloning
135
+ const newCanvas = canvas.cloneNode(true);
136
+ canvas.parentNode.replaceChild(newCanvas, canvas);
137
+ canvas = newCanvas;
138
+ ctx = canvas.getContext('2d');
139
+
140
+ // Hide modal
141
+ document.getElementById('gameModal').style.display = 'none';
142
+ currentGame = null;
143
+ }
144
+
145
+ function resetGame() {
146
+ if (currentGame) {
147
+ // Store the current game name before closing
148
+ const gameToRestart = currentGame;
149
+ closeGame();
150
+ // Small delay to ensure cleanup completes
151
+ setTimeout(() => openGame(gameToRestart), 100);
152
+ }
153
+ }
154
+
155
+ // ==================== SNAKE GAME ====================
156
+ let snake, food, direction, score;
157
+
158
+ function initSnake() {
159
+ // Reset game state
160
+ snake = [{x: 10, y: 10}];
161
+ food = {x: 15, y: 15};
162
+ direction = {x: 1, y: 0};
163
+ score = 0;
164
+
165
+ // Clear previous loop if any
166
+ if (gameLoop) {
167
+ cancelAnimationFrame(gameLoop);
168
+ gameLoop = null;
169
+ }
170
+
171
+ snakeLoop();
172
+ }
173
+
174
+ function handleSnakeInput(e) {
175
+ if (!currentGame || currentGame !== 'snake') return;
176
+
177
+ switch(e.key) {
178
+ case 'ArrowUp': if (direction.y === 0) direction = {x: 0, y: -1}; break;
179
+ case 'ArrowDown': if (direction.y === 0) direction = {x: 0, y: 1}; break;
180
+ case 'ArrowLeft': if (direction.x === 0) direction = {x: -1, y: 0}; break;
181
+ case 'ArrowRight': if (direction.x === 0) direction = {x: 1, y: 0}; break;
182
+ }
183
+
184
+ // Prevent default scrolling
185
+ if(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)) {
186
+ e.preventDefault();
187
+ }
188
+ }
189
+
190
+ function snakeLoop() {
191
+ if (currentGame !== 'snake') return;
192
+
193
+ // Move snake
194
+ const head = {x: snake[0].x + direction.x, y: snake[0].y + direction.y};
195
+
196
+ // Check walls
197
+ if (head.x < 0 || head.x >= 30 || head.y < 0 || head.y >= 20) {
198
+ gameOver('Game Over! Score: ' + score);
199
+ return;
200
+ }
201
+
202
+ // Check self collision
203
+ for (let segment of snake) {
204
+ if (head.x === segment.x && head.y === segment.y) {
205
+ gameOver('Game Over! Score: ' + score);
206
+ return;
207
+ }
208
+ }
209
+
210
+ snake.unshift(head);
211
+
212
+ // Check food
213
+ if (head.x === food.x && head.y === food.y) {
214
+ score += 10;
215
+ food = {
216
+ x: Math.floor(Math.random() * 30),
217
+ y: Math.floor(Math.random() * 20)
218
+ };
219
+ } else {
220
+ snake.pop();
221
+ }
222
+
223
+ // Draw
224
+ ctx.fillStyle = '#000';
225
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
226
+
227
+ // Draw snake
228
+ ctx.fillStyle = '#00ff00';
229
+ for (let segment of snake) {
230
+ ctx.fillRect(segment.x * 20, segment.y * 20, 18, 18);
231
+ }
232
+
233
+ // Draw food
234
+ ctx.fillStyle = '#ff0000';
235
+ ctx.fillRect(food.x * 20, food.y * 20, 18, 18);
236
+
237
+ // Draw score
238
+ ctx.fillStyle = '#fff';
239
+ ctx.font = '20px Courier';
240
+ ctx.fillText('Score: ' + score, 10, 30);
241
+
242
+ gameLoop = requestAnimationFrame(() => setTimeout(snakeLoop, 100));
243
+ }
244
+
245
+ // ==================== PONG GAME ====================
246
+ let pongBall, pongPaddle, pongAI, pongScore;
247
+
248
+ function initPong() {
249
+ pongBall = {x: canvas.width/2, y: canvas.height/2, dx: 4, dy: 4, radius: 8};
250
+ pongPaddle = {y: canvas.height/2 - 40, height: 80, width: 10};
251
+ pongAI = {y: canvas.height/2 - 40, height: 80, width: 10};
252
+ pongScore = {player: 0, ai: 0};
253
+
254
+ // Clear previous loop if any
255
+ if (gameLoop) {
256
+ cancelAnimationFrame(gameLoop);
257
+ gameLoop = null;
258
+ }
259
+
260
+ // Mouse control
261
+ canvas.addEventListener('mousemove', (e) => {
262
+ if (currentGame !== 'pong') return;
263
+ const rect = canvas.getBoundingClientRect();
264
+ pongPaddle.y = e.clientY - rect.top - pongPaddle.height / 2;
265
+ });
266
+
267
+ // Touch control for mobile
268
+ canvas.addEventListener('touchmove', (e) => {
269
+ if (currentGame !== 'pong') return;
270
+ e.preventDefault();
271
+ const rect = canvas.getBoundingClientRect();
272
+ const touch = e.touches[0];
273
+ pongPaddle.y = touch.clientY - rect.top - pongPaddle.height / 2;
274
+ }, {passive: false});
275
+
276
+ pongLoop();
277
+ }
278
+
279
+ function pongLoop() {
280
+ if (currentGame !== 'pong') return;
281
+
282
+ // Move ball
283
+ pongBall.x += pongBall.dx;
284
+ pongBall.y += pongBall.dy;
285
+
286
+ // Bounce off top/bottom
287
+ if (pongBall.y - pongBall.radius < 0 || pongBall.y + pongBall.radius > canvas.height) {
288
+ pongBall.dy = -pongBall.dy;
289
+ }
290
+
291
+ // AI paddle movement
292
+ const aiCenter = pongAI.y + pongAI.height / 2;
293
+ if (aiCenter < pongBall.y - 10) pongAI.y += 3;
294
+ if (aiCenter > pongBall.y + 10) pongAI.y -= 3;
295
+
296
+ // Player collision
297
+ if (pongBall.x - pongBall.radius < pongPaddle.width &&
298
+ pongBall.y > pongPaddle.y && pongBall.y < pongPaddle.y + pongPaddle.height) {
299
+ pongBall.dx = -pongBall.dx * 1.1;
300
+ }
301
+
302
+ // AI collision
303
+ if (pongBall.x + pongBall.radius > canvas.width - pongAI.width &&
304
+ pongBall.y > pongAI.y && pongBall.y < pongAI.y + pongAI.height) {
305
+ pongBall.dx = -pongBall.dx * 1.1;
306
+ }
307
+
308
+ // Scoring
309
+ if (pongBall.x < 0) {
310
+ pongScore.ai++;
311
+ resetPongBall();
312
+ }
313
+ if (pongBall.x > canvas.width) {
314
+ pongScore.player++;
315
+ resetPongBall();
316
+ }
317
+
318
+ // Draw
319
+ ctx.fillStyle = '#000';
320
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
321
+
322
+ // Draw paddles
323
+ ctx.fillStyle = '#00ff00';
324
+ ctx.fillRect(0, pongPaddle.y, pongPaddle.width, pongPaddle.height);
325
+ ctx.fillRect(canvas.width - pongAI.width, pongAI.y, pongAI.width, pongAI.height);
326
+
327
+ // Draw ball
328
+ ctx.beginPath();
329
+ ctx.arc(pongBall.x, pongBall.y, pongBall.radius, 0, Math.PI * 2);
330
+ ctx.fillStyle = '#fff';
331
+ ctx.fill();
332
+
333
+ // Draw score
334
+ ctx.fillStyle = '#fff';
335
+ ctx.font = '30px Courier';
336
+ ctx.fillText(pongScore.player, canvas.width / 4, 50);
337
+ ctx.fillText(pongScore.ai, 3 * canvas.width / 4, 50);
338
+
339
+ gameLoop = requestAnimationFrame(pongLoop);
340
+ }
341
+
342
+ function resetPongBall() {
343
+ pongBall.x = canvas.width / 2;
344
+ pongBall.y = canvas.height / 2;
345
+ pongBall.dx = (Math.random() > 0.5 ? 4 : -4);
346
+ pongBall.dy = (Math.random() * 4 - 2);
347
+ }
348
+
349
+ // ==================== BREAKOUT GAME ====================
350
+ let breakoutBall, breakoutPaddle, breakoutBricks, breakoutScore;
351
+
352
+ function initBreakout() {
353
+ breakoutBall = {x: canvas.width/2, y: canvas.height/2, dx: 3, dy: -3, radius: 6};
354
+ breakoutPaddle = {x: canvas.width/2 - 50, y: canvas.height - 30, width: 100, height: 10};
355
+ breakoutScore = 0;
356
+
357
+ // Create bricks - responsive to canvas size
358
+ const brickCols = Math.floor(canvas.width / 60);
359
+ const brickWidth = (canvas.width - (brickCols + 1) * 5) / brickCols;
360
+ breakoutBricks = [];
361
+ for (let row = 0; row < 5; row++) {
362
+ for (let col = 0; col < brickCols; col++) {
363
+ breakoutBricks.push({
364
+ x: col * (brickWidth + 5) + 5,
365
+ y: row * 25 + 30,
366
+ width: brickWidth,
367
+ height: 20,
368
+ color: `hsl(${row * 60}, 100%, 50%)`,
369
+ alive: true
370
+ });
371
+ }
372
+ }
373
+
374
+ // Clear previous loop if any
375
+ if (gameLoop) {
376
+ cancelAnimationFrame(gameLoop);
377
+ gameLoop = null;
378
+ }
379
+
380
+ // Mouse control
381
+ canvas.addEventListener('mousemove', (e) => {
382
+ if (currentGame !== 'breakout') return;
383
+ const rect = canvas.getBoundingClientRect();
384
+ breakoutPaddle.x = e.clientX - rect.left - breakoutPaddle.width / 2;
385
+ });
386
+
387
+ // Touch control for mobile
388
+ canvas.addEventListener('touchmove', (e) => {
389
+ if (currentGame !== 'breakout') return;
390
+ e.preventDefault();
391
+ const rect = canvas.getBoundingClientRect();
392
+ const touch = e.touches[0];
393
+ breakoutPaddle.x = touch.clientX - rect.left - breakoutPaddle.width / 2;
394
+ }, {passive: false});
395
+
396
+ breakoutLoop();
397
+ }
398
+
399
+ function breakoutLoop() {
400
+ if (currentGame !== 'breakout') return;
401
+
402
+ // Move ball
403
+ breakoutBall.x += breakoutBall.dx;
404
+ breakoutBall.y += breakoutBall.dy;
405
+
406
+ // Wall collision
407
+ if (breakoutBall.x - breakoutBall.radius < 0 || breakoutBall.x + breakoutBall.radius > canvas.width) {
408
+ breakoutBall.dx = -breakoutBall.dx;
409
+ }
410
+ if (breakoutBall.y - breakoutBall.radius < 0) {
411
+ breakoutBall.dy = -breakoutBall.dy;
412
+ }
413
+
414
+ // Paddle collision
415
+ if (breakoutBall.y + breakoutBall.radius > breakoutPaddle.y &&
416
+ breakoutBall.x > breakoutPaddle.x && breakoutBall.x < breakoutPaddle.x + breakoutPaddle.width) {
417
+ breakoutBall.dy = -breakoutBall.dy;
418
+ }
419
+
420
+ // Brick collision
421
+ for (let brick of breakoutBricks) {
422
+ if (brick.alive &&
423
+ breakoutBall.x > brick.x && breakoutBall.x < brick.x + brick.width &&
424
+ breakoutBall.y > brick.y && breakoutBall.y < brick.y + brick.height) {
425
+ brick.alive = false;
426
+ breakoutBall.dy = -breakoutBall.dy;
427
+ breakoutScore += 10;
428
+ }
429
+ }
430
+
431
+ // Game over
432
+ if (breakoutBall.y > canvas.height) {
433
+ gameOver('Game Over! Score: ' + breakoutScore);
434
+ return;
435
+ }
436
+
437
+ // Win condition
438
+ if (breakoutBricks.every(b => !b.alive)) {
439
+ gameOver('You Win! Score: ' + breakoutScore);
440
+ return;
441
+ }
442
+
443
+ // Draw
444
+ ctx.fillStyle = '#000';
445
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
446
+
447
+ // Draw bricks
448
+ for (let brick of breakoutBricks) {
449
+ if (brick.alive) {
450
+ ctx.fillStyle = brick.color;
451
+ ctx.fillRect(brick.x, brick.y, brick.width, brick.height);
452
+ }
453
+ }
454
+
455
+ // Draw paddle
456
+ ctx.fillStyle = '#00ff00';
457
+ ctx.fillRect(breakoutPaddle.x, breakoutPaddle.y, breakoutPaddle.width, breakoutPaddle.height);
458
+
459
+ // Draw ball
460
+ ctx.beginPath();
461
+ ctx.arc(breakoutBall.x, breakoutBall.y, breakoutBall.radius, 0, Math.PI * 2);
462
+ ctx.fillStyle = '#fff';
463
+ ctx.fill();
464
+
465
+ // Draw score
466
+ ctx.fillStyle = '#fff';
467
+ ctx.font = '20px Courier';
468
+ ctx.fillText('Score: ' + breakoutScore, 10, 25);
469
+
470
+ gameLoop = requestAnimationFrame(breakoutLoop);
471
+ }
472
+
473
+ // ==================== MEMORY GAME ====================
474
+ let memoryCards, memoryFlipped, memoryMatched, memoryCanFlip;
475
+
476
+ function initMemory() {
477
+ const emojis = ['🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼'];
478
+ memoryCards = [...emojis, ...emojis].sort(() => Math.random() - 0.5);
479
+ memoryFlipped = [];
480
+ memoryMatched = 0;
481
+ memoryCanFlip = true;
482
+
483
+ // Responsive canvas for mobile
484
+ const cols = 4;
485
+ const rows = 4;
486
+ const cardSize = Math.min(80, (canvas.width - 50) / cols);
487
+ const padding = 10;
488
+
489
+ canvas.width = cols * (cardSize + padding) + padding;
490
+ canvas.height = rows * (cardSize + padding) + padding + 40;
491
+
492
+ // Clear previous event listeners by cloning
493
+ const newCanvas = canvas.cloneNode(true);
494
+ canvas.parentNode.replaceChild(newCanvas, canvas);
495
+ canvas = newCanvas;
496
+ ctx = canvas.getContext('2d');
497
+
498
+ canvas.addEventListener('click', handleMemoryClick);
499
+
500
+ // Touch support
501
+ canvas.addEventListener('touchstart', handleMemoryTouch, {passive: false});
502
+
503
+ drawMemory();
504
+ }
505
+
506
+ function handleMemoryClick(e) {
507
+ if (!memoryCanFlip || currentGame !== 'memory') return;
508
+
509
+ const rect = canvas.getBoundingClientRect();
510
+ const x = e.clientX - rect.left;
511
+ const y = e.clientY - rect.top;
512
+
513
+ processMemoryFlip(x, y);
514
+ }
515
+
516
+ function handleMemoryTouch(e) {
517
+ if (!memoryCanFlip || currentGame !== 'memory') return;
518
+ e.preventDefault();
519
+
520
+ const rect = canvas.getBoundingClientRect();
521
+ const touch = e.touches[0];
522
+ const x = touch.clientX - rect.left;
523
+ const y = touch.clientY - rect.top;
524
+
525
+ processMemoryFlip(x, y);
526
+ }
527
+
528
+ function processMemoryFlip(x, y) {
529
+ const cols = 4;
530
+ const cardSize = Math.min(80, (canvas.width - 50) / cols);
531
+ const padding = 10;
532
+
533
+ const col = Math.floor((x - padding) / (cardSize + padding));
534
+ const row = Math.floor((y - padding) / (cardSize + padding));
535
+ const index = row * 4 + col;
536
+
537
+ if (index < 0 || index >= 16) return;
538
+ if (memoryFlipped.includes(index) || memoryCards[index] === null) return;
539
+
540
+ memoryFlipped.push(index);
541
+ drawMemory();
542
+
543
+ if (memoryFlipped.length === 2) {
544
+ memoryCanFlip = false;
545
+ const [first, second] = memoryFlipped;
546
+
547
+ if (memoryCards[first] === memoryCards[second]) {
548
+ memoryCards[first] = null;
549
+ memoryCards[second] = null;
550
+ memoryMatched += 2;
551
+ memoryFlipped = [];
552
+ memoryCanFlip = true;
553
+
554
+ if (memoryMatched === 16) {
555
+ setTimeout(() => gameOver('You Win! All pairs matched!'), 500);
556
+ }
557
+ } else {
558
+ setTimeout(() => {
559
+ memoryFlipped = [];
560
+ memoryCanFlip = true;
561
+ drawMemory();
562
+ }, 1000);
563
+ }
564
+ }
565
+ }
566
+
567
+ function drawMemory() {
568
+ const cols = 4;
569
+ const cardSize = Math.min(80, (canvas.width - 50) / cols);
570
+ const padding = 10;
571
+
572
+ ctx.fillStyle = '#2c3e50';
573
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
574
+
575
+ for (let i = 0; i < 16; i++) {
576
+ const row = Math.floor(i / 4);
577
+ const col = i % 4;
578
+ const x = col * (cardSize + padding) + padding;
579
+ const y = row * (cardSize + padding) + padding;
580
+
581
+ if (memoryCards[i] === null) {
582
+ ctx.fillStyle = '#27ae60';
583
+ ctx.fillRect(x, y, cardSize, cardSize);
584
+ } else if (memoryFlipped.includes(i)) {
585
+ ctx.fillStyle = '#ecf0f1';
586
+ ctx.fillRect(x, y, cardSize, cardSize);
587
+ ctx.fillStyle = '#2c3e50';
588
+ ctx.font = `${cardSize * 0.6}px Arial`;
589
+ ctx.textAlign = 'center';
590
+ ctx.textBaseline = 'middle';
591
+ ctx.fillText(memoryCards[i], x + cardSize/2, y + cardSize/2);
592
+ } else {
593
+ ctx.fillStyle = '#3498db';
594
+ ctx.fillRect(x, y, cardSize, cardSize);
595
+ ctx.fillStyle = '#2980b9';
596
+ ctx.fillRect(x + 5, y + 5, cardSize - 10, cardSize - 10);
597
+ }
598
+ }
599
+
600
+ // Draw score
601
+ ctx.fillStyle = '#ecf0f1';
602
+ ctx.font = '16px Arial';
603
+ ctx.textAlign = 'left';
604
+ ctx.fillText(`Matched: ${memoryMatched/2}/8`, 10, canvas.height - 10);
605
+ }
606
+
607
+ // ==================== TETRIS GAME ====================
608
+ let tetrisBoard, tetrisPiece, tetrisScore;
609
+
610
+ const TETRIS_SHAPES = [
611
+ [[1,1,1,1]], // I
612
+ [[1,1],[1,1]], // O
613
+ [[1,1,1],[0,1,0]], // T
614
+ [[1,1,1],[1,0,0]], // L
615
+ [[1,1,1],[0,0,1]], // J
616
+ [[0,1,1],[1,1,0]], // S
617
+ [[1,1,0],[0,1,1]] // Z
618
+ ];
619
+
620
+ function initTetris() {
621
+ tetrisBoard = Array(20).fill().map(() => Array(10).fill(0));
622
+ tetrisScore = 0;
623
+ newTetrisPiece();
624
+
625
+ // Clear previous loop if any
626
+ if (gameLoop) {
627
+ clearTimeout(gameLoop);
628
+ gameLoop = null;
629
+ }
630
+
631
+ tetrisLoop();
632
+ }
633
+
634
+ function newTetrisPiece() {
635
+ const shape = TETRIS_SHAPES[Math.floor(Math.random() * TETRIS_SHAPES.length)];
636
+ tetrisPiece = {
637
+ shape: shape,
638
+ x: 4,
639
+ y: 0,
640
+ color: `hsl(${Math.random() * 360}, 100%, 50%)`
641
+ };
642
+ }
643
+
644
+ function handleTetrisInput(e) {
645
+ if (!currentGame || currentGame !== 'tetris') return;
646
+
647
+ switch(e.key) {
648
+ case 'ArrowLeft': moveTetris(-1, 0); break;
649
+ case 'ArrowRight': moveTetris(1, 0); break;
650
+ case 'ArrowDown': moveTetris(0, 1); break;
651
+ case 'ArrowUp': rotateTetris(); break;
652
+ }
653
+
654
+ // Prevent default scrolling
655
+ if(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)) {
656
+ e.preventDefault();
657
+ }
658
+ }
659
+
660
+ function moveTetris(dx, dy) {
661
+ tetrisPiece.x += dx;
662
+ tetrisPiece.y += dy;
663
+
664
+ if (collision()) {
665
+ tetrisPiece.x -= dx;
666
+ tetrisPiece.y -= dy;
667
+
668
+ if (dy > 0) {
669
+ mergePiece();
670
+ clearLines();
671
+ newTetrisPiece();
672
+ if (collision()) {
673
+ gameOver('Game Over! Score: ' + tetrisScore);
674
+ }
675
+ }
676
+ }
677
+ }
678
+
679
+ function rotateTetris() {
680
+ const rotated = tetrisPiece.shape[0].map((_, i) =>
681
+ tetrisPiece.shape.map(row => row[i]).reverse()
682
+ );
683
+ const oldShape = tetrisPiece.shape;
684
+ tetrisPiece.shape = rotated;
685
+
686
+ if (collision()) {
687
+ tetrisPiece.shape = oldShape;
688
+ }
689
+ }
690
+
691
+ function collision() {
692
+ for (let y = 0; y < tetrisPiece.shape.length; y++) {
693
+ for (let x = 0; x < tetrisPiece.shape[y].length; x++) {
694
+ if (tetrisPiece.shape[y][x]) {
695
+ const boardX = tetrisPiece.x + x;
696
+ const boardY = tetrisPiece.y + y;
697
+
698
+ if (boardX < 0 || boardX >= 10 || boardY >= 20) return true;
699
+ if (boardY >= 0 && tetrisBoard[boardY][boardX]) return true;
700
+ }
701
+ }
702
+ }
703
+ return false;
704
+ }
705
+
706
+ function mergePiece() {
707
+ for (let y = 0; y < tetrisPiece.shape.length; y++) {
708
+ for (let x = 0; x < tetrisPiece.shape[y].length; x++) {
709
+ if (tetrisPiece.shape[y][x]) {
710
+ const boardY = tetrisPiece.y + y;
711
+ if (boardY >= 0) {
712
+ tetrisBoard[boardY][tetrisPiece.x + x] = tetrisPiece.color;
713
+ }
714
+ }
715
+ }
716
+ }
717
+ }
718
+
719
+ function clearLines() {
720
+ for (let y = tetrisBoard.length - 1; y >= 0; y--) {
721
+ if (tetrisBoard[y].every(cell => cell !== 0)) {
722
+ tetrisBoard.splice(y, 1);
723
+ tetrisBoard.unshift(Array(10).fill(0));
724
+ tetrisScore += 100;
725
+ }
726
+ }
727
+ }
728
+
729
+ function tetrisLoop() {
730
+ if (currentGame !== 'tetris') return;
731
+
732
+ // Auto-move down
733
+ if (!tetrisPiece) newTetrisPiece();
734
+ moveTetris(0, 1);
735
+
736
+ // Draw
737
+ ctx.fillStyle = '#000';
738
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
739
+
740
+ // Draw board
741
+ for (let y = 0; y < 20; y++) {
742
+ for (let x = 0; x < 10; x++) {
743
+ if (tetrisBoard[y][x]) {
744
+ ctx.fillStyle = tetrisBoard[y][x];
745
+ ctx.fillRect(x * 30, y * 20, 29, 19);
746
+ }
747
+ }
748
+ }
749
+
750
+ // Draw piece
751
+ ctx.fillStyle = tetrisPiece.color;
752
+ for (let y = 0; y < tetrisPiece.shape.length; y++) {
753
+ for (let x = 0; x < tetrisPiece.shape[y].length; x++) {
754
+ if (tetrisPiece.shape[y][x]) {
755
+ ctx.fillRect((tetrisPiece.x + x) * 30, (tetrisPiece.y + y) * 20, 29, 19);
756
+ }
757
+ }
758
+ }
759
+
760
+ // Draw score
761
+ ctx.fillStyle = '#fff';
762
+ ctx.font = '20px Courier';
763
+ ctx.fillText('Score: ' + tetrisScore, 10, 30);
764
+
765
+ gameLoop = setTimeout(() => requestAnimationFrame(tetrisLoop), 500);
766
+ }
767
+
768
+ // ==================== CHROME DINO GAME ====================
769
+ let dino, dinoObstacles, dinoScore, dinoJumping, dinoGravity;
770
+
771
+ function initDino() {
772
+ dino = {x: 50, y: canvas.height - 50, width: 30, height: 40, jumpVelocity: 0};
773
+ dinoObstacles = [];
774
+ dinoScore = 0;
775
+ dinoJumping = false;
776
+ dinoGravity = 0.8;
777
+ groundY = canvas.height - 10;
778
+
779
+ // Clear previous loop if any
780
+ if (gameLoop) {
781
+ cancelAnimationFrame(gameLoop);
782
+ gameLoop = null;
783
+ }
784
+
785
+ // Keyboard controls
786
+ document.addEventListener('keydown', (e) => {
787
+ if (currentGame !== 'dino') return;
788
+ if ((e.code === 'Space' || e.code === 'ArrowUp') && !dinoJumping) {
789
+ dinoJumping = true;
790
+ dino.jumpVelocity = -15;
791
+ e.preventDefault();
792
+ }
793
+ });
794
+
795
+ // Touch controls for mobile
796
+ canvas.addEventListener('touchstart', (e) => {
797
+ if (currentGame !== 'dino') return;
798
+ e.preventDefault();
799
+ if (!dinoJumping) {
800
+ dinoJumping = true;
801
+ dino.jumpVelocity = -15;
802
+ }
803
+ }, {passive: false});
804
+
805
+ dinoLoop();
806
+ }
807
+
808
+ function dinoLoop() {
809
+ if (currentGame !== 'dino') return;
810
+
811
+ // Update dino
812
+ if (dinoJumping) {
813
+ dino.y += dino.jumpVelocity;
814
+ dino.jumpVelocity += dinoGravity;
815
+
816
+ if (dino.y >= groundY - dino.height) {
817
+ dino.y = groundY - dino.height;
818
+ dinoJumping = false;
819
+ dino.jumpVelocity = 0;
820
+ }
821
+ }
822
+
823
+ // Spawn obstacles
824
+ if (Math.random() < 0.02) {
825
+ dinoObstacles.push({
826
+ x: canvas.width,
827
+ y: groundY - 30 - Math.random() * 30,
828
+ width: 20 + Math.random() * 20,
829
+ height: 30 + Math.random() * 30
830
+ });
831
+ }
832
+
833
+ // Move obstacles
834
+ for (let obs of dinoObstacles) {
835
+ obs.x -= 6;
836
+ }
837
+
838
+ // Remove off-screen
839
+ dinoObstacles = dinoObstacles.filter(obs => obs.x + obs.width > 0);
840
+
841
+ // Check collision
842
+ for (let obs of dinoObstacles) {
843
+ if (dino.x < obs.x + obs.width &&
844
+ dino.x + dino.width > obs.x &&
845
+ dino.y < obs.y + obs.height &&
846
+ dino.y + dino.height > obs.y) {
847
+ gameOver('Game Over! Score: ' + Math.floor(dinoScore));
848
+ return;
849
+ }
850
+ }
851
+
852
+ dinoScore += 0.1;
853
+
854
+ // Draw
855
+ ctx.fillStyle = '#f7f7f7';
856
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
857
+
858
+ // Draw ground
859
+ ctx.fillStyle = '#535353';
860
+ ctx.fillRect(0, groundY, canvas.width, 10);
861
+
862
+ // Draw dino
863
+ ctx.fillStyle = '#535353';
864
+ ctx.fillRect(dino.x, dino.y, dino.width, dino.height);
865
+
866
+ // Draw obstacles
867
+ for (let obs of dinoObstacles) {
868
+ ctx.fillRect(obs.x, obs.y, obs.width, obs.height);
869
+ }
870
+
871
+ // Draw score
872
+ ctx.fillStyle = '#535353';
873
+ ctx.font = '20px Courier';
874
+ ctx.fillText('Score: ' + Math.floor(dinoScore), 10, 30);
875
+
876
+ gameLoop = requestAnimationFrame(dinoLoop);
877
+ }
878
+
879
+ // Add keyup handler for smooth movement
880
+ let invadersPlayer = {x: 0, y: 0, width: 30, height: 20, dx: 0};
881
+ let invadersBullets = [];
882
+ let invadersAliens = [];
883
+ let invadersScore = 0;
884
+ let invadersDirection = 1; // 1 for right, -1 for left
885
+ let invadersMoveDown = false;
886
+
887
+ function shootBullet() {
888
+ if (!currentGame || currentGame !== 'invaders') return;
889
+ invadersBullets.push({
890
+ x: invadersPlayer.x + invadersPlayer.width / 2,
891
+ y: invadersPlayer.y,
892
+ dy: -5
893
+ });
894
+ }
895
+
896
+ function initInvaders() {
897
+ // Reset game state
898
+ invadersPlayer = {
899
+ x: canvas.width / 2 - 15,
900
+ y: canvas.height - 30,
901
+ width: 30,
902
+ height: 20,
903
+ dx: 0
904
+ };
905
+ invadersBullets = [];
906
+ invadersScore = 0;
907
+ invadersDirection = 1;
908
+ invadersMoveDown = false;
909
+
910
+ // Create alien grid
911
+ invadersAliens = [];
912
+ const rows = 4;
913
+ const cols = 8;
914
+ const alienWidth = 25;
915
+ const alienHeight = 20;
916
+ const padding = 10;
917
+
918
+ for (let row = 0; row < rows; row++) {
919
+ for (let col = 0; col < cols; col++) {
920
+ invadersAliens.push({
921
+ x: col * (alienWidth + padding) + 20,
922
+ y: row * (alienHeight + padding) + 30,
923
+ width: alienWidth,
924
+ height: alienHeight,
925
+ alive: true,
926
+ color: `hsl(${row * 90 + 120}, 100%, 60%)`
927
+ });
928
+ }
929
+ }
930
+
931
+ // Clear previous loop if any
932
+ if (gameLoop) {
933
+ cancelAnimationFrame(gameLoop);
934
+ gameLoop = null;
935
+ }
936
+
937
+ invadersLoop();
938
+ }
939
+
940
+ function invadersLoop() {
941
+ if (currentGame !== 'invaders') return;
942
+
943
+ // Move player
944
+ invadersPlayer.x += invadersPlayer.dx;
945
+
946
+ // Keep player on screen
947
+ if (invadersPlayer.x < 0) invadersPlayer.x = 0;
948
+ if (invadersPlayer.x > canvas.width - invadersPlayer.width) invadersPlayer.x = canvas.width - invadersPlayer.width;
949
+
950
+ // Move bullets
951
+ for (let bullet of invadersBullets) {
952
+ bullet.y += bullet.dy;
953
+ }
954
+
955
+ // Remove off-screen bullets
956
+ invadersBullets = invadersBullets.filter(bullet => bullet.y > 0);
957
+
958
+ // Check bullet-alien collisions
959
+ for (let bullet of invadersBullets) {
960
+ for (let alien of invadersAliens) {
961
+ if (alien.alive &&
962
+ bullet.x > alien.x && bullet.x < alien.x + alien.width &&
963
+ bullet.y > alien.y && bullet.y < alien.y + alien.height) {
964
+ alien.alive = false;
965
+ invadersScore += 10;
966
+ }
967
+ }
968
+ }
969
+
970
+ // Check win condition
971
+ if (invadersAliens.every(alien => !alien.alive)) {
972
+ gameOver('Victory! Score: ' + invadersScore);
973
+ return;
974
+ }
975
+
976
+ // Move aliens - check if any hit the edge
977
+ let hitEdge = false;
978
+ let rightmostX = 0;
979
+ let leftmostX = canvas.width;
980
+
981
+ // Find edges of alive aliens
982
+ for (let alien of invadersAliens) {
983
+ if (alien.alive) {
984
+ if (alien.x + alien.width > rightmostX) rightmostX = alien.x + alien.width;
985
+ if (alien.x < leftmostX) leftmostX = alien.x;
986
+ }
987
+ }
988
+
989
+ // Debug log
990
+ console.log('Direction:', invadersDirection, 'Rightmost:', rightmostX, 'Leftmost:', leftmostX, 'Canvas:', canvas.width);
991
+
992
+ // Check if aliens should move down and reverse
993
+ // Use >= for right edge, <= for left edge with margin
994
+ const margin = 5; // Safety margin
995
+ if (invadersDirection === 1 && rightmostX + margin >= canvas.width) {
996
+ console.log('Hit right edge! Reversing to left.');
997
+ invadersDirection = -1;
998
+ hitEdge = true;
999
+ } else if (invadersDirection === -1 && leftmostX - margin <= 0) {
1000
+ console.log('Hit left edge! Reversing to right.');
1001
+ invadersDirection = 1;
1002
+ hitEdge = true;
1003
+ }
1004
+
1005
+ // If hit edge, move down
1006
+ if (hitEdge) {
1007
+ for (let alien of invadersAliens) {
1008
+ if (alien.alive) {
1009
+ alien.y += 15; // Move down more
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ // Move all aliens horizontally
1015
+ for (let alien of invadersAliens) {
1016
+ if (alien.alive) {
1017
+ alien.x += invadersDirection * 3; // Move faster
1018
+ }
1019
+ }
1020
+
1021
+ // Check game over (aliens reach bottom)
1022
+ for (let alien of invadersAliens) {
1023
+ if (alien.alive && alien.y + alien.height >= invadersPlayer.y) {
1024
+ gameOver('Game Over! Aliens reached Earth! Score: ' + invadersScore);
1025
+ return;
1026
+ }
1027
+ }
1028
+
1029
+ // Draw
1030
+ ctx.fillStyle = '#000';
1031
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
1032
+
1033
+ // Draw stars background
1034
+ ctx.fillStyle = '#fff';
1035
+ for (let i = 0; i < 20; i++) {
1036
+ const x = (i * 37 + invadersScore) % canvas.width;
1037
+ const y = (i * 23) % canvas.height;
1038
+ ctx.fillRect(x, y, 2, 2);
1039
+ }
1040
+
1041
+ // Draw aliens
1042
+ for (let alien of invadersAliens) {
1043
+ if (alien.alive) {
1044
+ ctx.fillStyle = alien.color;
1045
+ ctx.fillRect(alien.x, alien.y, alien.width, alien.height);
1046
+ // Draw alien eyes
1047
+ ctx.fillStyle = '#000';
1048
+ ctx.fillRect(alien.x + 5, alien.y + 5, 4, 4);
1049
+ ctx.fillRect(alien.x + alien.width - 9, alien.y + 5, 4, 4);
1050
+ }
1051
+ }
1052
+
1053
+ // Draw player
1054
+ ctx.fillStyle = '#00ff00';
1055
+ ctx.fillRect(invadersPlayer.x, invadersPlayer.y, invadersPlayer.width, invadersPlayer.height);
1056
+ // Player cannon
1057
+ ctx.fillRect(invadersPlayer.x + 12, invadersPlayer.y - 5, 6, 5);
1058
+
1059
+ // Draw bullets
1060
+ ctx.fillStyle = '#ff0';
1061
+ for (let bullet of invadersBullets) {
1062
+ ctx.fillRect(bullet.x - 1, bullet.y, 2, 5);
1063
+ }
1064
+
1065
+ // Draw score
1066
+ ctx.fillStyle = '#fff';
1067
+ ctx.font = '20px Courier';
1068
+ ctx.fillText('Score: ' + invadersScore, 10, 25);
1069
+
1070
+ gameLoop = requestAnimationFrame(invadersLoop);
1071
+ }
1072
+
1073
+ // ==================== GAME OVER ====================
1074
+ function gameOver(message) {
1075
+ // Stop game loop but keep currentGame active for restart
1076
+ if (gameLoop) {
1077
+ if (currentGame === 'tetris') {
1078
+ clearTimeout(gameLoop);
1079
+ } else {
1080
+ cancelAnimationFrame(gameLoop);
1081
+ }
1082
+ gameLoop = null;
1083
+ }
1084
+
1085
+ // Draw game over screen
1086
+ ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
1087
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
1088
+
1089
+ ctx.fillStyle = '#fff';
1090
+ ctx.font = '24px Courier';
1091
+ ctx.textAlign = 'center';
1092
+ ctx.textBaseline = 'middle';
1093
+ ctx.fillText(message, canvas.width / 2, canvas.height / 2 - 20);
1094
+
1095
+ ctx.font = '16px Courier';
1096
+ ctx.fillText('Tap Restart button below', canvas.width / 2, canvas.height / 2 + 20);
1097
+
1098
+ ctx.textAlign = 'left';
1099
+ ctx.textBaseline = 'alphabetic';
1100
+ }
1101
+
1102
+ // Mobile control handlers
1103
+ function setupMobileControls(gameName) {
1104
+ // D-Pad buttons
1105
+ const btnUp = document.getElementById('btnUp');
1106
+ const btnDown = document.getElementById('btnDown');
1107
+ const btnLeft = document.getElementById('btnLeft');
1108
+ const btnRight = document.getElementById('btnRight');
1109
+ const btnAction = document.getElementById('btnAction');
1110
+
1111
+ // Remove old listeners
1112
+ const newBtnUp = btnUp.cloneNode(true);
1113
+ const newBtnDown = btnDown.cloneNode(true);
1114
+ const newBtnLeft = btnLeft.cloneNode(true);
1115
+ const newBtnRight = btnRight.cloneNode(true);
1116
+ const newBtnAction = btnAction.cloneNode(true);
1117
+
1118
+ btnUp.parentNode.replaceChild(newBtnUp, btnUp);
1119
+ btnDown.parentNode.replaceChild(newBtnDown, btnDown);
1120
+ btnLeft.parentNode.replaceChild(newBtnLeft, btnLeft);
1121
+ btnRight.parentNode.replaceChild(newBtnRight, btnRight);
1122
+ btnAction.parentNode.replaceChild(newBtnAction, btnAction);
1123
+
1124
+ // Add touch handlers
1125
+ if (gameName === 'snake') {
1126
+ newBtnUp.addEventListener('touchstart', (e) => { e.preventDefault(); if (direction.y === 0) direction = {x: 0, y: -1}; });
1127
+ newBtnDown.addEventListener('touchstart', (e) => { e.preventDefault(); if (direction.y === 0) direction = {x: 0, y: 1}; });
1128
+ newBtnLeft.addEventListener('touchstart', (e) => { e.preventDefault(); if (direction.x === 0) direction = {x: -1, y: 0}; });
1129
+ newBtnRight.addEventListener('touchstart', (e) => { e.preventDefault(); if (direction.x === 0) direction = {x: 1, y: 0}; });
1130
+ } else if (gameName === 'tetris') {
1131
+ newBtnUp.addEventListener('touchstart', (e) => { e.preventDefault(); rotateTetris(); });
1132
+ newBtnDown.addEventListener('touchstart', (e) => { e.preventDefault(); moveTetris(0, 1); });
1133
+ newBtnLeft.addEventListener('touchstart', (e) => { e.preventDefault(); moveTetris(-1, 0); });
1134
+ newBtnRight.addEventListener('touchstart', (e) => { e.preventDefault(); moveTetris(1, 0); });
1135
+
1136
+ // Hold down for repeated movement
1137
+ let moveInterval;
1138
+ newBtnDown.addEventListener('touchstart', (e) => {
1139
+ e.preventDefault();
1140
+ moveInterval = setInterval(() => moveTetris(0, 1), 100);
1141
+ });
1142
+ newBtnDown.addEventListener('touchend', () => clearInterval(moveInterval));
1143
+ } else if (gameName === 'invaders') {
1144
+ // Space Invaders controls
1145
+ newBtnLeft.addEventListener('touchstart', (e) => { e.preventDefault(); invadersPlayer.dx = -3; });
1146
+ newBtnLeft.addEventListener('touchend', (e) => { e.preventDefault(); if (invadersPlayer.dx < 0) invadersPlayer.dx = 0; });
1147
+ newBtnRight.addEventListener('touchstart', (e) => { e.preventDefault(); invadersPlayer.dx = 3; });
1148
+ newBtnRight.addEventListener('touchend', (e) => { e.preventDefault(); if (invadersPlayer.dx > 0) invadersPlayer.dx = 0; });
1149
+ newBtnUp.style.display = 'none';
1150
+ newBtnDown.style.display = 'none';
1151
+
1152
+ // Shoot button
1153
+ newBtnAction.addEventListener('touchstart', (e) => {
1154
+ e.preventDefault();
1155
+ shootBullet();
1156
+ });
1157
+ } else if (gameName === 'dino') {
1158
+ newBtnAction.addEventListener('touchstart', (e) => {
1159
+ e.preventDefault();
1160
+ if (!dinoJumping) {
1161
+ dinoJumping = true;
1162
+ dino.jumpVelocity = -15;
1163
+ }
1164
+ });
1165
+
1166
+ // Also allow tap on canvas to jump
1167
+ canvas.addEventListener('touchstart', (e) => {
1168
+ e.preventDefault();
1169
+ if (!dinoJumping) {
1170
+ dinoJumping = true;
1171
+ dino.jumpVelocity = -15;
1172
+ }
1173
+ });
1174
+ }
1175
+ }
1176
+
1177
+ // Global keyboard event listener
1178
+ document.addEventListener('keydown', (e) => {
1179
+ if (!currentGame) return;
1180
+
1181
+ switch(currentGame) {
1182
+ case 'snake':
1183
+ handleSnakeInput(e);
1184
+ break;
1185
+ case 'tetris':
1186
+ handleTetrisInput(e);
1187
+ break;
1188
+ case 'dino':
1189
+ if ((e.code === 'Space' || e.code === 'ArrowUp') && !dinoJumping) {
1190
+ dinoJumping = true;
1191
+ dino.jumpVelocity = -15;
1192
+ e.preventDefault();
1193
+ }
1194
+ break;
1195
+ case 'invaders':
1196
+ if (e.code === 'Space' || e.code === 'ArrowUp') {
1197
+ shootBullet();
1198
+ e.preventDefault();
1199
+ } else if (e.code === 'ArrowLeft') {
1200
+ invadersPlayer.dx = -3;
1201
+ } else if (e.code === 'ArrowRight') {
1202
+ invadersPlayer.dx = 3;
1203
+ }
1204
+ break;
1205
+ }
1206
+ });
1207
+
1208
+ // Add keyup handler for smooth movement
1209
+ document.addEventListener('keyup', (e) => {
1210
+ if (currentGame === 'invaders') {
1211
+ if (e.code === 'ArrowLeft' || e.code === 'ArrowRight') {
1212
+ invadersPlayer.dx = 0;
1213
+ }
1214
+ }
1215
+ });
1216
+
1217
+ // Prevent context menu on long press
1218
+ document.addEventListener('contextmenu', function(event) {
1219
+ if (event.target.tagName === 'CANVAS' || event.target.tagName === 'BUTTON') {
1220
+ event.preventDefault();
1221
+ }
1222
+ });
1223
+
1224
+ // Close modal when clicking outside
1225
+ window.onclick = function(event) {
1226
+ const modal = document.getElementById('gameModal');
1227
+ if (event.target === modal) {
1228
+ closeGame();
1229
+ }
1230
+ }