-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
320 lines (293 loc) · 8.88 KB
/
app.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
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
let speed = 1;
let GAME_DIMENSION = 40;
var timer;
var timeLeft = 60;
//*****CONSTANTS
const PRIMARY_BG = '#000000',SECONDARY_BG ='#000000',DISTANCE_THRESHOLD = 50;
//*****
let r = document.documentElement
let direction = {x:0,y:0}
let lastPaintTime = 0;
let snakeArray = [{x:5,y:15},{x:4,y:15},{x:3,y:15}]
let snakeElements = []
let foodArray = []
let foodOrderArray =[]
let score = 0;
let currentActiveFood = 0;
const background = document.querySelector('#board')
const foodOrder = document.querySelector('#food-order')
const Score = document.querySelector('#score')
r.style.setProperty('--primary-bg', PRIMARY_BG);
r.style.setProperty('--secondary-bg', SECONDARY_BG);
let WIDTH = background.offsetWidth;
let CELL_WIDTH = WIDTH / GAME_DIMENSION; // Width and Height of one Cell in px
function main(currentTime)
{
window.requestAnimationFrame(main)
if((currentTime -lastPaintTime)/100 < 1/speed)
return;
lastPaintTime = currentTime;
gameEngine();
}
//Initialize
function Initialize()
{
timeLeft = 60;
score = 0;
document.querySelector("#timer").innerHTML = timeLeft;
background.innerHTML=''
foodOrder.innerHTML = ''
snakeArray.forEach((ele,index)=>{
let snakeElement = createSnakeElement(ele.x,ele.y)
background.appendChild(snakeElement)
if(index===0)
snakeElement.classList.add("head");
snakeElements.push(snakeElement);
})
createNewFoodSequence();
}
//Timer
function updateTimer() {
if(!(direction.x===0&&direction.y===0)){
timeLeft = timeLeft - 1;
if(timeLeft >= 0)
document.querySelector('#timer').innerHTML = (timeLeft);
else
gameOver();
}
}
function startTimer() {
console.log("Start Timer")
timeLeft = 60;
timer = setInterval(updateTimer, 1000);
updateTimer();
}
//Timer
function gameOver() {
clearInterval(timer);
timer=null;
timeLeft = 60;
direction ={x:0,y:0}
snakeArray=[{x:5,y:15},{x:4,y:15},{x:3,y:15}]
snakeElements = []
foodArray = []
foodOrderArray = []
currentActiveFood = 0;
alert("Game Over");
Initialize();
}
function createSnakeElement(x,y){
let snakeElement = document.createElement('div');
snakeElement.classList.add('snake');
snakeElement.style.top=`${y*CELL_WIDTH}px`;
snakeElement.style.left=`${x*CELL_WIDTH}px`;
snakeElement.style.width = `${CELL_WIDTH}px`
snakeElement.style.height = `${CELL_WIDTH}px`
return snakeElement;
}
function isCollide(){
if(snakeElements[0].offsetTop>=WIDTH||snakeElements[0].offsetLeft>=WIDTH||snakeElements[0].offsetTop<0||snakeElements[0].offsetLeft<0)
return true;
}
//Increase Snake Length
function IncreaseSnakeLEngth(foodIndex){
let snakeElement = createSnakeElement(x=foodArray[foodIndex].offsetLeft,y=foodArray[foodIndex].offsetTop);
background.appendChild(snakeElement)
snakeElements.push(snakeElement)
snakeArray.push({...foodArray[foodIndex]});
}
//New Food Sequence
function createNewFoodSequence(){
for(var i=0;i<5;i++){
let {foodElement,foodOrderElement}= createNewFoodElement();
if(i===0)
{
foodElement.classList.add("active");
foodOrderElement.classList.add("active");
}
foodArray.push(foodElement);
foodOrderArray.push(foodOrderElement)
background.appendChild(foodElement);
foodOrder.appendChild(foodOrderElement);
}
}
//Check For Similar Color
function IsDuplicateFoodElement(color,X,Y)
{
let flag = 0;
if(X<=3||Y<=3||X>=37||Y>=37||color===PRIMARY_BG||color===SECONDARY_BG)
flag = 1;
else
{
foodArray.forEach((e)=>{
//console.log("Start")
// Position Check
let x = Math.floor(e.offsetLeft/CELL_WIDTH);
let y = Math.floor(e.offsetTop/CELL_WIDTH);
let posCheck = (Math.abs(x - X)<=2||Math.abs(y - Y)<=2);
let colorCheck = (color === PRIMARY_BG || color === SECONDARY_BG)
//console.log("x: "+x,"y: "+y,"X: "+X,"Y:"+Y,"E: "+color,"PBG: "+PRIMARY_BG,"SBG: "+SECONDARY_BG,"pos: "+posCheck,"color: "+colorCheck)
if(colorCheck)
flag = 1;
if(posCheck)
flag = 1;
})
}
if(flag)
return true;
else
return false;
}
function createNewFoodElement(){
//console.log("New Food Element Start")
let foodColor,foodX,foodY;
//console.log("Is Dup ",IsDuplicateFoodElement(foodColor,foodX,foodY))
do
{
foodColor = "#" + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0').toUpperCase();
foodX = Math.floor(Math.random()*GAME_DIMENSION);
foodY = Math.floor(Math.random()*GAME_DIMENSION);
}while(IsDuplicateFoodElement(foodColor,foodX,foodY))
let Element = document.createElement('div');
Element.style.top = `${foodY*CELL_WIDTH}px`;
Element.style.left = `${foodX*CELL_WIDTH}px`;
Element.style.backgroundColor = foodColor;
Element.style.width = `${CELL_WIDTH}px`
Element.style.height = `${CELL_WIDTH}px`
Element.classList.add('food');
let orderElement = document.createElement('div');
orderElement.style.backgroundColor = foodColor;
orderElement.classList.add('food');
return{foodElement:Element,foodOrderElement:orderElement}
}
function FoodCheck(){
if(foodArray[currentActiveFood].offsetLeft===snakeElements[0].offsetLeft&&foodArray[currentActiveFood].offsetTop===snakeElements[0].offsetTop)
{
//IncreaseSnakeLEngth(currentActiveFood)
foodArray[currentActiveFood].classList.remove('active')
foodArray[currentActiveFood].classList.add('inactive')
foodOrderArray[currentActiveFood].classList.remove('active')
currentActiveFood++;
if(currentActiveFood>=5){
currentActiveFood = 0;
foodArray = [];
foodOrderArray = [];
foodOrder.innerHTML = ''
createNewFoodSequence()
score+=3;
timeLeft+=8;
}
else
{
foodArray[currentActiveFood].classList.add('active')
foodOrderArray[currentActiveFood].classList.add('active')
score+=2;
}
}
else{
foodArray.forEach((e,i)=>{
if(e.offsetLeft===snakeElements[0].offsetLeft&&e.offsetTop===snakeElements[0].offsetTop&&i!==currentActiveFood)
{
e.classList.add("blink")
setTimeout(()=>e.classList.remove('blink'),500);
score-=1;
}
})
}
}
function gameEngine()
{
Score.innerHTML = score;
if(isCollide()){
gameOver();
}
FoodCheck();
for(let i=snakeArray.length-2;i>= 0;i--){
snakeArray[i+1] = {...snakeArray[i]}
}
for(let i=snakeArray.length-1;i>= 0;i--){
snakeElements[i].style.top = `${snakeArray[i].y*CELL_WIDTH}px`
snakeElements[i].style.left = `${snakeArray[i].x*CELL_WIDTH}px`
}
snakeArray[0].x+=direction.x;
snakeArray[0].y+=direction.y;
snakeElements[0].style.top = `${snakeArray[0].y*CELL_WIDTH}px`
snakeElements[0].style.left = `${snakeArray[0].x*CELL_WIDTH}px`
}
Initialize();
window.requestAnimationFrame(main);
function handleDirectionChange(code){
if(direction.x===0&&direction.y===0)
startTimer()
direction ={x:0,y:1}
switch(code){
case 0:
direction ={x:0,y:-1}
break;
case 1:
direction ={x:0,y:1}
break;
case 2:
direction ={x:-1,y:0}
break;
case 3:
direction ={x:1,y:0}
break;
}
}
window.addEventListener('keydown',(e)=>{
if(direction.x===0&&direction.y===0)
startTimer()
direction ={x:0,y:1}
switch(e.key){
case "ArrowUp":
handleDirectionChange(0)
break;
case "ArrowDown":
handleDirectionChange(1)
break;
case "ArrowLeft":
handleDirectionChange(2)
break;
case "ArrowRight":
handleDirectionChange(3)
break;
}
})
var swipedir,
startX,
startY,
distX,
distY,
threshold = 100,
restraint = 50,
allowedTime = 300, // maximum time allowed to travel that distance
elapsedTime,
startTime;
let touchArea = background;
touchArea.addEventListener('touchstart', function(e){
var touchobj = e.changedTouches[0]
dist = 0
startX = touchobj.pageX
startY = touchobj.pageY
startTime = new Date().getTime()
e.preventDefault()
}, false)
touchArea.addEventListener('touchmove', function(e){
e.preventDefault()
}, false)
touchArea.addEventListener('touchend', function(e){
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX
distY = touchobj.pageY - startY
elapsedTime = new Date().getTime() - startTime
if (elapsedTime <= allowedTime){
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){
(distX < 0)? handleDirectionChange(2) : handleDirectionChange(3)
}
else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){
(distY < 0)? handleDirectionChange(0): handleDirectionChange(1)
}
}
e.preventDefault()
}, false)