Search code examples
javascripthtmldice

Roll a dice counter and the player wins when they hit exactly 21


Im trying to make a dice counter where you can roll it for as many times as you want and you "win" when you hit 21. If you go over 21, the code will tell you that you lose and to try again. I can't figure out how to have it so there will be a different message when the total hits 21. Here is my code so far:

var clicks = 0;

function random()
{
  if (clicks > 21) {
    alert("You Got To 22! You Lose! Please Try Again!");
    location.reload();
  }

  clicks += Math.floor(Math.random() * 6) + 1;

document.getElementById("clicks").innerHTML = clicks;

};
<p> <button onclick="window.location.href='index.html'">Click Me To Go Back To The Rules!</button> </p>
<h2>Get To 21!</h2>
<div>
   <p> Click The Dice To Role! The Counter Below Will Record Your Score!</p>
</div>
<div>
</div>
<div>
   <p id="game"></p>
</div>
<div>
   <input type="image" value="clicks" onclick="random()" src="https://www.propdog.co.uk/image/cache/data/accessories/dice/force-4-500x500.jpg" alt="Dice2" width="250" height="250">  
</div>
<div>
   Total Count: <a id="clicks">0</a>
</div>


Solution

  • All you need to do is add an else if statement and compare if the value is equal to 21:

    clicks += Math.floor(Math.random() * 6) + 1;
    
    if (clicks > 21) {
      alert("You Got To 22! You Lose! Please Try Again!");
      location.reload();
    } else if (clicks == 21) {
      alert("You Got To 21! Good Job! You Win!");
      location.reload();
    }
    
    document.getElementById("clicks").innerHTML = clicks;