本文旨在指导开发者使用 JavaScript 实现一个简单的石头剪刀布游戏,并重点解决计分问题和优化游戏逻辑。我们将通过示例代码,详细讲解如何正确地跟踪玩家和电脑的得分,并提供一种更简洁的方式来判断胜负,提升代码的可读性和效率。
游戏初始化与用户输入
首先,我们需要定义游戏所需的变量,包括可选的选项(石头、剪刀、布),以及玩家和电脑的初始得分。 玩家的选择可以通过 prompt() 函数获取,并使用 .toLowerCase() 方法将其转换为小写,方便后续比较。为了确保用户输入有效,可以使用循环进行验证。
const choices = ['rock', 'paper', 'scissors']; let playerScore = 0; let computerScore = 0; 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 getComputerChoice() { return choices[Math.floor(Math.random() * choices.length)]; }
注意: 确保玩家的选择在 choices 数组中,否则提示用户重新输入。
胜负判断与计分
游戏的核心在于判断胜负。传统的 if…else if…else 结构虽然可行,但当选项增多时会变得冗长且难以维护。一种更简洁的方法是利用数组的索引,结合取模运算,将石头剪刀布的循环关系表示出来。
立即学习“Java免费学习笔记(深入)”;
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}` } }
这段代码的核心在于:
- choices.indexOf(playerSelection) 和 choices.indexOf(computerSelection) 分别获取玩家和电脑选择在数组中的索引。
- ((index1 – index2) + 3) % 3 利用取模运算,将循环关系转换为数值关系。如果结果为 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())
总结
通过上述步骤,我们实现了一个功能完善的石头剪刀布游戏。关键在于理解如何利用数组索引和取模运算,简化胜负判断的逻辑。这种方法不仅代码更简洁,而且更易于扩展,例如增加新的选项。在实际开发中,应注重代码的可读性和可维护性,选择最适合项目需求的方案。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END