布尔值作为参数/参数?

时间:2014-11-23 21:04:59

标签: javascript html5

我正在制作一个简单的HTML5游戏,我正在尝试实现一个成就系统。我的方法是创建一个具有名称,描述,条件等属性的成就对象......所以现在我需要做的就是通过调用类似于Achievement.LookARock = new Achievement("Look! A Rock!", "Mined stone for the first time!", (stone.count == 1), false);的东西来创建不同的Achievement对象。所以现在我所要做的就是检查成就条件是否正确。我通过致电setInterval来做到这一点。这是我正在使用的代码:

//Achievements
Achievement.LookARock = new Achievement("Look! A rock!", "Mined stone for the first time.", (stone.count >= 1), false);
Achievement.IGotWood = new Achievement("Haha... I got wood...", "Mined wood for the first time.", (wood.count == 1), false);
Achievement.Stone100 = new Achievement("Stone 100", "Mined 100 stone blocks.", (stone.count == 100), false);
Achievement.Stone500 = new Achievement("Stone 500", "Mined 500 stone blocks.", (stone.count == 500), false);
Achievement.Stone1000 = new Achievement("Stone 1000", "Mined 1000 stone blocks.", (stone.count == 1000), false);
Achievement.FirstCraft = new Achievement("First Craft", "Crafted your first item.", (craftedtools.length == 2), false);
Achievement.Shiny = new Achievement("Oooooo... shiny!", "Mined a diamond!", (diamond_ore.count == 1), false);
Achievement.ICantButter = new Achievement("I can't believe it's not butter!", "Mined gold!", (gold_ore.count == 1), false);
Achievement.IronMan = new Achievement("I am Iron Man...", "Mined metal!", (metal_ore == 1), false);
//Achievement.Level1 = new Achievement("Level 1 Completed!", "Crafted a Diamond Pickaxe!", craftedtools.includes(diamond_pick), false);

/*var achievements = [Achievement.LookARock, 
                    Achievement.IGotWood, 
                    Achievement.Stone100,
                    Achievement.Stone500,
                    Achievement.Stone1000,
                    Achievement.FirstCraft,
                    Achievement.Shiny,
                    Achievement.ICantButter,
                    Achievement.IronMan];*/

function checkAchievement(achievement){

    var condition = achievement.condition;
    var achieved = achievement.achieved;

    if(condition !== false){

        return true;

    }

    return false;

}

function checkAchievements(){

    for(var i = 0; i < achievements.length; i++){

        var a = achievements[i];

        if(checkAchievement(a)){

            alert(a.name + "\n" + a.description);

        }

    }

}

function update(){

    try{

        checkAchievements();

    }catch(e){

        console.log(e);

    }

}

changeTool(stone_pick);
makeMineGenerator();

setInterval(update, 50);

我确信它正在检查成就。但即使计数是正确的数量,条件总是返回假。有什么方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您创造成就的方式是有原因的。 (stone.count == 1)在调用Achievement构造函数之前进行求值,以便在创建对象时为condition属性分配false

你需要建立一个Achievement对象,其中包含一个在你想要检查成就时调用的函数。

Achievement.LookARock = new Achievement(
  "Look!  A Rock!", 
  "Mined stone for the first time!", 
  function() { 
    return stone.count == 1; 
  }, 
  false
);

然后检查成就,您可以使用if (achievement.condition())