Here's the code for a basic snake game using HTML, CSS, and JavaScript:
index.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> <link rel="stylesheet" href="style.css"> </head> <body> <div id="game-board"></div> <script src="script.js"></script> </body> </html>
style.css:
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
#game-board {
width: 600px;
height: 400px;
border: 1px solid black;
margin: 20px auto;
display: grid;
grid-template-columns: repeat(20, 1fr);
grid-template-rows: repeat(20, 1fr);
}
script.js:
const board = document.getElementById('game-board');
const blockSize = 20;
let snakeX = blockSize;
let snakeY = blockSize;
let velocityX = 0;
let velocityY = 0;
let snakeBody = [{ x: snakeX, y: snakeY }];
let foodX;
let foodY;
function generateFood() {
foodX = Math.floor(Math.random() * board.offsetWidth / blockSize) * blockSize;
foodY = Math.floor(Math.random() * board.offsetHeight / blockSize) * blockSize;
snakeBody.forEach(segment => {
if (segment.x === foodX && segment.y === foodY) {
generateFood();
}
});
}
function drawSnake() {
board.innerHTML = '';
snakeBody.forEach(segment => {
const snakeElement = document.createElement('div');
snakeElement.style.gridRowStart = segment.y / blockSize + 1;
snakeElement.style.gridColumnStart = segment.x / blockSize + 1;
snakeElement.classList.add('snake');
board.appendChild(snakeElement);
});
}
function drawFood() {
const foodElement = document.createElement('div');
foodElement.style.gridRowStart = foodY / blockSize + 1;
foodElement.style.gridColumnStart = foodX / blockSize + 1;
foodElement.classList.add('food');
board.appendChild(foodElement);
}
function checkCollision() {
// Check wall collision
if (snakeX + velocityX < 0 || snakeX + velocityX >= board.offsetWidth || snakeY + velocityY < 0 || snakeY + velocityY >= board.offsetHeight) {
gameOver();
return;
}
// Check self collision
for (let i = 1; i < snakeBody.length; i++) {
if (snakeX === snakeBody[i].x && snakeY === snakeBody[i].y) {
gameOver();
return;
}
}
}
function gameOver() {
alert('Game Over!');
clearInterval(gameLoop);
}
function changeDirection(event) {
const keyPressed = event.key;
if (keyPressed === 'ArrowLeft' && velocityX !== 1) {
velocityX = -1;
velocityY = 0;
} else if (keyPressed === 'ArrowRight' && velocityX !== -1) {
velocityX = 1;
velocityY = 0;
} else if (keyPressed === 'ArrowUp' && velocityY !== 1) {
velocityX = 0;
velocityY = -1;
} else if (keyPressed === 'ArrowDown' && velocityY !== -1) {
velocityX = 0;
velocityY = 1;
}
}
function moveSnake() {
snakeX += velocityX * blockSize;
snakeY += velocityY * blockSize;
checkCollision();
const newHead = { x: snakeX, y: snakeY };
snakeBody.unshift(newHead);
if (snakeX === foodX && snakeY === foodY) {
generateFood();
Resources:-