-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
96 lines (73 loc) · 2.28 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
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
const store = {
dims: {
width: 20,
height: 20,
},
filledCells: [],
};
function populateCells(cellsArray = []) {
store.filledCells = cellsArray;
}
function reset() {
store.filledCells = [];
}
const array = new Array(20).fill();
const allCells = [];
array.forEach((a, x) => {
array.forEach((b, y) => {
allCells.push({
x: x + 1,
y: y + 1,
});
});
});
function addCells() {
const filledCellStrings = store.filledCells.map((c) => JSON.stringify(c));
allCells.forEach((cell) => {
const filledCellIndex = filledCellStrings.indexOf(JSON.stringify(cell));
// landed on a filled cell
if (filledCellIndex > -1) {
store.filledCells.forEach((mainCell) => {
const filledNeighbours = store.filledCells.filter((otherCell) => {
const xDiff = Math.abs(mainCell.x - otherCell.x);
const yDiff = Math.abs(mainCell.y - otherCell.y);
const isSelf = (xDiff + yDiff === 0);
const isNeighbour = (xDiff <= 1 && yDiff <= 1);
return !isSelf && isNeighbour;
});
console.log('filledNeighbours:', filledNeighbours);
if (filledNeighbours.length >= 3) {
store.filledCells.push(cell);
}
});
}
});
}
function removeCells() {
store.filledCells = store.filledCells.filter((mainCell) => {
const filledNeighbours = store.filledCells.filter((otherCell) => {
const xDiff = Math.abs(mainCell.x - otherCell.x);
const yDiff = Math.abs(mainCell.y - otherCell.y);
const isSelf = (xDiff + yDiff === 0);
const isNeighbour = (xDiff <= 1 && yDiff <= 1);
return !isSelf && isNeighbour;
});
// console.log('mainCell:', mainCell);
// console.log('neighbours:', neighbours);
// console.log('=============================');
if (filledNeighbours.length <= 1) {
return false;
}
if (filledNeighbours.length >= 4) {
return false;
}
return true;
});
}
module.exports = {
store,
populateCells,
removeCells,
addCells,
reset,
};