Search code examples
javascriptnode.jswhile-loopstack-overflowprompt

Stack Overflow in CLI Node App


I'm building a cli Node app for a class. When I run it, I get stuck in an infinite loop which causes a stack overflow. I'm sure it's because prompt doesn't wait until the user enters input before the while iterates through, so what's the best way to handle this?

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

Solution

  • Have the function call itself after you receive the prompt. Example:

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