Snake Game JavaScript Code

Snake Game JavaScript Code
Project: Canvas - Snake Game
Author: Isaac
Edit Online: View on CodePen
License: MIT

This code implements a simple snake game using JavaScript and HTML canvas. The game allows the player to control a snake on the canvas, moving it in different directions using the arrow keys. The objective is to eat the randomly generated food items and grow the snake’s length. However, the game ends if the snake collides with itself.

The code utilizes various functions such as init() to initialize the game, add() to add segments to the snake’s body, createFood() to generate food items, and draw() to update the game state and draw the snake and food on the canvas. The game keeps track of the player’s score, which increases when food is consumed.

This code serves as a foundation for building a playable snake game and can be helpful for those interested in learning game development or implementing a classic game on their website.

How to Create Snake Game in JavaScript

1. First of all, load Google Fonts and Normalize CSS by adding the following CDN links into the head tag of your web/app project. (Optional)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lobster'>

2. Create an HTML5 canvas element with a unique id in which the snake game will be rendered.

<section class="content">
  <h1 class="title">Snake Game</h1>
  <canvas id="canvas" width="640" height="480"></canvas>
</section>

3. Style the basic interface of the snake game using the following CSS. You can also define your own styles to customize the game interface.

* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}
html,
body {
  width: 100%;
  height: 100%;
  position: relative;
}

body{
  background: url("http://imageshack.com/a/img924/148/lo4sih.jpg") #83a41a no-repeat bottom center !important;
  background-size: cover;
  font-size: 62.5%;
}
.content {
  display: flex;
  flex-flow: column;
  align-items: center;
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 1em;
}
.content .title {
  font: 5em Lobster, cursive;
  text-shadow: 0 2px 0 rgba(0,0,0,0.5);
  color: #fafafa;
  margin: -0.5em 0 0.5em 0;
}
.content canvas {
  background: #fafafa;
  box-shadow: 0 2px 16px rgba(0,0,0,0.25);
}

4. To activate the snake game, simply add the provided JavaScript code to your project. This will enable the game functionality and allow users to play the game on your website.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var dir, score, snake, food;
var speed = 222;
var speedSnake = 20;

document.addEventListener("keydown", function(e) {
  var keyCode = e.keyCode;
  if (keyCode == 37 && dir != "right") {
    dir = "left";
  }
  if (keyCode == 38 && dir != "down") {
    dir = "up";
  }
  if (keyCode == 39 && dir != "left") {
    dir = "right";
  }
  if (keyCode == 40 && dir != "up") {
    dir = "down";
  }
});

setInterval(draw, speed);

function init() {
  dir = "right";
  score = 0;
  snake = [{ x: 40, y: 40 }, { x: 60, y: 40 }, { x: 80, y: 40 }];
  createFood();
}

function add() {
  var lastsnake = snake[snake.length - 1];

  if (dir == "right") {
    snake.push({ x: lastsnake.x + speedSnake, y: lastsnake.y });
  }
  if (dir == "down") {
    snake.push({ x: lastsnake.x, y: lastsnake.y + speedSnake });
  }
  if (dir == "left") {
    snake.push({ x: lastsnake.x - speedSnake, y: lastsnake.y });
  }
  if (dir == "up") {
    snake.push({ x: lastsnake.x, y: lastsnake.y - speedSnake });
  }
}

function createFood() {
  food = {
    x: Math.floor(Math.random() * 25),
    y: Math.floor(Math.random() * 25)
  };
  for (var i = 0; i < snake.length; i++) {
    var snake2 = snake[i];
    if (food.x == snake2.x && food.y == snake2.y) {
      createFood();
    }
  }
}

function draw() {
  ctx.clearRect(0, 0, 888, 555);
  snake.shift();
  add();

  var lastsnake = snake[snake.length - 1];
  
  if (lastsnake.x == food.x * 20 && lastsnake.y == food.y * 20) {
    score += 5;
    add();
    createFood();
  }

  for (i = 0; i < snake.length; i++) {
    snake2 = snake[i];
    if (i == snake.length - 1) {
      ctx.fillStyle = "#83a41a";
    } else {
      ctx.fillStyle = "#b4ce3a";
    }
    if (snake2.x > 640) {
      snake2.x = 0;
    }
    if (snake2.x < 0) {
      snake2.x = 640;
    }
    if (snake2.y > 480) {
      snake2.y = 0;
    }
    if (snake2.y < 0) {
      snake2.y = 480;
    }

    if (
      snake2.x == lastsnake.x &&
      snake2.y == lastsnake.y &&
      i < snake.length - 2
    ) {
      alert("Fim de jogo, sua pontuação foi: " + score);
      init();
    }

    ctx.fillRect(snake2.x, snake2.y, 19, 19);
  }
  ctx.fillRect(food.x * 17, food.y * 20, 19, 19);
  ctx.fillText("Pontos: " + score, 10, 20);
}

requestAnimationFrame(init);

That’s all! hopefully, you have successfully integrated this Snake Game using this JavaScript source code. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply