How to create a snake game using html, CSS, JavaScript with free source code

Free complete code on how to create a JavaScript snake game using html, CSS for design, JavaScript for functionality. Get the full source code with the attached zipped source code for free.

How to create a snake game using html, CSS, JavaScript with free source code
Alpha code camp - snake game image screenshot

How to create a snake game using html, CSS, JavaScript with free source code

Table of content

  1. About the JavaScript snake game
  2. Features of the JavaScript snake game
  3. The script Files
  4. Step by step to create the JavaScript snake game
  5. How to run the zipped attached source code file
  6. Screenshots

About the JavaScript snake game

Learn how to create JavaScript snake game using html, css for design, javascript codes for its functionality. This game looks like the one mostly found in small phones, but with a slight difference. This project has more functionality than the older one. It is controlled using your computer keyboard. It includes a score board that shows score when game is over. This source code has a good comment structure; if you want to re-edit. The zipped file for this project will be added at the end of this article. You can download and edit.

Features of the JavaScript snake game

  • Easy code Documentation
  • Score board
  • Cursor pointer
  • Beautiful interface (both analog and digital)
  • Keyboard arrow navigation control
  • Game over if snake hits the wall or itself.
  • Responsive
  • Increases by eating food
  • Space button for pause

The Script Files         

  • HTML
  • CSS
  • JavaScript

Step by step to create the JavaScript snake game

  1. Create a folder and name it in your pc for storing the code files we will create.
  2. Open the code editor you are using (visual studio code, notepad++, etc).
  3. Create a file named index.html and save in the folder we created in first step.
  4. Copy the html code you will see below and paste into the index.html file.

    INDEX.HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Snake Game</title>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="script.js"></script>
    </head>
    <body onload="play_game()">
    <h1> Snake Game</h1>
    <div id="msg"></div>
    <canvas id="playArea" width="900" height="500">Your browser do not support HTML5</canvas>
    </body>
    </html>
    
  5. After you have paste the html code, save (ctrl + s) the code.
  6. Then create another CSS file named style.css and save in the same folder with the index file.
  7. Then paste the code you see below into it.

    STYLE.CSS

    h1 { 
        font-family: Arial, Helvetica, sans-serif; 
        text-align: center; 
    }
    body {
        text-align:center;
        font-family: Arial, Helvetica, sans-serif;
    }
    canvas { 
        border:none;
        box-shadow:1px 0px 10px #000032ce;
    }
    
  8. Then save it.
  9. Create a JavaScript file named Script.js. This JavaScript file gives the game its functionality.

    SCRIPT.JS

    function play_game()
    {
    var level = 130; // Game level, by decreasing will speed up
    var rect_w = 90; // Width
    var rect_h = 50; // Height
    var inc_score = 1; // Score
    var snake_color = "#000032"; // Snake Color
    var ctx; // Canvas attributes
    var tn = []; // temp directions storage
    var x_dir = [-1, 0, 1, 0]; // position adjusments
    var y_dir = [0, -1, 0, 1]; // position adjusments
    var queue = [];
    var frog = 1; // defalut food
    var map = [];
    var MR = Math.random;
    var X = 5 + (MR() * (rect_w - 10))|0; // Calculate positions
    var Y = 5 + (MR() * (rect_h - 10))|0; // Calculate positions
    var direction = MR() * 3 | 0;
    var interval = 0;
    var score = 0;
    var sum = 0, easy = 0;
    var i, dir;
    // getting play area 
    var c = document.getElementById('playArea');
    ctx = c.getContext('2d');
    // Map positions
    for (i = 0; i < rect_w; i++)
    {
    map[i] = [];
    }
    // random placement of snake food
    function rand_frog()
    {
    var x, y;
    do
    {
    x = MR() * rect_w|0;
    y = MR() * rect_h|0;
    }
    while (map[x][y]);
    map[x][y] = 1;
    ctx.fillStyle = snake_color;
    ctx.strokeRect(x * 10+1, y * 10+1, 8, 8);
    }
    // Default somewhere placement
    rand_frog();
    function set_game_speed()
    {
    if (easy)
    {
    X = (X+rect_w)%rect_w;
    Y = (Y+rect_h)%rect_h;
    }
    --inc_score;
    if (tn.length)
    {
    dir = tn.pop();
    if ((dir % 2) !== (direction % 2))
    {
    direction = dir;
    }
    }
    if ((easy || (0 <= X && 0 <= Y && X < rect_w && Y < rect_h)) && 2 !== map[X][Y])
    {
    if (1 === map[X][Y])
    {
    score+= Math.max(1, inc_score);
    inc_score = 1;
    rand_frog();
    frog++;
    }
    //ctx.fillStyle("#ffffff");
    ctx.fillRect(X * 10, Y * 10, 9, 9);
    map[X][Y] = 2;
    queue.unshift([X, Y]);
    X+= x_dir[direction];
    Y+= y_dir[direction];
    if (frog < queue.length)
    {
    dir = queue.pop()
    map[dir[0]][dir[1]] = 0;
    ctx.clearRect(dir[0] * 10, dir[1] * 10, 10, 10);
    }
    }
    else if (!tn.length)
    {
    var msg_score = document.getElementById("msg");
    msg_score.innerHTML = "<span style='font-size: 15pt'> GAME OVER <br /> Your Score </span><br /> <b style='font-size: 20pt'> "+score+"</b><br /><br /><input type='button' value='Play Again' onclick='window.location.reload();' style='background-color: #000032; color: white; font-size: 15pt; border: none; padding:15px; cursor: pointer;' />";
    document.getElementById("playArea").style.display = 'none';
    window.clearInterval(interval);
    }
    }
    interval = window.setInterval(set_game_speed, level);
    document.onkeydown = function(e) {
    var code = e.keyCode - 37;
    if (0 <= code && code < 4 && code !== tn[0])
    {
    tn.unshift(code);
    }
    else if (-5 == code)
    {
    if (interval)
    {
    window.clearInterval(interval);
    interval = 0;
    }
    else
    {
    interval = window.setInterval(set_game_speed, 60);
    }
    }
    else
    {
    dir = sum + code;
    if (dir == 44||dir==94||dir==126||dir==171) {
    sum+= code
    } else if (dir === 218) easy = 1;
    }
    }
    }
    
  10. Save the code.
  11. Run the code in your browser, you will see a screen like the one in the image screenshot below. (See below screenshot).

How to run the zipped attached source code file

  1. Go to the zipped attached files below.
  2. Click on the attached file for it to download.
  3. Go to your downloads folder in your system.
  4. Extract/unzip the file.
  5. Double click on the html file to view the output in your browser or
  6. You can open with your code/ text editor to make changes.

Screenshots

Image1

screenshot1

Image2

image screenshot

Files