• Home
  • Games
    Epic Games

    Epic Games Activate

    Mog Station

    Mog Station

    Riot MMO

    What Is Riot MMO?

    Chessboard

    How To Set Up A Chessboard

    Flimsy Mask

    Flimsy Mask Wotlk

    WOW

    What Is Wowhead?

    Starter Pokemon

    Starter Pokemon

  • Reviews
    Game Developer

    Why Game Developers Love Using Game Testing Services

  • News
    GTA-6

    Why Fans Believe GTA 6 Is Close To Launch

    Gamestop

    What is Gamestop? 

    Bandai Namco Aces

    Bandai Namco Aces is created by Bandai Namco and Ace Combat 8 Developer

    Halo 4

    Halo 4 PC review – John woke up

    Razor Build Guide

    Razor Build Guide For Genshin Impact

    Essential

    PlayStation Plus Essential vs. Extra vs. Premium: Which Should You Choose?

    Trending Tags

    • Top List
    • Adventure
    • eSport
    • Open World
    • Strategy
    • Sport
    • Console
    • Action
    • RPG
    • Racing
  • PS4
    PS5

    What Is PS5?

    PS4

    What is ps4?

    PlayStation

    Top 10 PlayStation news and reviews websites

    VR2

    Everything we know about PS VR2 so far

  • Xbox One
  • Tech
  • Sport
    • Football
    • Cricket
    • Wrestling
    • Golf
  • Home
  • Games
    Epic Games

    Epic Games Activate

    Mog Station

    Mog Station

    Riot MMO

    What Is Riot MMO?

    Chessboard

    How To Set Up A Chessboard

    Flimsy Mask

    Flimsy Mask Wotlk

    WOW

    What Is Wowhead?

    Starter Pokemon

    Starter Pokemon

  • Reviews
    Game Developer

    Why Game Developers Love Using Game Testing Services

  • News
    GTA-6

    Why Fans Believe GTA 6 Is Close To Launch

    Gamestop

    What is Gamestop? 

    Bandai Namco Aces

    Bandai Namco Aces is created by Bandai Namco and Ace Combat 8 Developer

    Halo 4

    Halo 4 PC review – John woke up

    Razor Build Guide

    Razor Build Guide For Genshin Impact

    Essential

    PlayStation Plus Essential vs. Extra vs. Premium: Which Should You Choose?

    Trending Tags

    • Top List
    • Adventure
    • eSport
    • Open World
    • Strategy
    • Sport
    • Console
    • Action
    • RPG
    • Racing
  • PS4
    PS5

    What Is PS5?

    PS4

    What is ps4?

    PlayStation

    Top 10 PlayStation news and reviews websites

    VR2

    Everything we know about PS VR2 so far

  • Xbox One
  • Tech
  • Sport
    • Football
    • Cricket
    • Wrestling
    • Golf
No Result
View All Result
No Result
View All Result
Home Games

How to Make a Snake Game Using HTML, CSS, and JavaScript

gameistic by gameistic
February 9, 2023
in Games
0 0
0
Snake Game
0
SHARES
29
VIEWS
Share on FacebookShare on Twitter

Recreate this old-school game in your browser and learn about JavaScript game dev along the way.

A snake game is a classic programming exercise you can use to improve your programming and problem-solving skills. You can create the game in a web browser using HTML, CSS, and JavaScript.

In the game, you control a snake that moves around a board. The snake grows in size as you collect food. The game will end if you collide with your own tailor on any of the walls.

Table of Contents

  • How to Create the UI for the Canvas
    • How to Draw the Snake
    • function drawSnake () {
    • How to Make the Snake Move
    • How to Add Food Onto the Canvas
    • How to Make the Snake Grow
    • How to End the Game
    • Learning JavaScript Concepts Through Games

How to Create the UI for the Canvas

Use HTML and CSS to add the canvas for the snake to move around on. There are many other HTML and CSS projects you can practice if you need to revise any basic concepts.

You can refer to this project’s GitHub repository for the full source code.

  1. Create a new file called “index.html”.
  2. Open the file using any text editor such as Visual Code or Atom. Add the basic HTML code structure:

<!doctype html>

<html lang=“en-US”>

  <head>

    <title>Snake Game</title>

  </head>

  <body>

  </body>

</html>

Inside the body tag, add a canvas to represent the game board for the snake.

<h2>Snake Game</h2>

<div id=“game”>

  <canvas id=“snake”></canvas>

</div>

In the same folder as your HTML file, create a new file called “styles.css”.

Inside, add some CSS for the overall web page. You can also style your website using other essential CSS tips and tricks.

#game {

  width:400px;

  height:400px;

  margin:0 auto;

  background-color:#eee;

}

h2 {

  text-align:center;

  font-family:Arial;

  font-size:36px;

} 

Inside your HTML file, add a link to the CSS in the head tag:

<link rel=“stylesheet” type=“text/css” href=“styles.css”>

To view the canvas, open your “index.html” file in a web browser.

How to Draw the Snake

In the example below, the black line represents the snake:

Multiple squares or “segments” make up the snake. As the snake grows, the number of squares also increases. At the beginning of the game, the snake’s length is one piece.

  1. Inside your HTML file, link to a new JavaScript file at the bottom of the body tag:

<body>

  <!– Your code here –>

  <script src=“script.js”></script>

</body>

Create script.js and start by getting the DOM element of the canvas:

var canvas = document.getElementById(“snake”)

Set the context for the canvas HTML element. In this case, you want the game to render a 2d canvas. This will allow you to draw multiple shapes or images onto the HTML element.

var canvas2d = canvas.getContext(“2d”);

Set other in-game variables such as whether the game has ended, and the height and width of the canvas:

var game ended = false;

canvas.width = 400;

canvas.height = 400;

Declare a variable called “snakeSegments”. This will hold the number of “squares” that the snake will take up. You can also create a variable to keep track of the snake’s length:

var snakeSegments = [];

var snake length = 1;

Declare the initial X and Y position of the snake:

var snakeX = 0;

var snakeY = 0;

Create a new function. Inside, add the starting snake piece to the snake segments array, with its starting X and Y coordinates:

function moveSnake() {

  snakeSegments.unshift({ x: snakeX, y: snakeY });
}

Create a new function. Inside, set the fill style to black. This is the color it will use to draw the snake:

function drawSnake () {

  canvas2d.fillStyle = “black”;
}

For every segment that makes up the snake’s size, draw a square with a width and height of 10 pixels:

  1.  for (var i = 0; i < snakeSegments.length; i++) {
  2.     canvas2d.fillRect(snakeSegments[i].x, snakeSegments[i].y, 10, 10);
      }
  3. Create a game loop that will run every 100 milliseconds. This will cause the game to constantly draw the snake in its new position, which will be very important when the snake starts moving:
  4. function gameLoop() {
  5.   moveSnake();
     drawSnake();
  6. Open the “index.html” file in a web browser to see the snake at the smallest size in its starting position.

How to Make the Snake Move

Add some logic to move the snake in different directions, depending on what button the player presses on the keyboard.

At the top of the file, declare the initial direction of the snake:

var direction X = 10;

var direction Y = 0;

Add an event handler that fires when the player presses a key:

document.onkey down = function(event) {

};

Inside the event handler, change the direction that the snake is moving, based on the pressed key:

switch (event.keyCode) {

  case 37: // Left arrow
    direction X = -10;
    direction Y = 0;
    break;
  case 38: // Up arrow
    direction X = 0;
    direction Y = -10;
    break;
  case 39: // Right arrow
    direction X = 10;
    direction Y = 0;
    break;
  case 40: // Down arrow
    direction X = 0;
    direction Y = 10;
    break;
}

In the moveSnake() function, use the direction to update the X and Y coordinates of the snake. For example, if the snake needs to move left, the X direction will be “-10”. This will update the X coordinate to remove 10 pixels for every frame of the game:

function move Snake() {

  snakeSegments.unshift({ x: snake X, y: snakeY });
  snake X += direction X;
  snakeY += direction Y;
}

The game currently does not remove previous segments while the snake is moving. This will make the snake look like this:

To fix this, clear the canvas before drawing the new snake in each frame, at the beginning of the drawSnake() function:

canvas2d.clearRect(0, 0, canvas.width, canvas.height);

You will also need to remove the last element of the snakeSegments array, inside the moveSnake() function:

while (snakeSegments.length > snake length) {

  snakeSegments.pop();
}

Open the “index.html” file and press the left, right, up, or down keys to move the snake.

How to Add Food Onto the Canvas

Add dots to the board game to represent food pieces for the snake.

Declare a new variable at the top of the file to store an array of food pieces:

var dots = [];

Create a new function. Inside, generate random X and Y coordinates for the dots. You can also ensure that only 10 dots are on the board at any time:

function spawnDots() {

  if(dots.length < 10) {
    var dotX = Math.floor(Math.random() * canvas.width);
    var dotY = Math.floor(Math.random() * canvas.height);
    dots.push({ x: dotX, y: dotY });
  }
}

After generating the X and Y coordinates for the food, draw them onto the canvas using a red color:

for (var i = 0; i < dots.length; i++) {

  canvas2d.fillStyle = “red”;
  canvas2d.fillRect(dots[i].x, dots[i].y, 10, 10);
}

Call the new spawnDots() function inside the game loop:

function gameLoop() {

  moveSnake();
  drawSnake();
  spawnDots();
  if(!gameEnded) {
    setTimeout(gameLoop, 100);
  }
}

Open the “index.html” file to view the food on the game board.

How to Make the Snake Grow

You can make the snake grow by incrementing its length when it collides with a food dot.

Create a new function. Inside it, loop through every element in the dots array:

function check collision() {

  for (var i = 0; i < dots.length; i++) {
        
  }
}

If the snake’s position matches the coordinates of any dots, increment the snake’s length, and delete the dot:

if (snakeX < dots[i].x + 10 &&

  snakeX + 10 > dots[i].x &&
  snakeY < dots[i].y + 10 &&
  snakeY + 10 > dots[i].y) {
    snakeLength++;
    dots.splice(i, 1);
}

Call the new check collision() function in the game loop:

function gameLoop() {

  moveSnake();
  drawSnake();
  spawnDots();
  check collision();
  if(!gameEnded) {
    setTimeout(game loop, 100);
  }
}

Open the “index.html” file in a web browser. Move the snake using the keyboard to collect the food pieces and grow the snake.

How to End the Game

To end the game, check if the snake collided with its own tail or any of the walls.

Create a new function to print a “Game Over” alert.

function game over() {

  setTimeout(function() {
    alert(“Game over!”);
  }, 500);
  game ended = true
}

Inside the check collision () function, check if the snake hit any of the canvas walls. If so, call the game over() function:

if (snake X < -10 ||

  snakeY < -10 ||
  snake X > canvas.width+10 ||
  snakeY > canvas.height+10) {
    game over();
}

To check if the head of the snake collided with any of the tail segments, loop through each piece of the snake:

for (var i = 1; i < snakeSegments.length; i++) {

}

Inside the for-loop, check if the location of the snake’s head matches any of the tail segments. If so, this means the head collided with a tail, so end the game:

if (snake X === snakeSegments[i].x && snakeY === snakeSegments[i].y) {

  game over();
}

Open the “index.html” file in a web browser. Try to hit a wall or your own tail to end the game.

Learning JavaScript Concepts Through Games

Creating games can be a great way to make your learning experience more enjoyable. Keep making more games to continue improving your JavaScript knowledge.

Tags: Snake Game
Previous Post

What is Wordle?

Next Post

Roblox Games

gameistic

gameistic

Next Post
Roblox Games

Roblox Games

Leave a Reply Cancel reply

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

  • Trending
  • Comments
  • Latest
Grinding down a gamers guide

Grinding down a gamers guide to nothing

October 28, 2022
2022 FIFA World Cup

2022 FIFA World Cup: Things you should know

August 6, 2022
Game Developer

Why Game Developers Love Using Game Testing Services

August 6, 2022
Tennis

A tennis net and a pickleball net are of the same height

August 4, 2022
Epic Games

Epic Games Activate

0
Tennis

A tennis net and a pickleball net are of the same height

0
best golf tips for beginners

The best golf tips for beginners

0
Game Developer

Why Game Developers Love Using Game Testing Services

0
Epic Games

Epic Games Activate

March 15, 2023
Mog Station

Mog Station

March 11, 2023
Riot MMO

What Is Riot MMO?

March 10, 2023
Chessboard

How To Set Up A Chessboard

March 9, 2023

Recommended

Epic Games

Epic Games Activate

March 15, 2023
Mog Station

Mog Station

March 11, 2023
Riot MMO

What Is Riot MMO?

March 10, 2023
Chessboard

How To Set Up A Chessboard

March 9, 2023

About Us

Gameistic is a website devoted to all things gaming. We love gaming and everything about it, from discussing the newest releases to playing the latest games. We want to share our passion for gaming with everyone and provide them with information, reviews, and insights.
Read more

Categories

  • Games
  • PC Gaming
  • PS4
  • Reviews
  • Sport

Tags

2022 FIFA Andrea Rene video game lover Bandai Namco Aces Basketball Shooting Game Casual Games Chessboard Chess Game Destructoid Dwarf Fortress dying light 2 Epic Games account Flimsy Mask Wotlk free pc games Game-clinching shots Game Developers GameStop Golf GTA 6 Halo 4 HD camera ICC Men's T20 World Cup Mog Station NFL Nintendo Pacman 30th Anniversary PlayStation Plus PS4 PS4 controllers PS4 games PS4 Pro PS5 PS VR2 Quest 2 Riot MMO Roblox Games Snake Game starter Pokemon Steam Tennis Unity Webgl Plane Games Vampire Survivors winter Cycling Jackets Wordle Wordle today Wowhead
  • Contact
  • About Us
  • Privacy & Policy

© 2022 Gameistic - All Rights Reserved.

No Result
View All Result
  • Home
  • Games
  • Reviews
  • News
  • PS4
  • Xbox One
  • Tech
  • Sport
    • Football
    • Cricket
    • Wrestling
    • Golf

© 2022 Gameistic - All Rights Reserved.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In