Untitled

 avatar
unknown
javascript
2 years ago
1.6 kB
7
Indexable
function getComputerChoice(){
    let choice = ["rock", "paper", "scissors"];
    let random = Math.floor(Math.random() * choice.length);
    let computerSelection = choice[random];
    return computerSelection;
}

const p = document.querySelector("p");
const buttons = document.querySelectorAll('button');
// we use the .forEach method to iterate through each button
buttons.forEach((button) => {

  // and for each one we add a 'click' listener
  button.addEventListener('click', () => {
    let playerSelection = String(button.className);
    playRound(getComputerChoice(), playerSelection);
  });
});

let cScore = 0;
let pScore = 0;
if(pScore == 5 || cScore == 5){
    console.log("match ended");
}


function playRound(computerSelection, playerSelection){
    if(computerSelection == "rock" && playerSelection == "paper"){
        resultRound = 1
        pScore ++;
    } else if(computerSelection == "rock" && playerSelection == "scissors"){
        resultRound = 2
        cScore ++;
    } else if(computerSelection == "paper" && playerSelection == "rock"){
        resultRound = 1
        pScore ++;
    } else if(computerSelection == "paper" && playerSelection == "scissors"){
        resultRound = 2
        cScore ++;
    } else if(computerSelection == "scissors" && playerSelection == "rock"){
        resultRound = 2
        cScore ++;
    } else if(computerSelection == "scissors" && playerSelection == "paper"){
        resultRound = 1
        pScore ++;
    } else{
        resultRound = "It's a tie!";
    }
    return resultRound;
}
Editor is loading...