Untitled

 avatar
unknown
plain_text
3 years ago
2.8 kB
5
Indexable
<!doctype html>
<html>
<head>
    <title>Snake Game</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="game-canvas" width="512" height="480"></canvas>
    <script>
        // Create the canvas
        var canvas = document.getElementById("game-canvas");
        var ctx = canvas.getContext("2d");

        // Background image
        var bgReady = false;
        var bgImage = new Image();
        bgImage.onload = function () {
            bgReady = true;
        };
        bgImage.src = "background.png";

        // Snake object
        var snake = {
            x: 0,
            y: 0,
            // Snake movement speed.
            // Increase by 20 for each food the snake eats
            speed: 20,
            // Initial snake length
            length: 3,
            // Snake body segments
            segments: [{x: 200, y: 200}, {x: 220, y: 200}, {x: 240, y: 200}]
        };

        // Food object
        var food = {
            x: 0,
            y: 0
        };

        // Handle keyboard controls
        var keysDown = {};

        addEventListener("keydown", function (e) {
            keysDown[e.keyCode] = true;
        }, false);

        addEventListener("keyup", function (e) {
            delete keysDown[e.keyCode];
        }, false);

        // Reset the game when the player catches a food
        var reset = function () {
            snake.x = 0;
            snake.y = 0;

            // Throw the food somewhere on the screen randomly
            food.x = 32 + (Math.random() * (canvas.width - 64));
            food.y = 32 + (Math.random() * (canvas.height - 64));
        };

        // Update game objects
        var update = function (modifier) {
            // Update snake position based on the keyboard input
            if (38 in keysDown) { // Player holding up
                snake.y -= snake.speed * modifier;
            }
            if (40 in keysDown) { // Player holding down
                snake.y += snake.speed * modifier;
            }
            if (37 in keysDown) { // Player holding left
                snake.x -= snake.speed * modifier;
            }
            if (39 in keysDown) { // Player holding right
                snake.x += snake.speed * modifier;
            }

            // Snake ate food?
            if (snake.x <= (food.x + 32)
                && food.x <= (snake.x + 32)
                && snake.y <= (food.y + 32)
                && food.y <= (snake.y + 32)) {
                // Increase snake length and speed
                snake.length += 1;
                snake.speed += 20;

                // Generate new food
                food.x = 32 + (Math.random() * (canvas.width - 64));
Editor is loading...