Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.3 kB
1
Indexable
Never
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

// 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));
        food.y = 32 + (Math.random() * (canvas.height - 64));
    }

    // Update snake body segments
    snake.segments.push({x: snake.x, y: snake.y});
    while (snake.segments.length > snake.length) {
        snake.segments.shift();
    }
};

// Draw