-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
57 lines (53 loc) · 1.04 KB
/
game.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
function operate(row) {
row = slide(row);
row = combine(row);
row = slide(row);
return row;
}
// making new array
function slide(row) {
let arr = row.filter(val => val);
let missing = 4 - arr.length;
let zeros = Array(missing).fill(0);
arr = zeros.concat(arr);
return arr;
}
// operating on array itself
function combine(row) {
for (let i = 3; i >= 1; i--) {
let a = row[i];
let b = row[i - 1];
if (a == b) {
row[i] = a + b;
score += row[i];
row[i - 1] = 0;
}
}
return row;
}
function isGameWon() {
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (grid[i][j] == 2048) {
return true;
}
}
}
return false;
}
function isGameOver() {
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (grid[i][j] == 0) {
return false;
}
if (i !== 3 && grid[i][j] === grid[i + 1][j]) {
return false;
}
if (j !== 3 && grid[i][j] === grid[i][j + 1]) {
return false;
}
}
}
return true;
}