Home > Software engineering >  My function (using an event listener) doesn't seem to give the expected output. How can I fix i
My function (using an event listener) doesn't seem to give the expected output. How can I fix i

Time:09-08

EDIT: I was able to make it kind of work using the onclick function directly in the html, but I would like to know how to make it work with an event listener, so pls still help with this. Thanks guys

So, I'm new at this, and am trying to make an app that lets you play a rock paper scissors game first to 5 against a robot. It's part of The Odin Project.

I haven't yet implemented the best to five bit of it, as I'm just trying to make my buttons work :(

My event listener seems to be working fine, but I still get a "NULL" player choice no matter which button is pressed, when obviously I should be getting "ROCK", "PAPER", or "SCISSORS".

Would someone mind pointing out where I'm going wrong?

Here's my Javascript:

let playerChoice = "NULL"
let computerChoice = "NULL"
let playerScore = 0
let computerScore = 0

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min   1)   min);
}

function getComputerChoice() {
    let numChoice = getRandomInt(1,3);

    let computerChoice = "NULL"
    if (numChoice == 1) {
        computerChoice = "ROCK";
    } else if (numChoice == 2) {
        computerChoice = "PAPER";
    } else if (numChoice == 3){
        computerChoice = "SCISSORS";
    } else {
        computerChoice = "NULL";
    }

    return computerChoice
}

function playerChoiceRock() {
    playerChoice = "ROCK"
}

function playerChoiceScissors() {
    playerChoice = "SCISSORS"
}

function playerChoicePaper() {
    playerChoice = "PAPER"
}


function getPlayerChoice() {
    document.getElementById("rockButton").addEventListener("click", playerChoiceRock)
    document.getElementById("scissorsButton").addEventListener("click", playerChoiceScissors)
    document.getElementById("paperButton").addEventListener("click", playerChoicePaper)
    return playerChoice
}

function playRound() {
    scoreComputer = document.getElementById("computerScore").innerHTML
    scorePlayer = document.getElementById("playerScore").innerHTML
    computerChoice = getComputerChoice()
    playerChoice = getPlayerChoice()
    


    if (computerChoice == "ROCK" && playerChoice == "PAPER") {
        scorePlayer = scorePlayer   1
    } else if (computerChoice == "ROCK" && playerChoice == "SCISSORS") {
        scoreComputer = scoreComputer   1
    } else if (computerChoice == "PAPER" && playerChoice == "SCISSORS") {
        scorePlayer = scorePlayer   1
    } else if (computerChoice == "PAPER" && playerChoice == "ROCK") {
        scoreComputer = scoreComputer   1
    } else if (computerChoice == "SCISSORS" && playerChoice == "PAPER") {
        scoreComputer = scoreComputer   1
    } else if (computerChoice == "SCISSORS" && playerChoice == "ROCK") {
        scorePlayer = scorePlayer   1
    } else {
        scorePlayer = scorePlayer
        scoreComputer = scoreComputer
    }
    alert(playerChoice)

    document.getElementById("playerScore").innerHTML = scorePlayer
    document.getElementById("computerScore").innerHTML = scoreComputer
} 

And here's my HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rock, Paper, Scissors</title>



</head>
<script src = "./script.js"></script>
<body>
    <div>
        <h1 style="display:flex; justify-content:center">Welcome To Rock, Paper Scissors.<h1></h1>
        <h3 style="display:flex; justify-content: center;">The directions are simple. You will play against a computer in Rock, Paper, Scissors best out of 5. Choose a weapon from the menu, and hope that luck is on your side!</h3>
        <h2 style="display: flex; justify-content: center;font-weight: bold;"><br><br>Rock beats Scissors, Scissors beats Paper, Paper beats Rock</h2>
    </div>
    <br>
    <br>
    <br>
    <br>
    <div style = "display: flex; justify-content: space-around;">
        <button id = "rockButton" style = "display: flex; flex-direction: column; justify-content: center;" id = "Rock" onclick="playRound()">
            <img src = ./stone.png alt = "image of a rock" height = "100px" width = "auto">
            <p style="margin-left: auto; margin-right: auto">Rock</p>
        </button>
        <button id = "paperButton" style = "display: flex; flex-direction: column; justify-content: center;" id = "Paper" onclick="playRound()">
            <img src = ./paper.png alt = "image of a Paper" height = "100px" width = "auto">
            <p style="margin-left: auto; margin-right: auto">Paper</p>
        </button>
        <button id = "scissorsButton" style = "display: flex; flex-direction: column; justify-content: center;" id = "Scissors" onclick="playRound()">
            <img src = ./scissors.png alt = "image of Scisors" height = "100px" width = "auto">
            <p style="margin-left: auto; margin-right: auto">Scissors</p>
        </button>
    </div>
    <div style = "display: flex; justify-content: center;">
        <div style = "display: flex; justify-content: space-around; white-space: nowrap; width: 70%;">
            <div style = "display: flex; white-space: nowrap;">
                <h1><br><br><br>Your Score: <h1 id = "playerScore" style = "margin-left: 5%; margin-right: 5%;"><br><br><br>0</h1></h1>
            </div>
            <div style = "display: flex; white-space: nowrap; justify-content: center;">
                <h1><br><br><br>Computer's Score: <h1 id = "computerScore" style = "margin-left: 5%; margin-right: 5%;"><br><br><br>0</h1></h1>
            </div>
        </div>
    </div>
    <div style = "display: flex; justify-content: center;">
        <h1 style = "font: 40px; display: flex;"><br>Game Result</h1>
        <h1 id = "gameResult"></h1>
    </div>
    <div>
</body>
</html>

Thanks all. I've tried to shuffle around the order in which the functions are executed, but it hasn't worked. Sorry if I'm asking a simple question, I'm pretty new and stumped :D

CodePudding user response:

Event listeners are fired after the listened events were invoked. In your case, you need to add the event listener before fetching player choice, which should be in the very beginning of your code.

let playerChoice = "NULL"
let computerChoice = "NULL"
let playerScore = 0
let computerScore = 0

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min   1)   min);
}

function getComputerChoice() {
  let numChoice = getRandomInt(1, 3);

  let computerChoice = "NULL"
  if (numChoice == 1) {
    computerChoice = "ROCK";
  } else if (numChoice == 2) {
    computerChoice = "PAPER";
  } else if (numChoice == 3) {
    computerChoice = "SCISSORS";
  } else {
    computerChoice = "NULL";
  }

  return computerChoice
}

function playerChoiceRock() {
  playerChoice = "ROCK"
}

function playerChoiceScissors() {
  playerChoice = "SCISSORS"
}

function playerChoicePaper() {
  playerChoice = "PAPER"
}


function getPlayerChoice() {
  return playerChoice
}


// add event listeners
document.getElementById("rockButton").addEventListener("click", playerChoiceRock)
document.getElementById("scissorsButton").addEventListener("click", playerChoiceScissors)
document.getElementById("paperButton").addEventListener("click", playerChoicePaper)

function playRound() {
  scoreComputer = document.getElementById("computerScore").innerHTML
  scorePlayer = document.getElementById("playerScore").innerHTML
  computerChoice = getComputerChoice()
  playerChoice = getPlayerChoice()

  if (computerChoice == "ROCK" && playerChoice == "PAPER") {
    scorePlayer = scorePlayer   1
  } else if (computerChoice == "ROCK" && playerChoice == "SCISSORS") {
    scoreComputer = scoreComputer   1
  } else if (computerChoice == "PAPER" && playerChoice == "SCISSORS") {
    scorePlayer = scorePlayer   1
  } else if (computerChoice == "PAPER" && playerChoice == "ROCK") {
    scoreComputer = scoreComputer   1
  } else if (computerChoice == "SCISSORS" && playerChoice == "PAPER") {
    scoreComputer = scoreComputer   1
  } else if (computerChoice == "SCISSORS" && playerChoice == "ROCK") {
    scorePlayer = scorePlayer   1
  } else {
    scorePlayer = scorePlayer
    scoreComputer = scoreComputer
  }

  alert(playerChoice)

  document.getElementById("playerScore").innerHTML = scorePlayer
  document.getElementById("computerScore").innerHTML = scoreComputer
}

// add event listeners after the choice event
document.getElementById("rockButton").addEventListener("click", playRound)
document.getElementById("scissorsButton").addEventListener("click", playRound)
document.getElementById("paperButton").addEventListener("click", playRound)
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rock, Paper, Scissors</title>



</head>
<script src="./script.js"></script>

<body>
  <div>
    <h1 style="display:flex; justify-content:center">Welcome To Rock, Paper Scissors.
      <h1></h1>
      <h3 style="display:flex; justify-content: center;">The directions are simple. You will play against a computer in Rock, Paper, Scissors best out of 5. Choose a weapon from the menu, and hope that luck is on your side!</h3>
      <h2 style="display: flex; justify-content: center;font-weight: bold;"><br><br>Rock beats Scissors, Scissors beats Paper, Paper beats Rock</h2>
  </div>
  <br>
  <br>
  <br>
  <br>
  <div style="display: flex; justify-content: space-around;">
    <button id="rockButton" style="display: flex; flex-direction: column; justify-content: center;" id="Rock">
            <img src = ./stone.png alt = "image of a rock" height = "100px" width = "auto">
            <p style="margin-left: auto; margin-right: auto">Rock</p>
        </button>
    <button id="paperButton" style="display: flex; flex-direction: column; justify-content: center;" id="Paper">
            <img src = ./paper.png alt = "image of a Paper" height = "100px" width = "auto">
            <p style="margin-left: auto; margin-right: auto">Paper</p>
        </button>
    <button id="scissorsButton" style="display: flex; flex-direction: column; justify-content: center;" id="Scissors">
            <img src = ./scissors.png alt = "image of Scisors" height = "100px" width = "auto">
            <p style="margin-left: auto; margin-right: auto">Scissors</p>
        </button>
  </div>
  <div style="display: flex; justify-content: center;">
    <div style="display: flex; justify-content: space-around; white-space: nowrap; width: 70%;">
      <div style="display: flex; white-space: nowrap;">
        <h1><br><br><br>Your Score:
          <h1 id="playerScore" style="margin-left: 5%; margin-right: 5%;"><br><br><br>0</h1>
        </h1>
      </div>
      <div style="display: flex; white-space: nowrap; justify-content: center;">
        <h1><br><br><br>Computer's Score:
          <h1 id="computerScore" style="margin-left: 5%; margin-right: 5%;"><br><br><br>0</h1>
        </h1>
      </div>
    </div>
  </div>
  <div style="display: flex; justify-content: center;">
    <h1 style="font: 40px; display: flex;"><br>Game Result</h1>
    <h1 id="gameResult"></h1>
  </div>
  <div>
</body>

</html>

Also note that you need to invoke the playRound function after playerChoice**** listeners. To do that, simply remove the inline listener and add the playRound listeners after adding playerChoice listeners.

CodePudding user response:

First, please check all your elements' id attribute.

You should set only one id in an element.

It's because your event doesn't pass to your function.

Base on this solution

You can use this function to bind your button

function showEvent(e) {
  e = e || window.event;
  var target = e.target || e.srcElement;
  console.log(target);
}

e.g.

 <button id="scissorsButton" onclick="showEvent(event)">

Then, you could see the event object in your browser console.

  • Related