🦌 Sleigh Snake - Christmas Snake Game 🎁

Guide Santa's sleigh around the snowy field and pick up the presents. Every present adds a reindeer to the line! Use the arrow keys, swipe on the field or tap the arrows. Don't hit the fence or your own reindeer!
Presents: 0  |  Best: 0
Press "Start", then choose a direction to set off!

The presents have fallen out of Santa's sack all over the snowy field 🎄, and only the sleigh can pick them up. Steer it with the arrow keys, a swipe on the field or the on-screen arrows. Every present you collect adds a reindeer to the back of the line, and the sleigh goes a little faster each time. Watch out: run into the fence or into your own reindeer and the round is over.

How long a reindeer team can you build before the sleigh crashes? 🎁

Here is the code
CSS
.slg-game {
    text-align: center;
}

.slg-game .instructions {
    max-width: 500px;
    margin: 0 auto 15px;
    font-size: 1em;
    color: #555;
}

.slg-info {
    margin-bottom: 10px;
    font-size: 1.2em;
}

.slg-canvas {
    display: block;
    width: 100%;
    max-width: 360px;
    height: auto;
    margin: 0 auto;
    border: 3px solid #1d6b3a;
    border-radius: 12px;
    background: #eef6fb;
    touch-action: none;
    user-select: none;
    -webkit-user-select: none;
}

.slg-pad {
    display: grid;
    grid-template-columns: repeat(3, 56px);
    grid-template-rows: repeat(2, 48px);
    gap: 6px;
    justify-content: center;
    margin: 12px auto 0;
    touch-action: manipulation;
}

.slg-dir {
    font-size: 1.3em;
    border: none;
    border-radius: 10px;
    background: #1d6b3a;
    color: #fff;
    cursor: pointer;
    touch-action: manipulation;
    user-select: none;
    -webkit-user-select: none;
}

.slg-dir:active {
    background: #c0392b;
}

.slg-up {
    grid-column: 2;
    grid-row: 1;
}

.slg-left {
    grid-column: 1;
    grid-row: 2;
}

.slg-down {
    grid-column: 2;
    grid-row: 2;
}

.slg-right {
    grid-column: 3;
    grid-row: 2;
}

.slg-message {
    min-height: 1.5em;
    margin: 12px 0;
    font-size: 1.1em;
    font-weight: bold;
    color: #c0392b;
}
HTML
<div class="slg-game">
    <h1>🦌 Sleigh Snake - Christmas Snake Game 🎁</h1>
    <div class="instructions">
        Guide Santa's sleigh around the snowy field and pick up the presents. Every present adds a reindeer to the line! Use the arrow keys, swipe on the field or tap the arrows. Don't hit the fence or your own reindeer!
    </div>
    <div class="slg-info">Presents: <span id="slgScore">0</span> &nbsp;|&nbsp; Best: <span id="slgBest">0</span></div>
    <canvas id="slgCanvas" class="slg-canvas" width="360" height="360" aria-label="Snowy field with Santa's sleigh"></canvas>
    <div class="slg-pad" id="slgPad">
        <button class="slg-dir slg-up" data-dir="up" aria-label="Up">▲</button>
        <button class="slg-dir slg-left" data-dir="left" aria-label="Left">◀</button>
        <button class="slg-dir slg-right" data-dir="right" aria-label="Right">▶</button>
        <button class="slg-dir slg-down" data-dir="down" aria-label="Down">▼</button>
    </div>
    <div class="slg-message" id="slgMessage">Press "Start", then choose a direction to set off!</div>
    <button class="start-btn" id="slgStart">Start</button>
</div>
JS
const canvas = document.getElementById('slgCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('slgScore');
const bestDisplay = document.getElementById('slgBest');
const message = document.getElementById('slgMessage');
const startButton = document.getElementById('slgStart');
const pad = document.getElementById('slgPad');
const hiddenScore = document.getElementById('hiddenScore');

const CELLS = 15;
const SIZE = canvas.width / CELLS;
const DIRS = {
    up: { x: 0, y: -1 },
    down: { x: 0, y: 1 },
    left: { x: -1, y: 0 },
    right: { x: 1, y: 0 }
};
const GIFT_COLORS = ['#e63946', '#2a9d8f', '#f4a261', '#7b5ea7'];

let snake, dir, queue, gift, score, running, waiting, lastTime, acc, animationId, flakes, sparkles;
let best = 0;

try {
    best = parseInt(localStorage.getItem('slgBest'), 10) || 0;
} catch (e) {
    best = 0;
}
bestDisplay.textContent = best;

// The share buttons are rendered after this script, so look them up when needed.
function setShareButtons(display) {
    const shareButtons = document.querySelector('.share-buttons');
    if (shareButtons) {
        shareButtons.style.display = display;
    }
}

function stepTime() {
    // Seconds per move: the sleigh speeds up with every present, down to a minimum
    return Math.max(0.075, 0.2 - score * 0.006);
}

function placeGift() {
    const free = [];
    for (let x = 0; x < CELLS; x++) {
        for (let y = 0; y < CELLS; y++) {
            if (!snake.some(function (s) { return s.x === x && s.y === y; })) {
                free.push({ x: x, y: y });
            }
        }
    }
    const cell = free[Math.floor(Math.random() * free.length)];
    gift = { x: cell.x, y: cell.y, color: GIFT_COLORS[Math.floor(Math.random() * GIFT_COLORS.length)] };
}

function makeFlakes() {
    flakes = [];
    for (let i = 0; i < 40; i++) {
        flakes.push({
            x: Math.random() * canvas.width,
            y: Math.random() * canvas.height,
            r: 1 + Math.random() * 2,
            v: 15 + Math.random() * 25
        });
    }
}

function reset() {
    snake = [{ x: 7, y: 7 }, { x: 6, y: 7 }, { x: 5, y: 7 }];
    dir = null;
    queue = [];
    score = 0;
    acc = 0;
    sparkles = [];
    scoreDisplay.textContent = score;
    hiddenScore.value = 0;
    placeGift();
}

function turn(name) {
    if (!running) {
        return;
    }
    const next = DIRS[name];
    const last = queue.length ? queue[queue.length - 1] : dir;
    // No turning back into the reindeer right behind the sleigh
    if (last && last.x === -next.x && last.y === -next.y) {
        return;
    }
    if (last && last.x === next.x && last.y === next.y) {
        return;
    }
    if (!dir && next.x === -1) {
        return;
    }
    if (queue.length < 3) {
        queue.push(next);
    }
    if (waiting) {
        waiting = false;
        message.textContent = 'Collect the presents! 🎁';
    }
}

function step() {
    if (queue.length) {
        dir = queue.shift();
    }
    if (!dir) {
        return;
    }
    const head = { x: snake[0].x + dir.x, y: snake[0].y + dir.y };
    const eating = head.x === gift.x && head.y === gift.y;
    // The last reindeer moves away this step unless the line grows
    const body = eating ? snake : snake.slice(0, -1);
    const hitWall = head.x < 0 || head.y < 0 || head.x >= CELLS || head.y >= CELLS;
    const hitSelf = body.some(function (s) { return s.x === head.x && s.y === head.y; });
    if (hitWall || hitSelf) {
        gameOver(hitWall ? 'The sleigh hit the fence!' : 'The sleigh ran into a reindeer!');
        return;
    }
    snake.unshift(head);
    if (eating) {
        score++;
        scoreDisplay.textContent = score;
        hiddenScore.value = score;
        for (let i = 0; i < 10; i++) {
            const a = Math.random() * Math.PI * 2;
            sparkles.push({
                x: (gift.x + 0.5) * SIZE,
                y: (gift.y + 0.5) * SIZE,
                vx: Math.cos(a) * 80,
                vy: Math.sin(a) * 80,
                life: 0.5,
                color: gift.color
            });
        }
        if (snake.length === CELLS * CELLS) {
            gameOver('The whole field is full of reindeer!');
            return;
        }
        placeGift();
    } else {
        snake.pop();
    }
}

function drawField() {
    ctx.fillStyle = '#eef6fb';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#e1eef7';
    for (let x = 0; x < CELLS; x++) {
        for (let y = 0; y < CELLS; y++) {
            if ((x + y) % 2 === 0) {
                ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);
            }
        }
    }
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
    flakes.forEach(function (f) {
        ctx.beginPath();
        ctx.arc(f.x, f.y, f.r, 0, Math.PI * 2);
        ctx.fill();
    });
}

function drawGift() {
    const x = gift.x * SIZE + 4;
    const y = gift.y * SIZE + 4;
    const s = SIZE - 8;
    ctx.fillStyle = gift.color;
    ctx.fillRect(x, y, s, s);
    ctx.fillStyle = '#ffd166';
    ctx.fillRect(x + s / 2 - 2, y, 4, s);
    ctx.fillRect(x, y + s / 2 - 2, s, 4);
}

function drawSnake() {
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = Math.floor(SIZE * 0.8) + 'px sans-serif';
    for (let i = snake.length - 1; i >= 0; i--) {
        const s = snake[i];
        const cx = (s.x + 0.5) * SIZE;
        const cy = (s.y + 0.5) * SIZE;
        if (i > 0) {
            // Harness linking each reindeer to the one in front
            const p = snake[i - 1];
            ctx.strokeStyle = '#8b5a2b';
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.moveTo(cx, cy);
            ctx.lineTo((p.x + 0.5) * SIZE, (p.y + 0.5) * SIZE);
            ctx.stroke();
        }
    }
    for (let i = snake.length - 1; i >= 0; i--) {
        const s = snake[i];
        const cx = (s.x + 0.5) * SIZE;
        const cy = (s.y + 0.5) * SIZE;
        if (i === 0) {
            ctx.fillStyle = '#c0392b';
            ctx.beginPath();
            ctx.arc(cx, cy, SIZE * 0.48, 0, Math.PI * 2);
            ctx.fill();
            ctx.fillText('🎅', cx, cy + 1);
        } else {
            ctx.fillText('🦌', cx, cy + 1);
        }
    }
}

function drawSparkles() {
    sparkles.forEach(function (p) {
        ctx.globalAlpha = Math.max(0, p.life * 2);
        ctx.fillStyle = p.color;
        ctx.fillRect(p.x - 2, p.y - 2, 4, 4);
    });
    ctx.globalAlpha = 1;
}

function draw() {
    drawField();
    drawGift();
    drawSnake();
    drawSparkles();
}

function update(dt) {
    flakes.forEach(function (f) {
        f.y += f.v * dt;
        if (f.y > canvas.height) {
            f.y = -3;
            f.x = Math.random() * canvas.width;
        }
    });
    sparkles.forEach(function (p) {
        p.x += p.vx * dt;
        p.y += p.vy * dt;
        p.life -= dt;
    });
    sparkles = sparkles.filter(function (p) { return p.life > 0; });
    if (running && !waiting) {
        acc += dt;
        while (running && acc >= stepTime()) {
            acc -= stepTime();
            step();
        }
    }
}

function loop(time) {
    if (lastTime === null) {
        lastTime = time;
    }
    const dt = Math.min(0.1, (time - lastTime) / 1000);
    lastTime = time;
    update(dt);
    draw();
    animationId = requestAnimationFrame(loop);
}

function startGame() {
    reset();
    running = true;
    waiting = true;
    setShareButtons('none');
    startButton.textContent = 'Restart';
    message.textContent = 'Choose a direction to set off! ⬆️➡️⬇️';
}

function gameOver(reason) {
    running = false;
    let text = reason + ' You delivered ' + score + ' present' + (score === 1 ? '' : 's') + '.';
    if (score > best) {
        best = score;
        bestDisplay.textContent = best;
        try {
            localStorage.setItem('slgBest', String(best));
        } catch (e) {
            // Storage unavailable: keep the best score for this visit only
        }
        if (score > 0) {
            text += ' New best! 🏆';
        }
    }
    message.textContent = text;
    startButton.textContent = 'Play again';
    hiddenScore.value = score;
    setShareButtons('flex');
}

document.addEventListener('keydown', function (e) {
    const keys = {
        ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right',
        w: 'up', s: 'down', a: 'left', d: 'right', W: 'up', S: 'down', A: 'left', D: 'right'
    };
    if (keys[e.key] && running) {
        e.preventDefault();
        turn(keys[e.key]);
    }
});

pad.addEventListener('pointerdown', function (e) {
    const button = e.target.closest('.slg-dir');
    if (button) {
        e.preventDefault();
        turn(button.getAttribute('data-dir'));
    }
});

let touchStart = null;
canvas.addEventListener('touchstart', function (e) {
    e.preventDefault();
    touchStart = { x: e.touches[0].clientX, y: e.touches[0].clientY };
}, { passive: false });

canvas.addEventListener('touchmove', function (e) {
    e.preventDefault();
    if (!touchStart) {
        return;
    }
    const dx = e.touches[0].clientX - touchStart.x;
    const dy = e.touches[0].clientY - touchStart.y;
    if (Math.abs(dx) < 20 && Math.abs(dy) < 20) {
        return;
    }
    if (Math.abs(dx) > Math.abs(dy)) {
        turn(dx > 0 ? 'right' : 'left');
    } else {
        turn(dy > 0 ? 'down' : 'up');
    }
    touchStart = { x: e.touches[0].clientX, y: e.touches[0].clientY };
}, { passive: false });

canvas.addEventListener('touchend', function () {
    touchStart = null;
});

startButton.addEventListener('click', startGame);

running = false;
waiting = false;
lastTime = null;
makeFlakes();
reset();
animationId = requestAnimationFrame(loop);