Added persistence of game state to localstorage after each move
Added rebuilding of game state from localstoage on page load Added New Game button to allow game restarts now that refreshes resume the game
This commit is contained in:
+35
-7
@@ -1,20 +1,32 @@
|
||||
function Grid(size) {
|
||||
function Grid(size, previousCellState) {
|
||||
this.size = size;
|
||||
|
||||
this.cells = [];
|
||||
|
||||
this.build();
|
||||
this.cells = previousCellState ? this.buildFromPreviousState(previousCellState) : this.buildNew();
|
||||
}
|
||||
|
||||
// Build a grid of the specified size
|
||||
Grid.prototype.build = function () {
|
||||
Grid.prototype.buildNew = function () {
|
||||
var cells = [];
|
||||
for (var x = 0; x < this.size; x++) {
|
||||
var row = this.cells[x] = [];
|
||||
var row = cells[x] = [];
|
||||
|
||||
for (var y = 0; y < this.size; y++) {
|
||||
row.push(null);
|
||||
}
|
||||
}
|
||||
return cells;
|
||||
};
|
||||
|
||||
Grid.prototype.buildFromPreviousState = function (state) {
|
||||
var cells = [];
|
||||
for (var x = 0; x < this.size; x++) {
|
||||
var row = cells[x] = [];
|
||||
|
||||
for (var y = 0; y < this.size; y++) {
|
||||
var tileState = state[x][y];
|
||||
row.push(tileState ? new Tile(tileState.position, tileState.value) : null);
|
||||
}
|
||||
}
|
||||
return cells;
|
||||
};
|
||||
|
||||
// Find the first available random position
|
||||
@@ -82,3 +94,19 @@ Grid.prototype.withinBounds = function (position) {
|
||||
return position.x >= 0 && position.x < this.size &&
|
||||
position.y >= 0 && position.y < this.size;
|
||||
};
|
||||
|
||||
Grid.prototype.gridState = function () {
|
||||
var cellState = [];
|
||||
for (var x = 0; x < this.size; x++) {
|
||||
var row = cellState[x] = [];
|
||||
|
||||
for (var y = 0; y < this.size; y++) {
|
||||
row.push(this.cells[x][y] ? this.cells[x][y].tileState() : null);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
size: this.size,
|
||||
cells: cellState
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user