空闲游戏结构对象的最佳方法

时间:2018-01-12 17:58:35

标签: javascript html5

我在JS / HTML5中制作了一个快速闲置游戏,它使用一个对象存储有关玩家升级的信息。

var buttons = {

    //Button Key : [Name, Button Count, Initial Cost, Effect (how
    //much money to add per click/sec), Cost Exponent, Effect to
    //add on next upgrade]

    "upgradeClick" : ["Upgrade!", 0, 0.50, 0.01, 10, 0.01],
    "upgradeAuto" : ["Automate!", 0, 1.00, 0.00, 50, 0.01],
    "buyCompany" : ["Start A Company!", 0, 500.00]
}

for(var i = 0; i < Object.keys(buttons).length; i++) (function(i) {
    var newButton = document.createElement("button");
    newButton.innerHTML = buttons[Object.keys(buttons)[i]][0] + "(" + buttons[Object.keys(buttons)[i]][1] + ")<br>" + buttons[Object.keys(buttons)[i]][2].toFixed(2);;
    newButton.id = Object.keys(buttons)[i];
    newButton.zIndex = 3;
    newButton.onclick = function() {
        if(d >= buttons[Object.keys(buttons)[i]][2]) {
            d -= buttons[Object.keys(buttons)[i]][2];
            buttons[Object.keys(buttons)[i]][1] += 1;
            buttons[Object.keys(buttons)[i]][2] = 0.5 * Math.pow(buttons[Object.keys(buttons)[i]][4], buttons[Object.keys(buttons)[i]][1]);
            buttons[Object.keys(buttons)[i]][3] += buttons[Object.keys(buttons)[i]][5];
            document.getElementById(this.id).innerHTML = buttons[this.id][0] + "(" + buttons[this.id][1] + ")<br>" + buttons[this.id][2].toFixed(2);;
            if(buttons[Object.keys(buttons)[i]][1] % 5 == 0) {
                buttons[Object.keys(buttons)[i]][3] += buttons[Object.keys(buttons)[i]][1] * 10;
            }
        }
    };
    document.body.appendChild(newButton);
})(i);

这是存储按钮的最佳方式吗?信息并检索它?这样做会影响程序的速度/性能吗?

1 个答案:

答案 0 :(得分:1)

我会将数据构建到对象中,并尝试使用变量来表示每个按钮,而不是挖掘buttons[Object.keys(buttons)[i]] ....来获取每个属性。我没有完全重做你的代码,但这里有一个如何构建它的示例。我不得不猜测数组中的值是基于我对闲人游戏的真棒(lol)知识。使用forEach而不是for循环可以很好地关闭循环的值,因此您不需要IIFE。

var buttons = [{
    name: "upgradeClick",
    text: "Upgrade!",
    qty: 0,
    price: 0.50,
    multiplier: 10,
    priceAdd: 0.01
},{
    name: "upgradeAuto",
    text: ... (etc)
}];

buttons.forEach(function (btn, i) {
    var newButton = document.createElement("button");
    newButton.innerHTML = btn.text + "(" + btn.qty + ")<br>" + btn.price.toFixed(2);
    newButton.id = btn.name;
    newButton.style.zIndex = 3;

    newButton.onclick = function () {
        if (d >= btn.price) {
            d -= btn.price;
            btn.qty++;

            btn.price = 0.5 * Math.pow(btn.multiplier, btn.qty);
            // etc
        }

    };

});