Click here to Skip to main content
15,891,372 members
Articles / All Topics
Technical Blog

Snakes and Ladders – An Attempt using HTML5

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
4 Aug 2013CPOL3 min read 8.9K   2  
Demonstration of the very simple and crude implementation of Snakes and Ladders game using HTML5

Introduction

This post 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 the 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 the 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 changed in the internet industry. Thus, there a demand for the 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 JavaScript. It can be used to draw shapes, images and animations. It promises to make life 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.

HTML
<!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 JavaScript.

JavaScript
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

JavaScript
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

JavaScript
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.

JavaScript
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 <img class="wp-smiley" alt=":)" src="http://manasbhardwaj.net/wp-includes/images/smilies/icon_smile.gif" /> ");
		initGame();
	}
}

The post Snakes and Ladders – An attempt using HTML5 appeared first on Manas Bhardwaj's Stream.

License

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


Written By
Architect
Netherlands Netherlands

Read my personal blog at www.manasbhardwaj.net.


Comments and Discussions

 
-- There are no messages in this forum --