⛷️ Slalom Rush - Ski Game 🏔️

Steer your skier between the red and blue flags of every gate. Drag or tap left and right, or use the arrow keys. Miss three gates or hit a tree and your run is over!
Gates: 0  |  Lives: ❤️❤️❤️  |  Best: 0
Press "Start", then move to drop in!

The ski season is opening in the mountains ⛷️, and the slalom course is ready. Steer your skier between the red and blue flags of every gate while the slope gets faster and the gates get narrower. Drag or tap left and right on mobile, hold the mouse on desktop, or use the arrow keys. Each gate you pass scores a point; miss three gates and your run is over, and crashing into a tree 🌲 ends it straight away.

How many gates can you pass before the bottom of the slope?

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

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

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

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

.slalom-message {
    min-height: 1.5em;
    margin: 12px 0;
    font-size: 1.1em;
    font-weight: bold;
    color: #1d4e89;
}
HTML
<div class="slalom-game">
    <h1>⛷️ Slalom Rush - Ski Game 🏔️</h1>
    <div class="instructions">
        Steer your skier between the red and blue flags of every gate. Drag or tap left and right, or use the arrow keys. Miss three gates or hit a tree and your run is over!
    </div>
    <div class="slalom-info">Gates: <span id="slalomScore">0</span> &nbsp;|&nbsp; Lives: <span id="slalomLives">❤️❤️❤️</span> &nbsp;|&nbsp; Best: <span id="slalomBest">0</span></div>
    <canvas id="slalomCanvas" class="slalom-canvas" width="360" height="540" aria-label="Ski slalom slope"></canvas>
    <div class="slalom-message" id="slalomMessage">Press "Start", then move to drop in!</div>
    <button class="start-btn" id="slalomStart">Start</button>
</div>
JS
const canvas = document.getElementById('slalomCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('slalomScore');
const livesDisplay = document.getElementById('slalomLives');
const bestDisplay = document.getElementById('slalomBest');
const message = document.getElementById('slalomMessage');
const startButton = document.getElementById('slalomStart');
const hiddenScore = document.getElementById('hiddenScore');

const W = canvas.width;
const H = canvas.height;
const SKIER_Y = H * 0.72;
const SKIER_SPEED = 260; // px per second when steering with keys
const MAX_LIVES = 3;

let skierX, targetX, speed, gates, trees, snow, score, lives, running, waiting, lastTime, animationId, nextGate, nextTree, keys, lean, flash;
let best = 0;

try {
    best = parseInt(localStorage.getItem('slalomBest'), 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 hearts(n) {
    let s = '';
    for (let i = 0; i < MAX_LIVES; i++) {
        s += i < n ? '❤️' : '🤍';
    }
    return s;
}

function reset() {
    skierX = W / 2;
    targetX = null;
    speed = 170;
    gates = [];
    trees = [];
    snow = [];
    score = 0;
    lives = MAX_LIVES;
    nextGate = 60;
    nextTree = 140;
    keys = { left: false, right: false };
    lean = 0;
    flash = 0;
    for (let i = 0; i < 40; i++) {
        snow.push({ x: Math.random() * W, y: Math.random() * H, r: 1 + Math.random() * 2 });
    }
    scoreDisplay.textContent = 0;
    livesDisplay.textContent = hearts(lives);
    hiddenScore.value = 0;
}

function gapWidth() {
    // Gates narrow as the score climbs, down to a minimum
    return Math.max(70, 130 - score * 2.2);
}

function addGate() {
    const gap = gapWidth();
    const margin = 30;
    const centre = margin + gap / 2 + Math.random() * (W - 2 * margin - gap);
    gates.push({ y: H + 30, centre: centre, gap: gap, red: gates.length % 2 === 0, done: false, result: '' });
}

function addTree() {
    // Trees stand away from the next gate's opening
    const side = Math.random() < 0.5;
    const x = side ? 12 + Math.random() * 50 : W - 12 - Math.random() * 50;
    let y = H + 40;
    const last = gates[gates.length - 1];
    if (last && Math.abs(last.y - y) < 70) {
        y = last.y + 90; // never right next to a gate
    }
    trees.push({ x: x, y: y, size: 26 + Math.random() * 10 });
}

function startGame() {
    cancelAnimationFrame(animationId);
    reset();
    running = true;
    waiting = true;
    setShareButtons('none');
    startButton.textContent = 'Restart';
    message.textContent = 'Drag, tap or press an arrow key to drop in!';
    draw();
}

function go() {
    if (running && waiting) {
        waiting = false;
        message.textContent = 'Go! Ski between the flags!';
        lastTime = performance.now();
        animationId = requestAnimationFrame(loop);
    }
}

function loseLife(text) {
    lives -= 1;
    livesDisplay.textContent = hearts(lives);
    flash = 0.35;
    message.textContent = text;
    if (lives <= 0) {
        endGame();
    }
}

function endGame() {
    running = false;
    cancelAnimationFrame(animationId);
    if (score > best) {
        best = score;
        bestDisplay.textContent = best;
        try {
            localStorage.setItem('slalomBest', String(best));
        } catch (e) {
            // ignore storage errors
        }
        message.textContent = 'Run over! New best: ' + score + ' gates 🏆';
    } else {
        message.textContent = 'Run over! You passed ' + score + ' gates. Best: ' + best;
    }
    setShareButtons('flex');
    draw();
}

function update(dt) {
    // Steering: pointer target, or keys
    if (targetX !== null) {
        const diff = targetX - skierX;
        const step = Math.sign(diff) * Math.min(Math.abs(diff), SKIER_SPEED * 1.6 * dt);
        skierX += step;
        lean = Math.max(-1, Math.min(1, diff / 40));
    } else if (keys.left || keys.right) {
        const dir = (keys.right ? 1 : 0) - (keys.left ? 1 : 0);
        skierX += dir * SKIER_SPEED * dt;
        lean = dir;
    } else {
        lean *= 0.85;
    }
    skierX = Math.max(14, Math.min(W - 14, skierX));

    // The slope speeds up slowly
    speed = Math.min(380, speed + 4 * dt);
    const dy = speed * dt;

    nextGate -= dy;
    if (nextGate <= 0) {
        addGate();
        nextGate = 150 + Math.random() * 60;
    }
    nextTree -= dy;
    if (nextTree <= 0) {
        addTree();
        nextTree = 160 + Math.random() * 120;
    }

    gates.forEach(function (gate) {
        gate.y -= dy;
        if (!gate.done && gate.y <= SKIER_Y) {
            gate.done = true;
            const half = gate.gap / 2;
            if (skierX > gate.centre - half && skierX < gate.centre + half) {
                score += 1;
                scoreDisplay.textContent = score;
                hiddenScore.value = score;
                gate.result = 'ok';
            } else {
                gate.result = 'miss';
                loseLife('Missed a gate! ' + (lives - 1 > 0 ? (lives - 1) + ' left' : ''));
            }
        }
    });
    gates = gates.filter(function (gate) { return gate.y > -40; });

    trees.forEach(function (tree) {
        tree.y -= dy;
        if (!tree.hit && Math.abs(tree.y - SKIER_Y) < tree.size * 0.45 && Math.abs(tree.x - skierX) < tree.size * 0.45) {
            tree.hit = true;
            lives = 1;
            loseLife('Ouch, a tree! 🌲');
        }
    });
    trees = trees.filter(function (tree) { return tree.y > -50; });

    snow.forEach(function (flake) {
        flake.y -= dy * 0.6;
        if (flake.y < 0) {
            flake.y = H;
            flake.x = Math.random() * W;
        }
    });

    if (flash > 0) {
        flash -= dt;
    }
}

function drawFlag(x, y, colour) {
    ctx.strokeStyle = '#333';
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.moveTo(x, y + 18);
    ctx.lineTo(x, y - 18);
    ctx.stroke();
    ctx.fillStyle = colour;
    ctx.beginPath();
    ctx.moveTo(x, y - 18);
    ctx.lineTo(x + (colour === '#d62828' ? 16 : -16), y - 11);
    ctx.lineTo(x, y - 4);
    ctx.closePath();
    ctx.fill();
}

function draw() {
    // Snow slope
    const gradient = ctx.createLinearGradient(0, 0, 0, H);
    gradient.addColorStop(0, '#e6f1ff');
    gradient.addColorStop(1, '#ffffff');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, W, H);

    ctx.fillStyle = 'rgba(160, 190, 220, 0.6)';
    (snow || []).forEach(function (flake) {
        ctx.beginPath();
        ctx.arc(flake.x, flake.y, flake.r, 0, Math.PI * 2);
        ctx.fill();
    });

    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    (gates || []).forEach(function (gate) {
        const colour = gate.red ? '#d62828' : '#1d4ed8';
        const half = gate.gap / 2;
        if (gate.result === 'ok') {
            ctx.fillStyle = 'rgba(34, 197, 94, 0.15)';
            ctx.fillRect(gate.centre - half, gate.y - 20, gate.gap, 40);
        }
        drawFlag(gate.centre - half, gate.y, colour);
        drawFlag(gate.centre + half, gate.y, colour);
    });

    (trees || []).forEach(function (tree) {
        ctx.font = tree.size + 'px serif';
        ctx.fillText('🌲', tree.x, tree.y);
    });

    // Skier
    ctx.save();
    ctx.translate(skierX, SKIER_Y);
    ctx.rotate(lean * 0.35);
    ctx.font = '32px serif';
    ctx.scale(lean < -0.1 ? -1 : 1, 1);
    ctx.fillText('⛷️', 0, 0);
    ctx.restore();

    if (flash > 0) {
        ctx.fillStyle = 'rgba(214, 40, 40, ' + (flash * 0.8) + ')';
        ctx.fillRect(0, 0, W, H);
    }

    if (waiting && running) {
        ctx.fillStyle = 'rgba(29, 78, 137, 0.85)';
        ctx.font = 'bold 20px sans-serif';
        ctx.fillText('Move to drop in!', W / 2, H * 0.4);
    }
}

function loop(now) {
    const dt = Math.min(0.05, (now - lastTime) / 1000);
    lastTime = now;
    update(dt);
    draw();
    if (running) {
        animationId = requestAnimationFrame(loop);
    }
}

function pointerX(event) {
    const rect = canvas.getBoundingClientRect();
    const clientX = event.touches ? event.touches[0].clientX : event.clientX;
    return (clientX - rect.left) * (W / rect.width);
}

canvas.addEventListener('touchstart', function (event) {
    event.preventDefault();
    if (!running) {
        return;
    }
    targetX = pointerX(event);
    go();
}, { passive: false });

canvas.addEventListener('touchmove', function (event) {
    event.preventDefault();
    if (running) {
        targetX = pointerX(event);
    }
}, { passive: false });

canvas.addEventListener('touchend', function (event) {
    event.preventDefault();
    targetX = null;
}, { passive: false });

let mouseDown = false;
canvas.addEventListener('mousedown', function (event) {
    if (!running) {
        return;
    }
    mouseDown = true;
    targetX = pointerX(event);
    go();
});
canvas.addEventListener('mousemove', function (event) {
    if (running && mouseDown) {
        targetX = pointerX(event);
    }
});
window.addEventListener('mouseup', function () {
    mouseDown = false;
    targetX = null;
});

document.addEventListener('keydown', function (event) {
    if (!running) {
        return;
    }
    if (event.key === 'ArrowLeft' || event.key === 'a' || event.key === 'q') {
        keys.left = true;
        event.preventDefault();
        go();
    } else if (event.key === 'ArrowRight' || event.key === 'd') {
        keys.right = true;
        event.preventDefault();
        go();
    }
});

document.addEventListener('keyup', function (event) {
    if (event.key === 'ArrowLeft' || event.key === 'a' || event.key === 'q') {
        keys.left = false;
    } else if (event.key === 'ArrowRight' || event.key === 'd') {
        keys.right = false;
    }
});

startButton.addEventListener('click', startGame);

reset();
running = false;
draw();