forks

Creation chat

ClarkZhang
做一个赛车游戏
11-20 08:22

登录 后可以评论

Assistant
我已准备好构建游戏,无需更多搜索。下面给你一个完整的赛车躲避小游戏:无限公路、玩家左右躲闪车流、躲避障碍物、计分、随时间加速、高分记录,并支持键盘与触摸操作。 (HTML code has been generated and updated; see above for the current version.) 我按「森林绿」配色实现:深绿色草地与深灰道路、玩家橙色赛车、随机多色对手车。控制方式包括键盘(←/→/A/D/W/空格)与手机端滑动半屏,画布已设 `touch-action:none` 避免滑动时滚动页面,并提供开始界面、计分、速度递增、碰撞判定与自定义弹窗。高分会存入 `localStorage`。 提示:预览区**右下角有 Console 面板**,运行时可查看游戏开始/碰撞/结算等日志;如遇到异常或想调整难度、车速,可把 Console 里的输出复制发给我,我据此继续修改。
▼ Code
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>极速公路 · 赛车躲避小游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>tailwind.config = { darkMode: 'class' }</script>
    <style>
        body { touch-action: manipulation; }
        canvas { touch-action: none; }
    </style>
</head>
<body class="min-h-screen bg-slate-50 dark:bg-slate-900 text-slate-700 dark:text-slate-200">

    <!-- 主题切换 -->
    <button id="theme-toggle-btn" class="fixed top-4 right-4 z-10 p-2 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors flex items-center justify-center" aria-label="Toggle theme" onclick="toggleTheme()">
        <svg id="icon-moon" class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path d="M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998z"/></svg>
        <svg id="icon-sun" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" aria-hidden="true" style="display:none"><circle cx="12" cy="12" r="4"></circle><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"></path></svg>
    </button>
    <script>
    function toggleTheme(){ var el=document.documentElement; var isDark=!el.classList.contains('dark'); el.classList.toggle('dark',isDark); localStorage.setItem('theme',isDark?'dark':'light'); applyTheme(isDark); }
    function applyTheme(isDark){ document.getElementById('icon-moon').style.display=isDark?'none':'block'; document.getElementById('icon-sun').style.display=isDark?'block':'none'; }
    document.addEventListener('DOMContentLoaded',function(){ var saved=localStorage.getItem('theme'); var isDark=saved==='dark'||(!saved&&window.matchMedia('(prefers-color-scheme: dark)').matches); document.documentElement.classList.toggle('dark',isDark); applyTheme(isDark); });
    </script>

    <!-- 自定义弹窗 -->
    <div id="custom-modal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 hidden" aria-hidden="true">
        <div class="rounded-xl bg-white dark:bg-slate-800 p-6 shadow-xl max-w-sm w-full border border-slate-200 dark:border-slate-700">
            <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 mb-1">🚦 撞车了!</h3>
            <p id="custom-modal-msg" class="text-slate-700 dark:text-slate-200 mb-5"></p>
            <div class="flex gap-3">
                <button type="button" onclick="hideModal()" class="flex-1 rounded-lg bg-slate-300 dark:bg-slate-600 px-4 py-2 text-slate-700 dark:text-slate-100 hover:bg-slate-400 dark:hover:bg-slate-500">关闭</button>
                <button type="button" onclick="hideModal(); startGame();" class="flex-1 rounded-lg bg-emerald-600 px-4 py-2 text-white hover:bg-emerald-700 dark:bg-emerald-500 dark:hover:bg-emerald-600">再来一局</button>
            </div>
        </div>
    </div>
    <script>
    function showModal(msg){ var el=document.getElementById('custom-modal'); document.getElementById('custom-modal-msg').textContent=msg||''; el.classList.remove('hidden'); }
    function hideModal(){ document.getElementById('custom-modal').classList.add('hidden'); }
    </script>

    <main class="max-w-3xl mx-auto px-4 py-8">
        <header class="text-center mb-6">
            <h1 class="text-3xl md:text-4xl font-extrabold text-slate-900 dark:text-slate-100">🏎️ 极速公路</h1>
            <p class="mt-1 text-slate-500 dark:text-slate-400">用 <kbd class="px-1.5 py-0.5 bg-slate-200 dark:bg-slate-700 rounded text-xs">←</kbd> <kbd class="px-1.5 py-0.5 bg-slate-200 dark:bg-slate-700 rounded text-xs">→</kbd> 或 <kbd class="px-1.5 py-0.5 bg-slate-200 dark:bg-slate-700 rounded text-xs">A</kbd> <kbd class="px-1.5 py-0.5 bg-slate-200 dark:bg-slate-700 rounded text-xs">D</kbd> 控制,手机端按住左右屏幕滑动</p>
        </header>

        <!-- 记分牌与状态 -->
        <div class="flex items-center justify-between mb-3 px-1 text-sm font-semibold">
            <div class="flex items-center gap-4">
                <span class="text-emerald-600 dark:text-emerald-400">得分 <b id="score">0</b></span>
                <span class="text-teal-600 dark:text-teal-400">最高 <b id="best">0</b></span>
            </div>
            <div id="status-pill" class="px-3 py-1 rounded-full bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 animate-pulse">▶ 运行中</div>
        </div>

        <!-- 游戏画布:显式高度,保证 iframe 预览可见 -->
        <div class="relative rounded-2xl overflow-hidden shadow-xl ring-1 ring-slate-200 dark:ring-slate-700 bg-slate-800">
            <canvas id="game" width="480" height="640" class="block w-full h-[70vh] max-h-[640px] min-h-[400px] touch-none select-none"></canvas>
            <div id="start-overlay" class="absolute inset-0 flex flex-col items-center justify-center bg-slate-900/70 text-center p-6">
                <p class="text-3xl mb-2">🏁</p>
                <h2 class="text-2xl font-bold text-white mb-2">准备出发</h2>
                <button type="button" onclick="startGame()" class="rounded-lg bg-emerald-600 px-6 py-3 font-bold text-white hover:bg-emerald-700 shadow-lg">开始游戏</button>
                <p id="hint" class="mt-3 text-xs text-slate-300 max-w-xs"></p>
            </div>
        </div>

        <p class="mt-4 text-center text-xs text-slate-400 dark:text-slate-500">速度会随时间提升 · 撞上其他车辆即结束 · 距离越远得分越高</p>
    </main>

    <script>
    // ===== Canvas 准备 =====
    const canvas = document.getElementById('game');
    const ctx = canvas.getContext('2d');
    const W = canvas.width, H = canvas.height;

    // ===== DOM 引用 =====
    const scoreEl = document.getElementById('score');
    const bestEl = document.getElementById('best');
    const statusPill = document.getElementById('status-pill');
    const startOverlay = document.getElementById('start-overlay');

    // ===== 游戏状态 =====
    const ROAD_W = 300;         // 道路宽度(逻辑像素)
    const ROAD_X = (W - ROAD_W) / 2;
    const CAR_W = 46, CAR_H = 84;
    let player = { x: ROAD_X + ROAD_W/2 - CAR_W/2, y: H - CAR_H - 30, speed: 6 };
    let enemies = [];
    let roadLines = [];         // 道路中央虚线
    let score = 0, distance = 0;
    let speed = 6;              // 全局速度(会递增)
    let running = false, over = false;
    let spawnTimer = 0;
    let lastKey = null;
    let best = parseInt(localStorage.getItem('racer_best') || '0', 10);
    bestEl.textContent = best;

    // 车道位置(3车道)
    const LANES = [ROAD_X + 150 - 60, ROAD_X + 150, ROAD_X + 150 + 60];

    function newPlayer(){
        player = { x: ROAD_X + ROAD_W/2 - CAR_W/2, y: H - CAR_H - 30, speed: 6 };
    }
    function resetRoad(){
        enemies = [];
        score = 0; distance = 0; speed = 6; spawnTimer = 0;
        roadLines = [];
        for (let i=0;i<8;i++) roadLines.push(i * 80);
    }

    function startGame(){
        resetRoad();
        newPlayer();
        over = false;
        running = true;
        startOverlay.classList.add('hidden');
        statusPill.textContent = '▶ 运行中';
        statusPill.className = 'px-3 py-1 rounded-full bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 animate-pulse';
        console.log('[' + new Date().toLocaleTimeString() + '] 游戏开始 speed=' + speed);
    }
    // 暴露给全局(按钮 onclick 使用)
    window.startGame = startGame;

    function gameOver(){
        over = running = true;  // over=true, running=true 用于停下但保留画面
        if (distance > best){
            best = Math.floor(distance);
            bestEl.textContent = best;
            localStorage.setItem('racer_best', best.toString());
        }
        statusPill.textContent = '☠ 已结束';
        statusPill.className = 'px-3 py-1 rounded-full bg-rose-100 dark:bg-rose-900/40 text-rose-700 dark:text-rose-300';
        const msg = '本次得分:' + score + '\n行驶距离:' + Math.floor(distance) + ' 米\n最高纪录:' + best + ' 米';
        console.log('[' + new Date().toLocaleTimeString() + '] 游戏结束 score=' + score + ' distance=' + Math.floor(distance) + ' best=' + best);
        showModal(msg);
    }

    // ===== 输入控制 =====
    // 键盘
    document.addEventListener('keydown', (e)=>{
        if (!running) return;
        if (e.code === 'ArrowLeft' || e.key === 'a' || e.key === 'A' || e.key === 'ArrowUp' || e.key === 'w' || e.key === 'W' || e.key === ' ') { player.x -= player.speed; e.preventDefault(); }
        if (e.code === 'ArrowRight' || e.key === 'd' || e.key === 'D') { player.x += player.speed; e.preventDefault(); }
    });

    // 触摸(方向按滑动/按住屏幕左右两侧)
    let touchSidelines = false;
    canvas.addEventListener('touchstart', (e)=>{
        if (!running) return;
        touchSidelines = true;
        e.preventDefault();
        onTouchMove(e.touches[0]);
    }, { passive:false });
    canvas.addEventListener('touchmove', (e)=>{
        if (!running) return;
        e.preventDefault();
        const t = e.touches[0];
        // 按住屏幕半区持续移动
        if (t.clientX < window.innerWidth/2) { player.x -= player.speed; }
        else { player.x += player.speed; }
    }, { passive:false });
    canvas.addEventListener('touchend', ()=>{ touchSidelines=false; }, { passive:true });

    function onTouchMove(t){
        const rect = canvas.getBoundingClientRect();
        const scale = canvas.width / rect.width;
        const x = (t.clientX - rect.left) * scale;
        if (x < ROAD_X + ROAD_W/2) { player.x -= player.speed; } else { player.x += player.speed; }
    }

    // ===== 生成敌人 =====
    function spawnEnemy(){
        const lane = LANES[Math.floor(Math.random()*LANES.length)];
        const w = CAR_W, h = CAR_H;
        // 随机颜色(避免与玩家撞色:玩家为橙红)
        const colors = ['#ef4444','#3b82f6','#f59e0b','#8b5cf6','#14b8a6','#94a3b8'];
        const color = colors[Math.floor(Math.random()*colors.length)];
        enemies.push({ x: lane - w/2, y: -h, w, h, color, hit:false });
    }

    // ===== 碰撞检测 =====
    function outOfLanes(car){
        return car.x < ROAD_X + 14 || car.x + car.w > ROAD_X + ROAD_W - 14;
    }
    function collides(a, b){
        return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
    }

    // ===== 更新逻辑 =====
    function update(){
        if (!running) return;

        // 玩家移动边界限制
        player.x = Math.max(ROAD_X + 10, Math.min(ROAD_X + ROAD_W - CAR_W - 10, player.x));

        // 距离与速度提升
        distance += speed * 0.05;
        speed = 6 + Math.floor(distance/250) * 0.5;
        if (speed > 16) speed = 16;
        score = Math.floor(distance);

        // 道路线移动
        for (let i=0;i<roadLines.length;i++){ roadLines[i] += speed; if (roadLines[i] > H) roadLines[i] -= H; }

        // 生成敌人(间距随速度)
        spawnTimer -= speed;
        if (spawnTimer <= 0){
            spawnEnemy();
            spawnTimer = 55 + Math.random()*70; // 帧数间隔,随速度增大实际密度升高
        }

        // 敌人移动 + 出界移除
        for (let i=enemies.length-1;i>=0;i--){
            const e = enemies[i];
            e.y += speed;
            if (e.y > H) { enemies.splice(i,1); continue; }
            if (!e.hit && collides(player, e)){
                e.hit = true;
                console.log('[' + new Date().toLocaleTimeString() + '] 发生碰撞 玩家=(' + Math.floor(player.x) + ',' + Math.floor(player.y) + ') 敌人=(' + Math.floor(e.x) + ',' + Math.floor(e.y) + ')');
                gameOver();
                return;
            }
        }
    }

    // ===== 绘制 =====
    function drawCar(x, y, w, h, color, isPlayer){
        // 车身
        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.roundRect(x, y, w, h, 10);
        ctx.fill();
        // 车窗
        ctx.fillStyle = isPlayer ? '#0f172a' : 'rgba(0,0,0,0.3)';
        ctx.beginPath();
        ctx.roundRect(x+7, y+10, w-14, h*0.28, 6);
        ctx.fill();
        // 前灯/尾灯
        ctx.fillStyle = isPlayer ? '#f8fafc' : '#fde68a';
        ctx.beginPath(); ctx.roundRect(x+5, y+2, 8, 6, 2); ctx.fill();
        ctx.beginPath(); ctx.roundRect(x+w-13, y+2, 8, 6, 2); ctx.fill();
        ctx.fillStyle = '#ef4444';
        ctx.beginPath(); ctx.roundRect(x+5, y+h-8, 8, 5, 2); ctx.fill();
        ctx.beginPath(); ctx.roundRect(x+w-13, y+h-8, 8, 5, 2); ctx.fill();
    }

    function draw(){
        // 背景(草地)
        ctx.fillStyle = '#14532d';
        ctx.fillRect(0,0,W,H);
        ctx.fillStyle = '#166534';
        ctx.fillRect(0, H*0.55, W, H*0.45);

        // 道路
        ctx.fillStyle = '#1f2937';
        ctx.fillRect(ROAD_X, 0, ROAD_W, H);
        // 路肩
        ctx.fillStyle = '#dc2626';
        ctx.fillRect(ROAD_X, 0, 10, H);
        ctx.fillRect(ROAD_X+ROAD_W-10, 0, 10, H);
        ctx.fillStyle = '#e5e7eb';
        ctx.fillRect(ROAD_X, 0, 4, H);
        ctx.fillRect(ROAD_X+ROAD_W-4, 0, 4, H);

        // 中央虚线(3车道用2条)
        for (let i=0;i<roadLines.length;i++){
            const y = roadLines[i];
            ctx.fillStyle = '#facc15';
            ctx.fillRect(ROAD_X+ROAD_W/2 - 30, y, 3, 40);
            ctx.fillRect(ROAD_X+ROAD_W/2 + 27, y, 3, 40);
        }

        // 敌人
        for (const e of enemies) drawCar(e.x, e.y, e.w, e.h, e.color, false);

        // 玩家
        drawCar(player.x, player.y, CAR_W, CAR_H, '#f97316', true);
    }

    // ===== 主循环 =====
    function loop(){
        requestAnimationFrame(loop);
        update();
        draw();
        scoreEl.textContent = score;
    }
    loop();
    </script>
</body>
</html>
11-20 08:23

登录 后可以评论

Comments

登录 后可以评论