Building a Simple Puzzle Game with HTML5 Canvas and JavaScript

 Building a Simple Puzzle Game with HTML5 Canvas and JavaScript



Creating a game using HTML5 canvas can be a fun and challenging project for developers of all skill levels. The HTML5 canvas element provides a powerful way to create interactive and dynamic graphics for games and other web applications. In this blog post, we will go over the process of building a simple puzzle game using HTML5 canvas and JavaScript.


First, we'll need to set up the HTML structure for our game. Create a new HTML file and add a canvas element to the body of the page.



<body>

    <canvas id="gameCanvas"></canvas>

</body>

It is also a good practice to set the width and height of the canvas in the script, So that canvas adjusts to different screen sizes.


Next, we'll create a new JavaScript file to handle the logic of our game. We'll start by getting a reference to the canvas element and setting up some basic variables.



var canvas = document.getElementById("gameCanvas");

var ctx = canvas.getContext("2d");

var board = [];

var tileSize = 32;

var blankTile = {"x":3,"y":3};

Now that we have a reference to the canvas, we can use the 2D rendering context (ctx) to draw graphics on the canvas. We can use the fillRect method to draw a tile of the puzzle board on the canvas.



function drawTile(x, y, num) {

    ctx.fillStyle = "gray";

    ctx.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);

    ctx.fillStyle = "white";

    ctx.font = "20px Arial";

    ctx.fillText(num, x * tileSize + 10, y * tileSize + 25);

}

With the basic draw function in place, we can now create a function to draw the whole puzzle board on the canvas



function drawBoard() {

    for (var y = 0; y < 4; y++) {

        for (var x = 0; x < 4; x++) {

            drawTile(x, y, board[y][x]);

        }

    }

}

In order to make the puzzle interactive, we'll need to handle user input to allow the player to move the tiles around.

We can use the addEventListener method to listen for mouse clicks on the canvas and determine which tile the user clicked on.


Copy code

canvas.addEventListener("click", function(event) {

    var x = Math.floor(event.clientX / tileSize);

    var y = Math.floor(event.clientY / tileSize);

    moveTile(x, y);

});

Now we need to check whether the tile is adjacent to the blank tile and can be moved or not. And then update the position of blank tile and the clicked tile.



function moveTile(x, y) {

    if (isAdjacent(x, y, blankTile.x, blankTile.y)) {

        board[blankTile.y][blankTile.x] = board[y][x];

        board[y][x] = "";

        blankTile.x = x;

        blankTile.y = y;

        drawBoard();

    }

}

With all the above code


in place, we now have a basic puzzle game that allows the player to click on tiles and move them around the board. To make the game more interesting, you could add more features such as a shuffle button to scramble the puzzle, a timer to track how long it takes to solve the puzzle, or a way to reset the puzzle to its original configuration. You could also consider styling the game by adding CSS to give it a more polished look, like adding a background image, or changing the font style for the tile numbers.


To make this game more fun, you can add more functionality in the game like level difficulty, score calculation, better UI, animations, etc.


Here is an example of complete code for this puzzle game:



<!DOCTYPE html>

<html>

<head>

    <title>Puzzle Game</title>

    <style>

        canvas {

            border: 1px solid black;

        }

    </style>

</head>

<body>

    <canvas id="gameCanvas"></canvas>

    <script>

        var canvas = document.getElementById("gameCanvas");

        var ctx = canvas.getContext("2d");

        canvas.width = 128;

        canvas.height = 128;


        var board = [

            [1, 2, 3, 4],

            [5, 6, 7, 8],

            [9, 10, 11, 12],

            ["", 13, 14, 15]

        ];

        var tileSize = 32;

        var blankTile = {"x":3,"y":3};


        function drawTile(x, y, num) {

            ctx.fillStyle = "gray";

            ctx.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);

            ctx.fillStyle = "white";

            ctx.font = "20px Arial";

            ctx.fillText(num, x * tileSize + 10, y * tileSize + 25);

        }


        function drawBoard() {

            for (var y = 0; y < 4; y++) {

                for (var x = 0; x < 4; x++) {

                    drawTile(x, y, board[y][x]);

                }

            }

        }


        drawBoard();


        canvas.addEventListener("click", function(event) {

            var x = Math.floor(event.clientX / tileSize);

            var y = Math.floor(event.clientY / tileSize);

            moveTile(x, y);

        });


        function moveTile(x, y) {

            if (isAdjacent(x, y, blankTile.x, blankTile.y)) {

                board[blankTile.y][blankTile.x] = board[y][x];

                board[y][x] = "";

                blankTile.x = x;

                blankTile.y = y;

                drawBoard();

            }

        }


        function isAdjacent(x1, y1, x2, y2) {

            return (Math.abs(x1 - x2) + Math.abs(y1 - y2) === 1);

        }

    </script>

</body>

</html>

I hope this gives you a good starting point for building your own game using HTML5 canvas




No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...