
本文旨在帮助开发者构建一个基于浏览器的 JavaScript 猜拳游戏,并解决计分逻辑问题。我们将提供清晰的代码示例,并深入探讨如何使用数组索引和模运算来简化胜负判断。通过本文,你将掌握如何编写一个功能完善、逻辑清晰的猜拳游戏。
一个简单的猜拳游戏通常包含以下几个核心部分:
原代码中使用大量的 if...else if...else 语句来判断胜负,这使得代码冗长且难以维护。我们可以利用数组索引和模运算来简化胜负判断逻辑。
核心思想:
立即学习“Java免费学习笔记(深入)”;
将 rock、paper、scissors 存储在一个数组中,然后通过比较玩家和电脑选择在数组中的索引来判断胜负。由于猜拳游戏存在循环克制关系 (Rock < Paper < Scissors < Rock),可以使用模运算来处理循环的情况。
代码示例:
const choices = ['rock', 'paper', 'scissors'];
let playerScore = 0;
let computerScore = 0;
function getComputerChoice() {
return choices[Math.floor(Math.random() * choices.length)];
}
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');
}
}
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}`
}
}
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())代码解释:
原代码没有对玩家的输入进行验证,如果玩家输入了无效的选择,程序会出错。我们可以使用 while 循环和 includes() 方法来确保玩家输入的选择是有效的。
代码示例:
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');
}
}代码解释:
通过使用数组索引和模运算,我们成功地简化了猜拳游戏的胜负判断逻辑。同时,通过添加输入验证,提高了程序的健壮性。
注意事项:
希望本文能够帮助你构建一个功能完善、逻辑清晰的 JavaScript 猜拳游戏。通过学习本文,你将能够更好地理解 JavaScript 数组、函数和控制流等基本概念,并将其应用到实际项目中。
以上就是JavaScript 猜拳游戏:完善计分与逻辑优化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号