SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software HTML5 Tutorials and HTML 5 Examples
Development resources, articles, tutorials, code samples and tools and downloads for ASP.Net, SQL Server, R Script, Windows, Windows Phone, AWS, SAP HANA and ABAP, like SAP UI5, Screen Personas, etc.




HTML5 Game Development on Lights Out Game with Javascript

This HTML5 tutorial shows HTML5 game development using HTML5 elements like audio using Javascript on a sample Lights Out game. I can suggest HTML5 developers to play Lights Out game before they dive into HTML5 codes and Javascript programming codes illustrated in this HTML5 tutorial. A short playing session will give a brief idea why HTML5 programming code is developed in below explained structure.

Lights Out game HTML5 codes
HTML5 game development tutorial explaining Lights Out game programming

Add reference to the CSS and Javascript files within the <head> tags of the online HTML5 game web page header. HTML5 and Javascript developers can download Javascript source codes of the Lights Out HTML5 game from kodyazlightsout.js.

<script src="kodyazlightsout.js"></script>

Then add the following HTML5 code into the game web page markup codes.

Board size:
<button onclick="javascript:resizeBoard(3);">3x3</button> or
<button onclick="javascript:resizeBoard(5);">5x5</button>
Time: <span id="timer"></span><br />
Movements: <span id="counter"></span><br />
<span id="square" class="board"></span><br />

We placed two HTML button elements and a place where we can display user's statistics showing total time passed in seconds and the number of toggles user has done.

The HTML span element with id equals to square is used for creating dynamic HTML code. Definetely HTML5 Output tag can be used instead of using span tag, but still there are web browsers with lack of HTML5 support for output tag. So that is why I preffered using old fashion span element for displaying the board content HTML codes.

Also we define the onload event of the HTML body element to execute resizeBoard() Javascript function with argument for building 3x3 game board.

<body onload="resizeBoard(3);">

The player can change the board size from 3x3 to 5x5 or vice versa using the buttons placed before statistics time and number of movements.

If you look at the Javascript include file, you will first realize a set of variables declared at the top of Javascript codes. These Javascript variables are:
var n // This is for defining board size. n is 3 for 3x3, n is 5 for 5x5 board
var box // Javascript two dimensional array variable, box[n][n]
var width // width of each image forming HTML5 game board
var height // height of each image forming HTML5 game board
var time // Total amount of time since last game start in seconds
var count // Number of toggles, movements for the current play
var measureTime // boolean flag helps to pause time measuring or not
var jsTimer // Integer variable which returns handle for Javascript timer
var lightColor // Color for case lights are on, turned on
var darkColor // Color for case lights are off, turned off

var n;
var box;
var width;
var height;
var time;
var count;
var measureTime;
var jsTimer;
var lightColor = "/images/games/lights-out/sky.png";
var darkColor = "/images/games/lights-out/blue.png";

To read the Javascript codes, HTML5 developers can start from the function resizeBoard()
This function only sets the image width and height attributes then calls another Javascript function named prepareTable().

var board = document.getElementById("square");
board.innerHTML = "";
n = p;
if (n < 5) {
 width = height = 101;
} else {
 width = height = 71;
}
prepareTable();

prepareTable() function creates two dimensional Javascript array which represents the HTML5 game board as rows and columns.

box = new Array(n);
for (i = 0; i < n; i = i + 1) {
 box[i] = new Array(n);
}

Then within the function codes, each array item is set to 0 or 1 by random using Math.round() and Math.random() functions.

for (i = 0; i < n; i = i + 1) {
 for (j = 0; j < n; j = j + 1) {
  box[i][j] = Math.round(Math.random());
 }
}

These randomly assigned 0 and 1 values correspond to lights turned on and turned off cases. The user interface is displaying 0 by using light color image and displays 1 by dark color image.
To create HTML image elements dynamically using Javascript programming, document.createElement("img") method is called once for each array item. And dynamically created image attributes like source attribute src is set according to the value of the array item. Additionally an onClick event attribute is created too with arguments pointing to array dimension. These arguments will enable Javascript programmer to define which image on board is pressed and will let developer to toggle required lights.

At the end each dynamically created image element is appended to the HTML span area which represents the game board by using square.appendChild(img); javascript code

var square = document.getElementById("square");
for (i = 0; i < n; i = i + 1) {
 for (j = 0; j < n; j = j + 1) {
  var img = document.createElement("img");
  img.setAttribute("id", "img" + i + j);
  img.setAttribute("data-x", i);
  img.setAttribute("data-y", j);
  if (box[i][j] == 1) {
   img.setAttribute("src", darkColor);
  } else {
   img.setAttribute("src", lightColor);
  }
  img.setAttribute("width", width);
  img.setAttribute("height", height);
  img.setAttribute("onClick", "javascript:nextMove(" + i + "," + j + ");");
  square.appendChild(img);
 }
 var br = document.createElement("br");
 square.appendChild(br);
}

The last section within prepareTable() Javascript function sets initial values for variables required when a new game is started. This is like enabling the timer to start from 0, resetting movements counter, etc.
Besides a new timer object is created by calling the jsTimer = self.setInterval(startTimer, 1000); Javascript code with time interval equals to 1 second.

count = -1;
countMovements();
measureTime = 1;
time = -1;
startTimer();
window.clearInterval(jsTimer);
jsTimer = self.setInterval(startTimer, 1000);

HTML5 programmers and Javascript developers can find the codes for countMovements() and startTimer() functions from the included Javascript file kodyazlightsout.js

At this point the HTML 5 game Lights Out is started and the game player is about to make his first move by tapping or pressing an image displayed on a board square. When image is pressed Javascript onClick event will be triggered which will execute the nextMove() Javascript function.

nextMove() Javascript function is the main program code that builds Lights Out HTML5 game. Javascript programme already know which image is pressed or clicked using the input arguments. These input paramaters to Javascript function correspond to two-dimensional array dimensions representing the game board programmatically.
Within the js codes, changeColor() function is called to toggle the color of squares on the board. Only the pressed square, top and bottom neighbours and left and right neigbors are affected. changeColor() function is called for each of the 4 neigbours and for the pressed image itself.

There are controls using if conditional statement to check if the pressed image is on the boarders of the HTML5 game board. This control will prevent a dimension out of max index javascript error.

changeColor(i, j);
if (j - 1 >= 0) changeColor(i, j - 1);
if (j + 1 < n) changeColor(i, j + 1);
if (i - 1 >= 0) changeColor(i - 1, j);
if (i + 1 < n) changeColor(i + 1, j);
countMovements();
checkResult();

After colors of the items are altered or toggled using the following changeColor() function, countMovements() function and checkResult() function are called. changeColor() calls document.getElementById() Javascript method to get the image element represented with input parameters i and j. Then its color is read from multi-dimensional array box[i][j] then its array value and image source is toggled between 0 and 1, and light and dark colors. This toggle between colors and bit values represent turning lights on and lights off.

var img = document.getElementById("img" + i + j);
if (box[i][j] == "1") {
 img.setAttribute("src", lightColor);
 box[i][j] = 0;
} else {
 img.setAttribute("src", darkColor);
 box[i][j] = 1;
}

checkResult() function is also important to control if game is completed by turning off or turning on all lights after each movement of the game player.
This Javascript function source code is very simple for HTML programmers. The first array item value is read. Then all array items are read sequentially and compared with the first value. If all are same then this means the game player successfully completed HTML5 game Lights Out by setting all lights to the same status. But even if one array item has a different status than others, this means the game is not yet completed successfully so waits for the next move of the player.

var val = box[0][0];
var fail = 0;
for (x = 0; x < n; x = x + 1) {
 for (y = 0; y < n; y = y + 1) {
  if (box[x][y] != val) {
   fail = 1;
  }
 }
}
if (fail == 0) {
 applause();
}

If HTML5 game is completed Javascript function applause() is called to play audio on HTML 5 page. First window.clearInterval() Javascript method is executed passing the timer handle created previously to stop measuring time any more.

After timer is stopped, an HTML5 audio element is created dynamically using Javascript programming code new Audio()
Since not all browsers support same audio formats, I added Javascript codes to test if web browser is supporting audio file format first then play it.

To test web browser support for HTML5 audio for specific sound file format, developers can use audio.canPlayType("audio/wav") or following sample codes by passing the audio format as an argument to the audio.canPlayType() method. After a successfully supported audio format is defined, audio.play() method is called to play sound on HTML page with HTML5 features.

measureTime = 0;
window.clearInterval(jsTimer);

var audio = new Audio();
if (audio.canPlayType("audio/mp3")) {
 audio.src = "/games/html5/applause.mp3";
}
else if (audio.canPlayType("audio/wav")) {
 audio.src = "/games/html5/applause.wav";
}
else if (audio.canPlayType("audio/ogg")) {
 audio.src = "/games/html5/applause.ogg";
}
audio.play();

Although not all of the source code of HTML5 game Lights Out is discussed in this HTML5 game development tutorial, most important parts is demonstrated with sample codes. I hope new game developers will find this HTML5 tutorial useful to see how HTML5 audio element can be used with different media formats and used dynamically with Javascript programming. Basic use of Javascript timer object created with setInterval() method has sample usage in this HTML 5 game development tutorial as well. Multi-dimensional arrays in Javascript has also sample code to represent the HTML5 game Lights Out programmatically. Please refer to Javascript tutorial Javascript MultiDimensional Array for samples and simple script to create array of arrays in Javascript.
Happy coding!




HTML5 Tutorials
HTML5 Books

70-480 Exam






Copyright © 2004 - 2019 Eralper YILMAZ. All rights reserved.
Community Server by Telligent Systems