如何正确调用此函数

How do I call this function correctly?

本文关键字:函数 调用 何正确      更新时间:2023-09-26

我正在使用Eloquent 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提前感谢您的帮助!

尝试将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;
      }
    }
  });