<!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="styles.css"> <!-- Link to CSS file -->
</head>
<body>
    <div id="gameArea">
        <!-- Snake and Food will be dynamically created here -->
    </div>
    <script src="script.js"></script> <!-- Link to JavaScript file -->
</body>
</html/* Styles for the game area */
#gameArea {
    width: 400px;
    height: 400px;
    border: 2px solid black;
    position: relative;
}

/* Styles for the snake */
.snakePart {
    width: 20px;
    height: 20px;
    background-color: green;
    position: absolute;
}

/* Styles for the food */
.food {
    width: 20px;
    height: 20px;
    background-color: red;
    position: absolute;
}
document.addEventListener("DOMContentLoaded", function() {
    const gameArea = document.getElementById("gameArea");
    const blockSize = 20; // Size of each block in pixels
    let snake = [{ x: 200, y: 200 }]; // Initial snake position
    let food = createFoodPosition(); // Initial food position
    let dx = 0; // Initial movement direction
    let dy = 0;
    let gameLoop;

    function createFoodPosition() {
        return {
            x: Math.floor(Math.random() * (gameArea.clientWidth / blockSize)) * blockSize,
            y: Math.floor(Math.random() * (gameArea.clientHeight / blockSize)) * blockSize
        };
    }

    function draw() {
        // Clear previous frame
        gameArea.innerHTML = '';

        // Draw snake
        snake.forEach(segment => {
            const snakePart = document.createElement("div");
            snakePart.classList.add("snakePart");
            snakePart.style.left = segment.x + "px";
            snakePart.style.top = segment.y + "px";
            gameArea.appendChild(snakePart);
        });

        // Draw food
        const foodElement = document.createElement("div");
        foodElement.classList.add("food");
        foodElement.style.left = food.x + "px";
        foodElement.style.top = food.y + "px";
        gameArea.appendChild(foodElement);
    }

    function update() {
        // Move snake
        const head = { x: snake[0].x + dx, y: snake[0].y + dy };
        snake.unshift(head);

        // Check for collision with food
        if (head.x === food.x && head.y === food.y) {
            food = createFoodPosition();
        } else {
            snake.pop();
        }

        // Check for collision with walls
        if (head.x < 0 || head.x >= gameArea.clientWidth || head.y < 0 || head.y >= gameArea.clientHeight) {
            clearInterval(gameLoop);
            alert("Game Over!");
        }

        // Check for collision with self
        for (let i = 1; i < snake.length; i++) {
            if (head.x === snake[i].x && head.y === snake[i].y) {
                clearInterval(gameLoop);
                alert("Game Over!");
            }
        }
    }

    function gameLoopFunction() {
        update();
        draw();
    }

    // Start the game loop
    gameLoop = setInterval(gameLoopFunction, 100);

    // Handle keyboard input
    document.addEventListener("keydown", function(event) {
        switch (event.key) {
            case "ArrowUp":
                dx = 0;
                dy = -blockSize;
                break;
            case "ArrowDown":
                dx = 0;
                dy = blockSize;
                break;
            case "ArrowLeft":
                dx = -blockSize;
                dy = 0;
                break;
            case "ArrowRight":
                dx = blockSize;
                dy = 0;
                break;
        }
    });
});
<!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>
        /* Styles for the game area */
        #gameArea {
            width: 400px;
            height: 400px;
            border: 2px solid black;
            position: relative;
        }

        /* Styles for the snake */
        .snakePart {
            width: 20px;
            height: 20px;
            background-color: green;
            position: absolute;
        }

        /* Styles for the food */
        .food {
            width: 20px;
            height: 20px;
            background-color: red;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="gameArea"></div>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const gameArea = document.getElementById("gameArea");
            const blockSize = 20; // Size of each block in pixels
            let snake = [{ x: 200, y: 200 }]; // Initial snake position
            let food = createFoodPosition(); // Initial food position
            let dx = 0; // Initial movement direction
            let dy = 0;
            let gameLoop;

            function createFoodPosition() {
                return {
                    x: Math.floor(Math.random() * (gameArea.clientWidth / blockSize)) * blockSize,
                    y: Math.floor(Math.random() * (gameArea.clientHeight / blockSize)) * blockSize
                };
            }

            function draw() {
                // Clear previous frame
                gameArea.innerHTML = '';

                // Draw snake
                snake.forEach(segment => {
                    const snakePart = document.createElement("div");
                    snakePart.classList.add("snakePart");
                    snakePart.style.left = segment.x + "px";
                    snakePart.style.top = segment.y + "px";
                    gameArea.appendChild(snakePart);
                });

                // Draw food
                const foodElement = document.createElement("div");
                foodElement.classList.add("food");
                foodElement.style.left = food.x + "px";
                foodElement.style.top = food.y + "px";
                gameArea.appendChild(foodElement);
            }

            function update() {
                // Move snake
                const head = { x: snake[0].x + dx, y: snake[0].y + dy };
                snake.unshift(head);

                // Check for collision with food
                if (head.x === food.x && head.y === food.y) {
                    food = createFoodPosition();
                } else {
                    snake.pop();
                }

                // Check for collision with walls
                if (head.x < 0 || head.x >= gameArea.clientWidth || head.y < 0 || head.y >= gameArea.clientHeight) {
                    clearInterval(gameLoop);
                    alert("Game Over!");
                }

                // Check for collision with self
                for (let i = 1; i < snake.length; i++) {
                    if (head.x === snake[i].x && head.y === snake[i].y) {
                        clearInterval(gameLoop);
                        alert("Game Over!");
                    }
                }
            }

            function gameLoopFunction() {
                update();
                draw();
            }

            // Start the game loop
            gameLoop = setInterval(gameLoopFunction, 100);

            // Handle keyboard input
            document.addEventListener("keydown", function(event) {
                switch (event.key) {
                    case "ArrowUp":
                        dx = 0;
                        dy = -blockSize;
                        break;
                    case "ArrowDown":
                        dx = 0;
                        dy = blockSize;
                        break;
                    case "ArrowLeft":
                        dx = -blockSize;
                        dy = 0;
                        break;
                    case "ArrowRight":
                        dx = blockSize;
                        dy = 0;
                        break;
                }
            });
        });
    </script>
</body>
</html>


 
by

HTML Online Editor & Compiler

Write, Run & Share HTML code online using OneCompiler's HTML online Code editor for free. It's one of the robust, feature-rich online Code editor for HTML language, running on the latest version HTML5. Getting started with the OneCompiler's HTML compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as HTML. You can also specify the stylesheet information in styles.css tab and scripts information in scripts.js tab and start coding.

About HTML

HTML(Hyper Text Markup language) is the standard markup language for Web pages, was created by Berners-Lee in the year 1991. Almost every web page over internet might be using HTML.

Syntax help

Fundamentals

  • Any HTML document must start with document declaration <!DOCTYPE html>
  • HTML documents begin with <html> and ends with </html>
  • Headings are defined with <h1> to <h6> where <h1> is the highest important heading and <h6> is the least important sub-heading.
  • Paragrahs are defined in <p>..</p> tag.
  • Links are defined in <a> tag.

    Example:

    <a href="https://onecompiler.com/html">HTML online compiler</a>
    
  • Images are defined in <img> tag, where src attribute consists of image name.
  • Buttons are defined in <button>..</button> tag
  • Lists are defined in <ul> for unordered/bullet list and <ol> for ordered/number list, and the list items are defined in <li>.

HTML Elements and Attributes

  • HTML element is everything present from start tag to end tag.
  • The text present between start and end tag is called HTML element content.
  • Anything can be a tagname but it's preferred to put the meaningful title to the content present as tag name.
  • Do not forget the end tag.
  • Elements with no content are called empty elements.
  • Elements can have attributes which provides additional information about the element.
  • In the below example, href is an attribute and a is the tag name.

    Example:

    <a href="https://onecompiler.com/html">HTML online compiler</a>
    

CSS

CSS(cascading style sheets) describes how HTML elements will look on the web page like color, font-style, font-size, background color etc.

Example:

Below is a sample style sheet which displays heading in green and in Candara font with padding space of 25px.

body{
  padding: 25px;
}
.title {
	color: #228B22;
	font-family: Candara;
}

HTML Tables

  • HTML Tables are defined in <table> tag.
  • Table row should be defined in <tr> tag
  • Table header should be defined in <th> tag
  • Table data should be defined in <td> tag
  • Table caption should be defined in <caption> tag

HTML-Javascript

  • Javascript is used in HTML pages to make them more interactive.
  • <script> is the tag used to write scripts in HTML
  • You can either reference a external script or write script code in this tag.

Example

<script src="script.js"></script>