You are currently viewing Complete Snake Game Code in HTML, CSS, and JavaScript – Easy to Customize and Implement

Complete Snake Game Code in HTML, CSS, and JavaScript – Easy to Customize and Implement

Learn how to create a fully functional Snake Game using HTML, CSS, and JavaScript with this step-by-step guide. Explore the code, features, and how to implement your own version of the classic Snake game on your website. Perfect for beginners and developers who want to enhance their web development skills.

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 class="game-container">
        <h1>Snake Game</h1>
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        <div class="controls">
            <button onclick="startGame()">Start Game</button>
            <p id="score">Score: 0</p>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

style.css

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #282c34;
    color: white;
    text-align: center;
}
.game-container {
    background: linear-gradient(135deg, #f06, #4a90e2);
    border-radius: 20px;
    padding: 20px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
    width: 450px;
}
h1 {
    color: white;
    font-size: 36px;
    margin-bottom: 20px;
}
canvas {
    border: 5px solid #fff;
    border-radius: 10px;
}
.controls {
    margin-top: 20px;
}
button {
    background-color: #4caf50;
    color: white;
    border: none;
    padding: 10px 20px;
    font-size: 18px;
    cursor: pointer;
    border-radius: 10px;
    transition: background-color 0.3s ease;
}
button:hover {
    background-color: #45a049;
}
#score {
    font-size: 20px;
    margin-top: 10px;
}

script.js

const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
let snake = [{ x: 50, y: 50 }];
let food = { x: 100, y: 100 };
let dx = 10, dy = 0;
let score = 0;
let gameInterval;
function startGame() {
    snake = [{ x: 50, y: 50 }];
    dx = 10;
    dy = 0;
    score = 0;
    document.getElementById("score").innerText = `Score: ${score}`;
    clearInterval(gameInterval);
    gameInterval = setInterval(gameLoop, 100);
}
function gameLoop() {
    clearCanvas();
    drawFood();
    moveSnake();
    drawSnake();
    checkCollision();
    updateScore();
}
function clearCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function drawFood() {
    ctx.fillStyle = "#ff6347"; // Tomato Red
    ctx.fillRect(food.x, food.y, 10, 10);
}
function moveSnake() {
    let head = { x: snake[0].x + dx, y: snake[0].y + dy };
    snake.unshift(head);
    if (head.x === food.x && head.y === food.y) {
        score += 10;
        food = generateFood();
    } else {
        snake.pop();
    }
}
function drawSnake() {
    ctx.fillStyle = "#32cd32"; // Lime Green
    for (let i = 0; i < snake.length; i++) {
        ctx.fillRect(snake[i].x, snake[i].y, 10, 10);
    }
}
function checkCollision() {
    let head = snake[0];
    // Check wall collision
    if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
        endGame();
    }
    // Check self-collision
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            endGame();
        }
    }
}
function generateFood() {
    let foodX = Math.floor(Math.random() * (canvas.width / 10)) * 10;
    let foodY = Math.floor(Math.random() * (canvas.height / 10)) * 10;
    return { x: foodX, y: foodY };
}
function updateScore() {
    document.getElementById("score").innerText = `Score: ${score}`;
}
function endGame() {
    clearInterval(gameInterval);
    alert("Game Over! Your final score is: " + score);
}
document.addEventListener("keydown", (event) => {
    if (event.key === "ArrowUp" && dy === 0) {
        dx = 0;
        dy = -10;
    } else if (event.key === "ArrowDown" && dy === 0) {
        dx = 0;
        dy = 10;
    } else if (event.key === "ArrowLeft" && dx === 0) {
        dx = -10;
        dy = 0;
    } else if (event.key === "ArrowRight" && dx === 0) {
        dx = 10;
        dy = 0;
    }
});

Leave a Reply