-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
240 lines (190 loc) · 5.77 KB
/
script.js
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
const gameBoard = document.querySelector(".board");
const gameRestart = document.querySelector(".reset");
const highScoreBox = document.querySelector("#high-score");
const currentScoreBox = document.querySelector("#score");
let lastRenderTime = 0;
let gameOver = false;
let currentScore = 0;
let highScore = 0;
let gridSize = 21;
let snakeSpeed = 5;
let gameStarted = true;
let snakeBody = [
{x:10,y:10},
]
let food = randomFoodPosition();
let inputDirection = {x : 0, y : 0};
let lastInputDirection = {x:0, y:0};
const foodSound = new Audio('music/food.mp3');
const gameOverSound = new Audio('music/gameover.mp3');
const musicSound = new Audio('music/music.mp3');
//Main Loop to run every few milisecond
function main(currenttime){
window.requestAnimationFrame(main);
if((currenttime - lastRenderTime)/1000 < 1/snakeSpeed){
return;
}
lastRenderTime = currenttime;
if(gameStarted){
gameEngine();
}
}
//Main Function /******************************** */
function gameEngine(){
// musicSound.play();
//Collision Check of the snake with border or its own body
checkCollision();
// If you have eaten the food, increment the score and regenerate the food
updateFood();
//Move the Snake
moveSnake();
//Drawing all The Elements - Snake & Food
drawSnake();
drawFood();
}
//Game Functions:
//What will happen if collision occurs
function checkCollision(){
if(isCollide(snakeBody)){
gameOverSound.play();
gameStarted = false;
gameRestart.addEventListener('click', (e)=>{
location.reload(true);
return;
// inputDirection = {x: 0, y: 0};
// snakeBody = [{x: 10, y: 10}];
// currentScore = 0;
// currentScoreBox.innerHTML = currentScore;
// snakeSpeed = 5;
// food = randomFoodPosition();
})
}
}
function isCollide(snake){
// If you bump into yourself
for (let i = 1; i < snakeBody.length; i++) {
if(snake[i].x === snake[0].x && snake[i].y === snake[0].y){
return true;
}
}
// If you bump into the wall
if(snake[0].x > gridSize || snake[0].x < 1 || snake[0].y > gridSize || snake[0].y < 1){
return true;
}
return false;
}
function updateFood(){
if(snakeBody[0].x === food.x && snakeBody[0].y === food.y){
foodSound.play();
//Update the Score
updateScore();
snakeSpeed += 0.5;
snakeBody.unshift({x: snakeBody[0].x + inputDirection.x, y: snakeBody[0].y + inputDirection.y});
//New Food Position
let newFoodPosition;
do{
newFoodPosition = randomFoodPosition();
}
while(newFoodPosition == null || onSnake(newFoodPosition));
food = newFoodPosition;
}
}
//get a Random position in the grid
function randomFoodPosition(){
return {
x : Math.floor(Math.random() * gridSize) + 1,
y : Math.floor(Math.random() * gridSize) + 1
}
}
//checks whether the food on the snake body or not
function onSnake(item){
// for (let i = 1; i < snakeBody.length; i++) {
snakeBody.some((segment) =>{
if(segment.x === item.x && segment.y === item.y){
return true;
}
})
return false;
}
function updateScore(){
currentScore += 1;
if(currentScore>highScore){
highScore = currentScore;
localStorage.setItem("HighScore", JSON.stringify(highScore));
highScoreBox.innerHTML = highScore;
}
currentScoreBox.innerHTML = currentScore;
}
function moveSnake(){
inputDirection = getInputDirection();
for (let i = snakeBody.length - 2; i>=0; i--) {
snakeBody[i+1] = {...snakeBody[i]};
}
snakeBody[0].x += inputDirection.x;
snakeBody[0].y += inputDirection.y;
}
function drawSnake(){
gameBoard.innerHTML = "";
snakeBody.forEach((element, index)=>{
let snakeElement = document.createElement("div");
snakeElement.style.gridColumnStart = element.x;
snakeElement.style.gridRowStart = element.y;
// if(index == 0){
// snakeElement.classList.add("head");
// }else{
// snakeElement.classList.add("snake");
// }
snakeElement.classList.add("snake");
gameBoard.appendChild(snakeElement);
})
}
function drawFood(){
let foodElement = document.createElement("div");
foodElement.style.gridColumnStart = food.x;
foodElement.style.gridRowStart = food.y;
foodElement.classList.add("food");
gameBoard.appendChild(foodElement);
}
//Set High Score to Local Storage
let hiscore = localStorage.getItem("HighScore");
if(hiscore === null){
highScore = 0;
localStorage.setItem("HighScore", JSON.stringify(highScore))
}
else{
highScore = JSON.parse(hiscore);
highScoreBox.innerHTML = hiscore;
}
//For looping
window.requestAnimationFrame(main);
//Getting the direction according to the keypress
window.addEventListener('keydown', (e)=>{
switch(e.key) {
case 'ArrowUp':
if(lastInputDirection.y !== 0) break;
inputDirection.x = 0;
inputDirection.y = -1;
break;
case 'ArrowDown':
if(lastInputDirection.y !== 0) break;
inputDirection.x = 0;
inputDirection.y = 1;
break;
case 'ArrowRight':
if(lastInputDirection.x !== 0) break;
inputDirection.x = 1;
inputDirection.y = 0;
break;
case 'ArrowLeft':
if(lastInputDirection.x !== 0) break;
inputDirection.x = -1;
inputDirection.y = 0;
break;
default:
break;
}
})
function getInputDirection(){
lastInputDirection = inputDirection;
return inputDirection;
}