
本文旨在帮助开发者构建一个基于浏览器的 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
游戏流程控制
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 开发中更加得心应手。










