Snake Game in JavaScript Code With Source Code

The Snake Game In JavaScript is a web-based game that is written in JavaScript and serves as the major interaction of the entire game, HTML (Hyper Text Mark Up Language) for the structure of the game, and CSS (Cascading Style Sheet) for the entire design of the game.

In addition, this game can be redesigned and made more unique based on what you like, just make sure that you have a basic knowledge of the language we used on this project.

Lastly, the project is designed and created to help IT students, professionals, and developers who want to explore or learn game development on the web.

What is Snake Game?

In JavaScript, Snake Game is a web arcade game developed to provide leisure time to gamers who like this kind of game.

Furthermore, the game is developed in JavaScript (JS) to become more realistic in the way it executes.

This Snake Game is very simple to understand and play, just a normal game you see mostly the game has also characteristics and functions such as a function to move from any direction, the snake can eat an apple, and once the snake eats a lot of apple the length of the snake become grow.

In addition, using the right and left keys you can control the head of the snake and all the parts of the snake will just follow, you just need to control the snake where the apple is located.

Don’t go in a direction where food is not located to avoid the snake hitting the wall

Lastly, the project also has created a function to display the score which start to a score of 0.

The project also includes tutorials and guidance for writing this project. Users can download and alter zip files as needed because the project is open source and I will provide the JavaScript source code you can copy and paste or download the entire source code below.

snake.js

class SnakeGame {
  constructor() {
    this.$app = document.querySelector('#app');
    this.$canvas = this.$app.querySelector('canvas');
    this.ctx = this.$canvas.getContext('2d');
    this.$startScreen = this.$app.querySelector('.start-screen');
    this.$score = this.$app.querySelector('.score');

    this.settings = {
      canvas: {
        width: window.innerWidth,
        height: window.innerHeight,
        background: '#000000',
        border: '#000'
      },
      snake: {
        size: 30,
        background: '#FF0000',
        border: '#000'
      }
    };

    this.game = {
     
      speed: 100,
      keyCodes: {
        38: 'up',
        40: 'down',
        39: 'right',
        37: 'left'
      }  
    };

    this.soundEffects = {
      score: new Audio('./sounds/itsourcecodescore.mp3'),
      gameOver: new Audio('./sounds/itsourcecodegameover.mp3')
    };

    this.setUpGame();
    this.init();
  }

  init() {
    
    this.$startScreen.querySelector('.options').addEventListener('click', event => {
      this.chooseDifficulty(event.target.dataset.difficulty);
    });

   
    this.$startScreen.querySelector('.play-btn').addEventListener('click', () => {
      this.startGame();
    });
  }

  chooseDifficulty(difficulty) {
    if(difficulty) {
      this.game.speed = difficulty;
      this.$startScreen.querySelectorAll('.options button').forEach(btn => btn.classList.remove('active'));
      event.target.classList.add('active');
    }
  }

  setUpGame() {
    
    const x = 300;
    const y = 300;

    this.snake = [
      { x: x, y: y },
      { x: x - this.settings.snake.size, y: y },
      { x: x - (this.settings.snake.size * 2), y: y },
      { x: x - (this.settings.snake.size * 3), y: y },
      { x: x - (this.settings.snake.size * 4), y: y }
    ];

    this.food = {
      active: false,
      background: '#FFFF00',
      border: '#73AA24',
      coordinates: {
        x: 0,
        y: 0  
      }
    };

    this.game.score = 0;
    this.game.direction = 'right';
    this.game.nextDirection = 'right';
  }

  startGame() {
    
    this.soundEffects.gameOver.pause();
    this.soundEffects.gameOver.currentTime = 0;

    
    this.$app.classList.add('game-in-progress');
    this.$app.classList.remove('game-over');
    this.$score.innerText = 0;

    this.generateSnake();

    this.startGameInterval = setInterval(() => {
      if(!this.detectCollision()) {
        this.generateSnake();
      } else {
        this.endGame();
      }
    }, this.game.speed);

    
    document.addEventListener('keydown', event => {
      this.changeDirection(event.keyCode);
    });
  }

  changeDirection(keyCode) {
    const validKeyPress = Object.keys(this.game.keyCodes).includes(keyCode.toString()); // Only allow (up|down|left|right)

    if(validKeyPress && this.validateDirectionChange(this.game.keyCodes[keyCode], this.game.direction)) {
      this.game.nextDirection = this.game.keyCodes[keyCode];
    }
  }

  
  validateDirectionChange(keyPress, currentDirection) {
    return (keyPress === 'left' && currentDirection !== 'right') || 
      (keyPress === 'right' && currentDirection !== 'left') ||
      (keyPress === 'up' && currentDirection !== 'down') ||
      (keyPress === 'down' && currentDirection !== 'up');
  }

  resetCanvas() {
    
    this.$canvas.width = this.settings.canvas.width;
    this.$canvas.height = this.settings.canvas.height;

    
    this.ctx.fillStyle = this.settings.canvas.background;
    this.ctx.fillRect(0, 0, this.$canvas.width, this.$canvas.height);
  }

  generateSnake() {
    let coordinate;

    switch(this.game.direction) {
      case 'right':
        coordinate = {
          x: this.snake[0].x + this.settings.snake.size,
          y: this.snake[0].y
        };
      break;
      case 'up':
        coordinate = {
          x: this.snake[0].x,
          y: this.snake[0].y - this.settings.snake.size
        };
      break;
      case 'left':
        coordinate = {
          x: this.snake[0].x - this.settings.snake.size,
          y: this.snake[0].y
        };
      break;
      case 'down':
        coordinate = {
          x: this.snake[0].x,
          y: this.snake[0].y + this.settings.snake.size
        };
    }

   
    this.snake.unshift(coordinate);
    this.resetCanvas();

    const ateFood = this.snake[0].x === this.food.coordinates.x && this.snake[0].y === this.food.coordinates.y;

    if(ateFood) {
      this.food.active = false;
      this.game.score += 10;
      this.$score.innerText = this.game.score;
      this.soundEffects.score.play();
    } else {
      this.snake.pop();
    }

    this.generateFood();
    this.drawSnake();
  }

  drawSnake() {
    const size = this.settings.snake.size;

    this.ctx.fillStyle = this.settings.snake.background;
    this.ctx.strokestyle = this.settings.snake.border;

    
    this.snake.forEach(coordinate => {
      this.ctx.fillRect(coordinate.x, coordinate.y, size, size);
      this.ctx.strokeRect(coordinate.x, coordinate.y, size, size);
    });

    this.game.direction = this.game.nextDirection;
  }

  generateFood() {
    
    if(this.food.active) {
      this.drawFood(this.food.coordinates.x, this.food.coordinates.y);
      return;
    }

    const gridSize = this.settings.snake.size;
    const xMax = this.settings.canvas.width - gridSize;
    const yMax = this.settings.canvas.height - gridSize;

    const x = Math.round((Math.random() * xMax) / gridSize) * gridSize;
    const y = Math.round((Math.random() * yMax) / gridSize) * gridSize;

    
    this.snake.forEach(coordinate => {
      const foodSnakeConflict = coordinate.x == x && coordinate.y == y;

      if(foodSnakeConflict) {
        this.generateFood();
      } else {
        this.drawFood(x, y);
      }
    });
  }

  drawFood(x, y) {
    const size = this.settings.snake.size;

    this.ctx.fillStyle = this.food.background;
    this.ctx.strokestyle = this.food.border;

    this.ctx.fillRect(x, y, size, size);
    this.ctx.strokeRect(x, y, size, size);

    this.food.active = true;
    this.food.coordinates.x = x;
    this.food.coordinates.y = y;
  }

  detectCollision() {
    
    for(let i = 4; i < this.snake.length; i++) {
      const selfCollison = this.snake[i].x === this.snake[0].x && this.snake[i].y === this.snake[0].y;

      if(selfCollison) {
        return true;
      }
    }

    
    const leftCollison = this.snake[0].x < 0;
    const topCollison = this.snake[0].y < 0;
    const rightCollison = this.snake[0].x > this.$canvas.width - this.settings.snake.size;
    const bottomCollison = this.snake[0].y > this.$canvas.height - this.settings.snake.size;

    return leftCollison || topCollison || rightCollison || bottomCollison;
  }

  endGame() {
    this.soundEffects.gameOver.play();

    clearInterval(this.startGameInterval);

    this.$app.classList.remove('game-in-progress');
    this.$app.classList.add('game-over');
    this.$startScreen.querySelector('.options h3').innerText = 'Game Over';
    this.$startScreen.querySelector('.options .end-score').innerText = `Score: ${this.game.score}`;

    this.setUpGame();
  }
}

const snakeGame = new SnakeGame();

Benefits of Snake Game:

  • Snake Game can help to learn productivity and increase focus
  • The functionality of the brain increased
  • Ability to solve problems quickly
  • Improved strategy and planning

Rules of Snake Game

The arrow key when the snake is used to move around the board in the game Snake. When the snake finds food, it eats it and grows larger as a result.

When the snake moves off the screen or into itself, the game is over. The goal is to grow the snake as big as possible before this happens just check if the snake can make it larger.

Why Snake Game is important?

The Snake Game in JavaScript Code is an excellent project for beginners it is important because it was developed on the web which means that you can play it online.

JavaScript is an excellent language to use. Web and mobile games benefit from JavaScript.

It’s also an excellent language for kids to learn because it’s generally simple to grasp and has a wealth of online resources for coders.

About the Project

This Snake Game Code JavaScript is a basic snake game similar to the ones we usually play.

We use different methods and functions such as canvas element, math.floor and math.random and CSS background color.

Users can use the left arrow key, right arrow key, up arrow key, and down arrow key to change the controls from their desktop.

You can lose the match if the snake does not reach the boundary.

Project Details and Technology

Project Name:Snake Game in JavaScript
AbstractThis basic small project for Snake Game using JavaScript is full and error-free, and it also comes with a free downloaded source code; simply locate the downloadable source code below and click to begin downloading. Before you begin downloading, you must first click the Run Quick Scan for Secure Download button.
Language/s Used:JavaScript
JavaScript version (Recommended):ES2015
Database:MYSQL
Type:Web Application
Developer:Source Code Hero
Updates:0

To begin constructing a Snake Game in JavaScript , make sure you have any platform for creating JavaScript, bootstrap, and HTML installed on your computer; in my instance, I’ll be using Sublime Text.

Steps how to run the project

Time needed: 3 minutes

  • Step 1: Download Source Code

    To get started, find the downloaded source code file below and click to start downloading it.

    Snake Game using Javascript

  • Step 2: Extract File

    Navigate to the file’s location when you’ve finished downloading it and right-click it to extract it.

    Snake Game using Javascript extract

  • Step 3: Run the project

    click the index.html inside the folder to start executing the project.
    Snake Game using Javascript index

Download the Source Code below

Summary

For those Web developers interested in learning more about web apps, this system is a fully functional project.

Related Article

Inquiries

If you have any questions or comments on the project, please leave a comment below.

Leave a Comment