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.
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
Asked: 2021-08-09 11:00:00 +0000
Seen: 7 times
Last updated: Jun 02 '21
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
What is the process for generating a dynamic subdomain/URL using vue.js?
How can I create a transition on click using CSS without the need for JavaScript?
How can the style of the loader be modified while the form submission is being processed?
I'm attempting to develop a Javascript-based comments section for my website.
What are some feasible methods to enable MIDI file playback on a web browser?