A Simple HTML5 Game



My son is having summer vacation and he wanted to learn animation and create games. He had learnt Flash and ActionScript a couple of years back. So he started developing a game in Flash. However he ran into few issues and sought my help. Since I don’t know Flash, I could not help him much. But I suggested that if he develops his game in HTML5, I could help him. So while teaching him HTML5 and animation, I ended up creating a very simple game, which I want to share here.

In this game, when you press the ‘Start’ button, a square starts moving inside a bigger square and the goal is to prevent the smaller square hitting the outer square, by controlling its motion using arrow keys. You don’t need to keep the keys pressed, just press and release any arrow key to change direction. The square moves on its own and accelerates as the game progresses. Give it a try –


The animation loop in this game is created using window.setInterval() function, initially in the startGame() function and then later when the square needs to be accelerated, in accelerate() function. Before creating a new interval in the accelerate(), old loop is cancelled by calling window.clearInterval(). The square is drawn in animateFunc(), which is called by setInterval() method at fixed interval. See the code listing at the end of this post.

Acceleration is controlled by three variables; xStep, yStep and interval. xStep and yStep determine how much the square should move along X and Y axis respectively. interval determines how frequently animateFunc() is called. The interval at which acceleration is changed is controlled by changeAccelerationInterval variable. The game can be made as simple or difficult as you want by tweaking values of these variables.

Key down event (for all arrow keys) is handled by handleKeyDown() and up event is handled by handleKeyUp(). The score is calculated by dividing number of seconds played by two.

Note that I haven’t used animation optimizations techniques I had discussed in my earlier posts in this game because there is not much to redraw on the Canvas and performance is quite good.

Though the game is very simple, I had fun developing it.

-Ram Kulkarni

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple Game</title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>

<script type="text/javascript">
    var currXPos = 0, currYPos = 0;;
    var width = 400, height = 300;
    var rectWidth = 20, rectHeight = 20;
    var xDir = 1, yDir = 1, xStep = 2, yStep = 2, interval = 60;
    var changeAccelerationInterval = 4000; //4 seconds
    var changeXDir = true, changeYDir = true;
    var stopAnimation = true;
    var scoreStartTime, acceStartTime = 0;

    $(document).ready(function(){
        can1 = $("#canvas1")[0];
        ctx = can1.getContext("2d");

        $(document).keydown(handleKeyDown);
        $(document).keyup(handleKeyUp);
        $("#startBtn").click (startGame);
    });

    function startGame()
    {
        xDir = yDir = 1;
        xStep = yStep = 2;
        interval = 60;
        changeXDir = changeYDir = true;
        currXPos = (width / 2) - (rectWidth / 2);
        currYPos = (height / 2) - (rectHeight / 2);

        stopAnimation = false;
        scoreStartTime = acceStartTime = (new Date()).getTime();
        $("#startBtn").hide();
        $("#scoreDiv").hide();
        animateFunc();
        intervalId = window.setInterval(animateFunc, interval);
    }

    function stopGame()
    {
        var timePlayed = (new Date()).getTime() - scoreStartTime;
        var score = new Number(timePlayed / (1000 * 2)).toFixed(0);
        $("#startBtn").show();
        window.clearInterval(intervalId);
        stopAnimation = true;
        $("#scoreDiv").html("You scored " + score + " points").show();
    }

    function accelerate()
    {
        if (interval > 3)
            interval -= 3;

        xStep++; yStep++;
        window.clearInterval(intervalId);
        acceStartTime = new Date().getTime();
        intervalId = window.setInterval(animateFunc, interval);
    }

    function isTimeToaccelerate()
    {
        if (((new Date()).getTime() - acceStartTime) > changeAccelerationInterval)
            return true;
        return false;
    }

    function handleKeyDown (event)
    {
        if (stopAnimation || (!changeXDir && !changeYDir))
            return;

        if (event.which < 37 || event.which > 40)
            return;

        if ((event.which == 38 || event.which == 40) && changeYDir)
        {
            if (event.which == 38) //up
                yDir = -1;
            else //down
                yDir = 1;
            changeYDir = false;
            event.preventDefault();
        }
        else if ((event.which == 37 || event.which == 39) && changeXDir)
        {
            if (event.which == 37) //left
                xDir = -1;
            else // right
                xDir = 1;
            changeXDir = false;
            event.preventDefault();
        }
    }

    function handleKeyUp (event)
    {
        switch (event.which)
        {
            case 38: //up
            case 40: //down
                changeYDir = true;
                event.preventDefault();
                break;
            case 37: //left
            case 39: //right
                changeXDir = true;
                event.preventDefault();
                break;
        }
    }

    function animateFunc()
    {
        ctx.beginPath();
        ctx.clearRect(0,0,width,height);
        ctx.rect(currXPos,currYPos, rectWidth,rectHeight);
        ctx.stroke();

        currXPos += xStep * xDir;
        currYPos += yStep * yDir;

        if (currXPos <= 0 || currXPos >= (width - rectWidth) ||
            currYPos <= 0 || currYPos >= (height - rectHeight))
        {
            stopGame();
            return;
        }

        if (isTimeToaccelerate())
            accelerate();
    }

    // get random number between X and Y
    function getRand(x, y) {
        return Math.floor(Math.random()*y)+x;
    }
</script>

</head>

<body >
<div id="kineticDiv"></div>
<canvas id="canvas1" height="300" width="400" style="border-style:solid;border-color:#DDD"></canvas><br>
<input id="startBtn" type="button" value="Start"> <br>
<div id="scoreDiv" style="background-color:#AAA; 
    font-size:larger;border-color:#000;
    border-style:outset;display:none;max-width:400px"></div>
</body>
</html>

One Reply to “A Simple HTML5 Game”

Leave a Reply