2014-11-03 101 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; 
     } 
    } 
    });