我正在尝试制造一个具有“数字猜谜游戏”功能的不和谐机器人。
当我运行机器人时,它给了我这个错误:
致命错误:接近堆限制分配的无效标记压缩失败-JavaScript堆内存不足
似乎while循环变成了无限循环。这是我的代码(所有函数和变量都已声明)
while (numberOfGuesses < 5) {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000,
max: 1
});
collector.on('collect', message => {
if (guess.length == 0 || !guessInRange(guess)) {
message.channel.send('please say 1~100');
} else {
if (parseInt(guess) == secretNumber) {
message.channel.send('Boom! Correct!');
return collector.stop();
} else if (parseInt(guess) < secretNumber) {
numberOfGuesses++;
message.channel.send('Too small');
collector.stop();
} else {
numberOfGuesses++;
message.channel.send('Too big');
collector.stop();
}
if (numberOfGuesses == 5) {
collector.stop();
return message.channel.send('Game over');
}
}
});
}
答案 0 :(得分:1)
原因是while循环运行得非常快。虽然消息传得很慢。 因此,到5个“猜测”到来时,循环可能已经运行了一百万次。从而使百万收藏家也赚了。
尝试一下:
function getGuesses(numberOfGuesses,maxGuesses){
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, { time: 10000, max: 1 });
collector.on('collect', message => {
if (guess.length == 0 || ! guessInRange(guess)) {
message.channel.send('please say 1~100');
} else {
if (parseInt(guess) == secretNumber) {
message.channel.send('Boom! Correct!');
return collector.stop();
} else if (parseInt(guess) < secretNumber) {
numberOfGuesses++;
message.channel.send('Too small');
collector.stop();
} else {
numberOfGuesses++;
message.channel.send('Too big');
collector.stop();
}
if (numberOfGuesses == maxGuesses) {
collector.stop();
return message.channel.send('Game over');
}
}
});
//Repeat if guesses still exist
collector.on('end', collected => {
if(numberOfGuessed < maxGuesses) getGuesses(numberOfGuesses,maxGuesses)
});
};
getGuesses(0,5);