Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Yes, it is possible to create a Rock, Paper, Scissors game using JavaScript and manipulate the DOM to display the game on a web page.

Here is an example code snippet for the basic structure of the game:

HTML:

<div id="game">
  <h1>Rock, Paper, Scissors Game</h1>
  <div id="results"></div>
  <button type="button" class="btn" id="rock">Rock</button>
  <button type="button" class="btn" id="paper">Paper</button>
  <button type="button" class="btn" id="scissors">Scissors</button>
</div>

JavaScript:

const buttons = document.querySelectorAll('.btn');
const resultsDiv = document.getElementById('results');

buttons.forEach((button) => {
  button.addEventListener('click', () => {
    const playerSelection = button.id;
    const computerSelection = getComputerSelection();
    const result = checkResult(playerSelection, computerSelection);
    displayResult(result);
  });
});

function getComputerSelection() {
  const choices = ['rock', 'paper', 'scissors'];
  const randomIndex = Math.floor(Math.random() * choices.length);
  return choices[randomIndex];
}

function checkResult(playerSelection, computerSelection) {
  if (playerSelection === computerSelection) {
    return "It's a tie!";
  } else if ((playerSelection === 'rock' && computerSelection === 'scissors') || 
             (playerSelection === 'paper' && computerSelection === 'rock') || 
             (playerSelection === 'scissors' && computerSelection === 'paper')) {
    return 'You win!';
  } else {
    return 'Computer wins!';
  }
}

function displayResult(result) {
  resultsDiv.innerHTML = result;
}

This code adds event listeners to each button in the game, which triggers the game logic when a button is clicked. The getComputerSelection function generates a random choice for the computer, and the checkResult function compares the player's choice to the computer's choice to determine the winner or if it's a tie. The displayResult function updates the game results on the web page using the resultsDiv element.