Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mamayaya1
GitHub Repository: mamayaya1/game
Path: blob/main/projects/9007199254740992/js/grid.js
4626 views
1
function Grid(size) {
2
this.size = size;
3
4
this.cells = [];
5
6
this.build();
7
}
8
9
// Build a grid of the specified size
10
Grid.prototype.build = function () {
11
for (var x = 0; x < this.size; x++) {
12
var row = this.cells[x] = [];
13
14
for (var y = 0; y < this.size; y++) {
15
row.push(null);
16
}
17
}
18
};
19
20
// Find the first available random position
21
Grid.prototype.randomAvailableCell = function () {
22
var cells = this.availableCells();
23
24
if (cells.length) {
25
return cells[Math.floor(Math.random() * cells.length)];
26
}
27
};
28
29
Grid.prototype.availableCells = function () {
30
var cells = [];
31
32
this.eachCell(function (x, y, tile) {
33
if (!tile) {
34
cells.push({ x: x, y: y });
35
}
36
});
37
38
return cells;
39
};
40
41
// Call callback for every cell
42
Grid.prototype.eachCell = function (callback) {
43
for (var x = 0; x < this.size; x++) {
44
for (var y = 0; y < this.size; y++) {
45
callback(x, y, this.cells[x][y]);
46
}
47
}
48
};
49
50
// Check if there are any cells available
51
Grid.prototype.cellsAvailable = function () {
52
return !!this.availableCells().length;
53
};
54
55
// Check if the specified cell is taken
56
Grid.prototype.cellAvailable = function (cell) {
57
return !this.cellOccupied(cell);
58
};
59
60
Grid.prototype.cellOccupied = function (cell) {
61
return !!this.cellContent(cell);
62
};
63
64
Grid.prototype.cellContent = function (cell) {
65
if (this.withinBounds(cell)) {
66
return this.cells[cell.x][cell.y];
67
} else {
68
return null;
69
}
70
};
71
72
// Inserts a tile at its position
73
Grid.prototype.insertTile = function (tile) {
74
this.cells[tile.x][tile.y] = tile;
75
};
76
77
Grid.prototype.removeTile = function (tile) {
78
this.cells[tile.x][tile.y] = null;
79
};
80
81
Grid.prototype.withinBounds = function (position) {
82
return position.x >= 0 && position.x < this.size &&
83
position.y >= 0 && position.y < this.size;
84
};
85
86