Creating a simple Snake game using HTML, CSS, and JavaScript is a great project to practice web development. Below is a basic implementation of the Snake game. This version is kept straightforward for clarity and ease of understanding:
HTML
First, let's set up the basic structure of our HTML file.
// script.js
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const box = 20;
const canvasSize = 400;
let snake = [];
snake[0] = { x: 10 * box, y: 10 * box };
let direction;
let food = {
x: Math.floor(Math.random() * (canvasSize / box)) * box,
y: Math.floor(Math.random() * (canvasSize / box)) * box
};
let score = 0;
document.addEventListener("keydown", moveDirection);
function moveDirection(event) {
if (event.keyCode == 37 && direction != "RIGHT") {
direction = "LEFT";
} else if (event.keyCode == 38 && direction != "DOWN") {
direction = "UP";
} else if (event.keyCode == 39 && direction != "LEFT") {
direction = "RIGHT";
} else if (event.keyCode == 40 && direction != "UP") {
direction = "DOWN";
}
}
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x == array[i].x && head.y == array[i].y) {
return true;
}
}
return false;
}
function draw() {
ctx.clearRect(0, 0, canvasSize, canvasSize);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i == 0 ? "blue" : "green";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "white";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction == "LEFT") snakeX -= box;
if (direction == "UP") snakeY -= box;
if (direction == "RIGHT") snakeX += box;
if (direction == "DOWN") snakeY += box;
if (snakeX == food.x && snakeY == food.y) {
score++;
food = {
x: Math.floor(Math.random() * (canvasSize / box)) * box,
y: Math.floor(Math.random() * (canvasSize / box)) * box
};
} else {
snake.pop();
}
let newHead = { x: snakeX, y: snakeY };
if (
snakeX < 0 ||
snakeY < 0 ||
snakeX >= canvasSize ||
snakeY >= canvasSize ||
collision(newHead, snake)
) {
clearInterval(game);
}
snake.unshift(newHead);
ctx.fillStyle = "black";
ctx.font = "16px Arial";
ctx.fillText("Score: " + score, box, canvasSize - box);
}
let game = setInterval(draw, 100);
How It Works
Canvas: The game is drawn on a 400x400 canvas.
Snake: The snake is represented as an array of objects with x and y properties.
Movement: We listen for arrow key presses to change the snake's direction.
Food: Food is randomly positioned on the grid, and when eaten, the snake grows.
Collision: The game checks for collisions with the walls or the snake itself. If a collision is detected, the game stops.
You can expand upon this basic implementation by adding features like sounds, increasing speed as the snake gets longer, or even different levels. Enjoy coding your Snake game!