Click here to Skip to main content
Click here to Skip to main content

Snakes and Ladders - An attempt using HTML5

, 4 Jun 2012
Rate this:
Please Sign up or sign in to vote.
First part of an attempt to create Snake and Ladders using HTML5.

Introduction

This article is intended to demonstrate the very simple and crude implementation of Snakes and Ladders game using HTML5. Recently, I started to dig deeper into HTML5. By the time I came to canvas part, this game was one of the candidates which I wanted to try with. For those of you who have never heard of this game, here is a Wiki article about it.

Background

Though, this game is usually played as a dual player. The current implementation is a single player and is more intended to show the concepts used and the potential behind it. Before I actually start explaining the code and implementation, I would like to touch the background by explaining the HTML Canvas element which is heart of the game. I assume that everyone reading this article would have heard about HTML5 by now.

HTML5 is the successor of HTML4. HTML4 was standardized in 1997 and since then a lot has change in the internet industry. Thus, there a demand for next standardized version of HTML to improve the language and at the same time support the various multimedia blocks which have almost become regular to usage in web development. In general, HTML5 includes many syntactical features like <video>, <audio>, <canvas>, etc. We will be briefly going through Canvas element before proceeding to its usage in Snakes & Ladders game.

Canvas

Canvas as the word suggests is a new element introduced in HTML5 which can be used to draw graphics using java script. It can be used to draw shapes, images and animations. It promises to make like easier for designers, animators by standardizing (we all know the absence of flash on iPads/iPhones).

The canvas element isn't supported in some older browsers, but is supported in Firefox 1.5 and later, Opera 9 and later, newer versions of Safari, Chrome, and Internet Explorer 9.

Using the code

Well, let's walk through the code to see the use of <canvas> in developing the game.

I started with a simple HTML page which contains a <canvas> element.

<!DOCTYPE html>
<html>
<head>
    <title>Manas Bhardwaj's Snake & Ladder</title>
</head>
<body>
    <canvas id="board" width="650" height="650">
    </canvas>
</body>
</html> 

Context

The next step would be access this canvas element using java script.
var canvas = document.getElementById("board");
var context = canvas.getContext("2d");   

In the first line we retrieve the canvas DOM node using the getElementById method. We can then access the drawing context using the getContext method. <canvas> creates a fixed size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown. We'll focus on the 2D rendering context.

Drawing Squares

function RenderSquareBoard() 
{        
    var colorA = "white";
    var colorB = "red";

    var initRow = 1; var totalRows = 10; var initcolumn = 1; var totalColumns = 10;

    var x = 0; var y = canvas.height - squareSize;

    var columnNr = 1; var leftToRight = true;
    for (var row = initRow; row <= totalRows; row++) 
    {
        if (leftToRight) 
        {
            x = 0;
        }
        else 
        {
            x = canvas.width - squareSize;
        }

        for (var column = initcolumn; column <= totalColumns; column++) 
        {
            if (columnNr % 2 == 0) 
            {
                context.fillStyle = colorA;
            }
            else 
            {
                context.fillStyle = colorB;
            }

            context.fillRect(x, y, squareSize, squareSize);

            squares[columnNr] = x.toString() + ',' + y.toString();

            contextText.font = "15px tahoma";
            contextText.fillStyle = "black";
            contextText.fillText(columnNr, x, y + squareSize);

            var x1, y1
            if (leftToRight) 
            {
                x += squareSize;

                x1 = x + (squareSize / 2);
            }
            else 
            {
                x -= squareSize;
                x1 = x - (squareSize / 2);
            }

            y1 = y - (squareSize / 2);

            columnNr++;
        }

        y -= squareSize;
        leftToRight = !leftToRight;
    }
}  
Apart from the logic how I build the different squares and keep their co-ordinates for later use to plot the player moves, the import aspect we will see here is draw a rectangle. Canvas only supports one primitive shape - rectangles. All other shapes must be created by combining one or more paths. It was at east handy for me as I did not have to do anything extra for that and could use the in-built functionality.

There are three functions that draw rectangles on the canvas:

fillRect(x,y,width,height): Draws a filled rectangle
strokeRect(x,y,width,height): Draws a rectangular outline
clearRect(x,y,width,height): Clears the specified area and makes it fully transparent

Drawing Images

function RenderSnakeAndLadders()
{
    var img = new Image();
    img.onload = function () 
    {
    context.drawImage(img, 66, 23);
    };
    img.src = "Images/SnakeA.gif";
}  

Importing images is basically a two step process. Firstly we need a reference to a JavaScript Image object or other canvas element as a source. It isn't possible to use images by simply providing a URL/path to them. Secondly we draw the image on the canvas using the drawImage function.

The GAME

I used two snakes and two ladders in my example to keep it simple. If a player falls on a ladder he climbs up the ladder and thus does not have to cover the whole path. Against this, if a player falls on Snake's mouth he slips down to the tail. On the click of a button, I generate a random number between 1 and 6. The position of the player is changed based on his score and a new rectangle is drawn to show his new location.
 function nextMove() 
        {
            var newMove = GenerateRandomNumber(6);
            alert("You got : " + newMove);

            _currentPos = _currentPos + newMove;

            switch (_currentPos) 
            {
            //ladder
            case 6:
            _currentPos = 46;
            break;
            //ladder
            case 39:
            _currentPos = 79;
            break;
            //snake
            case 99:
            _currentPos = 29;
            break;
            //snake
            case 72:
            _currentPos = 2;
            break;             
            }

            var coorintaes = squares[_currentPos];
            coorintaes = coorintaes.split(',');

            context.fillRect(coorintaes[0], coorintaes[1], squareSize, squareSize);

            if (_currentPos == 100)
            {
                alert("Congratulations, you have won the game :)");
                initGame();
            }
        }  

History

Version 0.5: Initial implementation demonstrating that canvas element can be used to implement the game.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Manas Bhardwaj
Architect
Netherlands Netherlands
Read my personal blog at www.manasbhardwaj.net.
Follow on   Twitter

Comments and Discussions

 
GeneralExcellent Try!!!! PinmemberToywarrior12-Jun-13 17:48 
QuestionMissing images PingroupAmarnath S3-Jun-12 4:49 
AnswerRe: Missing images PinmemberManas Bhardwaj3-Jun-12 5:10 
GeneralRe: Missing images PingroupAmarnath S3-Jun-12 19:21 
GeneralRe: Missing images PinmemberManas Bhardwaj4-Jun-12 5:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 4 Jun 2012
Article Copyright 2012 by Manas Bhardwaj
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid