Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
292 lines (248 loc) · 8.53 KB
/
Copy pathscript.js
File metadata and controls
292 lines (248 loc) · 8.53 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
const canvas = document.getElementById('gameCanvas');
const ctx = canvas ? canvas.getContext('2d') : null;
const scoreDisplay = document.getElementById('score');
const highScoreDisplay = document.getElementById('highScore');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resetBtn = document.getElementById('resetBtn');
// Error checking and logging
console.log('Canvas element found:', !!canvas);
console.log('Context found:', !!ctx);
console.log('Start button found:', !!startBtn);
if (!canvas) {
console.error('Canvas not found! Check HTML for id="gameCanvas"');
}
if (!startBtn) {
console.error('Start button not found! Check HTML for id="startBtn"');
}
const gridSize = 20;
const tileCount = canvas ? canvas.width / gridSize : 40;
let snake = [{ x: 10, y: 10 }];
let foods = []; // Changed from single food to multiple foods
let score = 0;
let highScore = localStorage.getItem('snakeHighScore') || 0;
let gameRunning = false;
let gamePaused = false;
let direction = { x: 1, y: 0 };
let nextDirection = { x: 1, y: 0 };
let gameEnded = false;
// Difficulty settings
const DIFFICULTY_SPEEDS = {
easy: 150, // Slower speed
medium: 100, // Normal speed
hard: 60 // Faster speed
};
const MIN_FOOD_COUNT = 5; // Always keep at least 5 mangoes on screen
function getCurrentSpeed() {
const difficultySelect = document.getElementById('difficulty');
const difficulty = difficultySelect ? difficultySelect.value : 'medium';
return DIFFICULTY_SPEEDS[difficulty];
}
// Display high score
highScoreDisplay.textContent = highScore;
// Event listeners - with null check
if (startBtn) startBtn.addEventListener('click', startGame);
if (pauseBtn) pauseBtn.addEventListener('click', togglePause);
if (resetBtn) resetBtn.addEventListener('click', resetGame);
// Arrow key controls
document.addEventListener('keydown', (e) => {
if (!gameRunning) {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
startGame();
}
}
if (e.key === 'ArrowUp' && direction.y === 0) nextDirection = { x: 0, y: -1 };
else if (e.key === 'ArrowDown' && direction.y === 0) nextDirection = { x: 0, y: 1 };
else if (e.key === 'ArrowLeft' && direction.x === 0) nextDirection = { x: -1, y: 0 };
else if (e.key === 'ArrowRight' && direction.x === 0) nextDirection = { x: 1, y: 0 };
});
function startGame() {
// If game ended, reset everything
if (gameEnded) {
snake = [{ x: 10, y: 10 }];
foods = []; // Reset foods array
score = 0;
direction = { x: 1, y: 0 };
nextDirection = { x: 1, y: 0 };
scoreDisplay.textContent = score;
gameEnded = false;
}
if (!gameRunning) {
gameRunning = true;
gamePaused = false;
pauseBtn.textContent = 'Pause';
startBtn.textContent = 'Resume';
// Initialize multiple foods if empty
if (foods.length === 0) {
for (let i = 0; i < MIN_FOOD_COUNT; i++) {
generateFood();
}
}
gameLoop();
}
}
function togglePause() {
if (gameRunning) {
gamePaused = !gamePaused;
pauseBtn.textContent = gamePaused ? 'Resume' : 'Pause';
if (!gamePaused) {
gameLoop();
}
}
}
function resetGame() {
snake = [{ x: 10, y: 10 }];
foods = []; // Reset to empty array
score = 0;
direction = { x: 1, y: 0 };
nextDirection = { x: 1, y: 0 };
gameRunning = false;
gamePaused = false;
gameEnded = false;
scoreDisplay.textContent = score;
pauseBtn.textContent = 'Pause';
startBtn.textContent = 'Start Game';
draw();
}
function gameLoop() {
if (!gameRunning || gamePaused) return;
update();
draw();
setTimeout(gameLoop, getCurrentSpeed());
}
function update() {
direction = nextDirection;
let head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
// Wall collision - game over
if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
endGame();
return;
}
// Check self collision
if (snake.some(segment => segment.x === head.x && segment.y === head.y)) {
endGame();
return;
}
snake.unshift(head);
// Check food collision with any food
let foodEaten = false;
foods = foods.filter(f => {
if (head.x === f.x && head.y === f.y) {
foodEaten = true;
return false; // Remove this food
}
return true; // Keep other foods
});
if (foodEaten) {
score += 10;
scoreDisplay.textContent = score;
} else {
snake.pop();
}
// Maintain minimum food count - INFINITE FOOD!
while (foods.length < MIN_FOOD_COUNT) {
generateFood();
}
}
function generateFood() {
let newFood;
let attempts = 0;
const maxAttempts = 500; // Much higher limit for harder levels
do {
newFood = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
attempts++;
// If 500 attempts without finding valid spot, place it anyway (allow overlap)
if (attempts >= maxAttempts) {
foods.push(newFood);
return;
}
} while (
snake.some(segment => segment.x === newFood.x && segment.y === newFood.y) ||
foods.some(food => food.x === newFood.x && food.y === newFood.y)
);
foods.push(newFood);
}
function draw() {
// Clear canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw grid
ctx.strokeStyle = '#222';
ctx.lineWidth = 0.5;
for (let i = 0; i <= tileCount; i++) {
ctx.beginPath();
ctx.moveTo(i * gridSize, 0);
ctx.lineTo(i * gridSize, canvas.height);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i * gridSize);
ctx.lineTo(canvas.width, i * gridSize);
ctx.stroke();
}
// Draw snake with curves and eyes
snake.forEach((segment, index) => {
const x = segment.x * gridSize + gridSize / 2;
const y = segment.y * gridSize + gridSize / 2;
const radius = gridSize / 2 - 1;
// Head - bright green with gradient
if (index === 0) {
ctx.fillStyle = '#00ff00';
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
// Add eyes
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(x - 5, y - 4, 2.5, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(x + 5, y - 4, 2.5, 0, Math.PI * 2);
ctx.fill();
// Add shine effect
ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
ctx.beginPath();
ctx.arc(x - 3, y - 3, 2, 0, Math.PI * 2);
ctx.fill();
} else {
// Body - darker green with gradient effect
const gradient = ctx.createRadialGradient(x, y, 0, x, y, radius);
gradient.addColorStop(0, '#00ff00');
gradient.addColorStop(1, '#00aa00');
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
// Add border for definition
ctx.strokeStyle = '#00ff00';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.stroke();
}
});
// Draw all foods - Mango emojis
foods.forEach(foodItem => {
const foodX = foodItem.x * gridSize + gridSize / 2;
const foodY = foodItem.y * gridSize + gridSize / 2;
// Draw mango emoji
ctx.font = `${gridSize - 4}px Arial`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('🥭', foodX, foodY);
});
}
function endGame() {
gameRunning = false;
gameEnded = true;
if (score > highScore) {
highScore = score;
highScoreDisplay.textContent = highScore;
localStorage.setItem('snakeHighScore', highScore);
}
startBtn.textContent = 'Start Game';
}
// Initial draw
draw();