2016-03-01 90 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