
本文旨在帮助开发者构建一个基于浏览器的 JavaScript 猜拳游戏,并解决计分逻辑和简化游戏判断的问题。我们将逐步优化代码,提供更清晰的结构和更简洁的实现方式,确保游戏逻辑的正确性和可维护性。最终,你将拥有一个功能完善、易于理解的猜拳游戏。
首先,我们定义游戏选项,并初始化玩家和电脑的分数。
const choices = ['rock', 'paper', 'scissors']; let playerScore = 0; let computerScore = 0;
接下来,实现获取电脑选择的函数 getComputerChoice,它会随机从 choices 数组中选择一个选项。
function getComputerChoice() {
return choices[Math.floor(Math.random() * choices.length)];
}为了确保用户输入有效,我们使用循环来验证玩家的选择。getPlayerChoice 函数会提示用户输入,并确保输入是 'rock'、'paper' 或 'scissors' 中的一个。
立即学习“Java免费学习笔记(深入)”;
function getPlayerChoice() {
let choice;
while(true) {
choice = prompt('Pick Rock, Paper, or Scissors?').toLowerCase();
if(choices.includes(choice)) return choice;
else console.log('Invalid choice, please try again');
}
}playRound 函数是游戏的核心,它决定了每一轮的胜负。 为了简化判断逻辑,利用选项在数组中的索引位置,结合取模运算,可以更简洁地判断胜负。
function playRound(playerSelection, computerSelection) {
if(playerSelection===computerSelection) {
return 'Draw'
}
else if((((choices.indexOf(playerSelection) - choices.indexOf(computerSelection)) + 3) % 3)===1) {
playerScore++;
return `You win! ${playerSelection} beats ${computerSelection}`;
}
else {
computerScore++;
return `You lose! ${computerSelection} beats ${playerSelection}`;
}
}这种方法基于猜拳的循环克制关系:Rock < Paper < Scissors < Rock。如果玩家的选择在数组中的索引比电脑的选择大1(考虑循环),则玩家获胜。
game 函数控制整个游戏流程,循环进行五轮游戏,并最终显示游戏结果。
function game() {
for (let i = 1; i <= 5; i++) {
const playerSelection = getPlayerChoice();
const computerSelection = getComputerChoice();
console.log(playRound(playerSelection, computerSelection));
}
if (playerScore > computerScore) {
return 'You beat the computer! You are a genius';
} else if (playerScore < computerScore) {
return `You got beat by the computer. Practice your throws!`;
} else {
return `You tied with the computer!`;
}
}
console.log(game());通过本文的教程,你已经掌握了如何使用 JavaScript 构建一个简单的猜拳游戏,并学习了如何优化代码逻辑和提高可读性。希望这些技巧能帮助你在未来的 JavaScript 开发中更加得心应手。
以上就是JavaScript 猜拳游戏:完善计分与逻辑优化教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号