Path: blob/main/projects/9007199254740992/js/grid.js
1834 views
function Grid(size) {1this.size = size;23this.cells = [];45this.build();6}78// Build a grid of the specified size9Grid.prototype.build = function () {10for (var x = 0; x < this.size; x++) {11var row = this.cells[x] = [];1213for (var y = 0; y < this.size; y++) {14row.push(null);15}16}17};1819// Find the first available random position20Grid.prototype.randomAvailableCell = function () {21var cells = this.availableCells();2223if (cells.length) {24return cells[Math.floor(Math.random() * cells.length)];25}26};2728Grid.prototype.availableCells = function () {29var cells = [];3031this.eachCell(function (x, y, tile) {32if (!tile) {33cells.push({ x: x, y: y });34}35});3637return cells;38};3940// Call callback for every cell41Grid.prototype.eachCell = function (callback) {42for (var x = 0; x < this.size; x++) {43for (var y = 0; y < this.size; y++) {44callback(x, y, this.cells[x][y]);45}46}47};4849// Check if there are any cells available50Grid.prototype.cellsAvailable = function () {51return !!this.availableCells().length;52};5354// Check if the specified cell is taken55Grid.prototype.cellAvailable = function (cell) {56return !this.cellOccupied(cell);57};5859Grid.prototype.cellOccupied = function (cell) {60return !!this.cellContent(cell);61};6263Grid.prototype.cellContent = function (cell) {64if (this.withinBounds(cell)) {65return this.cells[cell.x][cell.y];66} else {67return null;68}69};7071// Inserts a tile at its position72Grid.prototype.insertTile = function (tile) {73this.cells[tile.x][tile.y] = tile;74};7576Grid.prototype.removeTile = function (tile) {77this.cells[tile.x][tile.y] = null;78};7980Grid.prototype.withinBounds = function (position) {81return position.x >= 0 && position.x < this.size &&82position.y >= 0 && position.y < this.size;83};848586