Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mamayaya1
GitHub Repository: mamayaya1/game
Path: blob/main/projects/cupcake2048/js/grid.js
4626 views
1
function Grid(size, previousState) {
2
this.size = size;
3
this.cells = previousState ? this.fromState(previousState) : this.empty();
4
}
5
6
// Build a grid of the specified size
7
Grid.prototype.empty = function () {
8
var cells = [];
9
10
for (var x = 0; x < this.size; x++) {
11
var row = cells[x] = [];
12
13
for (var y = 0; y < this.size; y++) {
14
row.push(null);
15
}
16
}
17
18
return cells;
19
};
20
21
Grid.prototype.fromState = function (state) {
22
var cells = [];
23
24
for (var x = 0; x < this.size; x++) {
25
var row = cells[x] = [];
26
27
for (var y = 0; y < this.size; y++) {
28
var tile = state[x][y];
29
row.push(tile ? new Tile(tile.position, tile.value) : null);
30
}
31
}
32
33
return cells;
34
};
35
36
// Find the first available random position
37
Grid.prototype.randomAvailableCell = function () {
38
var cells = this.availableCells();
39
40
if (cells.length) {
41
return cells[Math.floor(Math.random() * cells.length)];
42
}
43
};
44
45
Grid.prototype.availableCells = function () {
46
var cells = [];
47
48
this.eachCell(function (x, y, tile) {
49
if (!tile) {
50
cells.push({ x: x, y: y });
51
}
52
});
53
54
return cells;
55
};
56
57
// Call callback for every cell
58
Grid.prototype.eachCell = function (callback) {
59
for (var x = 0; x < this.size; x++) {
60
for (var y = 0; y < this.size; y++) {
61
callback(x, y, this.cells[x][y]);
62
}
63
}
64
};
65
66
// Check if there are any cells available
67
Grid.prototype.cellsAvailable = function () {
68
return !!this.availableCells().length;
69
};
70
71
// Check if the specified cell is taken
72
Grid.prototype.cellAvailable = function (cell) {
73
return !this.cellOccupied(cell);
74
};
75
76
Grid.prototype.cellOccupied = function (cell) {
77
return !!this.cellContent(cell);
78
};
79
80
Grid.prototype.cellContent = function (cell) {
81
if (this.withinBounds(cell)) {
82
return this.cells[cell.x][cell.y];
83
} else {
84
return null;
85
}
86
};
87
88
// Inserts a tile at its position
89
Grid.prototype.insertTile = function (tile) {
90
this.cells[tile.x][tile.y] = tile;
91
};
92
93
Grid.prototype.removeTile = function (tile) {
94
this.cells[tile.x][tile.y] = null;
95
};
96
97
Grid.prototype.withinBounds = function (position) {
98
return position.x >= 0 && position.x < this.size &&
99
position.y >= 0 && position.y < this.size;
100
};
101
102
Grid.prototype.serialize = function () {
103
var cellState = [];
104
105
for (var x = 0; x < this.size; x++) {
106
var row = cellState[x] = [];
107
108
for (var y = 0; y < this.size; y++) {
109
row.push(this.cells[x][y] ? this.cells[x][y].serialize() : null);
110
}
111
}
112
113
return {
114
size: this.size,
115
cells: cellState
116
};
117
};
118
119