Dice Roll Programming Tutorial For Web Browser Games
Learn to program dice rolls using JavaScript for web browser based games. Integrate it with basic HTML and CSS or any other means of graphical representation you wish to apply for displaying the dice and their values to the user.
<!DOCTYPE html>
<html>
<head>
<style>
div.dice{
float:left;
width:32px;
background:#F5F5F5;
border:#999 1px solid;
padding:10px;
font-size:24px;
text-align:center;
margin:5px;
}
</style>
<script>
function rollDice(){
var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
die1.innerHTML = d1;
die2.innerHTML = d2;
status.innerHTML = "You rolled "+diceTotal+".";
if(d1 == d2){
status.innerHTML += " DOUBLES! You get a free turn!!";
}
}
</script>
</head>
<body>
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<button onclick="rollDice()">Roll Dice</button>
<h2 id="status" style="clear:left;"></h2>
</body>
</html>