如何编写一个循环来检查生命=== 0?

问题描述:

我正在制作一个非常简单的html5帆布游戏。我希望这样做,当玩家失去全部3条生命时,游戏重置。如何编写一个循环来检查生命=== 0?

我在想我可以做一个while循环,它总是检查生命=== 0然后运行一个函数,但是这打破了游戏,没有任何东西出现在画布上。

这是我的代码。

var lives = 3; 
while (lives <= 0) { 
var fullReset = function() { 

// Throw the monster somewhere on the screen randomly 
monster.x = 1 + (Math.random() * (canvas.width - 64)); 
monster.y = 1 + (Math.random() * (canvas.height - 64)); 
monster2.x = 1 + (Math.random() * (canvas.width - 100)); 
monster2.y = 1 + (Math.random() * (canvas.height - 100)); 


// player start again 
hero.x = canvas.width/2; 
hero.y = canvas.height/2; 

//score resets 
monstersCaught() = 0; 
lives() = 3; 
} 
fullReset(); 
} 
+1

如果(住=== 0) – prgrm

我认为你的方法存在一个概念错误。你从3条生命开始(在你的例子中缺少初始化)。然后,每当怪物遭到攻击时,你就减少一个人的生命并检查新的价值。当新值为零时,是时候重置游戏了。

所以,你的循环应该只处理移动你的对象,而只要怪物攻击并应用上述逻辑就会触发事件。

function gameLoop() { 

    var lives = 3; 
    if(lives <= 0) { 
    var fullReset = function() { 

    // Throw the monster somewhere on the screen randomly 
    monster.x = 1 + (Math.random() * (canvas.width - 64)); 
    monster.y = 1 + (Math.random() * (canvas.height - 64)); 
    monster2.x = 1 + (Math.random() * (canvas.width - 100)); 
    monster2.y = 1 + (Math.random() * (canvas.height - 100)); 


    // player start again 
    hero.x = canvas.width/2; 
    hero.y = canvas.height/2; 

    //score resets 
    monstersCaught() = 0; 
    lives() = 3; 
    } 
    fullReset(); 
    } 
    requestAnimationFrame(gameLoop); 
} 

你试过了requestAnimationFrame()这样你可能甚至不依赖于while循环和使用对象的换了个位置,每次再次提请画布上一遍又一遍。

这不是一个非常实用的方法来解决您的问题。

我会处理的是与一个OnEvent触发,例如当一个怪物的攻击,或者当玩家接触的怪物