Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mamayaya1
GitHub Repository: mamayaya1/game
Path: blob/main/projects/cupcake2048/js/local_storage_manager.js
4626 views
1
window.fakeStorage = {
2
_data: {},
3
4
setItem: function (id, val) {
5
return this._data[id] = String(val);
6
},
7
8
getItem: function (id) {
9
return this._data.hasOwnProperty(id) ? this._data[id] : undefined;
10
},
11
12
removeItem: function (id) {
13
return delete this._data[id];
14
},
15
16
clear: function () {
17
return this._data = {};
18
}
19
};
20
21
function LocalStorageManager() {
22
this.bestScoreKey = "bestScoreCupcakes";
23
this.bestPointsKey = "bestPointsCupcakes";
24
this.gameStateKey = "gameStateCupcakes";
25
26
var supported = this.localStorageSupported();
27
this.storage = supported ? window.localStorage : window.fakeStorage;
28
}
29
30
LocalStorageManager.prototype.localStorageSupported = function () {
31
var testKey = "test";
32
var storage = window.localStorage;
33
34
try {
35
storage.setItem(testKey, "1");
36
storage.removeItem(testKey);
37
return true;
38
} catch (error) {
39
return false;
40
}
41
};
42
43
// Best score getters/setters
44
LocalStorageManager.prototype.getBestScore = function () {
45
return this.storage.getItem(this.bestScoreKey) || 0;
46
};
47
48
LocalStorageManager.prototype.setBestScore = function (score) {
49
this.storage.setItem(this.bestScoreKey, score);
50
};
51
52
// Best points getters/setters
53
LocalStorageManager.prototype.getBestPoints = function () {
54
return this.storage.getItem(this.bestPointsKey) || 0;
55
};
56
57
LocalStorageManager.prototype.setBestPoints = function (points) {
58
this.storage.setItem(this.bestPointsKey, points);
59
};
60
61
// Game state getters/setters and clearing
62
LocalStorageManager.prototype.getGameState = function () {
63
var stateJSON = this.storage.getItem(this.gameStateKey);
64
return stateJSON ? JSON.parse(stateJSON) : null;
65
};
66
67
LocalStorageManager.prototype.setGameState = function (gameState) {
68
this.storage.setItem(this.gameStateKey, JSON.stringify(gameState));
69
};
70
71
LocalStorageManager.prototype.clearGameState = function () {
72
this.storage.removeItem(this.gameStateKey);
73
};
74
75