Rock, Paper, Scissors Game

Let's Play Rock, Paper, Scissors!

<div id="game">
  <h2>Make Your Choice</h2>

  <button type="button" id="rock">Rock</button>
  <button type="button" id="paper">Paper</button>
  <button type="button" id="scissors">Scissors</button>
</div>

<script>
  const choices = {
    rock: { name: 'Rock', defeats: ['scissors'] },
    paper: { name: 'Paper', defeats: ['rock'] },
    scissors: { name: 'Scissors', defeats: ['paper'] }
  };

  const playerChoice = document.querySelectorAll('button');
  playerChoice.forEach(choice => {
    choice.addEventListener('click', e => {
      const playerPick = choices[e.target.id];
      const computerPick = computerPlay();
      playRound(playerPick, computerPick);
    });
  });

  const computerPlay = () => {
    const keys = Object.keys(choices);
    const randomNumber = Math.floor(Math.random() * keys.length);
    return choices[keys[randomNumber]];
  };

  let playerScore = 0;
  let computerScore = 0;

  const playRound = (playerPick, computerPick) => {
    if (playerPick.defeats.includes(computerPick.name)) {
      playerScore++;
      console.log(`You Win! ${playerPick.name} beats ${computerPick.name}.`);
    } else if (playerPick.name === computerPick.name) {
      console.log(`It's a draw. You both chose ${playerPick.name}.`);
    } else {
      computerScore++;
      console.log(
        `You Lose! ${computerPick.name} beats ${playerPick.name}.`
      );
    }
    console.log(`Your Score: ${playerScore} Computer Score: ${computerScore}`);
  };
</script>
Play Rock Paper Scissors Online - Free HTML Game

原文地址: https://www.cveoy.top/t/topic/lmtp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录