gpt4 book ai didi

javascript - CLI Node 应用程序中的堆栈溢出

转载 作者:行者123 更新时间:2023-12-03 07:33:36 24 4
gpt4 key购买 nike

我正在为一个类构建一个 cli Node 应用程序。当我运行它时,我陷入无限循环,导致堆栈溢出。我确信这是因为提示不会等到用户在 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);
}

最佳答案

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

// ...

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

关于javascript - CLI Node 应用程序中的堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com