2014-11-03 99 views
1

我工作虽然雄辩的Javascript。我在第15章“平台游戏”的最后,我很难弄清楚如何让游戏暂停。如何正确调用此功能?

一个在本章结尾的练习要求你要做到这一点: “使人们有可能暂停(暂停),并按下Esc键暂停游戏

这可以通过改变来完成。 runLevel函数使用另一个键盘事件 处理程序,并在Esc键被击中时中断或恢复动画。“作者说你可以通过重新调整runLevel调用runAnimation的方式来做到这一点。 这里提到的功能:

function runLevel(level, Display, andThen) { 
    var display = new Display(document.body, level); 
    runAnimation(function(step) { 
     level.animate(step, arrows); 
     display.drawFrame(step); 
     if (level.isFinished()) { 
     display.clear(); 
     if (andThen) 
      andThen(level.status); 
     return false; 
     } 
    }); 
    } 

因此,我修改了函数:

function runLevel(level, Display, andThen) { 
    var display = new Display(document.body, level); 
    var paused = false; 

    addEventListener("keydown", function(event){ 
     if (event.keyCode == 27) { 
      paused = !paused; 
     } 
    }); 

    if (!paused){ 
     runAnimation(function(step) { 
      level.animate(step, arrows); 
      display.drawFrame(step); 
      if (level.isFinished()) { 
      display.clear(); 
      if (andThen) 
       andThen(level.status); 
      return false; 
      } 
     }); 
    } 

    } 

但游戏继续玩,即使我打逃脱。我不懂为什么。
游戏的完整代码可以在这里找到: http://eloquentjavascript.net/code/chapter/15_game.js 在此先感谢您的帮助!

+4

提示:调用了多少次runLevel函数? – zerkms 2014-11-03 00:46:06

回答

1

尝试将if语句放在回调函数中。

runAnimation(function(step) { 
    if (!paused){ 
     level.animate(step, arrows); 
     display.drawFrame(step); 
     if (level.isFinished()) { 
     display.clear(); 
     if (andThen) 
      andThen(level.status); 
     return false; 
     } 
    } 
    });