我正在研究js游戏,我觉得我正在重新编写很多代码。反正有没有使代码更优化或使它成为一个重要的功能?我希望这是足够的代码,如果不是,我将使用所有代码制作一个jfiddle。
// Shop, Double coffee
$("body").on("click", "#shopUpgradeDoublepoints", function() {
if(storeDoublePoints === false && totalClicks >= storeDoublePointsCost) {
storeDoublePoints = true;
storeReleventCheckMultiplier = true;
storeCurrentActive = "storeDoublePoints";
storeBoughtItems.push("upgradeDoublePoints");
totalClicks -= storeDoublePointsCost;
storeReleventMultiplier();
$("#shopUpgradeDoublepoints").fadeOut();
$(".clicks").html(totalClicks);
console.log("Unlocked doublepoints for " + storeDoublePointsCost + " coffee. Total coffee: " + totalClicks);
}
});
// Shop, Triple coffee
$("body").on("click", "#shopUpgradeTriplepoints", function() {
if(storeTriplePoints === false && totalClicks >= storeTriplePointsCost) {
storeTriplePoints = true;
storeCurrentActive = "storeTriplePoints";
storeBoughtItems.push("upgradeTriplePoints");
totalClicks -= storeTriplePointsCost;
storeReleventMultiplier();
$(".clicks").html(totalClicks);
$("#shopUpgradeTriplepoints").fadeOut();
console.log("Unlocked triplepoints for " + storeTriplePointsCost + " coffee. Total coffee: " + totalClicks);
}
});
// Shop, Quadruple coffee
$("body").on("click", "#shopUpgradeQuadruplepoints", function(){
if(storeQuadruplePoints === false && totalClicks >= storeQuadruplePointsCost) {
storeQuadruplePoints = true;
storeCurrentActive = "storeQuadruplePoints";
storeBoughtItems.push("upgradeQuadruplePoints");
totalClicks -= storeQuadruplePointsCost;
storeReleventMultiplier();
$("#shopUpgradeQuadruplepoints").fadeOut();
$(".clicks").html(totalClicks);
console.log("Unlocked quadruplepoints for " + storeQuadruplePointsCost + " coffee. Total coffee: " + totalClicks);
}
});
答案 0 :(得分:1)
我认为你可以将所有数据放在一个对象数组中,然后循环遍历它们并在其中处理一个函数,就像这样,
var items = [{
name: "Double",
points: false,
pointsCost: 1234
}, {
name: "Triple",
points: true,
pointsCost: 1234
}, {
name: "Quadruple",
points: false,
pointsCost: 1234
}];
for (var i = 0; i < items.length; i++) {
processItem(items[i]);
}
function processItem(item) {
var name = item.name + "points";
var id = "#showUpgrade" + name;
$("body").on("click", id, function() {
if (!item.points && totalClicks >= item.pointsCost) {
item.points = true;
storeCurrentActive = "store" + name;
storeBoughtItems.push("upgrade" + name);
totalClicks -= item.cost;
storeReleventMultiplier();
$(".clicks").html(totalClicks);
$(id).fadeOut();
console.log(`Unlocked ${name} for ${item.cost} coffee. Total coffee: ${totalClicks}`);
//console.log("Unlocked " + name + " for " + item.cost + " coffee. Total coffee: " + totalClicks);
}
});
}