Snake game

#4
by sekju - opened

😃: Write the code of the snake game. Use HTML, CSS and JavaScript in one file. Add scores and lives logic.
🤖: Here's a simple implementation of the Snake game using HTML, CSS, and JavaScript in a single file. This version includes scores and lives logic:

<!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>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #eee;
            font-family: Arial, sans-serif;
            text-align: center;
        }
        .game-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .game-area {
            position: relative;
            width: 400px;
            height: 400px;
            margin: 0 auto;
            border: 1px solid #ccc;
        }
        .snake, .food {
            position: absolute;
            width: 20px;
            height: 20px;
            border: 1px solid #000;
            background-color: #3498db;
        }
        .score {
            margin-top: 20px;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <div class="game-area">
            <div class="snake"></div>
            <div class="food"></div>
        </div>
        <div class="score">Score: <span id="score">0</span></div>
        <button id="startButton">Start Game</button>
    </div>

    <script>
        const gameArea = document.querySelector('.game-area');
        const snakeElement = document.querySelector('.snake');
        const foodElement = document.querySelector('.food');
        const scoreElement = document.getElementById('score');
        const startButton = document.getElementById('startButton');

        const gridSize = 20;
        const initialSnakeLength = 3;
        const initialSnakePositions = [{ x: 0, y: 0 }, { x: 0, y: -1 }, { x: 0, y: -2 }];
        const directions = {
            UP: 'up',
            DOWN: 'down',
            LEFT: 'left',
            RIGHT: 'right'
        };
        let currentDirection = directions.RIGHT;
        let newDirection = directions.RIGHT;

        let intervalId;
        let snakePositions = [...initialSnakePositions];
        let foodPosition;
        let score = 0;
        let lives = 3;

        function placeFood() {
            foodPosition = {
                x: Math.floor(Math.random() * (gameArea.clientWidth / gridSize)) * gridSize,
                y: Math.floor(Math.random() * (gameArea.clientHeight / gridSize)) * gridSize
            };
            foodElement.style.left = foodPosition.x + 'px';
            foodElement.style.top = foodPosition.y + 'px';
        }

        function moveSnake() {
            const head = snakePositions[0];
            const newHead = {
                x: head.x + (currentDirection === directions.RIGHT ? gridSize : currentDirection === directions.LEFT ? -gridSize : 0),
                y: head.y + (currentDirection === directions.DOWN ? gridSize : currentDirection === directions.UP ? -gridSize : 0)
            };

            // Check for collision with walls
            if (newHead.x < 0 || newHead.x >= gameArea.clientWidth || newHead.y < 0 || newHead.y >= gameArea.clientHeight) {
                clearInterval(intervalId);
                alert('Game Over! Press OK to restart.');
                location.reload();
            }

            // Check for collision with itself
            if (snakePositions.some(pos => pos.x === newHead.x && pos.y === newHead.y)) {
                clearInterval(intervalId);
                alert('Game Over! Press OK to restart.');
                location.reload();
            }

            // Check for food collision
            if (newHead.x === foodPosition.x && newHead.y === foodPosition.y) {
                score += 10;
                scoreElement.textContent = score;
                placeFood();
                snakePositions = [{ x: newHead.x, y: newHead.y }, ...snakePositions];
            } else {
                snakePositions = [{ x: newHead.x, y: newHead.y }, ...snakePositions.slice(0, initialSnakeLength)];
            }

            // Update snake position on screen
            snakeElement.style.left = head.x + 'px';
            snakeElement.style.top = head.y + 'px';

            // Update snake body positions
            for (let i = 1; i < snakePositions.length; i++) {
                const currentPos = snakePositions[i];
                const prevPos = snakePositions[i - 1];
                snakeElement.children[i].style.left = currentPos.x + 'px';
                snakeElement.children[i].style.top = currentPos.y + 'px';
            }
        }

        function handleKeyboardControls(event) {
            if (event.keyCode === 37 && currentDirection !== directions.RIGHT) {
                newDirection = directions.LEFT;
            } else if (event.keyCode === 38 && currentDirection !== directions.DOWN) {
                newDirection = directions.UP;
            } else if (event.keyCode === 39 && currentDirection !== directions.LEFT) {
                newDirection = directions.RIGHT;
            } else if (event.keyCode === 40 && currentDirection !== directions.UP) {
                newDirection = directions.DOWN;
            }
        }

        function startGame() {
            intervalId = setInterval(moveSnake, 100);
            document.addEventListener('keydown', handleKeyboardControls);
            placeFood();
        }

        startButton.addEventListener('click', startGame);

        for (let i = 0; i < initialSnakeLength; i++) {
            const newSegment = document.createElement('div');
            newSegment.style.left = initialSnakePositions[i].x + 'px';
            newSegment.style.top = initialSnakePositions[i].y + 'px';
            snakeElement.appendChild(newSegment);
        }
    </script>
</body>
</html>

This code sets up the Snake game with a start button, keyboard controls, food spawning, and collision detection. It also includes a score display and lives logic. The snake grows when it eats food, and the game ends when the snake collides with itself or the walls.

sarahooker changed discussion status to closed

Sign up or log in to comment