Javascript 🎲 Die Roller



Javascript 🎲 Die Roller

Early playing around with Javascript

Some time in the early 2000s I started learning a little Javascript. Roll the 🎲🎲.

function addDiceProperties( ) {
    var dieElements = getDieElements( );
    var x = 0;
    for( x = 0; x < dieElements.length; x++) {
        dieElements[x].onclick = dieElements[x].onkeypress =
        dieRoller(dieElements[x].innerHTML);
    }
}

function getDieElements( ) {
    var spans = document.getElementsByTagName("span");
    var dieElems = [];
    var isaDieRoll = /\bdieroll\b/;
    for(j = 0; j < spans.length; j++) {
        if ( isaDieRoll.test(spans[j].className ) ) {
            dieElems[dieElems.length] = spans[j];
        }
    }
    return dieElems;
}

function dieRoller(txt) {
    var count;
    var sides;
    var count_sides = getDieArgs(txt);
    count = count_sides[0];
    sides = count_sides[1];
    return function( ) {
        return rollDie(count, sides);
    };
}   

function rollDie(count, sides) {
    var results = 0;
    var i = 0;
    for(i = 0; i < count; i++) {
        results += intRand(1, sides);
    }
    console.log(results);
    document.getElementById("resultsbox").value = results;
}

function intRand(mini, maxi) {
    var range = maxi - mini + 1;
    return Math.floor(Math.random() * range + mini);
}

function getDieArgs(txt) {
    var pat = /([0-9]+)d([0-9]+)/;
    var res = [];
    var match = pat.exec(txt);
    res[0] = parseInt(match[1]);
    res[1] = parseInt(match[2]);
    return res; 
}