Files
2048/js/local_score_manager.js
T
Mark Frederiksen 02a24c0610 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
2014-03-18 14:48:55 -04:00

62 lines
1.5 KiB
JavaScript

window.fakeStorage = {
_data: {},
setItem: function (id, val) {
return this._data[id] = String(val);
},
getItem: function (id) {
return this._data.hasOwnProperty(id) ? this._data[id] : undefined;
},
removeItem: function (id) {
return delete this._data[id];
},
clear: function () {
return this._data = {};
}
};
function LocalScoreManager() {
this.bestScoreKey = "bestScore";
this.gameStateKey = "gameState";
var supported = this.localStorageSupported();
this.storage = supported ? window.localStorage : window.fakeStorage;
}
LocalScoreManager.prototype.localStorageSupported = function () {
var testKey = "test";
var storage = window.localStorage;
try {
storage.setItem(testKey, "1");
storage.removeItem(testKey);
return true;
} catch (error) {
return false;
}
};
LocalScoreManager.prototype.getBestScore = function () {
return this.storage.getItem(this.bestScoreKey) || 0;
};
LocalScoreManager.prototype.setBestScore = function (score) {
this.storage.setItem(this.bestScoreKey, score);
};
LocalScoreManager.prototype.getGameState = function () {
var stateJSON = this.storage.getItem(this.gameStateKey);
return stateJSON ? JSON.parse(stateJSON) : null;
};
LocalScoreManager.prototype.setGameState = function (gameState) {
this.storage.setItem(this.gameStateKey, JSON.stringify(gameState));
};
LocalScoreManager.prototype.clearGameState = function () {
this.storage.removeItem(this.gameStateKey);
};