Sliding Puzzle Game in JavaScript

Sliding Puzzle Game in JavaScript
Code Snippet:Slide Puzzle
Author: Natalie Girard
Published: January 12, 2024
Last Updated: January 22, 2024
Downloads: 1,889
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a classic sliding puzzle game where you rearrange numbered tiles. Player goal? Align the numbers sequentially, leaving the bottom right corner empty. Click a tile, and if it’s adjacent to the empty space, they swap positions.

You can use this code to create an engaging sliding puzzle game on your website. This will add a fun and interactive element for your visitors.

How to Create a Sliding Puzzle Game in JavaScript

1. First of all, load the Normalize CSS by adding the following CDN link into the head tag of your HTML document. (Optional)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

2. Create the HTML structure for the puzzle game as follows. Modify the tile numbers and initial arrangement in the HTML code to customize your puzzle.

<h1>Slide Puzzle</h1>
<p>The goal is to move the tiles until the numbers are positioned sequentially with the empty space in the bottom right corner.</p>
<div class="container">
  <div class="square" data-pos="0">1</div>
  <div class="square" data-pos="1">14</div>
  <div class="square" data-pos="2">9</div>
  <div class="square" data-pos="3">3</div>
  <div class="square" data-pos="4">12</div>
  <div class="square empty" data-pos="5"></div>
  <div class="square" data-pos="6">2</div>
  <div class="square" data-pos="7">6</div>
  <div class="square" data-pos="8">7</div>
  <div class="square" data-pos="9">10</div>
  <div class="square" data-pos="10">11</div>
  <div class="square" data-pos="11">4</div>
  <div class="square" data-pos="12">15</div>
  <div class="square" data-pos="13">5</div>
  <div class="square" data-pos="14">13</div>
  <div class="square" data-pos="15">8</div>
</div>

3. Now, style the game interface using the following CSS styles. Adjust the grid dimensions in the CSS by changing the values of height and width in the .container class. Furthermore, experiment with colors, fonts, and dimensions to match your website’s theme.

body {
  padding: 20px;
  text-align: center;
}

.container {
  margin: 50px;
  position: relative;
  height: 200px;
  width: 200px;
  margin: 15px auto;
}

.square {
  height: 50px;
  width: 50px;
  color: white;
  border: 1px solid white;
  background: #333;
  position: absolute;
  transition: left 0.5s, top 0.5s;
  box-sizing: border-box;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2;
  cursor: pointer;
}

.empty {
  background: white;
  z-index: 1;
}

[data-pos="0"] {
  left: 0;
  top: 0;
}

[data-pos="1"] {
  left: 50px;
  top: 0;
}

[data-pos="2"] {
  left: 100px;
  top: 0;
}

[data-pos="3"] {
  left: 150px;
  top: 0;
}

[data-pos="4"] {
  left: 0;
  top: 50px;
}

[data-pos="5"] {
  left: 50px;
  top: 50px;
}

[data-pos="6"] {
  left: 100px;
  top: 50px;
}

[data-pos="7"] {
  left: 150px;
  top: 50px;
}

[data-pos="8"] {
  left: 0;
  top: 100px;
}

[data-pos="9"] {
  left: 50px;
  top: 100px;
}

[data-pos="10"] {
  left: 100px;
  top: 100px;
}

[data-pos="11"] {
  left: 150px;
  top: 100px;
}

[data-pos="12"] {
  left: 0;
  top: 150px;
}

[data-pos="13"] {
  left: 50px;
  top: 150px;
}

[data-pos="14"] {
  left: 100px;
  top: 150px;
}

[data-pos="15"] {
  left: 150px;
  top: 150px;
}

4. Finally, add the following JavaScript code to your project to enable tile movement and swapping.

var squares = document.querySelectorAll('.square');
squares.forEach(square => {
  square.addEventListener('click', e => {
    e.preventDefault();    
    var firstPos = parseInt(e.target.dataset.pos);
    var empty = document.querySelectorAll('.empty')[0];
    var secondPos = parseInt(empty.dataset.pos);
    
    var top = secondPos-4;
    var bottom = secondPos+4;
    var left = secondPos-1;
    var right = secondPos+1;
    
    if (secondPos%4-left%4 < 1) {
      left = -1;
    }
    if (right%4-secondPos%4 < 1) {
      right = -1;
    }
    var posibilities = [left, right, top, bottom];
    
    if (posibilities.includes(firstPos)) {
      empty.dataset.pos = firstPos;
      e.target.dataset.pos = secondPos;
    }
  })
});

That’s all! hopefully, you have successfully created a sliding puzzle game in JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X