2016-03-01 15 views
0

我正在爲一個類構建cli節點應用程序。當我運行它時,我陷入了一個導致堆棧溢出的無限循環。我確定這是因爲提示不會等到用戶在迭代之前輸入輸入,那麼處理這個問題的最佳方法是什麼?CLI節點應用程序堆棧溢出

var prompt = require('prompt'); 

prompt.start(); 

// initialize fields 
var user = { 
health: 100, 
    damage: Math.floor(Math.random() * (5 - 2 + 1)) + 2 
}, 
    zombie = { 
     health: 20, 
     damage: Math.floor(Math.random() * (5 - 2 + 1)) + 2 
    }; 


while (user.health > 0 || zombie.health > 0) { 
    setTimeout(function() { 
     console.log('User:\t' + user.health + '\nZombie:\t' + zombie.health); 
     var randNum = Math.random * 10; 
     prompt.get(['guess'], function(err, result) { 
      if (result.guess === randNum) { 
       zombie.health -= user.damage; 
       console.log('You strike the Zombie!\nZombie takes ' + user.damage + ' points of damage.\nZombie has ' + zombie.health + 'health left.\n'); 
     } 
     else { 
      user.health -= zombie.damage; 
      console.log('Zombie slashes at you!\nYou take ' + zombie.damage + ' points of damage.\nYou have ' + user.health + ' health left.\n'); 
     } 
     console.log('Tomorrow is another day...\n'); 
     }); 
    }, 1000); 
} 
+0

while循環運行速度非常快,並且在第一秒鐘完成之前會創建數百個超時。 –

回答

1

在收到提示後有函數調用自己。例如:

// ... 

function runGame() { 
    if (user.health > 0 || zombie.health > 0) { 
     console.log('User:\t' + user.health + '\nZombie:\t' + zombie.health); 
     var randNum = Math.random * 10; 

     prompt.get(['guess'], function(err, result) { 
      if (result.guess === randNum) { 
       zombie.health -= user.damage; 
       console.log('You strike the Zombie!\nZombie takes ' + user.damage + ' points of damage.\nZombie has ' + zombie.health + 'health left.\n'); 
      } else { 
       user.health -= zombie.damage; 
       console.log('Zombie slashes at you!\nYou take ' + zombie.damage + ' points of damage.\nYou have ' + user.health + ' health left.\n'); 
      } 

      console.log('Tomorrow is another day...\n'); 

      runGame(); // Wait for more input after getting and parsing current input. 
     }); 
    } 
} 

runGame(); 
+0

謝謝!我發現我甚至不需要setTimeout(),我只需要從遞歸的角度考慮問題。 – Scorpio750

0

while循環進行得非常快。它會在第一秒完成之前創建數百個setTimout。

+0

對,所以我應該避免使用while循環?在這種情況下,不確定如何構建我的邏輯。 – Scorpio750