我是JS的新手,每天学习/编码一个小时或两个小时。我正在制作一款JS RPS游戏,一切都很好,除了当我试图为5胜制游戏运行一个函数时。它正确地计算了所有内容,但当它达到5时,我必须再运行一段时间才能得到Winner结果。
我理解它为什么这么做,因为在函数运行之前,值是<5.我只是不知道该怎么解决,我到处找了很多,但可能没有使用正确的搜索词。
代码:
const playRound = function (cpuChoice, playerChoice) {
if (playerChoice === cpuChoice) {
console.log(`You chose: ${playerChoice} and CPU chose ${cpuChoice}, It's a Tie`);
result('Tie!', 'yellow');
} else if ((playerChoice === 'rock' && cpuChoice === 'scissors') || (playerChoice === 'paper' && cpuChoice === 'rock') || (playerChoice === 'scissors' && cpuChoice === 'paper')) {
console.log(`You chose: ${playerChoice} and CPU chose ${cpuChoice}, You Win`);
result('You Win!', 'green');
playerScore++;
document.querySelector('.player-score').textContent = playerScore;
} else {
console.log(`You chose: ${playerChoice} and CPU chose ${cpuChoice}, You Lose`);
result('You Lose', 'red');
cpuScore++;
document.querySelector('.cpu-score').textContent = cpuScore;
}
};
const playGame = function (playerScore, cpuScore) {
if (playerScore === 5) {
console.log(`You Won The Best Of 5, ${playerScore} to ${cpuScore}.`);
} else if (cpuScore === 5) {
console.log(`You Lost The Best Of 5, ${playerScore} to ${cpuScore}.`);
} else if (playerScore < 5 && cpuScore < 5) {
playRound(cpuChoice, playerChoice);
console.log('next round');
}
};
将playGame
更改为,以便在每场比赛后进行中奖检查。
const playGame = function (playerScore, cpuScore) {
if (playerScore < 5 && cpuScore < 5) {
playRound(cpuChoice, playerChoice);
console.log('next round');
}
if (playerScore === 5) {
console.log(`You Won The Best Of 5, ${playerScore} to ${cpuScore}.`);
} else if (cpuScore === 5) {
console.log(`You Lost The Best Of 5, ${playerScore} to ${cpuScore}.`);
}
};