Skip to main content

Pac-Man Game in HTML, CSS, and JavaScript

In this tutorial, we will create a classic Pac-Man game using HTML, CSS, and JavaScript. Follow the steps to build the game board, Pac-Man, and implement the game logic.

HTML Structure

First, we need to set up the HTML structure for our Pac-Man game. This includes the game board and score display:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pac-Man Game</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Pac-Man Game</h1>
    <div id="game-board"></div>
    <div id="score-display">Score: 0</div>
    <script src="script.js"></script>
</body>
</html>

CSS Styling

Next, we add some CSS to style the game board, walls, dots, and score display:

body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    margin: 20px;
    background-color: #25afff;
    color: #fff;
}

h1 {
    color: black;
}

#game-board {
    margin-top: 20px;
    width: 400px;
    height: 400px;
    position: relative;
    background-color: #000;
    border: 10px solid #ff0421;
}

.wall {
    background-color: #00f;
}

.dot {
    background-color: rgb(232, 232, 232);
    border-radius: 50%;
    margin: 5px !important;
    width: 10px !important;
    height: 10px !important;
    position: absolute;
}

#score-display {
    margin-top: 10px;
    font-size: 24px;
    color: black;
}

JavaScript Functionality

Finally, let's add the JavaScript code to handle game logic, Pac-Man movement, and score updates:

document.addEventListener("DOMContentLoaded", () => {
    const board = document.getElementById("game-board");
    const scoreDisplay = document.getElementById("score-display");
    const width = 20;
    const cellSize = 20;
    let pacManPosition = { x: 1, y: 1 };
    let score = 0;
    let direction = { x: 1, y: 0 };

    const layout = [
        "WWWWWWWWWWWWWWWWWWWW",
        "W........W........W",
        "W.WWWWWW.W.WWWWWW.W",
        "W.W....W.W.W.....W",
        "W.W.WWWW.W.WWWW.W.W",
        "W........W........W",
        "W.WWWWWW.W.WWWWWW.W",
        "W.W...............W",
        "W.W.WWWWWW.W.WWWWWW",
        "W.W.W....W.W.W....W",
        "W.W.WWWWW.W.W.W.W.W",
        "W.W...............W",
        "W.W.WWWWWW.W.WWWWWW",
        "W........W........W",
        "W.WWWWWWW.W.WWWWWW.W",
        "W........W........W",
        "WWWWWWWWWWWWWWWWWWWW",
    ];

    let totalDots = 0;

    function createBoard() {
        for (let row = 0; row < layout.length; row++) {
            for (let col = 0; col < layout[row].length; col++) {
                const cell = document.createElement("div");
                cell.style.width = cellSize + "px";
                cell.style.height = cellSize + "px";
                cell.style.position = "absolute";
                cell.style.left = col * cellSize + "px";
                cell.style.top = row * cellSize + "px";

                if (layout[row][col] === "W") {
                    cell.classList.add("wall");
                } else if (layout[row][col] === ".") {
                    cell.classList.add("dot");
                    totalDots++;
                }

                board.appendChild(cell);
            }
        }
    }

    function createPacMan() {
        const pacMan = document.createElement("div");
        pacMan.style.width = cellSize + "px";
        pacMan.style.height = cellSize + "px";
        pacMan.style.backgroundColor = "yellow";
        pacMan.style.position = "absolute";
        pacMan.style.left = pacManPosition.x * cellSize + "px";
        pacMan.style.top = pacManPosition.y * cellSize + "px";
        pacMan.style.borderRadius = "50%";
        pacMan.classList.add("pacman");
        board.appendChild(pacMan);
        return pacMan;
    }

    function movePacMan(dx, dy) {
        const newX = pacManPosition.x + dx;
        const newY = pacManPosition.y + dy;

        if (layout[newY] && layout[newY][newX] !== undefined) {
            if (layout[newY][newX] === ".") {
                layout[newY][newX] = " ";
                score++;
                totalDots--;
                updateScore();

                const dotCells = Array.from(board.children).filter(
                    (child) =>
                        child.style.left === newX * cellSize + "px" &&
                        child.style.top === newY * cellSize + "px"
                );
                dotCells.forEach((cell) => cell.remove());

                pacManPosition.x = newX;
                pacManPosition.y = newY;
            }

            const pacMan = document.querySelector(".pacman");
            pacMan.style.left = pacManPosition.x * cellSize + "px";
            pacMan.style.top = pacManPosition.y * cellSize + "px";
        }
    }

    function updateScore() {
        scoreDisplay.textContent = "Score: " + score;
    }

    function autoMovePacMan() {
        movePacMan(direction.x, direction.y);

        const nextX = pacManPosition.x + direction.x;
        const nextY = pacManPosition.y + direction.y;

        if (layout[nextY] && layout[nextY][nextX] !== undefined) {
            if (layout[nextY][nextX] === "W") {
                direction = { x: -direction.y, y: direction.x };
            }
        }

        setTimeout(autoMovePacMan, 500);
    }

    function handleKeydown(event) {
        switch (event.key) {
            case "ArrowUp":
                direction = { x: 0, y: -1 };
                break;
            case "ArrowDown":
                direction = { x: 0, y: 1 };
                break;
            case "ArrowLeft":
                direction = { x: -1, y: 0 };
                break;
            case "ArrowRight":
                direction = { x: 1, y: 0 };
                break;
        }
    }

    createBoard();
    createPacMan();

    document.addEventListener("keydown", handleKeydown);
    autoMovePacMan();
});
    

Conclusion

This tutorial walked you through creating a simple Pac-Man game using HTML, CSS, and JavaScript. You learned how to set up the game board, style it, and implement the game logic for movement and scoring. Happy coding!

Comments

Popular posts from this blog

Creating an Interactive Tic Tac Toe Game

In this tutorial, we'll walk through the steps to create a dynamic Tic Tac Toe game using HTML, CSS, and JavaScript. This classic game is a great way to practice your web development skills and learn more about interactive web applications. HTML Structure We'll start with the HTML structure, which includes the game board, a reset button, and a status display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tic Tac Toe</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Tic Tac Toe</h1> <div id="board" class="board"></div> <button id="reset">Reset Game</button> <div id=...

Creating a Simple Car Racing Game with HTML, CSS, Javascript

In this post, we will create a simple car racing game using HTML, CSS, and JavaScript. This game will feature a player car, an opponent car, and a score counter. The player can move their car left and right to avoid collisions with the opponent car. Let's dive into the code! HTML Structure The HTML structure consists of a game area that contains the road, player car, opponent car, and score display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Car Racing Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="gameArea"> <div class="road"></div> <div class="playerCar"></div> <div class="opponentCar"></div...

Create Your Own Chrome Dino Game with HTML, CSS, and JavaScript

Have you ever wanted to create your own version of the Chrome Dino game? With just a few lines of HTML, CSS, and JavaScript, you can bring this iconic game to life. Here's a step-by-step guide to building a simple yet fun version of the Dino game. HTML Start by creating an HTML file to define the game structure. You'll need a container for the game, a <div> for the dinosaur, another <div> for the cactus, and a score display. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chrome Dino Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="game-container"> <div id="dino" class="dino"></div> <div id="cactus" class="cactus...