Created
October 16, 2024 18:30
-
-
Save AlvisonHunterArnuero/3e2b96273791ed848781286a339ee767 to your computer and use it in GitHub Desktop.
ROCK PAPER SCISSORS - JAVASCRIPT PART
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Instantiate all DOM elements referenced by their IDs | |
const playerChoice = document.getElementById('playerChoice'); | |
const pcChoice = document.getElementById('pcChoice'); | |
const winner = document.getElementById('winner'); | |
// Instantiate all DOM elements for event listeners | |
const rock = document.getElementById('rock'); | |
const paper = document.getElementById('paper'); | |
const scissors = document.getElementById('scissors'); | |
/** ----------- Global Variables Declaration ---------------- */ | |
// Array of choices representing the options in the game | |
const choices = ['rock', 'paper', 'scissors']; | |
// Object defining winning conditions for each choice | |
// I have placed the keys as the winning conditions | |
// and the values as the losing conditions for each choice. | |
const winningConditions = { | |
rock: 'scissors', // Rock crushes Scissors | |
paper: 'rock', // Paper covers Rock | |
scissors: 'paper', // Scissors cuts Paper | |
}; | |
// Function to randomly select a choice from the array of choices | |
const getRandomChoice = () => | |
choices[Math.floor(Math.random() * choices.length)]; | |
/// Function to determine the winner of a round | |
const getWinner = (playerSelection, computerSelection) => { | |
if (playerSelection === computerSelection) return "It's a tie!"; | |
return winningConditions[playerSelection] === computerSelection | |
? 'You win!' | |
: 'Computer wins!'; | |
}; | |
// Function to handle the game logic for each round | |
const playRound = (playerSelection) => { | |
const computerSelection = getRandomChoice(); | |
// Update DOM elements with the current selections and winner | |
playerChoice.textContent = playerSelection; // Display player's choice | |
pcChoice.textContent = computerSelection; // Display computer's choice | |
// Display the result on this span element of the DOM | |
winner.textContent = getWinner(playerSelection, computerSelection); | |
}; | |
// Attach event listeners to the images for user interaction | |
rock.addEventListener('click', () => playRound('rock')); | |
paper.addEventListener('click', () => playRound('paper')); | |
scissors.addEventListener('click', () => playRound('scissors')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment