Sumon Math Game With JQuery

October 9th, 2011 by aditia rahman / No Comments  

     

In today post I want to share how I make a simple sumon math game based on JQuery, this game inspired by hyperandroid, this game it quite nice to practice your self concentration about math addition.

JQuery Sumon Game

This post will create that simple nice game, just to show that you can make it with simple jquery, please note that I only add the basic rule of the game, which are, we have to pick the total number that matched the appear random number thats all.

Demo | Download

JQuery

In this example i’m using a little JQuery UI effect, so not to forget to include it on your script.

<script type="text/javascript">
function randomFromTo(from, to){
    return Math.floor(Math.random() * (to - from + 1) + from);
}

Array.prototype.clean = function(deleteValue) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == deleteValue) {
            this.splice(i, 1);
            i--;
        }
    }
    return this;
};

var sum = 0;
var tempindex = 0;
var numbers = new Array();

function generateRandomSum() {
    var looprand    = randomFromTo(1, 3);
    var total       = 0;
    var arrayIndex  = new Array();

    if (looprand > numbers.length) {
        looprand = numbers.length;
    }

    for (j=0; j<looprand; j++) {
        var randindex = randomFromTo(0, numbers.length - 1);
        randindex = getUnique(randindex, arrayIndex);

        total = total + numbers[randindex];
        arrayIndex[j] = randindex;
    }
    sum = total;
    $("#nextsum").html(total);
}

function getUnique(index, arrayIn) {
    if ((jQuery.inArray(index, arrayIn) == -1)) {
        return index;
    } else {
        rindex = randomFromTo(0, numbers.length - 1);
        return getUnique(rindex, arrayIn);
    }
}

var sumtemp = 0;
var numtemp = new Array();

// store temporary index in array
var arrIndex = new Array();
function boxClick(obj) {
    if (!$(obj).hasClass("disable")) {
        var clickedindex = parseInt($(obj).attr("id").replace("num", ""));
        var temp = parseInt($(obj).find("p").html());

        if (!$(obj).hasClass("red")) {
            $(obj).addClass("red clicked");
            // store clicked index in array
            arrIndex[tempindex] = clickedindex;
            sumtemp = sumtemp + temp;
            tempindex++;

            // temporary sum is match
            if (sumtemp == sum) {
                $(".clicked").unbind("click");
                $(".clicked").removeAttr("id");
                $(".clicked").addClass("disable");
                $(".clicked").animate({
                   backgroundColor: "#e3e3e3",
                   color: "#e3e3e3",
                   borderColor: "#e3e3e3"
                }, 500, function() {
                    $(".disable").removeClass("clicked");
                });

                // change each box id
                var y = 0;
                $("#dimcontainer div.boxnum").each(function(index) {
                    if (!$(this).hasClass("disable")) {
                        $(this).attr("id", "num"+y);
                        y++;
                    }
                });

                // delete matched number
                for ( z = 0; z < arrIndex.length; z++) {
                    delete numbers[arrIndex[z]];
                }

                // delete temporay index
                for ( e = 0; e <= arrIndex.length; e++) {
                    delete arrIndex[e];
                }
                arrIndex.clean(undefined);
                numbers.clean(undefined);

                sum = 0;
                sumtemp = 0;
                // reset index
                tempindex = 0;

                generateRandomSum();

                // Game Finished
                if (numbers.length == 0) {
                    $("#nextsum").html("Thanks For Playing!");
                }
            }

            // temporary sum not match
            if (sumtemp > sum) {
                $("#dimcontainer").effect("shake", { times: 1 }, "fast", function() {
                    sumtemp = 0;
                    $(".boxnum").removeClass("red");
                    $(".clicked").removeClass("clicked");
                    $("#sum").html(sumtemp);

                    // delete the temporary array & reset index
                    numtemp = new Array();
                    tempindex = 0;
                });
            }
        } else {
            $(obj).removeClass("red");
            $(obj).removeClass("clicked");

            // remove clicked index
            for (x = 0; x < arrIndex.length; x++) {
                if (arrIndex[x] == clickedindex) {
                    arrIndex.splice(x, 1);
                }
            }
            tempindex--;

            sumtemp = sumtemp - temp;
        }
    }
}

function start() {
    // create a number of box and generate random number in array
    sum          = 0;
    sumtemp      = 0;
    tempindex    = 0;
    var val          = parseInt($("#cbdim").val());
    var boxloop      = val * val;
    var boxleft      = ($(window).width() - (val * 78)) / 2;
    $("#dimcontainer").html('<div id="boxclear"></div>');
    $("#dimcontainer").css({
        width: (val * 78) + "px",
        left: boxleft + "px"
    });

    for ( i = 0; i < boxloop; i++) {
        numbers[i] = randomFromTo(1, 15);
        $('#boxclear').before('<div class="boxnum" id="num'+i+'" '+
            ' onclick="boxClick(this);"><p>'+numbers[i]+'</p></div>');
    }
    generateRandomSum();
}
</script>

1. function randomFromTo, from admixweb, this function will get random number between the two input parameter.

2. function Array.prototype.clean , from stackoverflow, this function will clean the array, I use this with javascript delete function to cleaning the array, since I haven’t found how to destroying an array in javascript.

3. function generateRandomSum, this function will pick the total random in array, the total picked number is random from one to three, and each index of the array must be unique.

4. function getUnique, this function will get unique index of array that stored in array, this are recursive function, it will continue run until find the unique array index.

5. function boxClick, this is the main event function of this example, many array variable used in this function, I admit I fell a little bit confuse when debugging this, that I have to delete array, change array, clean. etc.

6. function start, this is the initialization when displaying the box, it creating each box by looping on the fly, based on the dimensions size that picked.

HTML
<div id="container">
    <div id="pick">
        Pick Dimension: &nbsp;
        <select id="cbdim" style="font-size:18px;">
            <option value="3">3 x 3</option>
            <option value="4">4 x 4</option>
            <option value="5">5 x 5</option>
            <option value="6">6 x 6</option>
            <option value="7">7 x 7</option>
        </select>
        <button id="btnstart" onclick="start();">Start Game !</button>
    </div>
    <p id="pnext">Next Total: &nbsp;<span id="nextsum">0</span></p>

    <div id="dimcontainer">
        <div id="boxclear" style="clear:both"></div>
    </div>
</div>
CSS
* {
    font-family: Arial, "Free Sans";
}
body {
    background: #fff url("circles.png") repeat right top;
}
#container {
    margin: 0 auto;
    text-align: center;
}
#dimcontainer {
    padding: 2px;
    margin: 0 auto;
    left: 500px;
}
.boxnum {
    text-align: center;
    cursor: pointer;
    border: 2px solid #e3e3e3;
    background: #fff;
    width: 70px;
    height: 70px;
    margin: 2px;
    float: left;
    color: #D80000;
    -webkit-border-radius: .3em;
    -moz-border-radius: .3em;
    border-radius: .3em;
}
.boxnum:hover {
    background: #e3e3e3;
}
.boxnum p {
    margin-top: 20px;
    font-size: 28px;
    font-weight: bold;
    text-shadow: -1px 1px 1px #fff;
}
.red {
    background: #ff0000;
    border-color: #ff0000;
}
.red:hover {
    background: #ff0000 !important;
}
#boxclear {
    clear: both;
}
#pnext {
    font-size: 18px;
}
#nextsum {
    font-weight: bold;
    font-size: 30px;
    position: relative;
    top: 3px;
}
#pick {
    font-size: 18px;
}

That’s all, I know this example is not perfect but at least this is one of the way how you make it, you can improve it by adding some several features like, game scoring, help instruction, difficulty (by adding range in the random number), some bug fixing for preventing rapid click, etc.

Demo | Download

JQuery Sumon Game

        submit to reddit Delicious

No Comment Leave a Comment Subscribe RSS

Leave a Comment