How To Program Simple Puzzle Game

HTML Headings:


Puzzle games have been popular for many years, providing entertainment and challenge for players of all ages. Programming a simple puzzle game can be a fun and educational project for beginners in game development. In this article, we will guide you through the process of creating a basic puzzle game using HTML and JavaScript.


To program a simple puzzle game, you will need a basic understanding of HTML, CSS, and JavaScript. You will also need a text editor to write your code and a web browser to test and play your game.

Step 1: Setting Up the HTML Structure

Start by creating a new HTML file and opening it in your preferred text editor. Begin by adding the basic structure of an HTML document:

<!DOCTYPE html>



<title>Simple Puzzle Game</title>

<link rel="stylesheet" href="style.css">

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



<h1>Simple Puzzle Game</h1>

<div id="puzzle"></div>



Step 2: Styling the Puzzle Board

Create a new CSS file named “style.css” and link it to your HTML document. Add the following code to style the puzzle board:

#puzzle {

width: 300px;

height: 300px;

border: 1px solid black;

display: grid;

grid-template-columns: repeat(3, 1fr);

grid-template-rows: repeat(3, 1fr);

gap: 2px;

padding: 2px;


Step 3: Writing JavaScript Logic

Create a new JavaScript file named “script.js” and link it to your HTML document. Add the following code to define the logic of the puzzle game:

const puzzle = document.getElementById("puzzle");

const tiles = [];

for (let i = 0; i < 9; i++) {

const tile = document.createElement("div");





Step 4: Adding Interactivity

To make the puzzle tiles movable, add the following JavaScript code:

let emptyTileIndex = 8;

function swapTiles(index) {

const tile = tiles[index];

if (index - 1 === emptyTileIndex || index + 1 === emptyTileIndex ||

index - 3 === emptyTileIndex || index + 3 === emptyTileIndex) {

tiles[emptyTileIndex].innerHTML = tile.innerHTML;

tile.innerHTML = "";

emptyTileIndex = index;



tiles.forEach((tile, index) => {

tile.addEventListener("click", () => {




Step 5: Final Touches

Finally, add the following CSS code to style the puzzle tiles:

.tile {

border: 1px solid black;

display: flex;

align-items: center;

justify-content: center;

font-size: 24px;

cursor: pointer;



Congratulations! You have successfully programmed a simple puzzle game using HTML and JavaScript. You can now customize and expand upon this basic game by adding more features, such as a timer or scoring system. Happy coding!

Leave a Comment