<html>
  <head>
    <title>Rock Paper Scissors Game: Play Online & Learn the Code</title>
  </head>
  <body>
    <h1>Rock Paper Scissors Game</h1>
    <div class='game'>
      <button id='rock'>Rock</button>
      <button id='paper'>Paper</button>
      <button id='scissors'>Scissors</button>
    </div>
    <h2 id='result'></h2>
    <script>
      const rock = document.querySelector('#rock');
      const paper = document.querySelector('#paper');
      const scissors = document.querySelector('#scissors');
      const result = document.querySelector('#result');
<pre><code>  const computerChoice = () =&gt; {
    const choices = ['rock', 'paper', 'scissors'];
    const randomChoice = Math.floor(Math.random() * 3);
    return choices[randomChoice];
  }

  const determineWinner = (userChoice, computerChoice) =&gt; {
    if (userChoice === computerChoice) {
      return 'It's a tie!';
    } else if (userChoice === 'rock') {
      if (computerChoice === 'paper') {
        return 'Computer wins!';
      } else {
        return 'You win!';
      }
    } else if (userChoice === 'paper') {
      if (computerChoice === 'scissors') {
        return 'Computer wins!';
      } else {
        return 'You win!';
      }
    } else if (userChoice === 'scissors') {
      if (computerChoice === 'rock') {
        return 'Computer wins!';
      } else {
        return 'You win!';
      }
    }
  }

  const playGame = (userChoice) =&gt; {
    let computerChoice = computerChoice();
    result.innerHTML = `You chose ${userChoice}. Computer chose ${computerChoice}. ${determineWinner(userChoice, computerChoice)}`;
  }

  rock.addEventListener('click', () =&gt; {
    playGame('rock');
  });

  paper.addEventListener('click', () =&gt; {
    playGame('paper');
  });

  scissors.addEventListener('click', () =&gt; {
    playGame('scissors');
  });
&lt;/script&gt;
</code></pre>
  </body>
</html>
Rock Paper Scissors Game: Play Online & Learn the Code

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

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