How To Build a JavaScript Retro Galactic Snake Game

This tutorial demonstrates creating a fun game avoiding black holes using JavaScript, HTML, and CSS. Examples, code, and steps included.

Building a JavaScript game would probably sound shocking at first, but you read that right. You can develop a retro snake game using JavaScript. It’s a simple game where a snake-type figure moves around a box, trying to eat apple-type food to grow longer without touching the snake’s body itself or the black holes. It’s a retro game of the 70s/80s.

Not wanting to sound like a broken record, the ideal way to learn about JavaScript or any other programming language is to try out hands-on projects. Just as I have different “try it out yourself” examples in each of my articles, the goal is to harness enough skills to solve different problems. And creating a snake game off of a few lines of JavaScript code coupled with other HMTL and CSS codes shows you are on the right path. So, what are we waiting for? Let’s get right to it! 

First, we’ll need to create our base file’s location. Then, you’ll need to create files for the project for offline HTML editors. So, go ahead – create the index.html file, the style.css file, and the game.js (Javascript file).

HTML Snake Game Board Frame
HTML Snake Game Board Frame

The HTML file:

Here we create the webpage for the gameboard and scoreboard.

<!DOCTYPE html>
<html>
    <head lang="en">
      <meta charset="UTF-8" />
      <title>Retro Javascript Snake Game</title>
      <!-- Link our styles from snake_game.css -->
      <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
      <h2 id="header">Javascript Retro Galactic Snake Game</h2>
      <!--The scoreContainer represents the div that displays the game's score-->
      <div id="scoreContainer">
        <div class="scoreBoard">Food: <span id="pointsEarned">0</span></div>
        <div class="scoreBoard" style="display:none;" ;>Blocks: <span id="blocksTravelled">0</span></div>
      </div>
      <!-- The #gameContainer is used as the game's canvas-->
      <div id="gameContainer"></div>
    </body>
   <!-- #Load our snake_game.js containing the game logic -->
   <script src="game.js"></script>
</html>

The CSS File:

Once you’ve created the HTML file perfectly, we’ll move on to styling the web page. An HTML webpage will look like a car’s chassis and frame. To put the paint, the car tires, in this case, you need the stylesheet, which is what we’re about to do now. Also, the comment in each line of codes will guide you through their roles and importance. So, add the lines of code to your stylesheet:

body {
  text-align: center;
  background: #ffd079;
  font-family: Arial;
}

#header {
  text-align: center;
  color: black;
  font-weight: bold;
}

/*  The game's board style starts here  */

#gameContainer {
  width: 40vw;
  height: 40vw;
  margin: 0 auto 2vw auto;
  background-color: #0c1021;
  border: solid 10px slategrey;
  border-radius: 10px;
  -webkit-box-shadow: 0px 0px 20px 3px rgb(0 0 0 / 60%);
  -moz-box-shadow: 0px 0px 20px 3px rgba(0, 0, 0, 0.6);
  box-shadow: 0px 0px 20px 3px rgb(0 0 0 / 60%);
  overflow: hidden;
  transform: scale(0.75);
}

.gameBoardPixel {
  /* background-color: grey; */
  /*
    The 1vw used here represents 1% of the entire viewpoint height and width. It
	is also used in a calculation line in a javascript code below
	*/
  width: 1vw;
  height: 1vw;
  border-radius: 3px;
  float: left;
}
/* The game canva style ends here */

/* The snake style starts here */
.snakeBodyPixel {
  background-color: white;
}
/*  The snake style ends here */

/* The food style starts here */
.food {
  border-radius: 20px;
}

.food1 {
  background-color: #0077ff;
  transform: scale(1.2);
}

.food2 {
  background-color: red;
  transform: scale(2);
}

.food3 {
  background-color: orange;
  transform: scale(0.75);
}

.blackhole {
  box-shadow: 0 0 32px 15px #fff, /* inner white */ 0 0 64px 15px #f0f,
    /* middle magenta */ 0 0 61px 15px #0ff;
}

/* The food style ends here */

/* The game's score style */
#scoreContainer {
  width: 25vw;
  display: flex;
  margin: auto;
  justify-content: space-around;
}

.scoreBoard {
  color: black;
  background-color: orange;
  display: inline-block;
  padding: 1vw;
  width: 40%;
  font-size: 20px;
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
}
/* The game's score style ends here */

Snake Game Food Dots
Snake Game Food Dots

You may wonder how the food and black holes are created. Well, the food is created using these styles.

.food1 {
  background-color: #0077ff;
  transform: scale(1.2);
}

.food2 {
  background-color: red;
  transform: scale(2);
}

.food3 {
  background-color: orange;
  transform: scale(0.75);
}
CSS Styles for the Snake Game Black Holes
CSS Styles for the Snake Game Black Holes

The black holes on the other hand are created with these styles.

.blackhole {
  box-shadow: 0 0 32px 15px #fff, /* inner white */ 0 0 64px 15px #f0f,
    /* middle magenta */ 0 0 61px 15px #0ff;
}

Feels great, right? It’s not complex, and you can tweak the game’s theme and create a fascinating game with this. Now, we’ll move on to the star of the show – Javascript.

The Javascript File:

The game won’t function without its logic. The javascript file is written below, and it includes the score variable, which will initialize the game’s score. We’ve also added codes for the movement and other needed actions of the game, food, and black holes. So:

// This is the pixels on vertical or horizonal axis of the game itself in (SQUARE)
const GAME_PIXEL_COUNT = 40;
const SQUARE_OF_GAME_PIXEL_COUNT = Math.pow(GAME_PIXEL_COUNT, 2);

let totalFoodAte = 0;
let totalDistanceTravelled = 0;

/// Here's the game canva function
const gameContainer = document.getElementById("gameContainer");

const createGameBoardPixels = () => {
  // Populate the [#gameContainer] div with small div's representing game pixels
  for (let i = 1; i <= SQUARE_OF_GAME_PIXEL_COUNT; ++i) {
    gameContainer.innerHTML = `${gameContainer.innerHTML} <div class="gameBoardPixel" id="pixel${i}"></div>`;
  }
};

// This variable always holds the updated array of game pixels created by createGameBoardPixels() :
const gameBoardPixels = document.getElementsByClassName("gameBoardPixel");

/// THE FOOD:
let currentFoodPostion = 0;
let foodArray = ["food1", "food2", "food3"];

const createFood = (position) => {
  // Remove previous food;
  gameBoardPixels[position].classList.remove("food");
  gameBoardPixels[position].classList.remove("food1");
  gameBoardPixels[position].classList.remove("food2");
  gameBoardPixels[position].classList.remove("food3");

  // Create new food
  currentFoodPostion = Math.random();
  currentFoodPostion = Math.floor(
    currentFoodPostion * SQUARE_OF_GAME_PIXEL_COUNT
  );
  gameBoardPixels[currentFoodPostion].classList.add("food");

  let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
  gameBoardPixels[currentFoodPostion].classList.add(randomFood.toString());

  let foo = Math.random() * 100;
  if (foo < 40) {
    // 0-79 {
    blackhole();
  }
};

const blackhole = () => {
  // Create new food
  currentFoodPostion = Math.random();
  currentFoodPostion = Math.floor(
    currentFoodPostion * SQUARE_OF_GAME_PIXEL_COUNT
  );
  gameBoardPixels[currentFoodPostion].classList.add("food");

  let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
  gameBoardPixels[currentFoodPostion].classList.add("blackhole");
};

/// THE FOOD:
let currentFoodPostionPlot = 0;

const createFoodPlot = () => {
  // Create new food
  for (let i = 0; i < 10; i++) {
    let currentFoodPostionPlot = 0;
    currentFoodPostionPlot = Math.random();
    currentFoodPostionPlot = Math.floor(
      currentFoodPostionPlot * SQUARE_OF_GAME_PIXEL_COUNT
    );
    let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
    gameBoardPixels[currentFoodPostionPlot].classList.add("food");

    gameBoardPixels[currentFoodPostionPlot].classList.add(
      randomFood.toString()
    );

    let foo = Math.random() * 100;
    if (foo < 40) {
      // 0-79 {
      blackhole();
    }
  }
};

/// THE SNAKE:

// Direction codes (Keyboard key codes for arrow keys):
const LEFT_DIR = 37;
const UP_DIR = 38;
const RIGHT_DIR = 39;
const DOWN_DIR = 40;

// Set snake direction initially to right
let snakeCurrentDirection = RIGHT_DIR;

const changeDirection = (newDirectionCode) => {
  // Change the direction of the snake
  if (newDirectionCode == snakeCurrentDirection) return;

  if (newDirectionCode == LEFT_DIR && snakeCurrentDirection != RIGHT_DIR) {
    snakeCurrentDirection = newDirectionCode;
  } else if (newDirectionCode == UP_DIR && snakeCurrentDirection != DOWN_DIR) {
    snakeCurrentDirection = newDirectionCode;
  } else if (
    newDirectionCode == RIGHT_DIR &&
    snakeCurrentDirection != LEFT_DIR
  ) {
    snakeCurrentDirection = newDirectionCode;
  } else if (newDirectionCode == DOWN_DIR && snakeCurrentDirection != UP_DIR) {
    snakeCurrentDirection = newDirectionCode;
  }
};

// Let the starting position of the snake be at the middle of game board
let currentSnakeHeadPosition = SQUARE_OF_GAME_PIXEL_COUNT / 1;

// Initial snake length
let snakeLength = 1000;

// This will keep moving the snake constantly by calling this function repeatedly :
const moveSnake = () => {
  switch (snakeCurrentDirection) {
    case LEFT_DIR:
      --currentSnakeHeadPosition;
      const isSnakeHeadAtLastGameBoardPixelTowardsLeft =
        currentSnakeHeadPosition % GAME_PIXEL_COUNT == GAME_PIXEL_COUNT - 1 ||
        currentSnakeHeadPosition < 0;
      if (isSnakeHeadAtLastGameBoardPixelTowardsLeft) {
        currentSnakeHeadPosition = currentSnakeHeadPosition + GAME_PIXEL_COUNT;
      }
      break;
    case UP_DIR:
      currentSnakeHeadPosition = currentSnakeHeadPosition - GAME_PIXEL_COUNT;
      const isSnakeHeadAtLastGameBoardPixelTowardsUp =
        currentSnakeHeadPosition < 0;
      if (isSnakeHeadAtLastGameBoardPixelTowardsUp) {
        currentSnakeHeadPosition =
          currentSnakeHeadPosition + SQUARE_OF_GAME_PIXEL_COUNT;
      }
      break;
    case RIGHT_DIR:
      ++currentSnakeHeadPosition;
      const isSnakeHeadAtLastGameBoardPixelTowardsRight =
        currentSnakeHeadPosition % GAME_PIXEL_COUNT == 0;
      if (isSnakeHeadAtLastGameBoardPixelTowardsRight) {
        currentSnakeHeadPosition = currentSnakeHeadPosition - GAME_PIXEL_COUNT;
      }
      break;
    case DOWN_DIR:
      currentSnakeHeadPosition = currentSnakeHeadPosition + GAME_PIXEL_COUNT;
      const isSnakeHeadAtLastGameBoardPixelTowardsDown =
        currentSnakeHeadPosition > SQUARE_OF_GAME_PIXEL_COUNT - 1;
      if (isSnakeHeadAtLastGameBoardPixelTowardsDown) {
        currentSnakeHeadPosition =
          currentSnakeHeadPosition - SQUARE_OF_GAME_PIXEL_COUNT;
      }
      break;
    default:
      break;
  }

  let nextSnakeHeadPixel = gameBoardPixels[currentSnakeHeadPosition];

  // Kill snake if it bites itself:
  if (nextSnakeHeadPixel.classList.contains("snakeBodyPixel")) {
    // Stop moving the snake
    clearInterval(moveSnakeInterval);
    if (!alert(`GAME OVER! Your Final Score is ${totalFoodAte}`))
      window.location.reload();
  }

  let blackHole = gameBoardPixels[currentSnakeHeadPosition].classList.contains(
    "blackhole"
  );

  if (blackHole) {
    // Stop moving the snake
    clearInterval(moveSnakeInterval);
    if (
      !alert(
        `You've been swallowed by a Black Hole!! GAME OVER! Your Final Score is ${totalFoodAte}`
      )
    )
      window.location.reload();
  }

  nextSnakeHeadPixel.classList.add("snakeBodyPixel");

  setTimeout(() => {
    nextSnakeHeadPixel.classList.remove("snakeBodyPixel");
  }, snakeLength);

  // Update total distance travelled
  totalDistanceTravelled++;
  // Update in UI:
  document.getElementById("blocksTravelled").innerHTML = totalDistanceTravelled;

  let hasFood = gameBoardPixels[currentSnakeHeadPosition].classList.contains(
    "food"
  );

  if (hasFood) {
    // Update total food ate
    totalFoodAte++;
    // Update in UI:
    document.getElementById("pointsEarned").innerHTML = totalFoodAte;

    // Increase Snake length:
    snakeLength = snakeLength + 100;
    createFood(currentSnakeHeadPosition);
  }
};

/// CALL THE FOLLOWING FUNCTIONS TO RUN THE GAME:
// Create game board pixels:
createGameBoardPixels();

// Create initial food:
createFoodPlot();

// Move snake:
var moveSnakeInterval = setInterval(moveSnake, 100);

// Call change direction function on keyboard key-down event:
addEventListener("keydown", (e) => changeDirection(e.keyCode));

The code that listens for the key inputs is a JavaScript event listener. You can learn about Event Listeners in another article. The event listener changes the direction of the snake whenever one of the four arrows is pressed.

addEventListener("keydown", (e) => changeDirection(e.keyCode));

Trust me, with these lines of codes; you’ll have a stunning retro snake game. Develop yours and see if you’ll beat my 70 scores. Cheers! You may also edit this JavaScript game on codepen.io.

Recommended Article

Other Article