Ask Your Question
0

Can you manipulate the DOM using JavaScript to create a Rock, Paper, Scissors game?

asked 2021-08-09 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-06-02 04:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-09 11:00:00 +0000

Seen: 7 times

Last updated: Jun 02 '21