掷骰子,当玩家恰好命中 21 时获胜

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

我正在尝试制作一个骰子计数器,您可以随心所欲地掷骰子,当您掷到 21 时 "win"。如果您超过 21,代码会告诉您您输了并重试。我不知道如何获得它,所以当总数达到 21 时会有不同的消息。这是我目前的代码:

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>

您需要做的就是添加一个 else if 语句并比较值是否为 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;

添加else if条件,判断score是否== 21

var clicks = 0;

function random()
{
  if (clicks > 21) {
    alert("You Got To 22! You Lose! Please Try Again!");
    location.reload();
  } else if( clicks == 21 ) {
  alert("You Got To 21! You Win! Want to play another?");
    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>