我正在制作一个最少有5名玩家的游戏。
如果用户输入的值小于5,则应告知最小值为5,然后再次提示。
我的代码在用户输入为> = 5时起作用,但是在输入低于5时立即关闭,而不是执行应有的操作。
const readline = require('readline');
var players = []
var rl = readline.createInterface(process.stdin, process.stdout);
var playerNumber
//takes user input of how many players to prompt names for player 1, player 2, etc.
function readPlayers(playerCount, playerArr, curr = 0) {
if (playerCount < 5 || playerCount == curr) { //error is either found here
rl.close();
return;
}
rl.question("Enter name of player " + (curr + 1) + ": ", function (playerName) {
playerArr.push(playerName)
readPlayers(playerCount, playerArr, curr + 1);
});
}
function numberAndNames() {
rl.question("Enter number of players: ", function (answer) {
readPlayers(parseInt(answer), players);
var playerNumber = answer
});
rl.on('close', function () {
if (playerNumber < 5) { //or error is found here
console.log("Insuficient players. A minimum of 5 players is required.")
numberAndNames();
} else {
console.log("The players are: " + players.toString());
}
});
}
numberAndNames();