滚动骰子计数器,当玩家正好击中21时,玩家获胜

问题描述 投票:0回答:2

我试图制作一个骰子计数器,你可以根据需要多次滚动它,当你达到21时你就“赢”。如果你超过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>
javascript html dice
2个回答
1
投票

您需要做的就是添加一个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;

0
投票

如果条件添加else并检查得分== 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>
© www.soinside.com 2019 - 2024. All rights reserved.