-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
351 lines (308 loc) · 11.1 KB
/
Copy pathscript.js
File metadata and controls
351 lines (308 loc) · 11.1 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
// Info Section Logic
const infoSection = document.getElementById('infoSection');
const infoButton = document.getElementById('infoButton');
const closeInfoButton = document.getElementById('closeInfoButton');
infoButton.addEventListener('click', () => {
infoSection.style.display = 'flex';
});
closeInfoButton.addEventListener('click', () => {
infoSection.style.display = 'none';
});
// Game Canvas Setup
const canvas = document.getElementById('gameCanvas');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setSize(canvas.offsetWidth, canvas.offsetHeight);
renderer.shadowMap.enabled = true;
// Resize the canvas dynamically
function resizeGame() {
const gameContainer = document.getElementById('gameContainer');
const size = Math.min(window.innerWidth, window.innerHeight) * 0.8; // Scale to 80% of the viewport
gameContainer.style.width = `${size}px`;
gameContainer.style.height = `${size}px`;
renderer.setSize(size, size);
}
window.addEventListener('resize', resizeGame);
resizeGame(); // Initial resize
// Create the scene
const scene = new THREE.Scene();
// Set up the camera
const camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 100);
camera.position.set(0, 10, 0);
camera.lookAt(0, 0, 0);
// Add lighting
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(10, 10, 10);
scene.add(directionalLight);
// Load textures
const textureLoader = new THREE.TextureLoader();
const headTexture = textureLoader.load('assets/SnakeHead.png');
const bodyTexture = textureLoader.load('assets/SnakeBody.png');
const foodTexture = textureLoader.load('assets/Food.bmp');
// Materials
const headMaterial = new THREE.MeshStandardMaterial({ map: headTexture });
const bodyMaterial = new THREE.MeshStandardMaterial({ map: bodyTexture });
const foodMaterial = new THREE.MeshStandardMaterial({ map: foodTexture });
// Grid
const gridHelper = new THREE.GridHelper(20, 20, 0x888888, 0x444444);
scene.add(gridHelper);
// Game variables
const gridSize = 1;
const gridBoundary = 10;
const snakeGeometry = new THREE.BoxGeometry(gridSize, gridSize, gridSize);
const foodGeometry = new THREE.BoxGeometry(gridSize, gridSize, gridSize);
const food = new THREE.Mesh(foodGeometry, foodMaterial);
scene.add(food);
const snake = [];
let direction = { x: gridSize, z: 0 };
let snakeSpeed = 200;
let score = 0;
let foodsEaten = 0;
let startTime = Date.now();
let lastMoveTime = 0;
let isGameOver = false;
let gameMode = null;
// High scores
let highScoreClassic = parseInt(localStorage.getItem('snakeHighScoreClassic')) || 0;
let highScoreModern = parseInt(localStorage.getItem('snakeHighScoreModern')) || 0;
let currentHighScore = 0;
// UI Elements
const scoreElement = document.createElement('div');
scoreElement.id = 'scoreElement';
scoreElement.innerHTML = `Score: 0 | High Score: 0`;
document.body.appendChild(scoreElement);
const timerElement = document.createElement('div');
timerElement.id = 'timerElement';
timerElement.innerHTML = `Time: 0s`;
document.body.appendChild(timerElement);
// Game Over container
const gameOverContainer = document.createElement('div');
gameOverContainer.id = 'gameOverContainer';
gameOverContainer.style.display = 'none';
gameOverContainer.style.position = 'absolute';
gameOverContainer.style.top = '50%';
gameOverContainer.style.left = '50%';
gameOverContainer.style.transform = 'translate(-50%, -50%)';
gameOverContainer.style.textAlign = 'center';
gameOverContainer.style.color = 'white';
gameOverContainer.style.fontSize = '24px';
gameOverContainer.style.fontFamily = 'Arial, sans-serif';
gameOverContainer.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
gameOverContainer.style.padding = '20px';
gameOverContainer.style.borderRadius = '10px';
document.body.appendChild(gameOverContainer);
// Game Over text
const gameOverElement = document.createElement('div');
gameOverElement.id = 'gameOverElement';
gameOverContainer.appendChild(gameOverElement);
// Restart button
const restartButton = document.createElement('button');
restartButton.id = 'restartButton';
restartButton.innerText = 'Play Again';
restartButton.style.marginTop = '15px';
restartButton.style.padding = '10px 20px';
restartButton.style.fontSize = '18px';
restartButton.style.color = '#fff';
restartButton.style.backgroundColor = '#ff9f1c';
restartButton.style.border = 'none';
restartButton.style.borderRadius = '8px';
restartButton.style.cursor = 'pointer';
restartButton.addEventListener('click', () => location.reload()); // Reload the page to restart
gameOverContainer.appendChild(restartButton);
// Movement control
document.addEventListener('keydown', (event) => {
if (isGameOver) return;
switch (event.key) {
case 'ArrowUp': if (direction.z === 0) direction = { x: 0, z: -gridSize }; break;
case 'ArrowDown': if (direction.z === 0) direction = { x: 0, z: gridSize }; break;
case 'ArrowLeft': if (direction.x === 0) direction = { x: -gridSize, z: 0 }; break;
case 'ArrowRight': if (direction.x === 0) direction = { x: gridSize, z: 0 }; break;
}
});
// Snake initialization
function setupSnake() {
while (snake.length > 0) {
const segment = snake.pop();
scene.remove(segment);
}
const headSegment = new THREE.Mesh(snakeGeometry, headMaterial);
headSegment.position.set(0, 0.5, 0);
snake.push(headSegment);
scene.add(headSegment);
}
// Food positioning
// Generate a new food position ensuring it doesn't overlap with the snake
function generateFoodPosition() {
let newPosition;
const safeBoundary = gridBoundary - gridSize; // Ensure food doesn't spawn at the edge
do {
newPosition = new THREE.Vector3(
Math.floor(Math.random() * (safeBoundary * 2 / gridSize) - safeBoundary / gridSize) * gridSize,
0.5,
Math.floor(Math.random() * (safeBoundary * 2 / gridSize) - safeBoundary / gridSize) * gridSize
);
} while (snake.some(segment => segment.position.equals(newPosition)));
return newPosition;
}
function repositionFood() {
const newFoodPosition = generateFoodPosition();
food.position.copy(newFoodPosition);
}
// Head rotation logic
function updateHeadRotation() {
const head = snake[0];
if (direction.x === gridSize) {
head.rotation.set(0, -Math.PI / 2, 0); // Left
} else if (direction.x === -gridSize) {
head.rotation.set(0, Math.PI / 2, 0); // Right
} else if (direction.z === gridSize) {
head.rotation.set(0, Math.PI, 0); // Down
} else if (direction.z === -gridSize) {
head.rotation.set(0, 0, 0); // Up
}
}
// High score handling
function loadHighScore() {
if (gameMode === 'classic') currentHighScore = highScoreClassic;
else if (gameMode === 'modern') currentHighScore = highScoreModern;
scoreElement.innerHTML = `Score: ${score} | High Score: ${currentHighScore}`;
}
function saveHighScore() {
if (gameMode === 'classic') {
if (score > highScoreClassic) {
highScoreClassic = score;
localStorage.setItem('snakeHighScoreClassic', highScoreClassic);
}
} else if (gameMode === 'modern') {
if (score > highScoreModern) {
highScoreModern = score;
localStorage.setItem('snakeHighScoreModern', highScoreModern);
}
}
}
// Game logic
function updateSnake() {
const head = snake[0];
const newHeadPosition = new THREE.Vector3(
head.position.x + direction.x,
head.position.y,
head.position.z + direction.z
);
if (gameMode === 'classic') {
if (Math.abs(newHeadPosition.x) >= gridBoundary || Math.abs(newHeadPosition.z) >= gridBoundary) {
endGame('Game Over! You went off-screen.');
return;
}
} else if (gameMode === 'modern') {
if (newHeadPosition.x >= gridBoundary) newHeadPosition.x = -gridBoundary + gridSize;
if (newHeadPosition.x < -gridBoundary) newHeadPosition.x = gridBoundary - gridSize;
if (newHeadPosition.z >= gridBoundary) newHeadPosition.z = -gridBoundary + gridSize;
if (newHeadPosition.z < -gridBoundary) newHeadPosition.z = gridBoundary - gridSize;
}
for (let i = 1; i < snake.length; i++) {
if (newHeadPosition.equals(snake[i].position)) {
endGame('Game Over! You ran into yourself.');
return;
}
}
for (let i = snake.length - 1; i > 0; i--) {
snake[i].position.copy(snake[i - 1].position);
}
head.position.copy(newHeadPosition);
updateHeadRotation();
}
// Collision detection
function checkCollision() {
const head = snake[0];
if (head.position.distanceTo(food.position) < 0.5) {
addSnakeSegment();
repositionFood();
score += 10;
foodsEaten++;
if (gameMode === 'modern' && foodsEaten % 5 === 0) snakeSpeed = Math.max(50, snakeSpeed - 20);
scoreElement.innerHTML = `Score: ${score} | High Score: ${currentHighScore}`;
}
}
function addSnakeSegment() {
const newSegment = new THREE.Mesh(snakeGeometry, bodyMaterial);
newSegment.position.copy(snake[snake.length - 1].position);
snake.push(newSegment);
scene.add(newSegment);
}
// Timer
function updateTimer() {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
timerElement.innerHTML = `Time: ${elapsedTime}s`;
}
// Game loop
function animate(time) {
if (isGameOver) return;
if (time - lastMoveTime > snakeSpeed) {
updateSnake();
checkCollision();
lastMoveTime = time;
}
updateTimer();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
// Game mode selection
function displayGameModeMenu() {
const menu = document.createElement('div');
menu.style.position = 'absolute';
menu.style.top = '50%';
menu.style.left = '50%';
menu.style.transform = 'translate(-50%, -50%)';
menu.style.textAlign = 'center';
menu.style.color = 'white';
menu.style.fontSize = '30px';
const title = document.createElement('div');
title.innerText = 'Select Game Mode';
title.style.marginBottom = '20px';
menu.appendChild(title);
const classicButton = document.createElement('button');
classicButton.innerText = 'Classic Mode';
classicButton.style.fontSize = '20px';
classicButton.style.margin = '10px';
classicButton.onclick = () => {
gameMode = 'classic';
document.body.removeChild(menu);
startGame();
};
const modernButton = document.createElement('button');
modernButton.innerText = 'Modern Mode';
modernButton.style.fontSize = '20px';
modernButton.style.margin = '10px';
modernButton.onclick = () => {
gameMode = 'modern';
document.body.removeChild(menu);
startGame();
};
menu.appendChild(classicButton);
menu.appendChild(modernButton);
document.body.appendChild(menu);
}
function startGame() {
gameOverContainer.style.display = 'none'; // Hide game over screen
restartButton.style.display = 'none'; // Hide the restart button
loadHighScore();
setupSnake();
repositionFood();
animate();
}
function endGame(message) {
isGameOver = true;
saveHighScore();
gameOverElement.innerHTML = `
${message}<br>
Final Score: ${score}<br>
High Score: ${currentHighScore}
`;
gameOverContainer.style.display = 'block'; // Show the game over screen
restartButton.style.display = 'block'; // Show the restart button
// Center the restart button
restartButton.style.display = 'block';
restartButton.style.margin = '0 auto';
}
displayGameModeMenu();