How to Create a Candy Crush Game Using HTML, CSS and JavaScript (Free Source Codes)

Candy Crush Game Using HTML, CSS, and JavaScript (Free Source Code)

Candy crush game is widely known and played as one of the most effective puzzle games that attract many people. This article offers you with HTML, CSS and JavaScript source code to develop your copy of the Candy Crush Game for free.

This source code is useful for any JavaScript beginner since it applies good programming practices for best result and fastest learning.

GitHub Source: Candy Crush Game

Features

  • Interactive Gameplay: Each player can switch the candies in order to form the groups of three or more candies of the same type.
  • Dynamic Scoring System: The code also involves a scoring option that can change as the player pairs the candies.
  • Responsive Design: It has the responsiveness feature that allows it to run on mobile, tablet or any other computer device.
  • Smooth Animations: The candies shift and become invisible and have this wonderful way of shifting in and out through smooth animations.

Technologies Used

  • HTML (Hypertext Markup Language)
  • CSS (Cascading Style Sheets)
  • JS (JavaScript)

Recommended for You

Video Tutorial

HTML

Here is the HTML code for your index.html file:

<!DOCTYPE html>
<!-- 
====================================================
This code is developed by Shokat Javed at JV Codes
Website: www.jvcodes.com
====================================================
-->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>JVCodes.com - Candy Crush</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="scoreBoard">
      <h3>score</h3>
      <h1 id="score"></h1>
    </div>
    <div class="grid"></div>
    <script src="script.js" charset="utf-8" defer data-deferred="1"></script>
</body>
</html>

CSS

Here is the complete code for style.css file to style the Candy Crush Game:

/*
===================================================
This code is developed by Shokat Javed at JV Codes
Website: www.jvcodes.com
===================================================
*/
body {
  background-color: rgb(253, 253, 175);
  max-width: 100vh;
  display: flex;
  justify-content: center;
  align-items: center; 
  height: 100vh;
}

.grid {
  display: flex;
  flex-wrap: wrap;
  height: 560px;
  min-width: 560px;
  margin-left: 80px;
  margin-top: 50px;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 5px;
  color: #85796b;
  border-radius: 10px;
  box-shadow: 0 4px 4px rgba(0, 0, 0, 0.5) inset, 0 1px 0 #fff;
}

  .grid div {
    height: 70px;
    width: 70px;
  }
  
  h3 {
    font-family: "Montserrat", sans-serif;
    text-transform: uppercase;
  }
  
  h1 {
    font-family: "Montserrat", sans-serif;
    text-transform: uppercase;
    margin-top: -10px;
  }
     
  .scoreBoard {
    background-color: rgb(0, 20, 61, 0.9);
    border-radius: 10px;
    margin-top: 100px;
    margin-left: 500px;
    width: auto;
    height: 120px;
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    text-align: center;
    color: #ffffff;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5) inset, 0 1px 0 #fff;
  }

JavaScript

Here is the complete code for script.js file to function the Candy Crush Game:

/*
===================================================
This code is developed by Shokat Javed at JV Codes
Website: www.jvcodes.com
===================================================
*/
document.addEventListener("DOMContentLoaded", () => {
    candyCrushGame();
});

function candyCrushGame() {
    const grid = document.querySelector(".grid");
    const scoreDisplay = document.getElementById("score");
    const width = 8;
    const squares = [];
    let score = 0;

    const candyColors = [
        "url(https://raw.githubusercontent.com/arpit456jain/Amazing-Js-Projects/master/Candy%20Crush/utils/red-candy.png)",
        "url(https://raw.githubusercontent.com/arpit456jain/Amazing-Js-Projects/master/Candy%20Crush/utils/blue-candy.png)",
        "url(https://raw.githubusercontent.com/arpit456jain/Amazing-Js-Projects/master/Candy%20Crush/utils/green-candy.png)",
        "url(https://raw.githubusercontent.com/arpit456jain/Amazing-Js-Projects/master/Candy%20Crush/utils/yellow-candy.png)",
        "url(https://raw.githubusercontent.com/arpit456jain/Amazing-Js-Projects/master/Candy%20Crush/utils/orange-candy.png)",
        "url(https://raw.githubusercontent.com/arpit456jain/Amazing-Js-Projects/master/Candy%20Crush/utils/purple-candy.png)",
    ];

    // Creating Game Board
    function createBoard() {
        for (let i = 0; i < width * width; i++) {
            const square = document.createElement("div");
            square.setAttribute("draggable", true);
            square.setAttribute("id", i);
            let randomColor = Math.floor(Math.random() * candyColors.length);
            square.style.backgroundImage = candyColors[randomColor];
            grid.appendChild(square);
            squares.push(square);
        }
    }
    createBoard();
    
    // Dragging the Candy
    let colorBeingDragged;
    let colorBeingReplaced;
    let squareIdBeingDragged;
    let squareIdBeingReplaced;

    squares.forEach((square) =>
        square.addEventListener("dragstart", dragStart)
    );
    squares.forEach((square) => square.addEventListener("dragend", dragEnd));
    squares.forEach((square) => square.addEventListener("dragover", dragOver));
    squares.forEach((square) =>
        square.addEventListener("dragenter", dragEnter)
    );
    squares.forEach((square) =>
        square.addEventListener("drageleave", dragLeave)
    );
    squares.forEach((square) => square.addEventListener("drop", dragDrop));

    function dragStart() {
        colorBeingDragged = this.style.backgroundImage;
        squareIdBeingDragged = parseInt(this.id);
        // this.style.backgroundImage = ''
    }

    function dragOver(e) {
        e.preventDefault();
    }

    function dragEnter(e) {
        e.preventDefault();
    }

    function dragLeave() {
        this.style.backgroundImage = "";
    }

    function dragDrop() {
        colorBeingReplaced = this.style.backgroundImage;
        squareIdBeingReplaced = parseInt(this.id);
        this.style.backgroundImage = colorBeingDragged;
        squares[
            squareIdBeingDragged
        ].style.backgroundImage = colorBeingReplaced;
    }

    function dragEnd() {
        //Defining, What is a valid move?
        let validMoves = [
            squareIdBeingDragged - 1,
            squareIdBeingDragged - width,
            squareIdBeingDragged + 1,
            squareIdBeingDragged + width
        ];
        let validMove = validMoves.includes(squareIdBeingReplaced);

        if (squareIdBeingReplaced && validMove) {
            squareIdBeingReplaced = null;
        } else if (squareIdBeingReplaced && !validMove) {
            squares[
                squareIdBeingReplaced
            ].style.backgroundImage = colorBeingReplaced;
            squares[
                squareIdBeingDragged
            ].style.backgroundImage = colorBeingDragged;
        } else
            squares[
                squareIdBeingDragged
            ].style.backgroundImage = colorBeingDragged;
    }
    
    //Dropping candies once some have been cleared
    function moveIntoSquareBelow() {
        for (i = 0; i < 55; i++) {
            if (squares[i + width].style.backgroundImage === "") {
                squares[i + width].style.backgroundImage =
                    squares[i].style.backgroundImage;
                squares[i].style.backgroundImage = "";
                const firstRow = [0, 1, 2, 3, 4, 5, 6, 7];
                const isFirstRow = firstRow.includes(i);
                if (isFirstRow && squares[i].style.backgroundImage === "") {
                    let randomColor = Math.floor(
                        Math.random() * candyColors.length
                    );
                    squares[i].style.backgroundImage = candyColors[randomColor];
                }
            }
        }
    }

    ///-> Checking for Matches <-///

    //For Row of Four
    function checkRowForFour() {
        for (i = 0; i < 60; i++) {
            let rowOfFour = [i, i + 1, i + 2, i + 3];
            let decidedColor = squares[i].style.backgroundImage;
            const isBlank = squares[i].style.backgroundImage === "";

            const notValid = [
                5,
                6,
                7,
                13,
                14,
                15,
                21,
                22,
                23,
                29,
                30,
                31,
                37,
                38,
                39,
                45,
                46,
                47,
                53,
                54,
                55
            ];
            if (notValid.includes(i)) continue;

            if (
                rowOfFour.every(
                    (index) =>
                        squares[index].style.backgroundImage === decidedColor &&
                        !isBlank
                )
            ) {
                score += 4;
                scoreDisplay.innerHTML = score;
                rowOfFour.forEach((index) => {
                    squares[index].style.backgroundImage = "";
                });
            }
        }
    }
    checkRowForFour();
    
    //For Column of Four
    function checkColumnForFour() {
        for (i = 0; i < 39; i++) {
            let columnOfFour = [i, i + width, i + width * 2, i + width * 3];
            let decidedColor = squares[i].style.backgroundImage;
            const isBlank = squares[i].style.backgroundImage === "";

            if (
                columnOfFour.every(
                    (index) =>
                        squares[index].style.backgroundImage === decidedColor &&
                        !isBlank
                )
            ) {
                score += 4;
                scoreDisplay.innerHTML = score;
                columnOfFour.forEach((index) => {
                    squares[index].style.backgroundImage = "";
                });
            }
        }
    }
    checkColumnForFour();

    //For Row of Three
    function checkRowForThree() {
        for (i = 0; i < 61; i++) {
            let rowOfThree = [i, i + 1, i + 2];
            let decidedColor = squares[i].style.backgroundImage;
            const isBlank = squares[i].style.backgroundImage === "";

            const notValid = [
                6,
                7,
                14,
                15,
                22,
                23,
                30,
                31,
                38,
                39,
                46,
                47,
                54,
                55
            ];
            if (notValid.includes(i)) continue;

            if (
                rowOfThree.every(
                    (index) =>
                        squares[index].style.backgroundImage === decidedColor &&
                        !isBlank
                )
            ) {
                score += 3;
                scoreDisplay.innerHTML = score;
                rowOfThree.forEach((index) => {
                    squares[index].style.backgroundImage = "";
                });
            }
        }
    }
    checkRowForThree();
    
    //For Column of Three
    function checkColumnForThree() {
        for (i = 0; i < 47; i++) {
            let columnOfThree = [i, i + width, i + width * 2];
            let decidedColor = squares[i].style.backgroundImage;
            const isBlank = squares[i].style.backgroundImage === "";

            if (
                columnOfThree.every(
                    (index) =>
                        squares[index].style.backgroundImage === decidedColor &&
                        !isBlank
                )
            ) {
                score += 3;
                scoreDisplay.innerHTML = score;
                columnOfThree.forEach((index) => {
                    squares[index].style.backgroundImage = "";
                });
            }
        }
    }
    checkColumnForThree();

    window.setInterval(function () {
        checkRowForFour();
        checkColumnForFour();
        checkRowForThree();
        checkColumnForThree();
        moveIntoSquareBelow();
    }, 100);
}

Download Source Code

From the button below, you can download the source codes of the candy crush game free without being restricted by any copyright. This code can be used and changed when needed for individual or educational use.

Conclusion

You are free to use this source code of the Candy Crush Game on your websites in order to attract the users and add some spice into your projects. Remember to acknowledge the JV Source Codes by using this page as a reference.

If you met any problem or need assistance, please do not hesitate to write a comment. I would be glad to assist you and make your learning perfectly fine. Check out my other projects and content and don’t forget to hit the subscribe button for more amazing designs.

Download JV Source Codes

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *