CrapsGame Example -- Source Code

HTML Page -- index.htm

 <!DOCTYPE html>
<html lang="en">
    <head>
        <meta content="text/html; charset=utf-8" 
            http-equiv="Content-Type">
        <title>CrapsGame Example</title>
        <link rel="stylesheet" href='styles.css'>
        <script src="script.js"></script>
    </head>

    <body>
        <h1>CrapsGame Example</h1>
        <button id="btn1">Roll Dice</button><br>
        <p>Green check means you win; red X means you lose.</p>
        <img id="img1">
        <p id="rolls" />
    </body>
</html>

CSS Sheet -- styles.css

/* Styles for MathRiddles1 Example */
body { background-color: #E0E0FF; 
       color: #000080; 
       font-family: Tahoma, Verdana, sans-serif; }
button { color: #000080; }
h1 { color: #800000; }
img { height: 25px; }
#img1 , #rolls {
    vertical-align: middle;
    display: inline-block; }
button { margin-bottom: 10px; }

JavaScript Script -- script.js

 // CrapsGame Example
// Source code file: script.js
function rollDice( ) {
    return Math.floor(Math.random( ) * 6) +
           Math.floor(Math.random( ) * 6) + 2;
}

function displayOutcome( ) {
    var image = document.getElementById("img1");
    var para = document.getElementById("rolls");
    var sum = rollDice( );
    para.innerHTML = sum + " ";
    if (sum == 7 || sum == 11) {
        image.src = "images/green-check.png";
    }
    else if (sum == 2 || sum == 3 || sum == 12) {
        image.src = "images/red-x.png"; 
    }
    else {
        var point = sum;
        while(true) {
            var sum = rollDice( );
            para.innerHTML += sum + " ";
            if (sum == point) {
                image.src = "images/green-check.png";
                break;
            }
            else if (sum == 7) {
                image.src = "images/red-x.png";
                break; 
            }
        }
    }
}

function init( ) {
    var button = document.getElementById("btn1");
    button.addEventListener("click", displayOutcome);
}

window.addEventListener("load", init);