Untitled

Anonymous
HTML
11/04/2026 7:33 PM
9.7 KB
8
Indexable
Never
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Retro Snake Game</title>
    <style>
        body {
            background-color: #111;
            color: #fff;
            font-family: 'Courier New', Courier, monospace;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
            overflow: hidden;
        }
        h1 {
            margin-bottom: 5px;
            font-size: 2rem;
            text-transform: uppercase;
            letter-spacing: 2px;
            text-shadow: 0 0 10px #4CAF50;
        }
        #score-board {
            font-size: 1.2rem;
            margin-bottom: 15px;
            color: #4CAF50;
        }
        #game-container {
            position: relative;
            border: 4px solid #4CAF50;
            box-shadow: 0 0 20px rgba(76, 175, 80, 0.5);
            background-color: #000;
        }
        canvas {
            display: block;
        }
        #overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 10;
        }
        #overlay h2 {
            font-size: 2.5rem;
            color: #ff3333;
            margin: 0 0 10px 0;
            text-shadow: 0 0 10px rgba(255, 51, 51, 0.5);
        }
        #overlay p {
            font-size: 1rem;
            color: #bbb;
            margin: 0 0 20px 0;
        }
        button {
            background-color: #4CAF50;
            color: #000;
            border: none;
            padding: 12px 30px;
            font-size: 1.1rem;
            font-family: inherit;
            font-weight: bold;
            cursor: pointer;
            text-transform: uppercase;
            box-shadow: 0 0 10px rgba(76, 175, 80, 0.4);
            transition: all 0.2s ease;
        }
        button:hover {
            background-color: #fff;
            box-shadow: 0 0 15px #fff;
        }
        .controls-hint {
            margin-top: 15px;
            font-size: 0.85rem;
            color: #666;
            text-align: center;
        }
    </style>
</head>
<body>

    <h1>Snake 🐍</h1>
    <div id="score-board">SCORE: <span id="score">0</span> | HIGH SCORE: <span id="high-score">0</span></div>

    <div id="game-container">
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        <div id="overlay">
            <h2 id="overlay-title">SNAKE</h2>
            <p id="overlay-desc">Use Arrow Keys or WASD to navigate.</p>
            <button id="start-btn">Play Game</button>
        </div>
    </div>

    <div class="controls-hint">
        Use <b>Arrow Keys</b> or <b>W, A, S, D</b> to turn.<br>
        Don't hit the walls or yourself!
    </div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const highScoreElement = document.getElementById('high-score');
        const overlay = document.getElementById('overlay');
        const overlayTitle = document.getElementById('overlay-title');
        const overlayDesc = document.getElementById('overlay-desc');
        const startBtn = document.getElementById('start-btn');

        // Grid configurations
        const gridSize = 20;
        const tileCount = canvas.width / gridSize;

        // Game state variables
        let snake = [];
        let food = { x: 0, y: 0 };
        let dx = gridSize;
        let dy = 0;
        let nextDx = dx;
        let nextDy = dy;
        let score = 0;
        let highScore = localStorage.getItem('snakeHighScore') || 0;
        let gameInterval = null;
        let isRunning = false;
        const gameSpeed = 100; // lower = faster (milliseconds per frame)

        highScoreElement.textContent = highScore;

        // Start / Restart event listener
        startBtn.addEventListener('click', startGame);

        // Listen to keystrokes
        window.addEventListener('keydown', changeDirection);

        function resetGame() {
            // Position snake horizontally in the middle initially
            snake = [
                { x: gridSize * 5, y: gridSize * 10 },
                { x: gridSize * 4, y: gridSize * 10 },
                { x: gridSize * 3, y: gridSize * 10 }
            ];
            dx = gridSize;
            dy = 0;
            nextDx = dx;
            nextDy = dy;
            score = 0;
            scoreElement.textContent = score;
            generateFood();
        }

        function startGame() {
            resetGame();
            overlay.style.display = 'none';
            isRunning = true;
            if (gameInterval) clearInterval(gameInterval);
            gameInterval = setInterval(gameLoop, gameSpeed);
        }

        function gameOver() {
            isRunning = false;
            clearInterval(gameInterval);
            if (score > highScore) {
                highScore = score;
                localStorage.setItem('snakeHighScore', highScore);
                highScoreElement.textContent = highScore;
            }
            overlayTitle.textContent = "GAME OVER";
            overlayDesc.textContent = `You scored ${score} points!`;
            startBtn.textContent = "Try Again";
            overlay.style.display = 'flex';
        }

        function generateFood() {
            // Pick a random grid block
            food.x = Math.floor(Math.random() * tileCount) * gridSize;
            food.y = Math.floor(Math.random() * tileCount) * gridSize;

            // Make sure food does not spawn directly on top of the snake's body
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === food.x && snake[i].y === food.y) {
                    generateFood();
                    break;
                }
            }
        }

        function gameLoop() {
            // Commit direction changes at the step interval to prevent instant double turns crashing the snake
            dx = nextDx;
            dy = nextDy;

            moveSnake();

            if (checkCollision()) {
                gameOver();
                return;
            }

            checkFoodConsumption();
            drawGame();
        }

        function moveSnake() {
            // Calculate where the head will move next
            const head = { x: snake[0].x + dx, y: snake[0].y + dy };
            // Unshift places the new head element at the front of the body array
            snake.unshift(head);
        }

        function checkFoodConsumption() {
            const hasEaten = snake[0].x === food.x && snake[0].y === food.y;
            if (hasEaten) {
                score += 10;
                scoreElement.textContent = score;
                generateFood();
            } else {
                // If it didn't eat food, slice off the tail to simulate movement forward
                snake.pop();
            }
        }

        function checkCollision() {
            const head = snake[0];

            // 1. Boundary hits
            if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
                return true;
            }

            // 2. Self hits (ignore evaluating the index 0 head against itself)
            for (let i = 1; i < snake.length; i++) {
                if (head.x === snake[i].x && head.y === snake[i].y) {
                    return true;
                }
            }
            return false;
        }

        function drawGame() {
            // Clear entire screen canvas background
            ctx.fillStyle = '#000000';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // Draw Neon Food block
            ctx.fillStyle = '#ff3333';
            ctx.shadowBlur = 10;
            ctx.shadowColor = '#ff3333';
            ctx.fillRect(food.x + 2, food.y + 2, gridSize - 4, gridSize - 4);

            // Draw Snake blocks
            snake.forEach((part, index) => {
                // Make the snake head a slightly lighter neon shade than the body parts
                ctx.fillStyle = index === 0 ? '#6fff75' : '#4CAF50';
                ctx.shadowBlur = index === 0 ? 8 : 0;
                ctx.shadowColor = '#4CAF50';
                ctx.fillRect(part.x + 1, part.y + 1, gridSize - 2, gridSize - 2);
            });
            
            // Clear shadow configuration properties for alternative render states
            ctx.shadowBlur = 0;
        }

        function changeDirection(event) {
            if (!isRunning) return;

            const keyPressed = event.keyCode;
            
            // Standard Keyboard Keycodes Configuration
            const LEFT = 37,  A_KEY = 65;
            const UP = 38,    W_KEY = 87;
            const RIGHT = 39, D_KEY = 68;
            const DOWN = 40,  S_KEY = 83;

            const goingUp = (dy === -gridSize);
            const goingDown = (dy === gridSize);
            const goingRight = (dx === gridSize);
            const goingLeft = (dx === -gridSize);

            // Conditional filtering rules to prevent full 180-degree self-collisions
            if ((keyPressed === LEFT || keyPressed === A_KEY) && !goingRight) {
                nextDx = -gridSize;
                nextDy = 0;
            }
            if ((keyPressed === UP || keyPressed === W_KEY) && !goingDown) {
                nextDx = 0;
                nextDy = -gridSize;
            }
            if ((keyPressed === RIGHT || keyPressed === D_KEY) && !goingLeft) {
                nextDx = gridSize;
                nextDy = 0;
            }
Editor is loading...
Leave a Comment