-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
189 lines (162 loc) · 5.82 KB
/
script.js
File metadata and controls
189 lines (162 loc) · 5.82 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
const playBoard = document.querySelector(".play-board");
const scoreElement = document.querySelector(".score");
const highScoreElement = document.querySelector(".high-score");
const controls = document.querySelectorAll(".controls i");
let gameOver = false;
let foodX, foodY;
let snakeX = 5, snakeY = 5;
let velocityX = 0, velocityY = 0;
let snakeBody = [];
let setIntervalId;
let score = 0;
let isPaused = false;
// Getting high score from the local storage
let highScore = localStorage.getItem("high-score") || 0;
highScoreElement.innerText = `High Score: ${highScore}`;
const updateFoodPosition = () => {
// Passing a random 1 - 30 value as food position
foodX = Math.floor(Math.random() * 30) + 1;
foodY = Math.floor(Math.random() * 30) + 1;
}
const eatSound = document.getElementById("eat-sound");
const gameoverSound = document.getElementById("gameover-sound");
eatSound.play();
gameoverSound.play();
const resetGame = () => {
snakeX = 5;
snakeY = 5;
velocityX = 0;
velocityY = 0;
snakeBody = [];
gameOver = false;
score = 0;
scoreElement.innerText = `Score: ${score}`;
updateFoodPosition();
document.getElementById("game-over-overlay").classList.add("hidden");
setIntervalId = setInterval(initGame, 100);
};
const handleGameOver = () => {
pauseBtn.disabled = true;
// pauseBtn.innerText = "Game Over";
clearInterval(setIntervalId);
gameoverSound.play();
document.getElementById("final-score").innerText = score;
document.getElementById("game-over-overlay").classList.remove("hidden");
const restartListener = (e) => {
if (e.key === "Enter") {
document.removeEventListener("keydown", restartListener);
resetGame();
}
};
document.addEventListener("keydown", restartListener);
};
const changeDirection = e => {
// Changing velocity value based on key press
if(e.key === "ArrowUp" && velocityY != 1) {
velocityX = 0;
velocityY = -1;
} else if(e.key === "ArrowDown" && velocityY != -1) {
velocityX = 0;
velocityY = 1;
} else if(e.key === "ArrowLeft" && velocityX != 1) {
velocityX = -1;
velocityY = 0;
} else if(e.key === "ArrowRight" && velocityX != -1) {
velocityX = 1;
velocityY = 0;
}
}
// Calling changeDirection on each key click and passing key dataset value as an object
controls.forEach(button => button.addEventListener("click", () => changeDirection({ key: button.dataset.key })));
let touchStartX = 0;
let touchStartY = 0;
document.addEventListener("touchstart", (e) => {
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
}, false);
document.addEventListener("touchend", (e) => {
const touchEndX = e.changedTouches[0].clientX;
const touchEndY = e.changedTouches[0].clientY;
const dx = touchEndX - touchStartX;
const dy = touchEndY - touchStartY;
// Check if swipe distance is enough (prevent accidental touch)
if (Math.abs(dx) > Math.abs(dy)) {
if (dx > 30 && velocityX !== -1) {
// Right swipe
velocityX = 1;
velocityY = 0;
} else if (dx < -30 && velocityX !== 1) {
// Left swipe
velocityX = -1;
velocityY = 0;
}
} else {
if (dy > 30 && velocityY !== -1) {
// Down swipe
velocityX = 0;
velocityY = 1;
} else if (dy < -30 && velocityY !== 1) {
// Up swipe
velocityX = 0;
velocityY = -1;
}
}
}, false);
const initGame = () => {
if (isPaused) return; // Don't run game loop if paused
// if (gameOver) return handleGameOver();
if(gameOver) return handleGameOver();
let html = `<div class="food" style="grid-area: ${foodY} / ${foodX}"></div>`;
// Checking if the snake hit the food
if(snakeX === foodX && snakeY === foodY) {
updateFoodPosition();
// snakeBody.push([foodY, foodX]); // Pushing food position to snake body array
snakeBody.push([snakeX, snakeY]);
score++; // increment score by 1
highScore = score >= highScore ? score : highScore;
localStorage.setItem("high-score", highScore);
scoreElement.innerText = `Score: ${score}`;
highScoreElement.innerText = `High Score: ${highScore}`;
}
// Updating the snake's head position based on the current velocity
snakeX += velocityX;
snakeY += velocityY;
// Shifting forward the values of the elements in the snake body by one
for (let i = snakeBody.length - 1; i > 0; i--) {
snakeBody[i] = snakeBody[i - 1];
}
snakeBody[0] = [snakeX, snakeY]; // Setting first element of snake body to current snake position
// Checking if the snake's head is out of wall, if so setting gameOver to true
if(snakeX <= 0 || snakeX > 30 || snakeY <= 0 || snakeY > 30) {
return gameOver = true;
}
for (let i = 0; i < snakeBody.length; i++) {
// Adding a div for each part of the snake's body
html += `<div class="head" style="grid-area: ${snakeBody[i][1]} / ${snakeBody[i][0]}"></div>`;
// Checking if the snake head hit the body, if so set gameOver to true
if (i !== 0 && snakeBody[0][1] === snakeBody[i][1] && snakeBody[0][0] === snakeBody[i][0]) {
gameOver = true;
}
}
playBoard.innerHTML = html;
}
const pauseBtn = document.getElementById("pauseBtn");
pauseBtn.addEventListener("click", () => {
if (gameOver) return;
isPaused = !isPaused;
pauseBtn.innerText = isPaused ? "Play" : "Pause";
});
document.addEventListener("keydown", (e) => {
if (e.code === "Space") {
if (gameOver) return;
e.preventDefault();
isPaused = !isPaused;
pauseBtn.innerText = isPaused ? "Play" : "Pause";
}
if (e.code === "Enter" && gameOver) {
location.reload(); // Restart game
}
});
updateFoodPosition();
setIntervalId = setInterval(initGame, 100);
document.addEventListener("keyup", changeDirection);