Home > Mobile >  innerHTML results display about 80% of the time an event listener fires
innerHTML results display about 80% of the time an event listener fires

Time:08-27

let gameButton = document.querySelector('#start-game');
let rockButton = document.querySelector('#rock');
let paperButton = document.querySelector('#paper');
let scissorButton = document.querySelector('#scissors');
let gameDisplay = document.querySelector('#game-display');
let playerScore = document.querySelector('#player-score');
let computerScore = document.querySelector('#computer-score');
let roundDecision = document.querySelector('#round-decision');
let roundDisplay = document.querySelector('#round-display');
let gameDecision = document.querySelector('#game-decision');
let computerPoints = 0;
let playerPoints = 0;
let roundCount = 0;
let gameActive = true;
let playerChoice;

// Begin with a function called getComputerChoice
function getComputerChoice() {
  // Create computer choices
  let computerChoices = ['Rock', 'Paper', 'Scissors'];
  // Randomly generate a choice
  let randomChoice = Math.floor(Math.random() * computerChoices.length);
  // Return the choice, uppercase
  return computerChoices[randomChoice];
}

// Write a function that plays a single round of Rock Paper Scissors that takes two parameters - the playerSelection and computerSelection
function playRound(playerSelection, computerSelection) {
  // Define win/lose parameters
  if (playerSelection == computerSelection) {
    roundDecision.textContent = 'Tie game.';
    // renderDisplay();
    return roundDecision.textContent;
  } else if (
    // The function should - and then return a string that declares the winner of the round
    // Make your function’s playerSelection parameter case-insensitive (so users can input rock, ROCK, RocK or any other variation).
    (computerSelection == 'Rock' && playerSelection == 'Scissors') ||
    (computerSelection == 'Paper' && playerSelection == 'Rock') ||
    (computerSelection == 'Scissors' && playerSelection == 'Paper')
  ) {
    roundDecision.textContent = `You lose!`;
    return roundDecision.textContent;
  } else if (
    // The function should - and then return a string that declares the winner of the round
    // Make your function’s playerSelection parameter case-insensitive (so users can input rock, ROCK, RocK or any other variation).
    (playerSelection == 'Rock' && computerSelection == 'Scissors') ||
    (playerSelection == 'Paper' && computerSelection == 'Rock') ||
    (playerSelection == 'Scissors' && computerSelection == 'Paper')
  ) {
    roundDecision.textContent = `You win!`;
    return roundDecision.textContent;
  }
}

// Write a NEW function called game().
// Called by event listeners
function initGame() {
  let computerSelection = getComputerChoice();
  let play = playRound(playerChoice, computerSelection);
  let winner;
  roundCount  ;

  if (play.includes('You win!')) {
    playerPoints  ;
    roundDisplay.textContent = roundCount;
    roundDecision.textContent = 'Player wins this round';
    winner = 'Player';
    playerScore.innerHTML = `${playerPoints} <br> Chose: ${playerChoice.toUpperCase()}`;
    playerPoints === 5 ? callGame(playerPoints, winner) : (gameActive = true);
  } else if (play.includes('You lose!')) {
    computerPoints  ;
    roundDisplay.textContent = roundCount;
    roundDecision.textContent = 'Computer wins this round';
    winner = 'Computer';
    computerScore.innerHTML = `${computerPoints} <br> Chose: ${computerSelection.toUpperCase()}`;
    computerPoints === 5
      ? callGame(computerPoints, winner)
      : (gameActive = true);
  } else {
    roundDisplay.textContent = roundCount;
    playerScore.innerHTML = `${playerPoints} <br> Chose: ${playerChoice.toUpperCase()}`;
    computerScore.innerHTML = `${computerPoints} <br> Chose: ${computerSelection.toUpperCase()}`;
    roundDecision.textContent = `It's a tie! The player and the computer both chose ${computerSelection.toUpperCase()}.`;
  }
}

// ----------------------- Game decision -----------------------

function callGame(points, whoWon) {
  gameDecision.textContent = `${whoWon} wins the game with ${points} points`;
  roundDecision.classList.remove('round-decision');
  roundDecision.classList.add('end-game');
  roundDecision.textContent = 'Game Over';
  gameOver();
}

// ----------------------- End/reset -----------------------

function gameOver() {
  computerPoints = 0;
  playerPoints = 0;
  gameActive = false;
  setChoicesInactive();
}

function resetGame() {
  return window.location.reload(true);
}

// ----------------------- Display -----------------------

function setChoicesInactive() {
  rockButton.classList.add('inactive');
  paperButton.classList.add('inactive');
  scissorButton.classList.add('inactive');
  rockButton.disabled = true;
  paperButton.disabled = true;
  scissorButton.disabled = true;
}

// ----------------------- Game buttons -----------------------

gameButton.addEventListener('click', () => {
  resetGame();
  initGame();
});

// ----------------------- Player choices -----------------------

rockButton.addEventListener('click', e => {
  playerChoice = e.target.value;
  initGame();
});

paperButton.addEventListener('click', e => {
  playerChoice = e.target.value;
  initGame();
});

scissorButton.addEventListener('click', e => {
  playerChoice = e.target.value;
  initGame();
});
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
/* font-family: 'Poppins', sans-serif; */

* {
  box-sizing: border-box;
}

html {
  height: 100%;
  font-family: 'Poppins', sans-serif;
  font-size: 10px;
}

body {
  margin: 0;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 2.5em;
  padding: 2em;
}

.choices {
  display: flex;
  flex-direction: column;
}

input {
  margin: 0.75em;
  padding: 1.25em;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 1rem;
}


.title {
  font-size: 3rem;
  text-align: center;
}

.game-display {
  text-align: center;
  margin-top: 2em;
  font-size: 2rem;
}

.score-container {
  /* border: 2px solid black; */
  display: flex;
  flex-direction: column;  
  gap: 5em;
}

.player-container, .computer-container {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  width: 12em;
  border: 4px solid black;
  border-radius: 10px;
}

.container__restart {
  margin-top: 2em;
}

.end-game {
  color: #fff;
  background-color: #000;
  border: 2px solid #000;
  padding: .5em;
  border-radius: 0.5em;
}

.inactive {
  pointer-events: none;
  opacity: 0.5;
  background: #CCC;
}

button {
  text-transform: uppercase;
  color: white;
  background-color: #ec3925;
  font-size: 1.5rem;
  padding: 1em;
  border-radius: 0.5em;
  border: none;
  -webkit-transition: box-shadow 300ms ease-in-out, color 300ms ease-in-out;
  transition: box-shadow 300ms ease-in-out, color 300ms ease-in-out;
}

.btn:hover {
  cursor: grab;
  background-color: #f5f5f5;
  box-shadow: 0 0 40px 40px #e74c3c inset;
}

.btn:active {
  padding: 3em;
  opacity: 0.8;
  transition: 800ms;
  cursor: grabbing;
}

.reset-button {
  border: 4px solid black;
}

.reset-button:hover {
  cursor: grab;
  background-color: #da766b;
}

.reset-button:active {
  padding: 0;
  margin: .75em;
  opacity: 0.8;
  font-size: 1.75rem;
  transition: 800ms;
  cursor: grabbing;
}

@media (min-width: 800px) {

  .choices {
    flex-direction: row;
    justify-content: space-between;
  }

  .score-container {
    flex-direction: row;
  }
}
<!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>
  <link rel="stylesheet" type="text/css" href="styles/style.css">
  <script type="text/javascript" src="scripts/main.js" defer></script>
</head>
  <body>
    <div >
      <div >
        <h1>Rock | Paper | Scissors</h1>
      </div>
      <div >
    <input type="image" src="https://res.cloudinary.com/angelrodriguez/image/upload/v1661546120/Odin Roshambo/rock.png" alt="rock fist image" width="200px" height="auto" id="rock"  title="Rock" value="Rock"/>
    <input type="image" src="https://res.cloudinary.com/angelrodriguez/image/upload/v1661546120/Odin Roshambo/paper.png" alt="paper image" width="200px" height="auto" id="paper"  title="Paper" value="Paper"/>
    <input type="image" src="https://res.cloudinary.com/angelrodriguez/image/upload/v1661546120/Odin Roshambo/scissors.png" alt="scissors image" width="200px" height="auto" id="scissors"  title="Scissors" value="Scissors"/>
  </div>
      <div id="game-display" >
        <h2>Round: <span id="round-display" ></span></h2>
        <h3><span id="round-decision" ></span></h3>
        <h3><span id="game-decision" ></span></h3>
      </div>
      <div >
        <div >
          <p>Player: <span id="player-score" ></span></p>
          <span id="player-choice" ></span>
        </div>
        <div >
          <p>Computer: <span id="computer-score" ></span></p>
          <span id="player-choice" ></span></div>
      </div>
      <div >
        <button id="start-game"  type="button">Restart Game</button>
      </div>
    </div>
  </body>
</html>

I created a rock, paper, scissors game for The Odin Project. Now I'm running into an issue where the .innerHTML results in my if/else statements of the initGame() function show about 80% of the time one of the three event listeners representing Rock, Paper, or Scissors is pressed. The other 20% of the time, only the prior selection shows up in the player or computer score display box.

I tried reordering the events in each conditional statement, even placing playerScore.innerHTML or computerScore.innerHTML at the bottom of the statement, but I'm still getting the same results.

I'm not getting any error messages in the console, but when I console log what's being added to either playerScore.innerHTML or computerScore.innerHTML, it shows what the eventListener choice is 100% of the time.

I'm hoping that the player and computer score boxes display the eventListener choice each time it's fired.

CodePudding user response:

Unless it's a tie, you only show the winner's choice in their box each round. You should display both choices in the box every time.

Move this code out of the if/else blocks, since it should be the same for every round. The only code in those blocks should be incrementing the appropriate points variables and displaythe roundDecision messages.

let gameButton = document.querySelector('#start-game');
let rockButton = document.querySelector('#rock');
let paperButton = document.querySelector('#paper');
let scissorButton = document.querySelector('#scissors');
let gameDisplay = document.querySelector('#game-display');
let playerScore = document.querySelector('#player-score');
let computerScore = document.querySelector('#computer-score');
let roundDecision = document.querySelector('#round-decision');
let roundDisplay = document.querySelector('#round-display');
let gameDecision = document.querySelector('#game-decision');
let computerPoints = 0;
let playerPoints = 0;
let roundCount = 0;
let gameActive = true;
let playerChoice;

// Begin with a function called getComputerChoice
function getComputerChoice() {
  // Create computer choices
  let computerChoices = ['Rock', 'Paper', 'Scissors'];
  // Randomly generate a choice
  let randomChoice = Math.floor(Math.random() * computerChoices.length);
  // Return the choice, uppercase
  return computerChoices[randomChoice];
}

// Write a function that plays a single round of Rock Paper Scissors that takes two parameters - the playerSelection and computerSelection
function playRound(playerSelection, computerSelection) {
  // Define win/lose parameters
  if (playerSelection == computerSelection) {
    roundDecision.textContent = 'Tie game.';
    // renderDisplay();
    return roundDecision.textContent;
  } else if (
    // The function should - and then return a string that declares the winner of the round
    // Make your function’s playerSelection parameter case-insensitive (so users can input rock, ROCK, RocK or any other variation).
    (computerSelection == 'Rock' && playerSelection == 'Scissors') ||
    (computerSelection == 'Paper' && playerSelection == 'Rock') ||
    (computerSelection == 'Scissors' && playerSelection == 'Paper')
  ) {
    roundDecision.textContent = `You lose!`;
    return roundDecision.textContent;
  } else if (
    // The function should - and then return a string that declares the winner of the round
    // Make your function’s playerSelection parameter case-insensitive (so users can input rock, ROCK, RocK or any other variation).
    (playerSelection == 'Rock' && computerSelection == 'Scissors') ||
    (playerSelection == 'Paper' && computerSelection == 'Rock') ||
    (playerSelection == 'Scissors' && computerSelection == 'Paper')
  ) {
    roundDecision.textContent = `You win!`;
    return roundDecision.textContent;
  }
}

// Write a NEW function called game().
// Called by event listeners
function initGame() {
  let computerSelection = getComputerChoice();
  let play = playRound(playerChoice, computerSelection);

  if (play.includes('You win!')) {
    playerPoints  ;
    roundDecision.textContent = 'Player wins this round';
  } else if (play.includes('You lose!')) {
    computerPoints  ;
    roundDecision.textContent = 'Computer wins this round';
  } else {
    roundDecision.textContent = `It's a tie! The player and the computer both chose ${computerSelection.toUpperCase()}.`;
  }
  roundCount  ;
  roundDisplay.textContent = roundCount;
  playerScore.innerHTML = `${playerPoints} <br> Chose: ${playerChoice.toUpperCase()}`;
  computerScore.innerHTML = `${computerPoints} <br> Chose: ${computerSelection.toUpperCase()}`;
  if (computerPoints == 5) {
    callGame(computerPoints, 'Computer');
  } else if (playerPoints == 5) {
    callGame(playerPoints, 'Player');
  } else {
    gameActive = true;
  }
}

// ----------------------- Game decision -----------------------

function callGame(points, whoWon) {
  gameDecision.textContent = `${whoWon} wins the game with ${points} points`;
  roundDecision.classList.remove('round-decision');
  roundDecision.classList.add('end-game');
  roundDecision.textContent = 'Game Over';
  gameOver();
}

// ----------------------- End/reset -----------------------

function gameOver() {
  computerPoints = 0;
  playerPoints = 0;
  gameActive = false;
  setChoicesInactive();
}

function resetGame() {
  return window.location.reload(true);
}

// ----------------------- Display -----------------------

function setChoicesInactive() {
  rockButton.classList.add('inactive');
  paperButton.classList.add('inactive');
  scissorButton.classList.add('inactive');
  rockButton.disabled = true;
  paperButton.disabled = true;
  scissorButton.disabled = true;
}

// ----------------------- Game buttons -----------------------

gameButton.addEventListener('click', () => {
  resetGame();
  initGame();
});

// ----------------------- Player choices -----------------------

rockButton.addEventListener('click', e => {
  playerChoice = e.target.value;
  initGame();
});

paperButton.addEventListener('click', e => {
  playerChoice = e.target.value;
  initGame();
});

scissorButton.addEventListener('click', e => {
  playerChoice = e.target.value;
  initGame();
});
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');

/* font-family: 'Poppins', sans-serif; */

* {
  box-sizing: border-box;
}

html {
  height: 100%;
  font-family: 'Poppins', sans-serif;
  font-size: 10px;
}

body {
  margin: 0;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 2.5em;
  padding: 2em;
}

.choices {
  display: flex;
  flex-direction: column;
}

input {
  margin: 0.75em;
  padding: 1.25em;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 1rem;
}

.title {
  font-size: 3rem;
  text-align: center;
}

.game-display {
  text-align: center;
  margin-top: 2em;
  font-size: 2rem;
}

.score-container {
  /* border: 2px solid black; */
  display: flex;
  flex-direction: column;
  gap: 5em;
}

.player-container,
.computer-container {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  width: 12em;
  border: 4px solid black;
  border-radius: 10px;
}

.container__restart {
  margin-top: 2em;
}

.end-game {
  color: #fff;
  background-color: #000;
  border: 2px solid #000;
  padding: .5em;
  border-radius: 0.5em;
}

.inactive {
  pointer-events: none;
  opacity: 0.5;
  background: #CCC;
}

button {
  text-transform: uppercase;
  color: white;
  background-color: #ec3925;
  font-size: 1.5rem;
  padding: 1em;
  border-radius: 0.5em;
  border: none;
  -webkit-transition: box-shadow 300ms ease-in-out, color 300ms ease-in-out;
  transition: box-shadow 300ms ease-in-out, color 300ms ease-in-out;
}

.btn:hover {
  cursor: grab;
  background-color: #f5f5f5;
  box-shadow: 0 0 40px 40px #e74c3c inset;
}

.btn:active {
  padding: 3em;
  opacity: 0.8;
  transition: 800ms;
  cursor: grabbing;
}

.reset-button {
  border: 4px solid black;
}

.reset-button:hover {
  cursor: grab;
  background-color: #da766b;
}

.reset-button:active {
  padding: 0;
  margin: .75em;
  opacity: 0.8;
  font-size: 1.75rem;
  transition: 800ms;
  cursor: grabbing;
}

@media (min-width: 800px) {
  .choices {
    flex-direction: row;
    justify-content: space-between;
  }
  .score-container {
    flex-direction: row;
  }
}
<!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>
  <link rel="stylesheet" type="text/css" href="styles/style.css">
  <script type="text/javascript" src="scripts/main.js" defer></script>
</head>

<body>
  <div >
    <div >
      <h1>Rock | Paper | Scissors</h1>
    </div>
    <div >
      <input type="image" src="assets/rock.png" alt="rock fist image" width="200px" height="auto" id="rock"  title="Rock" value="Rock" />
      <input type="image" src="assets/paper.png" alt="paper image" width="200px" height="auto" id="paper"  title="Paper" value="Paper" />
      <input type="image" src="assets/scissors.png" alt="scissors image" width="200px" height="auto" id="scissors"  title="Scissors" value="Scissors" />
    </div>
    <div id="game-display" >
      <h2>Round: <span id="round-display" ></span></h2>
      <h3><span id="round-decision" ></span></h3>
      <h3><span id="game-decision" ></span></h3>
    </div>
    <div >
      <div >
        <p>Player: <span id="player-score" ></span></p>
        <span id="player-choice" ></span>
      </div>
      <div >
        <p>Computer: <span id="computer-score" ></span></p>
        <span id="player-choice" ></span></div>
    </div>
    <div >
      <button id="start-game"  type="button">Restart Game</button>
    </div>
  </div>
</body>

</html>

  • Related