Path: blob/main/projects/cupcake2048/js/grid.js
1834 views
function Grid(size, previousState) {1this.size = size;2this.cells = previousState ? this.fromState(previousState) : this.empty();3}45// Build a grid of the specified size6Grid.prototype.empty = function () {7var cells = [];89for (var x = 0; x < this.size; x++) {10var row = cells[x] = [];1112for (var y = 0; y < this.size; y++) {13row.push(null);14}15}1617return cells;18};1920Grid.prototype.fromState = function (state) {21var cells = [];2223for (var x = 0; x < this.size; x++) {24var row = cells[x] = [];2526for (var y = 0; y < this.size; y++) {27var tile = state[x][y];28row.push(tile ? new Tile(tile.position, tile.value) : null);29}30}3132return cells;33};3435// Find the first available random position36Grid.prototype.randomAvailableCell = function () {37var cells = this.availableCells();3839if (cells.length) {40return cells[Math.floor(Math.random() * cells.length)];41}42};4344Grid.prototype.availableCells = function () {45var cells = [];4647this.eachCell(function (x, y, tile) {48if (!tile) {49cells.push({ x: x, y: y });50}51});5253return cells;54};5556// Call callback for every cell57Grid.prototype.eachCell = function (callback) {58for (var x = 0; x < this.size; x++) {59for (var y = 0; y < this.size; y++) {60callback(x, y, this.cells[x][y]);61}62}63};6465// Check if there are any cells available66Grid.prototype.cellsAvailable = function () {67return !!this.availableCells().length;68};6970// Check if the specified cell is taken71Grid.prototype.cellAvailable = function (cell) {72return !this.cellOccupied(cell);73};7475Grid.prototype.cellOccupied = function (cell) {76return !!this.cellContent(cell);77};7879Grid.prototype.cellContent = function (cell) {80if (this.withinBounds(cell)) {81return this.cells[cell.x][cell.y];82} else {83return null;84}85};8687// Inserts a tile at its position88Grid.prototype.insertTile = function (tile) {89this.cells[tile.x][tile.y] = tile;90};9192Grid.prototype.removeTile = function (tile) {93this.cells[tile.x][tile.y] = null;94};9596Grid.prototype.withinBounds = function (position) {97return position.x >= 0 && position.x < this.size &&98position.y >= 0 && position.y < this.size;99};100101Grid.prototype.serialize = function () {102var cellState = [];103104for (var x = 0; x < this.size; x++) {105var row = cellState[x] = [];106107for (var y = 0; y < this.size; y++) {108row.push(this.cells[x][y] ? this.cells[x][y].serialize() : null);109}110}111112return {113size: this.size,114cells: cellState115};116};117118119