-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogic.js
More file actions
499 lines (413 loc) · 10.9 KB
/
Copy pathlogic.js
File metadata and controls
499 lines (413 loc) · 10.9 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// JavaScript is primarily used for implementing the logic and functionality of web applications.
// variables
let board;
let score = 0;
let rows = 4;
let columns = 4;
// boolean true/false of scores
let is2048Exist = false;
let is4096Exist = false;
let is8192Exist = false;
// used for mobile (touch) input; (x, y) coordinates
let startX = 0;
let startY = 0;
/** setGame()
* A function sets the game board to have tiles, and these tiles should have corressponding
* colors based on their values and this is through the help of updateTile() function
*/
function setGame() {
// Initialize the 4x4 game board with all tiles set to 0.
board = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]; // Goal, we will use the backend board to add and move the tiles of the frontend board.
for (let r=0; r<rows; r++) {
for (let c=0; c<columns; c++) {
let tile = document.createElement("div");
tile.id = r.toString() + "-" + c.toString();
let num = board[r][c];
// updates the appearance and color of the tiles
updateTile(tile, num);
document.getElementById("board").append(tile);
}
}
// call to generate random 2s
setTwo();
setTwo();
}
// updates the appearance and the color of the tile
function updateTile(tile, num) {
tile.innerText = "";
tile.classList.value = "";
tile.classList.add("tile");
if (num > 0) {
tile.innerText = num.toString();
if (num <= 4096) {
tile.classList.add("x" + num.toString());
}
else {
tile.classList.add("x8192");
}
}
}
/**
* The 'load' event set with an event handler.
* The 'load' event is fired when the whole page is loaded including all dependent resources
* (css, js, images, etc.).
*/
window.onload = function() {
setGame();
}
/** handleSlide()
* A function responsible for the logic whenever arrow keys are pressed.
*/
function handleSlide(e) {
// displays what key is being pressed
console.log(e.code);
// disables the default behaviour of browser on key-events
e.preventDefault();
if (e.code=="ArrowLeft" && canMoveLeft()==true) {
slideLeft();
setTwo();
}
else if (e.code=="ArrowRight" && canMoveRight()==true) {
slideRight();
setTwo();
}
else if (e.code=="ArrowUp" && canMoveUp()==true) {
slideUp();
setTwo();
}
else if (e.code=="ArrowDown" && canMoveDown()==true) {
slideDown();
setTwo();
}
// dom score
document.getElementById('score').innerText = score;
checkWin();
if (hasLost() == true) {
setTimeout(() => {
alert("Game Over!");
restartGame();
alert("Click any arrow key to restart.");
})
}
}
document.addEventListener("keydown", handleSlide);
function filterZero(row) {
return row.filter(num => num != 0);
}
function slide(row) {
row = filterZero(row);
for (let i=0; i<row.length-1; i++){
if (row[i] == row[i+1]) {
row[i] *= 2;
row[i+1] = 0;
// updates the score
score += row[i];
}
}
while(row.length < columns){
row.push(0);
}
return row;
}
function slideLeft() {
// A loop repeats a programmed task
for (let r=0; r<rows; r++) {
let row = board[r];
// copy row, for animation
let originalRow = row.slice();
row = slide(row);
board[r] = row;
for (let c = 0; c<columns; c++) {
let tile= document.getElementById(r.toString() + "-" + c.toString());
let num = board[r][c];
updateTile(tile, num);
if(originalRow[c]!==num && num!==0){
// If the current tile is not equal to the the original tile, let's apply animation
tile.style.animation = "slide-from-right 0.3s";
setTimeout(() => {
tile.style.animation = "";
}, 300)
}
}
}
}
function slideRight() {
for (let r=0; r<rows; r++) {
let row = board[r];
// copy row, for animation
let originalRow = row.slice();
// the .reverse() method reverses the functionality of the slideLeft() - the code is originally from slideLeft().
row.reverse();
row = slide(row);
row.reverse();
board[r] = row;
for (let c = 0; c<columns; c++) {
let tile= document.getElementById(r.toString() + "-" + c.toString());
let num = board[r][c];
updateTile(tile, num);
if (originalRow[c]!==num && num!==0) {
// If the current tile is not equal to the the original tile, let's apply animation
tile.style.animation = "slide-from-left 0.3s";
setTimeout(() => {
tile.style.animation = "";
}, 300)
}
}
}
}
function slideUp() {
for (let c=0; c<columns; c++) {
let col = [board[0][c], board[1][c], board[2][c], board[3][c]];
// copy column, for animation
let originalcol = col.slice();
col = slide(col);
// apply animation
let changedIndeces = [];
for (let r=0; r<rows; r++) {
board[r][c] = col[r];
if (originalcol !== col[r]) {
changedIndeces.push(r);
}
}
for (let r=0; r<rows; r++) {
board[r][c] = col[r];
let tile = document.getElementById(r.toString() + "-" + c.toString());
let num = board[r][c];
updateTile(tile, num);
// apply animation
if (changedIndeces.includes(r) && num!==0) {
// If the current tile is not equal to the the original tile, let's apply animation
tile.style.animation = "slide-from-bottom 0.3s";
setTimeout(() => {
tile.style.animation = "";
}, 300)
}
}
}
}
function slideDown () {
for (let c=0; c<columns; c++) {
let col = [board[0][c], board[1][c], board[2][c], board[3][c]];
// copy column, for animation
let originalcol = col.slice();
// reverse() reverses the functionality of slideUp(), which will be used for the functionality of slideDown()
col.reverse();
col = slide(col);
col.reverse();
// apply animation
let changedIndeces = [];
for (let r=0; r<rows; r++) {
board[r][c] = col[r];
if (originalcol !== col[r]) {
changedIndeces.push(r);
}
}
for (let r=0; r<rows; r++) {
board[r][c] = col[r];
let tile = document.getElementById(r.toString() + "-" + c.toString());
let num = board[r][c];
updateTile(tile, num);
// apply animation
if (changedIndeces.includes(r) && num!==0) {
// If the current tile is not equal to the the original tile, let's apply animation
tile.style.animation = "slide-from-top 0.3s";
setTimeout(() => {
tile.style.animation = "";
}, 300)
}
}
}
}
function hasEmptyTile() {
for (let r=0; r<rows; r++) {
for (let c=0; c<columns; c++) {
// when a tile is empty
if (board[r][c] == 0) {
return true;
}
}
}
// when a tile is not empty
return false;
}
function setTwo() {
if (hasEmptyTile() == false) {
return;
}
// generate a new tile
let found = false;
while(!found){
let r = Math.floor(Math.random() * rows);
let c = Math.floor(Math.random() * columns);
if(board[r][c] == 0){
board[r][c] = 2;
let tile = document.getElementById(r.toString() + "-" + c.toString());
tile.innerText = "2";
tile.classList.add("x2");
found = true;
}
}
}
function checkWin() {
for (let r=0; r<rows; r++) {
for (let c=0; c<columns; c++) {
if (board[r][c]>=2048 && !is2048Exist) {
alert("You win! 2048");
is2048Exist = true;
}
else if (board[r][c]>=4096 && !is4096Exist) {
alert("You win! 4096");
is4096Exist = true;
}
else if (board[r][c]>=8192 && !is8192Exist) {
alert("You win! 8192");
is8192Exist = true;
}
}
}
}
function hasLost() {
for (let r=0; r<rows; r++) {
for (let c=0; c<columns; c++) {
if (board[r][c] === 0 ) {
return false;
}
const currentTile = board[r][c];
if (
r > 0 && board[r - 1][c] === currentTile ||
r < rows - 1 && board[r + 1][c] === currentTile ||
c > 0 && board[r][c - 1] === currentTile ||
c < columns - 1 && board[r][c + 1] === currentTile
) {
// Found adjacent cells with the same value, user has not lost
return false;
}
}
}
return true;
}
function restartGame() {
for (let r=0; r<rows; r++) {
for (let c=0; c<columns; c++) {
board[r][c] = 0;
score = 0;
}
}
setTwo();
}
// MOBILE FUNCTIONALITY
// captures the start of touch coordinates
document.addEventListener('touchstart', (e) => {
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
});
// calculate start to end touches information when touch input ends
document.addEventListener('touchend', (e) => {
if (!e.target.className.includes("tile")) {
return;
}
// difference of the start and end touch coordinates
let diffX = startX - e.changedTouches[0].clientX;
let diffY = startY - e.changedTouches[0].clientY;
if (Math.abs(diffX) > Math.abs(diffY)) {
// positive difference: leftward
if (diffX>0 && canMoveLeft()) {
slideLeft();
setTwo();
}
// negative difference: rightward
else if (diffX<0 && canMoveRight()) {
slideRight();
setTwo();
}
} else {
// positive difference: upward
if (diffY>0 && canMoveUp()) {
slideUp();
setTwo();
}
// negative difference: downward
else if (diffY<0 && canMoveDown()) {
slideDown();
setTwo();
}
}
// update score
document.getElementById('score').innerText = score;
// Notify for game-won or game-lost
checkWin();
if (hasLost() == true) {
setTimeout(() => {
alert("Game Over!");
restartGame();
alert("Click any arrow key to restart.");
})
}
});
// runs when there is touch input movement ('touchend' and 'touchstart')
document.addEventListener('touchmove', (e) => {
if (!e.target.className.includes("tile")) {
return;
}
// prevents scrolling on moving-touch input
e.preventDefault();
},
// necessary to make preventDefault work - { passive: false }
{ passive : false });
// conditions for moving tiles leftward
function canMoveLeft() {
for (let r=0; r<rows; r++) {
for (let c=1; c<columns; c++) {
if (board[r][c] !== 0) {
if (board[r][c-1]===0 || board[r][c-1]===board[r][c]) {
return true;
}
}
}
}
return false;
}
// conditions for moving tiles rightward
function canMoveRight() {
for (let r=0; r<rows; r++) {
for (let c=0; c<columns-1; c++) {
if (board[r][c] !== 0) {
if (board[r][c+1]===0 || board[r][c+1]===board[r][c]) {
return true;
}
}
}
}
return false;
}
// conditions for moving upward
function canMoveUp() {
for (let c=0; c<columns; c++) {
for (let r=1; r<rows; r++) {
if (board[r][c] !== 0) {
if (board[r-1][c]===0 || board[r-1][c]===board[r][c]) {
return true;
}
}
}
}
return false;
}
// conditions for moving downward
function canMoveDown() {
for (let c=0; c<columns; c++) {
for (let r=0; r<rows-1; r++) {
if (board[r][c] !== 0) {
if (board[r+1][c]===0 || board[r+1][c]===board[r][c]) {
return true;
}
}
}
}
return false;
}