我有一个问题,想出如何使用我使用的格式保存和加载我的游戏
所以我有这个
var upgradeButtonsData = [
{icon: 'dagger', name: 'Attack', level: 0, cost: 5, purchaseHandler: function(button, player) {
player.clickDmg += 1;
}},
{icon: 'swordIcon1', name: 'Auto-Attack', level: 0, cost: 25, purchaseHandler: function(button, player) {
player.dps += 5;
}}
];
我需要以与我游戏剩余部分相同的格式保存和加载它,例如我正在保存我的玩家金像这样
localStorage.setItem("playerGold",this.player.gold);
然后像这样加载它
playerGold_save = localStorage.getItem("playerGold") || "0";
this.player.gold = parseInt(playerGold_save);
我想做一些类似上面的代码,但我不知道如何
如果它的相关内容如何使用上面的代码
onUpgradeButtonClick: function(button, pointer) {
// make this a function so that it updates after we buy
function getAdjustedCost() {
return Math.ceil(button.details.cost + (button.details.level * 1.46));
}
if (this.player.gold - getAdjustedCost() >= 0) {
this.player.gold -= getAdjustedCost();
this.playerGoldText.text = 'Gold: ' + this.player.gold;
button.details.level++;
button.text.text = button.details.name + ': ' + button.details.level;
button.costText.text = 'Cost: ' + getAdjustedCost();
button.details.purchaseHandler.call(this, button, this.player);
}
},
我也使用Phaser作为框架
修改
显然人们对我要求我不想要如何保存已经完成的黄金的信息感到困惑,这只是我想要如何保存升级的一个例外保存'攻击的等级和成本以及'自动攻击的等级和下次游戏加载的成本
抱歉任何困惑修改 我想要保存这个代码
var upgradeButtonsData = [
{icon: 'dagger', name: 'Attack', level: 0, cost: 5, purchaseHandler: function(button, player) {
player.clickDmg += 1;
}},
{icon: 'swordIcon1', name: 'Auto-Attack', level: 0, cost: 25, purchaseHandler: function(button, player) {
player.dps += 5;
}}
];
答案 0 :(得分:0)
编辑:以下是保存和加载升级程序数据的代码:
function saveUpgrader() {
var save = [];
for(var i = 0; i < upgradeButtonsData.length; i++)
save.push([upgradeButtonsData[i].level, upgradeButtonsData[i].cost]); // [0] = level ; [1] = cost
try { localStorage.setItem('upgrader_save', JSON.stringify(save)); }
catch(e) {
alert('Failed to save upgrader\'s data');
}
}
function loadUpgrader() {
if(!localStorage.getItem('upgrader_save'))
return ;
try {
var json = JSON.parse(localStorage.getItem('upgrader_save'));
for(var i = 0; i < json.length; i++) {
upgradeButtonsData[i].level = json[i][0];
upgradeButtonsData[i].cost = json[i][1];
}
}
catch(e) {
alert('Failed to load upgrader\'s data');
}
}
调用saveUpgrader
函数将每个项目的level
和cost
保存到升级程序中,或loadUpgrader
加载它们(它将覆盖当前级别和费用)
注意:如果要将项目添加到升级程序,请在现有元素之后添加它,如下所示:
var upgradeButtonsData = [
{icon: 'dagger', name: 'Attack', level: 0, cost: 5, purchaseHandler: function(button, player) {
player.clickDmg += 1;
}},
{icon: 'swordIcon1', name: 'Auto-Attack', level: 0, cost: 25, purchaseHandler: function(button, player) {
player.dps += 5;
}},
// Add the new element here
{icon: '...', name: '...', level: 0, cost: 75, purchaseHandler: function(button, player) {
...
}}
];
如果在其他元素之前添加新元素,则保存将被破坏并做一些不好的事情。
我希望能帮到你:)。