Repository navigation
Expand file tree
/
Copy pathgame.js
More file actions
797 lines (664 loc) · 26.3 KB
/
Copy pathgame.js
File metadata and controls
797 lines (664 loc) · 26.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
// AI Snake Game - Enhanced Implementation
class GameEngine {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.gridSize = 20;
this.gameState = 'menu'; // menu, playing, paused, gameOver
// Game entities
this.playerSnake = new PlayerSnake(100, 100, '#00ff88');
this.aiSnake = new AISnake(600, 400, '#ff4757');
this.food = [];
this.particles = [];
this.powerUps = [];
// Game stats
this.playerScore = 0;
this.aiScore = 0;
this.gameLevel = 1;
this.powerUpTimer = 0;
// Performance tracking
this.lastTime = 0;
this.gameSpeed = 150; // ms between moves
this.lastMove = 0;
// Sentiment Analysis
this.sentimentEngine = new SentimentEngine();
this.playerActions = [];
this.gameStartTime = Date.now();
// Visual effects
this.screenShake = { x: 0, y: 0, intensity: 0 };
this.backgroundHue = 0;
this.setupEventListeners();
this.spawnFood();
this.gameLoop();
}
setupEventListeners() {
// Keyboard controls with sentiment tracking
document.addEventListener('keydown', (e) => {
if (this.gameState === 'playing') {
this.playerSnake.handleInput(e.key);
this.sentimentEngine.recordAction('input', Date.now());
}
if (e.key === ' ') {
this.togglePause();
}
});
// UI controls
document.getElementById('startBtn').addEventListener('click', () => {
this.startGame();
});
document.getElementById('pauseBtn').addEventListener('click', () => {
this.togglePause();
});
}
startGame() {
this.gameState = 'playing';
this.playerScore = 0;
this.aiScore = 0;
this.updateScore();
// Reset snakes
this.playerSnake.reset(100, 100);
this.aiSnake.reset(600, 400);
this.spawnFood();
}
togglePause() {
if (this.gameState === 'playing') {
this.gameState = 'paused';
} else if (this.gameState === 'paused') {
this.gameState = 'playing';
}
}
spawnFood() {
const x = Math.floor(Math.random() * (this.canvas.width / this.gridSize)) * this.gridSize;
const y = Math.floor(Math.random() * (this.canvas.height / this.gridSize)) * this.gridSize;
// Ensure food doesn't spawn on snakes
const onSnake = this.playerSnake.segments.some(seg => seg.x === x && seg.y === y) ||
this.aiSnake.segments.some(seg => seg.x === x && seg.y === y);
if (!onSnake) {
this.food.push(new Food(x, y));
} else {
this.spawnFood(); // Try again
}
}
update(deltaTime) {
if (this.gameState !== 'playing') return;
// Update sentiment analysis
this.sentimentEngine.update(this.playerScore, this.aiScore, deltaTime);
const sentiment = this.sentimentEngine.getCurrentSentiment();
// Adjust game based on sentiment
this.adaptToSentiment(sentiment);
// Update particles
this.updateParticles();
// Update screen shake
this.updateScreenShake();
// Move snakes at controlled speed
if (deltaTime - this.lastMove > this.gameSpeed) {
this.playerSnake.move();
this.aiSnake.move(this.food, [this.playerSnake]);
this.lastMove = deltaTime;
// Check collisions
this.checkCollisions();
}
// Update background animation
this.backgroundHue += 0.5;
if (this.backgroundHue > 360) this.backgroundHue = 0;
}
checkCollisions() {
// Player snake collisions
this.checkSnakeCollisions(this.playerSnake, true);
this.checkSnakeCollisions(this.aiSnake, false);
// Food collisions
this.checkFoodCollisions();
}
checkSnakeCollisions(snake, isPlayer) {
const head = snake.segments[0];
// Wall collisions
if (head.x < 0 || head.x >= this.canvas.width ||
head.y < 0 || head.y >= this.canvas.height) {
this.gameOver(isPlayer ? 'AI Wins!' : 'Player Wins!');
return;
}
// Self collision
for (let i = 1; i < snake.segments.length; i++) {
if (head.x === snake.segments[i].x && head.y === snake.segments[i].y) {
this.gameOver(isPlayer ? 'AI Wins!' : 'Player Wins!');
return;
}
}
// Snake vs snake collision
const otherSnake = isPlayer ? this.aiSnake : this.playerSnake;
for (let segment of otherSnake.segments) {
if (head.x === segment.x && head.y === segment.y) {
this.gameOver(isPlayer ? 'AI Wins!' : 'Player Wins!');
return;
}
}
}
checkFoodCollisions() {
this.food = this.food.filter(food => {
// Player food collision
if (this.playerSnake.segments[0].x === food.x &&
this.playerSnake.segments[0].y === food.y) {
this.playerSnake.grow();
this.playerScore += 10;
this.updateScore();
this.spawnFood();
this.createParticleEffect(food.x, food.y, '#00ff88');
return false;
}
// AI food collision
if (this.aiSnake.segments[0].x === food.x &&
this.aiSnake.segments[0].y === food.y) {
this.aiSnake.grow();
this.aiScore += 10;
this.updateScore();
this.spawnFood();
this.createParticleEffect(food.x, food.y, '#ff4757');
return false;
}
return true;
});
}
createParticleEffect(x, y, color) {
// Enhanced particle system
for (let i = 0; i < 12; i++) {
const angle = (Math.PI * 2 * i) / 12;
const speed = 3 + Math.random() * 4;
this.particles.push({
x: x + this.gridSize / 2,
y: y + this.gridSize / 2,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed,
life: 60,
maxLife: 60,
color: color,
size: 3 + Math.random() * 3
});
}
// Screen shake on food consumption
this.addScreenShake(3);
}
updateParticles() {
this.particles = this.particles.filter(particle => {
particle.x += particle.vx;
particle.y += particle.vy;
particle.vx *= 0.98;
particle.vy *= 0.98;
particle.life--;
return particle.life > 0;
});
}
addScreenShake(intensity) {
this.screenShake.intensity = Math.max(this.screenShake.intensity, intensity);
}
updateScreenShake() {
if (this.screenShake.intensity > 0) {
this.screenShake.x = (Math.random() - 0.5) * this.screenShake.intensity;
this.screenShake.y = (Math.random() - 0.5) * this.screenShake.intensity;
this.screenShake.intensity *= 0.9;
if (this.screenShake.intensity < 0.1) {
this.screenShake.intensity = 0;
this.screenShake.x = 0;
this.screenShake.y = 0;
}
}
}
adaptToSentiment(sentiment) {
// Adjust game speed based on sentiment
if (sentiment.frustration > 0.7) {
this.gameSpeed = Math.min(200, this.gameSpeed + 1); // Slow down
this.aiSnake.intelligence = Math.max(0.3, this.aiSnake.intelligence - 0.01); // Make AI easier
} else if (sentiment.engagement > 0.8) {
this.gameSpeed = Math.max(100, this.gameSpeed - 1); // Speed up
this.aiSnake.intelligence = Math.min(1.0, this.aiSnake.intelligence + 0.01); // Make AI harder
}
// Change visual theme based on sentiment
if (sentiment.boredom > 0.6) {
this.backgroundHue += 2; // Faster color changes
}
}
gameOver(message) {
this.gameState = 'gameOver';
setTimeout(() => {
alert(message);
this.gameState = 'menu';
}, 100);
}
updateScore() {
document.getElementById('playerScore').textContent = this.playerScore;
document.getElementById('aiScore').textContent = this.aiScore;
}
render() {
// Save context for screen shake
this.ctx.save();
this.ctx.translate(this.screenShake.x, this.screenShake.y);
// Clear canvas with animated gradient background
const gradient = this.ctx.createLinearGradient(0, 0, this.canvas.width, this.canvas.height);
const hue1 = (this.backgroundHue) % 360;
const hue2 = (this.backgroundHue + 60) % 360;
gradient.addColorStop(0, `hsla(${hue1}, 70%, 50%, 0.1)`);
gradient.addColorStop(1, `hsla(${hue2}, 70%, 50%, 0.1)`);
this.ctx.fillStyle = gradient;
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// Render particles
this.renderParticles();
// Render game entities
this.playerSnake.render(this.ctx);
this.aiSnake.render(this.ctx);
// Render food with enhanced glow effect
this.food.forEach(food => food.render(this.ctx));
// Render sentiment feedback
this.renderSentimentFeedback();
// Render game state overlay
if (this.gameState === 'paused') {
this.renderPauseOverlay();
} else if (this.gameState === 'menu') {
this.renderMenuOverlay();
}
// Restore context
this.ctx.restore();
}
renderParticles() {
this.particles.forEach(particle => {
const alpha = particle.life / particle.maxLife;
this.ctx.save();
this.ctx.globalAlpha = alpha;
this.ctx.fillStyle = particle.color;
this.ctx.shadowColor = particle.color;
this.ctx.shadowBlur = 10;
this.ctx.beginPath();
this.ctx.arc(particle.x, particle.y, particle.size * alpha, 0, Math.PI * 2);
this.ctx.fill();
this.ctx.restore();
});
}
renderSentimentFeedback() {
const sentiment = this.sentimentEngine.getCurrentSentiment();
// Show encouraging messages for frustration
if (sentiment.frustration > 0.7) {
this.ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
this.ctx.font = '24px Arial';
this.ctx.textAlign = 'center';
this.ctx.fillText('You got this! 💪', this.canvas.width / 2, 50);
}
// Show excitement for high engagement
if (sentiment.engagement > 0.8) {
this.ctx.fillStyle = 'rgba(255, 215, 0, 0.8)';
this.ctx.font = '20px Arial';
this.ctx.textAlign = 'center';
this.ctx.fillText('🔥 ON FIRE! 🔥', this.canvas.width / 2, 80);
}
}
renderPauseOverlay() {
this.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.fillStyle = '#fff';
this.ctx.font = '48px Arial';
this.ctx.textAlign = 'center';
this.ctx.fillText('PAUSED', this.canvas.width / 2, this.canvas.height / 2);
}
renderMenuOverlay() {
this.ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.fillStyle = '#fff';
this.ctx.font = '36px Arial';
this.ctx.textAlign = 'center';
this.ctx.fillText('Press Start to Play', this.canvas.width / 2, this.canvas.height / 2);
}
gameLoop(currentTime = 0) {
const deltaTime = currentTime - this.lastTime;
this.lastTime = currentTime;
this.update(currentTime);
this.render();
requestAnimationFrame((time) => this.gameLoop(time));
}
}
// Snake base class
class Snake {
constructor(x, y, color) {
this.segments = [{ x, y }];
this.direction = { x: this.gridSize, y: 0 };
this.color = color;
this.gridSize = 20;
this.growPending = false;
}
move() {
const head = { ...this.segments[0] };
head.x += this.direction.x;
head.y += this.direction.y;
this.segments.unshift(head);
if (!this.growPending) {
this.segments.pop();
} else {
this.growPending = false;
}
}
grow() {
this.growPending = true;
}
reset(x, y) {
this.segments = [{ x, y }];
this.direction = { x: this.gridSize, y: 0 };
this.growPending = false;
}
render(ctx) {
// Enhanced snake rendering with gradient trails and glow
this.segments.forEach((segment, index) => {
const alpha = index === 0 ? 1 : Math.max(0.3, 1 - (index * 0.08));
const size = index === 0 ? this.gridSize : this.gridSize * (0.9 - index * 0.02);
// Multi-layer glow effect
ctx.shadowColor = this.color;
ctx.shadowBlur = index === 0 ? 20 : 10;
// Outer glow
ctx.fillStyle = `${this.color}${Math.floor(alpha * 0.3 * 255).toString(16).padStart(2, '0')}`;
ctx.fillRect(segment.x - 2, segment.y - 2, this.gridSize + 4, this.gridSize + 4);
// Main body with gradient
const gradient = ctx.createRadialGradient(
segment.x + this.gridSize/2, segment.y + this.gridSize/2, 0,
segment.x + this.gridSize/2, segment.y + this.gridSize/2, this.gridSize/2
);
gradient.addColorStop(0, this.color);
gradient.addColorStop(0.7, this.color + 'CC');
gradient.addColorStop(1, this.color + '66');
ctx.fillStyle = gradient;
const offset = (this.gridSize - size) / 2;
ctx.fillRect(segment.x + offset, segment.y + offset, size, size);
// Head special effects
if (index === 0) {
// Eyes
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
ctx.fillRect(segment.x + 4, segment.y + 4, 3, 3);
ctx.fillRect(segment.x + 13, segment.y + 4, 3, 3);
ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
ctx.fillRect(segment.x + 5, segment.y + 5, 1, 1);
ctx.fillRect(segment.x + 14, segment.y + 5, 1, 1);
// Inner highlight
ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
ctx.fillRect(segment.x + 3, segment.y + 3, this.gridSize - 6, this.gridSize - 6);
} else {
// Body segments inner glow
ctx.fillStyle = `rgba(255, 255, 255, ${alpha * 0.2})`;
ctx.fillRect(segment.x + 4, segment.y + 4, this.gridSize - 8, this.gridSize - 8);
}
});
ctx.shadowBlur = 0;
}
}
// Player Snake
class PlayerSnake extends Snake {
handleInput(key) {
const directions = {
'ArrowUp': { x: 0, y: -this.gridSize },
'ArrowDown': { x: 0, y: this.gridSize },
'ArrowLeft': { x: -this.gridSize, y: 0 },
'ArrowRight': { x: this.gridSize, y: 0 },
'w': { x: 0, y: -this.gridSize },
's': { x: 0, y: this.gridSize },
'a': { x: -this.gridSize, y: 0 },
'd': { x: this.gridSize, y: 0 }
};
const newDirection = directions[key];
if (newDirection) {
// Prevent 180-degree turns
if (newDirection.x !== -this.direction.x || newDirection.y !== -this.direction.y) {
this.direction = newDirection;
}
}
}
}
// AI Snake with enhanced pathfinding
class AISnake extends Snake {
constructor(x, y, color) {
super(x, y, color);
this.target = null;
this.pathfindingCooldown = 0;
this.intelligence = 0.7; // Adaptive intelligence level
this.lastPositions = [];
}
move(food, obstacles) {
// Enhanced AI: adaptive pathfinding with multiple strategies
if (this.pathfindingCooldown <= 0) {
this.findTarget(food, obstacles);
this.pathfindingCooldown = Math.floor(3 + (1 - this.intelligence) * 5);
} else {
this.pathfindingCooldown--;
}
if (this.target) {
this.moveTowardsTarget(obstacles);
}
// Track positions for stuck detection
this.lastPositions.push({...this.segments[0]});
if (this.lastPositions.length > 10) {
this.lastPositions.shift();
}
super.move();
}
findTarget(food, obstacles) {
if (food.length === 0) return;
const head = this.segments[0];
let bestFood = null;
let bestScore = -Infinity;
food.forEach(f => {
const distance = this.getDistance(head, f);
const safety = this.evaluateSafety(f, obstacles);
const score = (100 - distance) * safety * this.intelligence;
if (score > bestScore) {
bestScore = score;
bestFood = f;
}
});
this.target = bestFood;
}
evaluateSafety(position, obstacles) {
let safety = 1.0;
// Check proximity to walls
const wallDistance = Math.min(
position.x, position.y,
800 - position.x, 600 - position.y
);
if (wallDistance < 40) safety *= 0.5;
// Check proximity to obstacles
obstacles.forEach(obstacle => {
obstacle.segments.forEach(segment => {
const distance = this.getDistance(position, segment);
if (distance < 60) safety *= 0.7;
});
});
return safety;
}
moveTowardsTarget(obstacles) {
const head = this.segments[0];
// A* pathfinding for intelligent movement
const possibleMoves = [
{ x: 0, y: -this.gridSize, name: 'up' },
{ x: 0, y: this.gridSize, name: 'down' },
{ x: -this.gridSize, y: 0, name: 'left' },
{ x: this.gridSize, y: 0, name: 'right' }
];
let bestMove = null;
let bestScore = -Infinity;
possibleMoves.forEach(move => {
if (move.x === -this.direction.x && move.y === -this.direction.y) return; // No 180 turns
const newPos = { x: head.x + move.x, y: head.y + move.y };
if (this.isSafeDirection(move, obstacles)) {
const distanceToTarget = this.getDistance(newPos, this.target);
const safety = this.evaluateSafety(newPos, obstacles);
const score = (200 - distanceToTarget) * safety;
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
}
});
if (bestMove) {
this.direction = { x: bestMove.x, y: bestMove.y };
}
}
isSafeDirection(direction, obstacles) {
const head = this.segments[0];
const newPos = { x: head.x + direction.x, y: head.y + direction.y };
// Check walls
if (newPos.x < 0 || newPos.x >= 800 || newPos.y < 0 || newPos.y >= 600) {
return false;
}
// Check self collision
for (let i = 1; i < this.segments.length; i++) {
if (newPos.x === this.segments[i].x && newPos.y === this.segments[i].y) {
return false;
}
}
// Check obstacles (other snakes)
for (let obstacle of obstacles) {
for (let segment of obstacle.segments) {
if (newPos.x === segment.x && newPos.y === segment.y) {
return false;
}
}
}
return true;
}
getDistance(pos1, pos2) {
return Math.abs(pos1.x - pos2.x) + Math.abs(pos1.y - pos2.y);
}
}
// Sentiment Analysis Engine
class SentimentEngine {
constructor() {
this.actions = [];
this.gameEvents = [];
this.currentSentiment = {
frustration: 0,
engagement: 0,
boredom: 0,
excitement: 0
};
this.lastScoreUpdate = 0;
this.rapidInputCount = 0;
this.lastInputTime = 0;
}
recordAction(type, timestamp) {
this.actions.push({ type, timestamp });
// Detect rapid inputs (potential frustration)
if (type === 'input') {
if (timestamp - this.lastInputTime < 100) {
this.rapidInputCount++;
} else {
this.rapidInputCount = 0;
}
this.lastInputTime = timestamp;
}
// Keep only recent actions
const cutoff = timestamp - 10000; // 10 seconds
this.actions = this.actions.filter(action => action.timestamp > cutoff);
}
update(playerScore, aiScore, deltaTime) {
const now = Date.now();
// Analyze score progression
this.analyzeScoreProgression(playerScore, aiScore, now);
// Analyze input patterns
this.analyzeInputPatterns();
// Update sentiment values
this.updateSentimentValues(deltaTime);
}
analyzeScoreProgression(playerScore, aiScore, timestamp) {
if (playerScore > this.lastScoreUpdate) {
this.currentSentiment.excitement += 0.3;
this.currentSentiment.engagement += 0.2;
this.currentSentiment.frustration *= 0.7;
} else if (aiScore > this.lastScoreUpdate && playerScore === this.lastScoreUpdate) {
this.currentSentiment.frustration += 0.2;
this.currentSentiment.excitement *= 0.8;
}
this.lastScoreUpdate = Math.max(playerScore, aiScore);
}
analyzeInputPatterns() {
// Rapid inputs suggest frustration
if (this.rapidInputCount > 5) {
this.currentSentiment.frustration += 0.1;
}
// Long periods without input suggest boredom
const timeSinceLastInput = Date.now() - this.lastInputTime;
if (timeSinceLastInput > 3000) {
this.currentSentiment.boredom += 0.05;
this.currentSentiment.engagement *= 0.95;
}
// Consistent input suggests engagement
const recentInputs = this.actions.filter(a => a.type === 'input' && Date.now() - a.timestamp < 2000);
if (recentInputs.length > 3 && recentInputs.length < 8) {
this.currentSentiment.engagement += 0.05;
}
}
updateSentimentValues(deltaTime) {
// Natural decay of sentiment values
const decay = 0.99;
this.currentSentiment.frustration *= decay;
this.currentSentiment.engagement *= decay;
this.currentSentiment.boredom *= decay;
this.currentSentiment.excitement *= decay;
// Clamp values
Object.keys(this.currentSentiment).forEach(key => {
this.currentSentiment[key] = Math.max(0, Math.min(1, this.currentSentiment[key]));
});
}
getCurrentSentiment() {
return { ...this.currentSentiment };
}
}
// Enhanced Food class with better graphics
class Food {
constructor(x, y) {
this.x = x;
this.y = y;
this.gridSize = 20;
this.pulsePhase = Math.random() * Math.PI * 2;
this.rotationPhase = Math.random() * Math.PI * 2;
this.type = Math.random() > 0.8 ? 'special' : 'normal';
this.color = this.type === 'special' ? '#ff6b6b' : '#ffff00';
}
render(ctx) {
// Enhanced animated effects
this.pulsePhase += 0.15;
this.rotationPhase += 0.1;
const pulse = Math.sin(this.pulsePhase) * 0.4 + 0.8;
const rotation = this.rotationPhase;
ctx.save();
ctx.translate(this.x + this.gridSize / 2, this.y + this.gridSize / 2);
ctx.rotate(rotation);
// Multi-layer glow effect
const glowLayers = [
{ size: 25, alpha: 0.1, blur: 20 },
{ size: 18, alpha: 0.3, blur: 15 },
{ size: 12, alpha: 0.6, blur: 10 }
];
glowLayers.forEach(layer => {
ctx.shadowColor = this.color;
ctx.shadowBlur = layer.blur * pulse;
ctx.fillStyle = `${this.color}${Math.floor(layer.alpha * pulse * 255).toString(16).padStart(2, '0')}`;
ctx.fillRect(-layer.size/2, -layer.size/2, layer.size, layer.size);
});
// Main food body with gradient
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, this.gridSize/2);
gradient.addColorStop(0, this.color);
gradient.addColorStop(0.7, this.color + '80');
gradient.addColorStop(1, this.color + '20');
ctx.fillStyle = gradient;
ctx.fillRect(-this.gridSize/2 + 2, -this.gridSize/2 + 2, this.gridSize - 4, this.gridSize - 4);
// Special food effects
if (this.type === 'special') {
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fillRect(-2, -2, 4, 4);
ctx.fillRect(-6, -1, 2, 2);
ctx.fillRect(4, -1, 2, 2);
ctx.fillRect(-1, -6, 2, 2);
ctx.fillRect(-1, 4, 2, 2);
}
// Inner highlight
ctx.fillStyle = `rgba(255, 255, 255, ${0.6 * pulse})`;
ctx.fillRect(-this.gridSize/2 + 4, -this.gridSize/2 + 4, this.gridSize - 8, this.gridSize - 8);
ctx.restore();
ctx.shadowBlur = 0;
}
}
// Initialize game when page loads
document.addEventListener('DOMContentLoaded', () => {
new GameEngine();
});