Building a Tile Puzzle Game Using JavaScript: Step-by-Step Guide

20 Nov 2024 01:16 PM

Creating a tile puzzle game involves several stages, from setting up the structure to adding functionality. Here's how you can do it step by step.

Step 1: Set Up the Basic HTML Structure

Create a basic HTML file to host the game.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tile Puzzle Game</title>
</head>
<body>
  <div class="container">
    <h1>Tile Puzzle Game</h1>
    <div id="game-board"></div>
    <button id="shuffle-button">Shuffle</button>
    <p id="message"></p>
  </div>
</body>
</html>

Step 2: Style the Game Board with CSS

Add the CSS to style the grid and make it visually appealing.

<style>
  body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    margin: 0;
    background-color: #f4f4f4;
  }

  .container {
    text-align: center;
  }

  #game-board {
    display: grid;
    grid-template-columns: repeat(4, 80px);
    grid-template-rows: repeat(4, 80px);
    gap: 5px;
    margin: 20px auto;
  }

  .tile {
    width: 80px;
    height: 80px;
    background-color: #007bff;
    color: white;
    font-size: 24px;
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }

  .tile.blank {
    background-color: #f4f4f4;
    cursor: default;
  }

  button {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
  }

  #message {
    margin-top: 20px;
    font-size: 18px;
    color: green;
  }
</style>

Step 3: Initialize the Game Board with JavaScript

Write JavaScript to create the initial puzzle grid.

<script>
  const boardSize = 4; // 4x4 grid
  const board = [];
  const gameBoard = document.getElementById('game-board');
  const shuffleButton = document.getElementById('shuffle-button');
  const message = document.getElementById('message');

  // Initialize the board
  function initBoard() {
    const numbers = [...Array(boardSize * boardSize).keys()].map(i => i + 1);
    numbers[numbers.length - 1] = null; // Last tile is blank
    for (let i = 0; i < boardSize; i++) {
      board[i] = numbers.slice(i * boardSize, (i + 1) * boardSize);
    }
    renderBoard();
  }

  // Render the board
  function renderBoard() {
    gameBoard.innerHTML = '';
    for (let i = 0; i < boardSize; i++) {
      for (let j = 0; j < boardSize; j++) {
        const tile = document.createElement('div');
        tile.classList.add('tile');
        if (board[i][j]) {
          tile.textContent = board[i][j];
        } else {
          tile.classList.add('blank');
        }
        tile.addEventListener('click', () => moveTile(i, j));
        gameBoard.appendChild(tile);
      }
    }
  }
</script>

Step 4: Add Shuffle Functionality

Allow users to randomize the tiles.

<script>
  // Shuffle the board
  function shuffleBoard() {
    message.textContent = '';
    for (let i = 0; i < 1000; i++) {
      const blankPos = findBlank();
      const neighbors = getNeighbors(blankPos.x, blankPos.y);
      const randomNeighbor = neighbors[Math.floor(Math.random() * neighbors.length)];
      swapTiles(blankPos.x, blankPos.y, randomNeighbor.x, randomNeighbor.y);
    }
    renderBoard();
  }

  // Find the blank tile
  function findBlank() {
    for (let i = 0; i < boardSize; i++) {
      for (let j = 0; j < boardSize; j++) {
        if (board[i][j] === null) return { x: i, y: j };
      }
    }
  }

  // Get neighboring tiles
  function getNeighbors(x, y) {
    const neighbors = [];
    if (x > 0) neighbors.push({ x: x - 1, y }); // Above
    if (x < boardSize - 1) neighbors.push({ x: x + 1, y }); // Below
    if (y > 0) neighbors.push({ x, y: y - 1 }); // Left
    if (y < boardSize - 1) neighbors.push({ x, y: y + 1 }); // Right
    return neighbors;
  }

  shuffleButton.addEventListener('click', shuffleBoard);
</script>

Step 5: Enable Tile Movement

Allow tiles to move into the blank space when clicked.

<script>
  // Move a tile
  function moveTile(x, y) {
    const blankPos = findBlank();
    if (Math.abs(x - blankPos.x) + Math.abs(y - blankPos.y) === 1) {
      swapTiles(x, y, blankPos.x, blankPos.y);
      renderBoard();
      if (checkWin()) {
        message.textContent = 'Congratulations! You solved the puzzle!';
      }
    }
  }

  // Swap two tiles
  function swapTiles(x1, y1, x2, y2) {
    const temp = board[x1][y1];
    board[x1][y1] = board[x2][y2];
    board[x2][y2] = temp;
  }
</script>

Step 6: Add Win Detection

Detect when the tiles are arranged in the correct order.

<script>
  // Check if the player has won
  function checkWin() {
    const flatBoard = board.flat();
    for (let i = 0; i < flatBoard.length - 1; i++) {
      if (flatBoard[i] !== i + 1) return false;
    }
    return true;
  }

  // Initialize the game
  initBoard();
</script>

Final Code

Combine all these sections into a single file as shown in the earlier response, and you’ll have a fully functional Tile Puzzle Game.

Enhancements

  1. Add a timer or moves counter to increase difficulty.
  2. Provide different levels, such as 3x3 or 5x5 grids.
  3. Introduce a reset button to return the board to its original state.

This step-by-step guide should help you create the game and expand it further as needed.

 

2
59