Advanced Snake Game

BASIC  CODE:-

 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Advanced Snake Game</title>

    

    <style>

        body {

            display: flex;

            flex-direction: column;

            align-items: center;

            justify-content: center;

            height: 100vh;

            margin: 0;

            background-color: #000; /* Dark background */

            font-family: 'Arial', sans-serif;

            color: #ecf0f1;

        }


        h1 {

            color: #2ecc71; /* Green title */

        }


        #score {

            font-size: 1.5em;

            margin-bottom: 20px;

            color: #f1c40f; /* Yellow score */

        }


        #gameCanvas {

            border: 5px solid #2ecc71; /* Green border */

            background-color: #34495e; /* Canvas background */

            box-shadow: 0 0 20px rgba(46, 204, 113, 0.5); /* Glowing effect */

        }


        .game-over-message {

            position: absolute;

            background-color: rgba(0, 0, 0, 0.8);

            color: white;

            padding: 30px;

            border-radius: 10px;

            text-align: center;

            font-size: 2em;

            display: none; /* Default hidden */

            z-index: 10;

        }

    </style>

</head>

<body>

    <h1>Classic Snake Game</h1>

    <div id="score">Score: 0</div>

    <canvas id="gameCanvas" width="400" height="400"></canvas>

    

    <div class="game-over-message" id="gameOverMessage">

        GAME OVER! <br>

        Your Final Score: <span id="finalScore">0</span> <br>

        Press R to Restart

    </div>


    <script>

        // JavaScript Game Logic

        

        const canvas = document.getElementById('gameCanvas');

        const ctx = canvas.getContext('2d');

        const scoreDisplay = document.getElementById('score');

        const gameOverMessage = document.getElementById('gameOverMessage');

        const finalScoreDisplay = document.getElementById('finalScore');


        const gridSize = 20; // Har box ki size (20px)

        const tileCount = canvas.width / gridSize; // Canvas mein kitne boxes hain (20 boxes)

        let snake = [];

        let food = {};

        let velocityX = 1; // Shuruat mein right ki taraf chalega

        let velocityY = 0;

        let score = 0;

        let gameLoopId;

        let isGameOver = false;


        // --- Game Setup ---

        function resetGame() {

            isGameOver = false;

            gameOverMessage.style.display = 'none';

            score = 0;

            scoreDisplay.textContent = 'Score: 0';

            

            // Snake ko beech mein shuru karein

            snake = [{ x: 10, y: 10 }];

            velocityX = 1;

            velocityY = 0;

            

            placeFood();

            

            // Purana loop band karein aur naya shuru karein (Taki speed control ho)

            if (gameLoopId) clearInterval(gameLoopId);

            gameLoopId = setInterval(gameLoop,300); // Har 100ms mein update hoga

        }


        // Khana (Food) ko randomly place karein

        function placeFood() {

            food.x = Math.floor(Math.random() * tileCount);

            food.y = Math.floor(Math.random() * tileCount);

            

            // Ensure food does not spawn on the snake

            for (let i = 0; i < snake.length; i++) {

                if (snake[i].x === food.x && snake[i].y === food.y) {

                    placeFood(); // Agar snake par aaya toh dobara place karein

                }

            }

        }


        // --- Game Drawing Functions ---

        function drawBoard() {

            // Background clear karein

            ctx.fillStyle = '#34495e';

            ctx.fillRect(0, 0, canvas.width, canvas.height);

        }


        function drawSnake() {

            ctx.fillStyle = '#2ecc71'; // Green color for snake

            for (let i = 0; i < snake.length; i++) {

                ctx.fillRect(snake[i].x * gridSize, snake[i].y * gridSize, gridSize - 1, gridSize - 1);

            }

        }


        function drawFood() {

            ctx.fillStyle = '#e74c3c'; // Red color for food

            ctx.beginPath();

            // Food ko thoda gol (circle) bana dein, thoda alag dikhega

            ctx.arc(

                (food.x * gridSize) + gridSize / 2, 

                (food.y * gridSize) + gridSize / 2, 

                gridSize / 2 - 2, 

                0, 

                Math.PI * 2

            );

            ctx.fill();

        }


        // --- Game Logic ---

        function updateSnake() {

            // Naya head position calculate karein

            let headX = snake[0].x + velocityX;

            let headY = snake[0].y + velocityY;

            

            // Check for wall collision

            if (headX < 0 || headX >= tileCount || headY < 0 || headY >= tileCount) {

                endGame();

                return;

            }

            

            // Check for self collision

            for (let i = 1; i < snake.length; i++) {

                if (headX === snake[i].x && headY === snake[i].y) {

                    endGame();

                    return;

                }

            }


            // Naya head ko aage jod dein

            snake.unshift({ x: headX, y: headY });


            // Check for food consumption

            if (headX === food.x && headY === food.y) {

                score++;

                scoreDisplay.textContent = `Score: ${score}`;

                placeFood(); // Naya khana place karein

                // Body se tail hatayeinge nahi (jisse snake bada ho jaye)

            } else {

                snake.pop(); // Agar khana nahi khaya toh tail hata dein (jisse move karne ka effect aaye)

            }

        }


        function endGame() {

            isGameOver = true;

            clearInterval(gameLoopId);

            finalScoreDisplay.textContent = score;

            gameOverMessage.style.display = 'block';

        }


        // --- Main Game Loop ---

        function gameLoop() {

            if (isGameOver) return;

            

            updateSnake();

            drawBoard();

            drawFood();

            drawSnake();

        }


        // --- Input Handling ---

        document.addEventListener('keydown', (e) => {

            // Arrow Keys ke liye switch case

            switch(e.key) {

                case 'ArrowUp':

                case 'w':

                    // Agar neeche nahi ja rahe toh upar ja sakte hain

                    if (velocityY !== 1) { velocityX = 0; velocityY = -1; }

                    break;

                case 'ArrowDown':

                case 's':

                    // Agar upar nahi ja rahe toh neeche ja sakte hain

                    if (velocityY !== -1) { velocityX = 0; velocityY = 1; }

                    break;

                case 'ArrowLeft':

                case 'a':

                    // Agar right nahi ja rahe toh left ja sakte hain

                    if (velocityX !== 1) { velocityX = -1; velocityY = 0; }

                    break;

                case 'ArrowRight':

                case 'd':

                    // Agar left nahi ja rahe toh right ja sakte hain

                    if (velocityX !== -1) { velocityX = 1; velocityY = 0; }

                    break;

                case 'r':

                case 'R':

                    if (isGameOver) { resetGame(); }

                    break;

            }

        });


        // Game shuru karein

        resetGame();

        

    </script>

</body>

</html>

Post a Comment

Previous Post Next Post