Как насчет использования JSON.stringify
перед сохранением данных и JSON.parse
после их возврата из хранилища. Это "сохраняет" типы. Не нужно индивидуально заботиться о правильной процедуре приведения типов данных. Я также предлагаю использовать ровно один объект хранения для всех данных игры / игрока.
Ключ хранения для установки / получения ровно одного объекта данных может представлять собой комбинацию имени игры и личности игрока. имя пользователя / идентификатор ... как ...
localStorage.setItem('adventure-x-charlie', JSON.stringify(data));
... с data
, выглядящим примерно так ...
const data = { moneyAdd: 1, money: 1000, crystals: 0, wood: 0, metal: 0, sword: 0, rsword: 0, hasAnvil: false };
Реорганизованный пример кода OP может оказаться что только что было сказано (к сожалению, localStorage
не работает для «изолированных ящиков с кодом», но ...). Вставка следующего кода в консоль инструментов разработчика тоже делает свое дело ...
const RolePlay = (function () {
// local module functionality
// ... dealing with session data
const defaultSessionData = {
// profitValue: 1
moneyAdd: 1,
money: 1000,
crystal: 0,
wood: 0,
metal: 0,
sword: 0,
rsword: 0,
hasAnvil: false
};
function resetSessionData(data) {
return Object.assign(data, defaultSessionData);
}
function getInitialSessionData(sessionId) {
return (
JSON.parse(localStorage.getItem(sessionId))
|| resetSessionData({})
);
}
function persistSessionData(sessionId, data) {
return localStorage.setItem(sessionId, JSON.stringify(data));
}
// local module functionality
// ... dealing with session data display
function displayCrystalCount(data) {
alert(`You own ${ data.crystal } crystal(s).`);
}
function displayMetalCount(data) {
alert(`You have ${ data.metal } metal(s).`);
}
function displayWoodCount(data) {
alert(`You have ${ data.wood } wood(s).`);
}
function displaySavings(data) {
alert(`You 've got ${ data.money } bucks.`);
}
function displayInventory(data) {
alert(`\
Here is your inventory:\n\
${ data.money } bucks\n\
${ data.crystal } crystal(s)\n\
${ data.wood } wood(s)\n\
${ data.metal } metal(s)\n\
${ data.sword } sword(s)\n\
has anvil (${ data.hasAnvil })\n\
${ data.rsword } reinforced sword(s)\
`);
}
// local module functionality
// ... dealing with state changes of session data
function incrementInventoryCount(data, key, value) {
data[key] = (data[key] + (value || 1));
}
function decrementInventoryCount(data, key, value) {
data[key] = (data[key] - (value || 1));
}
function craftBasicSword(data) {
const isConfirmed = confirm(`\
Are you sure you want to buy one basic sword\
for 2 metals, 1 wood, and 1 crystal?\
`);
if (isConfirmed) {
if (
data.crystal >= 1
&& data.wood >= 1
&& data.metal >= 2
) {
decrementInventoryCount(data, 'metal', 2);
decrementInventoryCount(data, 'wood');
decrementInventoryCount(data, 'crystal');
incrementInventoryCount(data, 'sword');
alert(`\
Transaction completed. You now have\
${ data.sword } basic sword(s).\
`);
} else {
alert('Insufficient Funds. Transaction Cancelled.');
}
} else {
alert('Transaction cancelled.');
}
}
function craftReinforcedSword(data) {
const isConfirmed = confirm(`\
Are you sure you want to craft one reinforced sword\
with 1 basic sword and 2 metals with an anvil?\
`);
if (isConfirmed) {
if (
data.hasAnvil
&& data.sword >= 1
&& data.metal >= 2
) {
decrementInventoryCount(data, 'sword');
decrementInventoryCount(data, 'metal', 2);
incrementInventoryCount(data, 'rsword');
alert(`\
Transaction completed. You now have\
${ data.rsword } reinforced sword(s).\
`);
} else {
alert('Insufficient Funds. Transaction Cancelled.');
}
} else {
alert('Transaction cancelled.');
}
}
function craftAnvil(data) {
const isConfirmed = confirm(`\
Are you sure you want to craft\
one iron anvil for 4 metals?\
`);
if (isConfirmed) {
if (data.metal >= 4) {
decrementInventoryCount(data, 'metal', 4);
data.hasAnvil = true;
alert(`\
Transaction completed. You now have\
an anvil (${ data.hasAnvil }).\
`);
} else {
alert('Insufficient Funds. Transaction Cancelled.');
}
} else {
alert('Transaction cancelled.');
}
}
function sellBasicSword(data) {
const isConfirmed = confirm(`\
Are you sure you want to sell\
a basic sword and grab 150 bucks?\
`);
if (isConfirmed) {
if (data.sword >= 1) {
incrementInventoryCount(data, 'money', 150);
decrementInventoryCount(data, 'sword');
alert(`\
Transaction completed. You've just sold a basic sword.\
You now have ${ data.sword } basic sword(s)\
and ${ data.money } bucks in total.\
`);
} else {
alert('Insufficient Funds. Transaction Cancelled.');
}
} else {
alert('Transaction cancelled.');
}
}
function sellReinforcedSword(data) {
const isConfirmed = confirm(`\
Are you sure you want to sell\
a reinforced sword and grab 250 bucks?\
`);
if (isConfirmed) {
if (data.rsword >= 1) {
incrementInventoryCount(data, 'money', 250);
decrementInventoryCount(data, 'rsword');
alert(`\
Transaction completed. You've just sold a reinforced sword.\
You now have ${ data.sword } reinforced sword(s)\
and ${ data.money } bucks in total.\
`);
} else {
alert('Insufficient Funds. Transaction Cancelled.');
}
} else {
alert('Transaction cancelled.');
}
}
function buyOneBasicInventory(data, key, value) {
const isConfirmed = confirm(`\
Are you sure you want to buy one\
${ key } for ${ value } bucks?\
`);
if (isConfirmed) {
if (data.money >= value) {
decrementInventoryCount(data, 'money', value);
incrementInventoryCount(data, key);
alert(`\
Transaction completed.\
You now have ${ data[key] } ${ key }(s).\
`);
} else {
alert('Insufficient Funds. Transaction Cancelled.');
}
} else {
alert('Transaction cancelled.');
}
}
// Session constructor
function Session(sessionId, options/* { moneyAdd: 10 } */) {
// locally scoped session state for each session instance.
const state = Object.assign(
// get initial state either from local storage or from default configuration.
getInitialSessionData(sessionId),
// be capable of overwriting some of the session data via an `options` object.
(options || {})
);
// debugger;
this.persistData = function () {
// debugger;
persistSessionData(sessionId, state);
};
// could be `gainMoney`
this.addMoney = function () {
incrementInventoryCount(state, 'money', state.moneyAdd);
// incrementInventoryCount(state, 'money', state.profitValue);
};
// should be `addCrystal`
this.getCrystal = function () {
incrementInventoryCount(state, 'crystal');
};
// should be `addMetal`
this.getMetal = function () {
incrementInventoryCount(state, 'metal');
};
// should be `addWood`
this.getWood = function () {
incrementInventoryCount(state, 'wood');
};
this.buyCrystal = function () {
buyOneBasicInventory(state, 'crystal', 100);
};
this.buyMetal = function () {
buyOneBasicInventory(state, 'metal', 40);
};
this.buyWood = function () {
buyOneBasicInventory(state, 'wood', 20);
};
this.displayCrystals = function () {
displayCrystalCount(state);
};
this.displayMetal = function () {
displayMetalCount(state);
};
this.displayWood = function () {
displayWoodCount(state);
};
this.displayMoney = function () {
displaySavings(state);
};
this.displayInventory = function () {
displayInventory(state);
};
this.craftAnvil = function () {
craftAnvil(state);
};
this.craftSword = function () {
craftBasicSword(state);
};
this.craftRSword = function () {
craftReinforcedSword(state);
};
this.sellSword = function () {
sellBasicSword(state);
};
this.sellRSword = function () {
sellReinforcedSword(state);
};
}
// `RolePlay` module with `Session` constructor
return {
Session: Session
};
}());
const session = new RolePlay.Session('RolePlayX_charlie', { moneyAdd: 10 });
console.log('Object.keys(session) : ', Object.keys(session));
session.persistData();
console.log('recoveredSessionData : ', JSON.parse(localStorage.getItem('RolePlayX_charlie')));