in ,

Creating A puzzle game ‘Lights Off’ using HTML5 canvas

Though earlier I have presented various earnest HTML5 Tutorial post, however today I am not going to say more about HTML5. Even, tons of HTML5 tutorials are becoming online on the internet and proliferating in numbers every day. As HTML5 has been emerged as an robust web-development program or application which is highly efficient to bring great amusing result that will verily make you or either users or client more amused and delighted like never before.

Though HTML5 flaunts over various advantages and features out of which one most interesting elements of HTML5 elements is <canvas>. With this element the web-developer can draw anything whatever they want by employing JavaScript. Though I am also not familiar and never play with this <canvas> element, but still I am also avid to play finger on this.

Therefore, I attempt to re-built a native game for iPhone, but with HTML5 <canvas>. Further, I would like to add here that though I am attempting to built this game but it might be not a real application, however, the basic motive of this HTML5 tutorial is not to create a game application but is to show the functionality of <canvas> element. Hence, the demo for this application being provided here works only with those browsers who are compatible with this <canvas> element.

demo

However, just take a chance to see whether you can solve this puzzle. Simply you are required to click on panel of light which toggle it along with another four adjacent light. Or just go into the insight of code and learn some additional thing about <canvas> element.

Below I have incorporated a video for the game in action for those users who don’t have a compatible browsers that can support HTML5 <canvas> element.

<iframe width="560" height="315" src="https://www.youtube.com/embed/v8ikTvQWfoc" frameborder="0" allowfullscreen></iframe>

HTML/CSS

The HTML and CSS are not too spectacular: just simply the HTML5 <canvas> element with an assigned ID and a container styled with some CSS.

<div id="lightcontainer">
<canvas id="lightpanel" width="500" height="500"></canvas>
</div>

#lightcontainer { margin:20px auto; width:500px; }
#lightpanel { background-color:#002B33;
-moz-box-shadow:0 0 5px #999; -moz-border-radius:10px;
-webkit-box-shadow:0 0 5px #999; -webkit-border-radius:10px;
box-shadow:0 0 5px #999; border-radius:10px;

The Idea

For your better comprehension, I have included some snapshots to elaborate the idea, that hopefully make the things more clear to you.

HTML5 canvas

First of all you are required to create the playing field. This field contains light panels of dimension 5×5.

HTML5 canvas

Now, we are required to implement logic regarding light switch. As you can view the example, it turns on or off the light panels as well as diagonal and horizontal panels. When the panel is on, it will be turned off, and if it is off it will turned on. In the snapshot, the marked red arrows instruct the users where they have clicked in an empty field.

HTML5 canvas

Next, attempt to create the beginning position and enable the users to switch off the lights in order to end the game.

JavaScript

And, this is the JavaScript where a little bit of jQuery has been employed.

// Two dimensional array that represents the playing field
// A "x" stands for "on"
// A "o" stands for "off"
var lightField =

[
[ "x", "o", "o", "x", "x" ],
[ "o", "o", "x", "o", "x" ],
[ "o", "x", "o", "x", "o" ],
[ "x", "o", "x", "o", "o" ],
[ "x", "x", "o", "o", "x" ]
];

In my standpoint a two dimensional array would be perfect to build a playing field. It is very easy and convenient to work with the code, but it also matters that how the playing field will appeared eventually, since it is the code which represents the field exactly.

// Attach a mouse click event listener
$("#lightpanel").click(function(e) {

// e will give us absolute x, y so we need to calculate relative to canvas position
var pos = $("#lightpanel").position();
var ox = e.pageX - pos.left;
var oy = e.pageY - pos.top;

// Check which fields we need to flip
// 100 = width of the tile
var yField = Math.floor(oy / 100);
var xField = Math.floor(ox / 100);

// The field itself
lightField[yField][xField] = lightField[yField][xField] == "x" ? "o" : "x";

// The field above
if(yField-1 >= 0) {
lightField[yField-1][xField] = lightField[yField-1][xField] == "x" ? "o" : "x";
}

// The field underneath
if(yField+1 < 5) {
lightField[yField+1][xField] = lightField[yField+1][xField] == "x" ? "o" : "x";
}

// The field to the left
if(xField-1 >= 0) {
lightField[yField][xField-1] = lightField[yField][xField-1] == "x" ? "o" : "x";
}

// The field to the right
if(xField+1 < 5) {
lightField[yField][xField+1] = lightField[yField][xField+1] == "x" ? "o" : "x";
}

repaintPanel();
});

To the playing field, this function include mouse listener which is useful to check the field clicked by users. On the ground of that information, it used to flips the adjacent fields in account of single line IF statement. We analyze for >=0 and <5 though we are not supposed to get out the array bounds.

Now, you may see here that this function calls the repaintPanel() at the bottom. Now, just go ahead to see how this function will appear:

function repaintPanel() {

// Retrieve the canvas
var canvas = document.getElementById("lightpanel");

// Check if the browser supports <canvas>
if (!canvas.getContext){
alert("This demo requires a browser that supports the <canvas> element.");
return;
} else {
clear();

// Get the context to draw on
var ctx = canvas.getContext("2d");

// Create the fields
var allLightsAreOff = true;
for(var i = 0; i < lightField.length; i++) { // Rows
for (var j = 0; j < lightField[i].length; j++) { // Columns

// Set up the brush
ctx.lineWidth = 3;
ctx.strokeStyle = "#83BD08";

// Start drawing
ctx.beginPath();

// arc( x, y, radius, startAngle, endAngle, anticlockwise)
ctx.arc(j * 100 + 50, i * 100 + 50, 40, 0, Math.PI*2, true);

// Actual draw of the border
ctx.stroke();

// Check if we need to fill the border
if(lightField[i][j] == "x") 
{
ctx.fillStyle = "#FFBD38";
ctx.beginPath();
ctx.arc(j * 100 + 50, i * 100 + 50, 38, 0, Math.PI*2, true);
ctx.fill();

// Since we need to fill this field, not all the lights are off
allLightsAreOff = false;
}
}
}

// Check if all the lights are off
if(allLightsAreOff) {
// User can't click anymore
userCanClick = false;

// Show message
alert("All lights are off, you finished the game!");
}
}
}

Hopefully, my comments transforms this tutorial more interesting. Simply, we are retrieving the canvas in order to draw filed on it. Since the drawing is not clear by element, therefore we attempted to re-draw this manually be clearing the contents. Therefore, firstly we call clear() method.

function clear()
{
var canvas = document.getElementById("lightpanel");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 500, 500);
}

It’s all about the code we needed to create this nice little game.

What do you think?

Written by Steven Bowen

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading…

0

Comments

0 comments

Mobile Application Development: Must Know Key Point Aspects

Top 10 Killer WordPress themes using short code