Lets Create A Simple Snake Game

let’s create a full Snake game with HTML5 Canvas and JavaScript. This game will have the following features:

  1. Start screen with a button to start the game.
  2. End screen displaying the final score and an option to restart the game.
  3. Snake movement controlled by arrow keys.
  4. Food (represented by red squares) appearing randomly on the canvas.
  5. Snake growing longer when it eats food.
  6. Game over when the snake collides with the canvas edges or itself.

Here’s the code for the full Snake game:

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
canvas {
border: 1px solid #000;
background-color: #eee;
display: block;
margin: 0 auto;
}

.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
color: #fff;
font-size: 24px;
}

#startScreen {
animation: fadeIn 2s forwards;
}

@keyframes fadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}

#endScreen {
display: none;
}
</style>
</head>
<body>
<canvas id="snakeCanvas" width="400" height="400"></canvas>
<div id="startScreen" class="overlay">
<h1>Welcome to Snake Game</h1>
<button id="startButton">Start Game</button>
</div>
<div id="endScreen" class="overlay">
<h1>Game Over</h1>
<p>Your score: <span id="score">0</span></p>
<button id="restartButton">Restart Game</button>
</div>

<script>
const canvas = document.getElementById('snakeCanvas');
const ctx = canvas.getContext('2d');
const scale = 20;
const rows = canvas.height / scale;
const columns = canvas.width / scale;
let snake;
let food;
let gameInterval;
let startScreen = document.getElementById('startScreen');
let endScreen = document.getElementById('endScreen');
let scoreDisplay = document.getElementById('score');

function startGame() {
snake = new Snake();
food = new Food();
food.pickLocation();

gameInterval = setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
food.draw();
snake.update();
snake.draw();

if (snake.eat(food)) {
food.pickLocation();
scoreDisplay.innerText = snake.total;
}

snake.checkCollision();
}, 250);

startScreen.style.display = 'none';
endScreen.style.display = 'none';
canvas.style.display = 'block';
canvas.focus();
}

function endGame() {
clearInterval(gameInterval);
endScreen.style.display = 'flex';
canvas.style.display = 'none';
scoreDisplay.innerText = snake.total;
}

document.getElementById('startButton').addEventListener('click', startGame);
document.getElementById('restartButton').addEventListener('click', startGame);

window.addEventListener('keydown', (event) => {
const direction = event.key.replace('Arrow', '');
snake.changeDirection(direction);
});

function Snake() {
this.x = 0;
this.y = 0;
this.xSpeed = scale * 1;
this.ySpeed = 0;
this.total = 0;
this.tail = [];

this.draw = function() {
ctx.fillStyle = '#00f';
for (let i = 0; i < this.tail.length; i++) {
ctx.fillRect(this.tail[i].x, this.tail[i].y, scale, scale);
}
ctx.fillRect(this.x, this.y, scale, scale);
};

this.update = function() {
for (let i = 0; i < this.tail.length - 1; i++) {
this.tail[i] = this.tail[i + 1];
}
this.tail[this.total - 1] = { x: this.x, y: this.y };

this.x += this.xSpeed;
this.y += this.ySpeed;

if (this.x >= canvas.width) {
this.x = 0;
} else if (this.x < 0) {
this.x = canvas.width - scale;
}

if (this.y >= canvas.height) {
this.y = 0;
} else if (this.y < 0) {
this.y = canvas.height - scale;
}
};

this.changeDirection = function(direction) {
switch (direction) {
case 'Up':
if (this.ySpeed === 0) {
this.xSpeed = 0;
this.ySpeed = -scale * 1;
}
break;
case 'Down':
if (this.ySpeed === 0) {
this.xSpeed = 0;
this.ySpeed = scale * 1;
}
break;
case 'Left':
if (this.xSpeed === 0) {
this.xSpeed = -scale * 1;
this.ySpeed = 0;
}
break;
case 'Right':
if (this.xSpeed === 0) {
this.xSpeed = scale * 1;
this.ySpeed = 0;
}
break;
}
};

this.eat = function(food) {
if (this.x === food.x && this.y === food.y) {
this.total++;
return true;
}
return false;
};

this.checkCollision = function() {
for (let i = 0; i < this.tail.length; i++) {
if (this.x === this.tail[i].x && this.y === this.tail[i].y) {
endGame();
}
}
};
}

function Food() {
this.x;
this.y;

this.pickLocation = function() {
this.x = Math.floor(Math.random() * rows) * scale;
this.y = Math.floor(Math.random() * columns) * scale;
};

this.draw = function() {
ctx.fillStyle = '#f00';
ctx.fillRect(this.x, this.y, scale, scale);
};
}
</script>
</body>
</html>

This code sets up a complete Snake game with a start screen, end screen, and all the necessary game mechanics. Players can control the snake using arrow keys, eat food to grow longer, and the game ends if the snake collides with the canvas edges or itself.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *