Create Sliding Puzzle Game in Web Browser

Keith Chan
7 min readFeb 9, 2020
Photo by Clément H on Unsplash

There are lots of applications in our computers and handsets that we use everyday. Software developers created those applications, we follow the workflow and rules in them. If we can create our own application, we can set our own workflow and rules.

It is a long road to become a sophisticated programmer. However, it is always fun to have a try. As Matthew MacDonald said, the main activity of developing an application is not writing code, but planning and testing.

I am not trying to teach you programming skill here but sharing the flow of problem solving. I hope you find it is interesting and going to learn more programming skills on the Internet after reading this.

Something to be Done by Computer

We are trying to create a sliding puzzle game on computer.

There are some examples on the Internet you can refer to. Here is one of them.

The Platform

Any computer program needs a platform to run. You may heard about Java, .net or Python. They all need specific software installed in your computer. However, you have at least one application already installed on your computer can run programs — web browser. You may have FireFox, Chrome or Safari installed. All of them can run JavaScript.

You need to compile, deploy and then execute a program in most of the platforms. But if you write JavaScript and saved in a text file, you only need to open the file in web browser. I will provide the source code, therefore you can simply run the program in your web browser. If you want to update the source code, you may need to learn HTML, JavaScript and CSS.

Breakdown the Problem

Here is the problem breakdown and the related technology.

  1. Draw game board on screen — HTML, CSS & JavaScript
  2. A place to store the tiles — Array in JavaScript
  3. A function to shuffle the tiles when game start — JavaScript
  4. A function to move tiles — JavaScript
  5. A function to refresh the game board on screen — JavaScript
  6. Count the clicks and detect the game when finished — JavaScript

Problem Solving Flow

The flow will be shown below. There are useful links or Google search link of those critical technical terms. Click to find out more.

Draw Game Board on Screen & Create Array for Tiles

A nested for loop is used to draw the matrix game board in HTML table and store the tiles values in an JavaScript 2-dimensional array from 1 to 15 and a space.

Game board

Shuffle Tiles

Each tile is represented by two indexes, showing the horizontal and vertical position. The tile can only be moved to adjacent space, which is one index unchanged and the other one increased or decreased by one. The space is in the position (3, 3) before shuffle, therefore only tiles in position (2, 3) and (3, 2) can be moved.

Tile Indexes

Shuffle tiles means moving tiles for a number of times. A variable is used to setup shuffle times. There are also variables to store the indexes of moving tile and space. The move means swapping the information of tile and space.

Refresh Display

The above moves are only changing data in the memory. Finally, we need to update the display using nested for loop again.

Shuffled Tiles — Game Started

Game Playing and Check Successful

At this point, we have the game board ready, but how to make it playable? We need to handle the the mouse click. We are using onclick JavaScript Event to handle it. We already created the functions for moving tiles and refresh display in shuffle. Therefore we can reuse them here. After clicking the tile, it moves and then refresh. These moves are just data swapping just like before, but we need one restriction. It is restricted to move tile if the space is not next to it. If statement is used here to check is it next to the space.

To measure how good you finish the game, we count the number of moves you did. We added a counter variable which increment each time player clicks. After that, we need to check the finish point, all 15 tiles at the right place. Here another counter variable is used, once the counter meet 15, you win the game, and a message box will be shown to inform you.

Playing Game, Showing Number of Moves

Source Code

The following is the source code. Simply copy and paste the text to a text editor, save the file with .html extension. Then open the file in your favourite web browser or simply double click the file to open. To start a new game, just reload the page.

It is a bit hard to read source code below. You can find a text editor which can display source code. Visual Studio Code is one of the choices.

Source code also available on GitHub.

<!DOCTYPE html>
<html>
<head>
<style>
.grid {
width: 300px;
height: 300px;
display: flex;
justify-content: center;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
div {
padding: 10px;
font-family: Arial;
font-size: 15pt;
}
table, th, td {
border: 1px solid black;
padding: 10px;
text-align: center;
font-family: Arial;
font-size: 25pt;
}
</style>
<script type="text/javascript">
// Grid Size
var _gridHeight = 4;
var _gridWidth = 4;
// Array to Store Tiles
var _tiles = new Array(_gridHeight);
for (var i=0; i<_gridHeight; i++) {
_tiles[i] = new Array(_gridWidth);
}
// Space Location
var _spaceLocArray = [(_gridHeight-1), (_gridWidth-1)];
// Click Count
var _clickCount = 0;
// Successful Flag
var _success = false;
// Draw Game Board and Create the Tiles
function generateGrid() {
var divGrid = document.getElementById("grid");
var strGrid = "";
strGrid += "<table id='board'>";
for (var h=0; h<_gridHeight; h++) {
strGrid += "<tr>";
for (var w=0; w<_gridWidth; w++) {
var locId = "loc_" + h + "_" + w;
_tiles[h][w] = (h*_gridWidth+w+1);
// The Last Tile is Empty
if (w == _gridHeight-1 && h == _gridWidth-1) _tiles[h][w] = "";
strGrid +=
"<td id='"+locId+"' " +
"onclick='moveTile(["+h+","+w+"], true);refresh();'>" +
_tiles[h][w] +
"</td>";
}
strGrid += "</tr>";
}
strGrid += "</table>"
strGrid += "<div>Moves: <div id='moves'></div></div>";
divGrid.innerHTML = strGrid;
}
// Shuffle Tiles when Start
function shuffle() {
// Shuffle Times
var shuffleTimes = 100;
// Tile to be Moved
var moveTileArray = new Array(2);
// Moving Direction from the Space
var moveDirection;
for (var i=0; i<shuffleTimes; i++) {
// Find a Moving Direction
do {
moveTileArray[0] = _spaceLocArray[0];
moveTileArray[1] = _spaceLocArray[1];
moveDirection = Math.floor(Math.random() * 4);
switch (moveDirection) {
case 0:
moveTileArray[0]--;
break;
case 1:
moveTileArray[1]++;
break;
case 2:
moveTileArray[0]++;
break;
case 3:
moveTileArray[1]--;
break;
}
} while (moveTileArray[0]<0 || moveTileArray[0]>=_gridHeight ||
moveTileArray[1]<0 || moveTileArray[1]>=_gridWidth)
moveTile(moveTileArray, false);
}
refresh();
}
// Move Tile - Update the Tile Array & Space Array
function moveTile(moveTileArray, updateClickCount) {
if ((_spaceLocArray[0] == moveTileArray[0] &&
Math.abs(_spaceLocArray[1]-moveTileArray[1])==1)
||
(_spaceLocArray[1] == moveTileArray[1] &&
Math.abs(_spaceLocArray[0]-moveTileArray[0])==1)
) {
// Move Tile to Space
_tiles[_spaceLocArray[0]][_spaceLocArray[1]] = _tiles[moveTileArray[0]][ moveTileArray[1]];
// Move Space to New Location
_tiles[moveTileArray[0]][moveTileArray[1]] = "";
// Set the Space
_spaceLocArray[0] = moveTileArray[0];
_spaceLocArray[1] = moveTileArray[1];

if (updateClickCount) _clickCount++;
document.getElementById("moves").innerHTML = _clickCount;
}
}
// Refresh Display & Check Successful
function refresh() {
var checkSuccess = 0;
for (var h=0; h<_gridHeight; h++) {
for (var w=0; w<_gridWidth; w++) {
var locId = "loc_" + h + "_" + w;
var cell = document.getElementById(locId);
cell.innerHTML = _tiles[h][w];
if (_tiles[h][w] == (h*_gridWidth+w+1)) checkSuccess++;
}
}
// Check Success
if (checkSuccess >= (_gridHeight*_gridWidth-1))
alert("You finished in " + _clickCount + " moves!");
}
</script>
</head>
<body onload="generateGrid();shuffle();">
<div id="grid" class="grid"></div>
</body>
</html>

Little Exercise

The game can be changed with minor updates in source code. Take a look at the following puzzle.

8x3 Puzzle

Two parameters control the width and height of the game board. Please try to change the value in source code to create the above 8x3 puzzle. Moreover, because the number of tiles increased, more shuffle times maybe applied when initiate the game. Please try to decrease and increase the shuffle times to see the different.

Interested?

Do you want to try?

--

--