Search code examples
javascriptfunctionif-statementvariablescomparison

Change two values depending on specific comparisons between two other values?


I am making a small game and I have two variables; one for the player's choice and another for the computer's random choice. The player can choose between attack1, attack2, and attack3. And so will the computer (using Math.random()).

I want to increase the score of the winner if they choose an option that beats the computer's option. And increase the number of draws if they choose the same.

I have written an if-else statement that accomplishes this but I think it should be possible to make it shorter or better. Let's call the attacks rock, paper, and scissors so it's easy to see who would win:

THE WHOLE JS CODE IS IN THE CODE SNIPPET AND JSFiddle

    if (playerChoice === computerChoice) {
        draw++;
    } else if (playerScore === rock && computerChoice === scissors) {
        playerScore++;
    } else if (playerScore === paper && computerChoice === rock) {
        playerScore++;
    } else if (playerChoice === scissors && computerChoice === paper) {
        playerScore++;
    } else {
        computerScore++;
    }

I am using a function to check if any of the three statements are true, and if so the player's score should increase, and if not the computer's score should increase.

JDFiddle: https://jsfiddle.net/Lowxc31b/

Snippet:

var playerScore = 0;
var computerScore = 0;
var draw = 0;
var possibleChoices = ["rock", "paper", "scissors"];

var playerScoreEl = document.getElementById("playerScore");
var computerScoreEl = document.getElementById("computerScore");
var drawEl = document.getElementById("draw");
var rockEl = document.getElementById("rock");
var paperEl = document.getElementById("paper");
var scissorsEl = document.getElementById("scissors");

var buttonsEl = document.getElementsByClassName("button");
for (var i = 0; i < buttonsEl.length; i++) {
  buttonsEl[i].addEventListener("click", checkResult);
}

function checkResult(e) {
  var playerChoice = e.target.id;
  var randomChoice = Math.floor(Math.random() * 3);
  var computerChoice = possibleChoices[randomChoice];

  if (playerChoice === computerChoice) {
    draw++;
  } else if (playerChoice === rockEl.id && computerChoice === "scissors") {
    playerScore++;
  } else if (playerChoice === paperEl.id && computerChoice === "rock") {
    playerScore++;
  } else if (playerChoice === scissorsEl.id && computerChoice === "paper") {
    playerScore++;
  } else {
    computerScore++;
  }
  playerScoreEl.innerHTML = playerScore;
  computerScoreEl.innerHTML = computerScore;
  drawEl.innerHTML = draw;
}
body {
  font-family: Arial, Helvetica, sans-serif;
  background-color: #ecf0f1;
  font-size: 21px;
}

p {
  display: inline-block;
  margin: 10px;
}

#button {
  margin: 10px;
}

#wrapping {
  width: max-content;
  margin: auto;
}

#rock,
#paper,
#scissors {
  cursor: pointer;
}
<html lang="no">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rock paper scissors</title>
</head>

<body>
  <div id="wrapping">
    <b>Player: </b>
    <p id="playerScore"> 0 </p> <br>
    <b>Computer: </b>
    <p id="computerScore"> 0 </p> <br>
    <b>Draw's: </b>
    <p id="draw"> 0 </p> <br>
    <div id="buttons">
      <button id="rock" class="button"> Rock </button>
      <button id="paper" class="button"> Paper </button>
      <button id="scissors" class="button"> Scissors </button>
    </div>
    <p id="info"> </p>
  </div>
</body>

</html>


Solution

  • You could turn the choices into numbers alone, and then just check whether the difference between the computer's and the player's, modulo 3, is 0, 1, or 2:

      var playerChoice = Number(e.target.id); // could also remove the IDs entirely
            // and check the child element index among its siblings
      var computerChoice = Math.floor(Math.random() * 3);
      // Need to add 3 so that negative results get %d properly:
      const diff = (playerChoice - computerChoice + 3) % 3;
      if (diff === 0) {
        draw++;
      } else if (diff === 1) {
        playerScore++;
      } else {
        computerScore++;
      }
    

    var playerScore = 0;
    var computerScore = 0;
    var draw = 0;
    var possibleChoices = ["rock", "paper", "scissors"];
    
    var playerScoreEl = document.getElementById("playerScore");
    var computerScoreEl = document.getElementById("computerScore");
    var drawEl = document.getElementById("draw");
    var rockEl = document.getElementById("rock");
    var paperEl = document.getElementById("paper");
    var scissorsEl = document.getElementById("scissors");
    
    var buttonsEl = document.getElementsByClassName("button");
    for (var i = 0; i < buttonsEl.length; i++) {
      buttonsEl[i].addEventListener("click", checkResult);
    }
    
    const choices = ['rock', 'paper', 'scissors'];
    function checkResult(e) {
      var playerChoice = Number(e.target.id);
      var computerChoice = Math.floor(Math.random() * 3);
      console.log('Player played', choices[playerChoice], 'Computer played', choices[computerChoice]);
      const diff = (playerChoice - computerChoice + 3) % 3;
      if (diff === 0) {
        draw++;
      } else if (diff === 1) {
        playerScore++;
      } else {
        computerScore++;
      }
      playerScoreEl.innerHTML = playerScore;
      computerScoreEl.innerHTML = computerScore;
      drawEl.innerHTML = draw;
    }
    body {
      font-family: Arial, Helvetica, sans-serif;
      background-color: #ecf0f1;
      font-size: 21px;
    }
    
    p {
      display: inline-block;
      margin: 10px;
    }
    
    #button {
      margin: 10px;
    }
    
    #wrapping {
      width: max-content;
      margin: auto;
    }
    
    #rock,
    #paper,
    #scissors {
      cursor: pointer;
    }
    <html lang="no">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Rock paper scissors</title>
    </head>
    
    <body>
      <div id="wrapping">
        <b>Player: </b>
        <p id="playerScore"> 0 </p> <br>
        <b>Computer: </b>
        <p id="computerScore"> 0 </p> <br>
        <b>Draw's: </b>
        <p id="draw"> 0 </p> <br>
        <div id="buttons">
          <button id="0" class="button"> Rock </button>
          <button id="1" class="button"> Paper </button>
          <button id="2" class="button"> Scissors </button>
        </div>
        <p id="info"> </p>
      </div>
    </body>
    
    </html>