Snake Game Using HTML, CSS and JavaScript (source code)

Intro:

Welcome to our new blog post on how to create the classic Snake Game using HTML, CSS, and JavaScript. This game is a perfect example of how you can use these three technologies together to create a fun and interactive experience for players.

Whether you’re a beginner looking to learn more about web development or an experienced programmer looking for a new project, this post will provide you with the necessary tools and knowledge to build your own version of the Snake game.

In this post, we will walk you through the process of building the game, step by step. We’ll start by creating the game’s structure and layout using HTML, then move on to styling and design using CSS.

Finally, we’ll implement the game logic and functionality using JavaScript. By the end of the post, you’ll have a fully functional Snake game that you can customize and build upon for your own use.

So, get ready to put your coding skills to the test, and let’s get started on building the Snake game using HTML, CSS, and JavaScript!

Recently I created an Age Calculator Using Javascript Please check this.

What is Snake Game?

Snake Game using HTML CSS Javascript with Source Code

The Snake game is a classic and popular game in which players control a snake that moves around a screen, eating food while avoiding obstacles. The objective of the game is to score as many points as possible before the snake crashes into the walls or its own tail.

The game is usually played on a square or rectangular grid, where the snake must move in one of four directions (up, down, left, or right) to eat food and grow in size. As the snake grows, it becomes more difficult to avoid obstacles and the player must be more strategic in their movements.

The game can be found on various platforms and devices like Mobile games, Computer games, or even some Calculators.

How to Create a snake game using HTML CSS and JavaScript

How to Create a snake game using HTML CSS and JavaScript

There are lots of methods to create a Snake game using HTML, CSS, and JavaScript. I think this is the best project for beginners while learning web development technologies. Here are the general steps you can follow to create your own Snake game:

  1. Start by creating the game’s structure and layout using HTML. You can use div elements to create the game board and use CSS to position and style the elements.
  2. Use CSS to design and style the game. You can create different CSS classes for the snake, food, and obstacles, and use CSS properties such as color, size, and position to make them look the way you want.
  3. Implement the game logic and functionality using JavaScript. You can create a JavaScript function to move the snake based on user input, and use JavaScript to check for collisions with the walls or the snake’s tail.
  4. Use JavaScript to randomly generate the food for the snake to eat, and keep track of the score.
  5. Create a game overstate, and reset the game when it’s over.
  6. Finally, test your game and make any necessary adjustments.

Note:  It’s a high-level explanation of creating the game, this project might include more complex elements and features, like collision detection, game over state, and scoring system, and also it will require a deep understanding of the languages and technologies involved.

Source Code of Snake Game Using HTML CSS and JavaScript:

You know I also provide a complete source code for my all projects so here is the complete source code of this Snake Game Using HTML, CSS, and Javascript. Just Copy the given code and paste it into your files then your game is ready to play.😀

HTML File

First Create an HTML file with a (.html) extension and copy the given code and paste in an HTML file.

<!DOCTYPE html>
<html>
    <!-- Created By Coding Pakistan -->
<head>
    <meta charset="UTF-8">
    <meta name="viewport",
        content="width=device-width, initial-scale=1.0">
    <title>Snake Game - Codingpakistan.com </title>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
</head>
<body>
    <h1>Snake Game with
        <div class="geeks">Codingpakistan.com</div>
    </h1>
    <canvas id="board"></canvas>
</body>
</html>

CSS File

Second Create a CSS file with a (.css) extension and copy the given code and paste it into a CSS file.

/* Created by Coding Pakistan */
body {
    text-align: center;
}
.geeks {
    font-size: 40px;
    font-weight: bold;
    color: rgb(132, 20, 207);
}

JavaScript File

var blockSize = 25;
var total_row = 17; //total row number
var total_col = 17; //total column number
var board;
var context;
var snakeX = blockSize * 5;
var snakeY = blockSize * 5;
// Set the total number of rows and columns
var speedX = 0; //speed of snake in x coordinate.
var speedY = 0; //speed of snake in Y coordinate.
var snakeBody = [];
var foodX;
var foodY;
var gameOver = false;
window.onload = function () {
    // Set board height and width
    board = document.getElementById("board");
    board.height = total_row * blockSize;
    board.width = total_col * blockSize;
    context = board.getContext("2d");
    placeFood();
    document.addEventListener("keyup", changeDirection); //for movements
    // Set snake speed
    setInterval(update, 1000 / 10);
}
function update() {
    if (gameOver) {
        return;
    }
    // Background of a Game
    context.fillStyle = "green";
    context.fillRect(0, 0, board.width, board.height);
    // Set food color and position
    context.fillStyle = "yellow";
    context.fillRect(foodX, foodY, blockSize, blockSize);
    if (snakeX == foodX && snakeY == foodY) {
        snakeBody.push([foodX, foodY]);
       placeFood();
    }
    // body of snake will grow
    for (let i = snakeBody.length - 1; i > 0; i--) {
        // it will store previous part of snake to the current part
        snakeBody[i] = snakeBody[i - 1];
    }
    if (snakeBody.length) {
        snakeBody[0] = [snakeX, snakeY];
    }
    context.fillStyle = "white";
    snakeX += speedX * blockSize; //updating Snake position in X cordinate.
    snakeY += speedY * blockSize; //updating Snake position in Y cordinate.
    context.fillRect(snakeX, snakeY, blockSize, blockSize);
    for (let i = 0; i < snakeBody.length; i++) {
        context.fillRect(snakeBody[i][0], snakeBody[i][1], blockSize, blockSize);
    }
    if (snakeX < 0
        || snakeX > total_col * blockSize
        || snakeY < 0
        || snakeY > total_row * blockSize) { 
       // Out of bound condition
        gameOver = true;
        alert("Game Over");
    }
    for (let i = 0; i < snakeBody.length; i++) {
        if (snakeX == snakeBody[i][0] && snakeY == snakeBody[i][1]) {          
            // Snake eats own body
            gameOver = true;
            alert("Game Over");
        }
    }
}
// Movement of the Snake - We are using addEventListener
function changeDirection(e) {
    if (e.code == "ArrowUp" && speedY != 1) {
        // If up arrow key pressed with this condition...
        // snake will not move in the opposite direction
        speedX = 0;
        speedY = -1;
    }
    else if (e.code == "ArrowDown" && speedY != -1) {
        //If down arrow key pressed
        speedX = 0;
        speedY = 1;
    }
    else if (e.code == "ArrowLeft" && speedX != 1) {
        //If left arrow key pressed
        speedX = -1;
        speedY = 0;
    }
    else if (e.code == "ArrowRight" && speedX != -1) {
        //If Right arrow key pressed
        speedX = 1;
        speedY = 0;
    }
}
// Randomly place food
function placeFood() {
    // in x cordinates.
    foodX = Math.floor(Math.random() * total_col) * blockSize; 
    //in y cordinates.
    foodY = Math.floor(Math.random() * total_row) * blockSize;
}

You Might Like This

Download Source Code

If your Snake Game code does not work correctly any technical problem so please download the code files and extract them and use them accordingly to your requirements.

Snake Game Using HTML, CSS and JavaScript (source code)

Conclusion:

In conclusion, building a Snake game using HTML, CSS, and JavaScript is a great way to learn web development and gain experience with these technologies. We’ve walked you through the process of creating the game’s structure and layout with HTML, styling, and design with CSS, and implementing the game logic and functionality with JavaScript.

With the knowledge you’ve gained from this tutorial, you should now have a solid foundation to build upon and customize your own version of the Snake game.

We hope you had fun following along with this tutorial and that you’re excited to continue learning more about web development. Remember that creating a game like this is a fun way to learn and it will give you a sense of accomplishment, but also it could be a great addition to your portfolio.

Thanks for reading and happy coding!

Leave a Comment