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

Trending 10 months ago

Recreate this old-school crippled successful your browser and study astir JavaScript crippled dev on nan way.

Person holding a Game Boy

A snake crippled is simply a classical programming workout you tin usage to amended your programming and problem-solving skills. You tin create nan crippled successful a web browser utilizing HTML, CSS, and JavaScript.

In nan game, you power a snake that moves astir a board. The snake grows successful size arsenic you cod food. The crippled will extremity if you collide pinch your ain tail aliases immoderate of nan walls.

How to Create nan UI for nan Canvas

Use HTML and CSS to adhd nan canvas for nan snake to move astir on. There are galore different HTML and CSS projects you tin believe on, if you request to revise immoderate basal concepts.

You tin mention to this project’s GitHub repository for nan afloat root code.

  1. Create a caller record called "index.html".
  2. Open nan record utilizing immoderate matter editor specified arsenic Visual Code aliases Atom. Add nan basal HTML codification structure: <!doctype html>
    <html lang="en-US">
        <title>Snake Game</title>


  3. Inside nan assemblage tag, adhd a canvas to correspond nan crippled committee for nan snake. <h2>Snake Game</h2>
    <div id="game">
      <canvas id="snake"></canvas>
  4. In nan aforesaid files arsenic your HTML file, create a caller record called "styles.css".
  5. Inside, adhd immoderate CSS for nan wide web page. You tin besides style your website utilizing different essential CSS tips and tricks. #game {
      margin:0 auto;
    h2 {
  6. Inside your HTML file, adhd a nexus to nan CSS successful nan caput tag: <link rel="stylesheet" type="text/css" href="styles.css">
  7. To position nan canvas, unfastened your "index.html" record successful a web browser.
    Snake crippled pinch quiet canvas

How to Draw nan Snake

In nan illustration below, nan achromatic statement represents nan snake:

Snake crippled pinch snake example

Multiple squares aliases "segments" dress up nan snake. As nan snake grows, nan number of squares besides increases. At nan opening of nan game, nan snake’s magnitude is 1 piece.

  1. Inside your HTML file, nexus to a caller JavaScript record astatine nan bottommost of nan assemblage tag: <body>
      <script src="script.js"></script>
  2. Create script.js and commencement by getting nan DOM constituent of nan canvas: var canvas = document.getElementById("snake");
  3. Set nan discourse for nan canvas HTML element. In this case, you want nan crippled to render a 2d canvas. This will let you to tie aggregate shapes aliases images onto nan HTML element. var canvas2d = canvas.getContext("2d");
  4. Set different in-game variables specified arsenic whether nan crippled has ended, and nan tallness and width of nan canvas: var gameEnded = false;
    canvas.width = 400;
    canvas.height = 400;
  5. Declare a adaptable called "snakeSegments". This will clasp nan number of "squares" that nan snake will return up. You tin besides create a adaptable to support way of nan snake's length: var snakeSegments = [];
    var snakeLength = 1;
  6. Declare nan first X and Y position of nan snake: var snakeX = 0;
    var snakeY = 0;
  7. Create a caller function. Inside, adhd nan starting snake portion to nan snakeSegments array, pinch its starting X and Y coordinates: function moveSnake() {
      snakeSegments.unshift({ x: snakeX, y: snakeY });
  8. Create a caller function. Inside, group nan capable style to black. This is nan colour it will usage to tie nan snake: function drawSnake() {
      canvas2d.fillStyle = "black";
  9. For each conception that makes up nan snake's size, tie a quadrate pinch a width and tallness of 10 pixels:   for (var one = 0; one < snakeSegments.length; i++) {
        canvas2d.fillRect(snakeSegments[i].x, snakeSegments[i].y, 10, 10);
  10. Create a crippled loop that will tally each 100 milliseconds. This will origin nan crippled to perpetually tie nan snake successful its caller position, which will beryllium very important erstwhile nan snake starts moving: function gameLoop() {
  11. Open nan "index.html" record successful a web browser to spot nan snake astatine its smallest size successful its starting position.
    Snake crippled pinch snake successful starting position

How to Make nan Snake Move

Add immoderate logic to move nan snake successful different directions, depending connected what fastener nan subordinate presses connected nan keyboard.

  1. At nan apical of nan file, state nan first guidance of nan snake: var directionX = 10;
    var directionY = 0;
  2. Add an arena handler that fires erstwhile nan subordinate presses a key: document.onkeydown = function(event) {


  3. Inside nan arena handler, alteration nan guidance that nan snake is moving, based connected nan pressed key: switch (event.keyCode) {
      case 37:
        directionX = -10;
        directionY = 0;
      case 38:
        directionX = 0;
        directionY = -10;
      case 39:
        directionX = 10;
        directionY = 0;
      case 40:
        directionX = 0;
        directionY = 10;
  4. In nan moveSnake() function, usage nan guidance to update nan X and Y coordinates of nan snake. For example, if nan snake needs to move left, nan X guidance will beryllium "-10". This will update nan X coordinate to region 10 pixels for each framework of nan game: function moveSnake() {
      snakeSegments.unshift({ x: snakeX, y: snakeY });
      snakeX += directionX;
      snakeY += directionY;
  5. The crippled presently does not region erstwhile segments while nan snake is moving. This will make nan snake look for illustration this:
  6. Snake illustration without deleting segments
    To hole this, clear nan canvas earlier drafting nan caller snake successful each frame, astatine nan opening of nan drawSnake() function: canvas2d.clearRect(0, 0, canvas.width, canvas.height);
  7. You will besides request to region nan past constituent of nan snakeSegments array, wrong nan moveSnake() function: while (snakeSegments.length > snakeLength) {
  8. Open nan "index.html" record and property nan left, right, up, aliases down keys to move nan snake.
    Single snake portion moving astir board

How to Add Food Onto nan Canvas

Add dots to nan committee crippled to correspond nutrient pieces for nan snake.

  1. Declare a caller adaptable astatine nan apical of nan record to shop an array of nutrient pieces: var dots = [];
  2. Create a caller function. Inside, make random X and Y coordinates for nan dots. You tin besides guarantee that only 10 dots are connected nan committee astatine immoderate 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 });
  3. After generating nan X and Y coordinates for nan food, tie them onto nan canvas utilizing a reddish color: for (var one = 0; one < dots.length; i++) {
      canvas2d.fillStyle = "red";
      canvas2d.fillRect(dots[i].x, dots[i].y, 10, 10);
  4. Call nan caller spawnDots() usability wrong nan crippled loop: function gameLoop() {
      if(!gameEnded) {
        setTimeout(gameLoop, 100);
  5. Open nan "index.html" record to position nan nutrient connected nan crippled board.
    Snake crippled pinch nutrient pieces connected board

How to Make nan Snake Grow

You tin make nan snake turn by incrementing its magnitude erstwhile it collides pinch a nutrient dot.

  1. Create a caller function. Inside it, loop done each constituent successful nan dots array: function checkCollision() {
      for (var one = 0; one < dots.length; i++) {
  2. If nan snake's position matches nan coordinates of immoderate dots, increment nan snake's length, and delete nan dot: if (snakeX < dots[i].x + 10 &&
      snakeX + 10 > dots[i].x &&
      snakeY < dots[i].y + 10 &&
      snakeY + 10 > dots[i].y) {
        dots.splice(i, 1);
  3. Call nan caller checkCollision() usability successful nan crippled loop: function gameLoop() {
      if(!gameEnded) {
        setTimeout(gameLoop, 100);
  4. Open nan "index.html" record successful a web browser. Move nan snake utilizing nan keyboard to cod nan nutrient pieces and turn nan snake.
    Snake crippled pinch last crippled board

How to End nan Game

To extremity nan game, cheque if nan snake collided pinch its ain tail, aliases immoderate of nan walls.

  1. Create a caller usability to people a "Game Over" alert. function gameOver() {
      setTimeout(function() {
        alert("Game over!");
      }, 500);
      gameEnded = true
  2. Inside nan checkCollision() function, cheque if nan snake deed immoderate of nan canvas' walls. If so, telephone nan gameOver() function: if (snakeX < -10 ||
      snakeY < -10 ||
      snakeX > canvas.width+10 ||
      snakeY > canvas.height+10) {
  3. To cheque if nan caput of nan snake collided pinch immoderate of nan tail segments, loop done each portion of nan snake: for (var one = 1; one < snakeSegments.length; i++) {


  4. Inside nan for-loop, cheque if nan location of nan snake's caput matches immoderate of nan tail segments. If so, this intends nan caput collided pinch a tail, truthful extremity nan game: if (snakeX === snakeSegments[i].x && snakeY === snakeSegments[i].y) {
  5. Open nan "index.html" record successful a web browser. Try to deed a wall aliases your ain tail to extremity nan game.
    Game complete alert successful snake game

Learning JavaScript Concepts Through Games

Creating games tin beryllium a awesome measurement to make your learning acquisition much enjoyable. Keep making much games to proceed improving your JavaScript knowledge.

Source useuf