CLI 节点应用程序中的堆栈溢出

Stack Overflow in CLI Node App

我正在为 class 构建一个 cli Node 应用程序。当我 运行 它时,我陷入了无限循环,导致堆栈溢出。我确定这是因为 prompt 不会等到用户在 while 循环之前输入输入,那么处理这个问题的最佳方法是什么?

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);
}

while 循环非常快。在第一秒内第一个完成之前,它将创建数百个 setTimouts。

收到提示后让函数自行调用。示例:

// ...

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();