Sliding Puzzle

The aim of this challenge is to use HTML, CSS and Javascript to create an interactive sliding puzzle.

Step 1: Creating 9 tiles from a single picture, using CSS


Our aim is the use a single picture file called flower.png and to create 9 CSS classes for each tile of the picture as displayed below:
sliding-puzzle-slicing

We will create our tiles using DIV tags. We will use the flower.png picture file as the background for each tile and by applying different background-position we will create the 9 different tiles as needed.

Step 2: Table Layout


We now need to position our 9 tiles using a 3×3 table layout in HTML & CSS. To do so, we will use the display property in CSS using the following three options:

  • display: table;
  • display: table-row;
  • display: table-cell;

This is an alternative to using the <TABLE>, <TR> and <TD> tags in HTML.

Step 3: Adding Interactivity and Game Logic using JavaScript


For each cell we will add an onClick attribute to call a JavaScript function to implement the game logic when the user clicks on one of the 9 cells.

We will also add a re-shuffle button to shuffle all the tiles and start a new game.

Full Code


We have implemented the HTML and CSS code above and added on onClick attribute on each tile. When a tile is clicked the javascript function clickTile() is called. This is where the code will check if the tiles can be swapped.

We have also added the “New Game” button and the JavaScript code to reshuffle all the tiles of the grid.

See the Pen Sliding Puzzle by 101 Computing (@101Computing) on CodePen.

Your Challenge


Amend the HTML, CSS and JavaScript code provided above to create a sliding puzzle based on a 4×4 grid (instead of 3×3).
sliding-puzzle-4x4

Tips:

  1. Start by changing the HTML code to add enough <DIV> tags to create a grid of 16 tiles.
  2. Change the CSS code to add extra classes for .tile10, .tile11, … to .tile16.
    Not that you will have to use more accurate background positioning using the following approach:

    You will also need to revisit the CSS definitions for classes .tile1, .tile2, … to .tile9.
    Note that the white tile should now be tile 16.

  3. Adapt the JavaScript code to ensure it works with a 4 by 4 grid instead of a 3 by 3 grid.
Share Button