How To Create Snake Game In JavaScript?
Snake game, Was the most popular game in the 19th century that’s why most people know this game. Snake game is a classical single-player game where the player controls a growing snake that moves around a box for eating food.
In this game, A snake moves around a box trying to eat food. When the snake successfully eats the food, the length of the snake increases and the movement becomes faster. And if a snake crashes the wall of box game is over.
How to control the snake:
The player controls the movement of the snake using the arrow keys, Up, Down, Right, or Left keys on a keyboard. The snake moves continuously in a specific direction until the player changes its direction.
Code In Jsfeed Editer:
HTML
Let’s start the code, First, we create the game structure with HTML and CSS, which includes a canvas element where the game will be displayed.
<h1>Snake Game with Javascript<div class="snake"></div></h1>
<canvas id="board"></canvas>
CSS
In CSS, we give styling the canvas elements with background, border, and box styling.
body {
text-align: center;
font-family: Georgia, serif;
}
.snake {
font-size: 20px;
font-weight: bold;
color: green;
}
Play other game too : Flappy bird game
JavaScript
We have written most of the code in JavaScript to create a snake and their feature like moving, food eating, wall crashing, and controlling the game.
var blockSize = 20;
var total_row = 20;
var total_col = 20;
var board;
var context;
var snakeX = blockSize * 5;
var snakeY = blockSize * 5;
// Set the total number of rows and columns
var speedX = 0; //speed of snake in x coordinate.
var speedY = 0; //speed of snake in Y coordinate.
var snakeBody = [];
var foodX;
var foodY;
var gameOver = false;
window.onload = function () {
// Set board height and width
board = document.getElementById("board");
board.height = total_row * blockSize;
board.width = total_col * blockSize;
context = board.getContext("2d");
placeFood();
document.addEventListener("keyup", changeDirection); //for movements
// Set snake speed
setInterval(update, 2000 / 10);
}
function update() {
if (gameOver) {
return;
}
// Background of a Game
context.fillStyle = "black";
context.fillRect(0, 0, board.width, board.height);
// Set food color and position
context.fillStyle = "#fff";
context.fillRect(foodX, foodY, blockSize, blockSize);
if (snakeX == foodX && snakeY == foodY) {
snakeBody.push([foodX, foodY]);
placeFood();
}
// body of snake will grow
for (let i = snakeBody.length - 1; i > 0; i--) {
// it will store previous part of snake to the current part
snakeBody[i] = snakeBody[i - 1];
}
if (snakeBody.length) {
snakeBody[0] = [snakeX, snakeY];
}
context.fillStyle = "#ff3c00";
snakeX += speedX * blockSize; //updating Snake position in X coordinate.
snakeY += speedY * blockSize; //updating Snake position in Y coordinate.
context.fillRect(snakeX, snakeY, blockSize, blockSize);
for (let i = 0; i < snakeBody.length; i++) {
context.fillRect(snakeBody[i][0], snakeBody[i][1], blockSize, blockSize);
}
if (snakeX < 0
|| snakeX > total_col * blockSize
|| snakeY < 0
|| snakeY > total_row * blockSize) {
// Out of bound condition
gameOver = true;
alert("Game Over");
}
for (let i = 0; i < snakeBody.length; i++) {
if (snakeX == snakeBody[i][0] && snakeY == snakeBody[i][1]) {
// Snake eats own body
gameOver = true;
alert("Game Over");
}
}
}
// Movement of the Snake - We are using addEventListener
function changeDirection(e) {
if (e.code == "ArrowUp" && speedY != 1) {
speedX = 0;
speedY = -1;
}
else if (e.code == "ArrowDown" && speedY != -1) {
//If down arrow key pressed
speedX = 0;
speedY = 1;
}
else if (e.code == "ArrowLeft" && speedX != 1) {
//If left arrow key pressed
speedX = -1;
speedY = 0;
}
else if (e.code == "ArrowRight" && speedX != -1) {
//If Right arrow key pressed
speedX = 1;
speedY = 0;
}
}
// Randomly place food
function placeFood() {
// in x coordinates.
foodX = Math.floor(Math.random() * total_col) * blockSize;
//in y coordinates.
foodY = Math.floor(Math.random() * total_row) * blockSize;
}
By following the steps in this blog post, you have successfully created a classic snake game using HTML, CSS, and JavaScript. The game employs HTML's canvas element and JavaScript methods to operate based on the established rules.
Thank You !
Tags
Share
Published:
COMMENTS ( 0 )
Sign up to join the conversation
Add your feedback for Shuka Design’s project by signing in or signing up.