Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash-lite-preview-06-17-thinking· GoogleHugging Face LMArena Human Preference 140K

用html+js生成可以离线执行的minecraft类小游戏,需要有基础的移动能力及方块放置与破坏逻辑,世界生成与重力。

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-03-26-experimental’s answer.
  1. User

    用html+js生成可以离线执行的minecraft类小游戏,需要有基础的移动能力及方块放置与破坏逻辑,世界生成与重力。

  2. Gemini Assistant

    好的,我们可以创建一个基础的、可以离线运行的Minecraft风格小游戏。这个版本将侧重于核心机制:方块世界、玩家移动、重力、方块破坏和放置。为了简化,我们将使用2D Canvas实现一个俯视视角(Top-Down),这比实现第一个人称的3D投影要容易得多,但仍然能体现核心玩法。

    核心思路:

    1. HTML: 提供一个<canvas>元素用于渲染,以及一些说明文字。
    2. CSS: 简单样式化页面和Canvas。
    3. JavaScript:
      • Canvas渲染: 使用Canvas API绘制方块、玩家。
      • 世界: 使用二维数组表示方块,如 world[x][y]。
      • 玩家: 一个对象包含位置、速度、状态。
      • 输入: 监听键盘(WASD移动,空格跳跃)和鼠标(点击破坏/放置)。
      • 物理: 实现简单的重力,只对玩家生效,并进行碰撞检测。
      • 游戏循环: 使用 requestAnimationFrame 实现流畅更新和渲染。
      • 状态管理: 跟踪当前选择的方块类型。
      • 离线: 所有代码都在HTML文件中,无需服务器。

    代码实现:

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>简易方块游戏</title>
        <style>
            body {
                display: flex;
                flex-direction: column; /* 垂直排列 */
                justify-content: center;
                align-items: center;
                height: 100vh;
                margin: 0;
                background-color: #333;
                color: #eee;
                font-family: sans-serif;
                overflow: hidden; /* 防止滚动条 */
            }
            canvas {
                border: 1px solid #eee;
                background-color: #87CEEB; /* 天蓝色背景 */
                cursor: crosshair; /* 鼠标样式 */
            }
            .info {
                margin-top: 15px;
                text-align: center;
            }
            .controls {
                margin-top: 10px;
                font-size: 0.9em;
                background-color: rgba(0,0,0,0.3);
                padding: 8px;
                border-radius: 5px;
            }
        </style>
    </head>
    <body>
    
        <h1>简易方块游戏</h1>
        <canvas id="gameCanvas"></canvas>
        <div class="info">
            <div class="controls">
                移动: WASD | 跳跃: 空格 | 破坏/放置: 鼠标左键/右键<br>
                切换方块: 1 (土块), 2 (石块), 3 (木块), 4 (玻璃)
            </div>
            <div>当前选择: <span id="selectedBlockType">土块</span></div>
            <div>(游戏会自动居中显示玩家)</div>
        </div>
    
        <script>
            const canvas = document.getElementById('gameCanvas');
            const ctx = canvas.getContext('2d');
    
            // --- 配置 ---
            const WORLD_WIDTH = 100; // 世界宽度(方块数)
            const WORLD_HEIGHT = 64; // 世界高度(方块数)
            const BLOCK_SIZE = 32;   // 每个方块的像素大小
    
            const CANVAS_WIDTH = 640; // Canvas 渲染宽度
            const CANVAS_HEIGHT = 480; // Canvas 渲染高度
    
            const GRAVITY = 0.5;      // 重力加速度
            const JUMP_FORCE = -12;   // 跳跃力
            const MOVE_SPEED = 4;     // 移动速度
            const PLAYER_WIDTH = 20;  // 玩家碰撞宽度
            const PLAYER_HEIGHT = 28;// 玩家碰撞高度
    
            canvas.width = CANVAS_WIDTH;
            canvas.height = CANVAS_HEIGHT;
    
            // --- 方块定义 ---
            const BLOCK_TYPES = {
                AIR: 0,
                GRASS: 1,
                DIRT: 2,
                STONE: 3,
                WOOD: 4,
                GLASS: 5
            };
    
            const BLOCK_COLORS = {
                [BLOCK_TYPES.AIR]: 'rgba(135, 206, 235, 0)', // 透明
                [BLOCK_TYPES.GRASS]: '#228B22', // 森林绿
                [BLOCK_TYPES.DIRT]: '#8B4513',  // 马鞍棕
                [BLOCK_TYPES.STONE]: '#708090', // 灰色
                [BLOCK_TYPES.WOOD]: '#A0522D',  // 锈色
                [BLOCK_TYPES.GLASS]: 'rgba(173, 216, 230, 0.5)' // 半透明浅蓝色
            };
    
            const BLOCK_NAMES = {
                [BLOCK_TYPES.GRASS]: '草块',
                [BLOCK_TYPES.DIRT]: '土块',
                [BLOCK_TYPES.STONE]: '石块',
                [BLOCK_TYPES.WOOD]: '木块',
                [BLOCK_TYPES.GLASS]: '玻璃'
            };
    
            // --- 游戏状态 ---
            let world = []; // 二维数组 world[x][y]
            let player = {
                x: WORLD_WIDTH / 2, // 玩家在世界中的X坐标(方块单位)
                y: WORLD_HEIGHT / 2, // 玩家在世界中的Y坐标(方块单位)
                vx: 0,              // 水平速度
                vy: 0,              // 垂直速度
                width: PLAYER_WIDTH,
                height: PLAYER_HEIGHT,
                onGround: false,
                selectedBlock: BLOCK_TYPES.DIRT // 默认选择土块
            };
    
            let keysPressed = {}; // 存储按键状态
            let mouse = { x: 0, y: 0, leftPressed: false, rightPressed: false };
            let cameraOffset = { x: 0, y: 0 }; // Canvas相对于世界原点的偏移
    
            const selectedBlockDisplay = document.getElementById('selectedBlockType');
    
            // --- 初始化 ---
            function init() {
                generateWorld();
                // 初始玩家位置放在生成的地形上
                player.y = findSurfaceY(player.x) - 2; // 放在地表上方一点
                if (player.y < 0) player.y = 0; // 防止生成在地下
    
                setupEventListeners();
                gameLoop();
            }
    
            // --- 世界生成 ---
            function generateWorld() {
                world = Array(WORLD_WIDTH).fill(0).map(() => Array(WORLD_HEIGHT).fill(BLOCK_TYPES.AIR));
    
                // 简单的地形生成:地表 + 地下
                let terrainHeight = WORLD_HEIGHT - 10; // 基础地表高度
                for (let x = 0; x < WORLD_WIDTH; x++) {
                    // 添加一些随机性
                    let currentHeight = terrainHeight + Math.floor(Math.random() * 6) - 3;
                    if (currentHeight < 1) currentHeight = 1;
                    if (currentHeight >= WORLD_HEIGHT) currentHeight = WORLD_HEIGHT - 1;
    
                    for (let y = 0; y < WORLD_HEIGHT; y++) {
                        if (y === currentHeight) {
                            world[x][y] = BLOCK_TYPES.GRASS; // 草块
                        } else if (y > currentHeight && y < currentHeight + 4) {
                            world[x][y] = BLOCK_TYPES.DIRT; // 土块
                        } else if (y >= currentHeight + 4) {
                            world[x][y] = BLOCK_TYPES.STONE; // 石块
                        }
                    }
                }
                 // 在特定区域添加一些树
                for(let x = 10; x < WORLD_WIDTH - 10; x+= 10) {
                    placeTree(x, terrainHeight);
                }
            }
    
            // 辅助函数:查找x坐标对应的地面Y坐标
            function findSurfaceY(worldX) {
                for (let y = 0; y < WORLD_HEIGHT; y++) {
                    if (world[worldX][y] !== BLOCK_TYPES.AIR) {
                        return y;
                    }
                }
                return WORLD_HEIGHT - 1;
            }
    
            // 辅助函数:放置一棵简单的树
            function placeTree(startX, terrainY) {
                 const trunkHeight = 4 + Math.floor(Math.random() * 3);
                 // 树干
                 for (let i = 0; i < trunkHeight; i++) {
                     setBlockSafe(startX, terrainY - 1 - i, BLOCK_TYPES.WOOD);
                 }
                 // 树冠
                 const canopyHeight = 2;
                 const canopyRadius = 2;
                 for (let ly = 0; lyly < canopyHeight; ly++) {
                     for (let dx = -canopyRadius + ly; dx <= canopyRadius - ly; dx++) {
                        setBlockSafe(startX + dx, terrainY - 1 - trunkHeight - ly, BLOCK_TYPES.WOOD);
                     }
                 }
                 // 顶层
                  for (let dx = -1; dx <= 1; dx++) {
                     setBlockSafe(startX + dx, terrainY - 1 - trunkHeight - canopyHeight, BLOCK_TYPES.WOOD);
                 }
            }
    
    
            // --- 事件监听 ---
            function setupEventListeners() {
                document.addEventListener('keydown', (e) => {
                    keysPressed[e.key.toLowerCase()] = true;
                    // 数字键切换方块
                    if (e.key >= '1' && e.key <= '5') {
                        const blockNum = parseInt(e.key);
                        const blockType = [BLOCK_TYPES.DIRT, BLOCK_TYPES.STONE, BLOCK_TYPES.WOOD, BLOCK_TYPES.GLASS][blockNum - 1];
                        if (blockType !== undefined) {
                            player.selectedBlock = blockType;
                            selectedBlockDisplay.textContent = BLOCK_NAMES[blockType] || '未知';
                        }
                    }
                });
                document.addEventListener('keyup', (e) => {
                    keysPressed[e.key.toLowerCase()] = false;
                });
    
                canvas.addEventListener('mousemove', (e) => {
                    // 计算相对于Canvas的鼠标坐标
                    const rect = canvas.getBoundingClientRect();
                    mouse.x = e.clientX - rect.left;
                    mouse.y = e.clientY - rect.top;
    
                    // 如果是第一人称视角,这里需要转换成世界坐标并进行射线检测
                    // 但在2D俯视视角下,我们直接用鼠标点击的画布坐标来定位要操作的方块
                });
    
                canvas.addEventListener('mousedown', (e) => {
                    // 阻止默认的右键菜单
                    if (e.button === 2) {
                        e.preventDefault();
                    }
                    // 记录鼠标点击状态
                    if (e.button === 0) mouse.leftPressed = true; // 左键
                    if (e.button === 2) mouse.rightPressed = true; // 右键
    
                    // 处理点击操作(在gameLoop中处理,因为需要知道当前选择的方块)
                });
    
                canvas.addEventListener('mouseup', (e) => {
                    if (e.button === 0) mouse.leftPressed = false;
                    if (e.button === 2) mouse.rightPressed = false;
                });
                 // 移动端触摸事件模拟鼠标事件
                canvas.addEventListener('touchstart', (e) => {
                    e.preventDefault(); // 防止页面滚动
                     const rect = canvas.getBoundingClientRect();
                    // 模拟鼠标移动和左键按下
                    const touch = e.touches[0];
                    mouse.x = touch.clientX - rect.left;
                    mouse.y = touch.clientY - rect.top;
                    mouse.leftPressed = true;
                    // 简单的处理:第一次触摸视为放置(右键),后续触摸(如果需要多点)再处理
                    // 这里简化为触摸即视为左键点击(破坏)
                     handleMouseClick(mouse.x, mouse.y, 0); // 模拟左键点击
                });
                canvas.addEventListener('touchmove', (e) => {
                     e.preventDefault();
                     const rect = canvas.getBoundingClientRect();
                     const touch = e.touches[0];
                     mouse.x = touch.clientX - rect.left;
                     mouse.y = touch.clientY - rect.top;
                      // 允许触摸拖拽放置
                      if(mouse.rightPressed) {
                          handleMouseClick(mouse.x, mouse.y, 2);
                      }
                });
                canvas.addEventListener('touchend', (e) => {
                    e.preventDefault();
                    mouse.leftPressed = false;
                    mouse.rightPressed = false;
                });
            }
    
            // --- 辅助函数:获取世界坐标 ---
            // 将画布坐标转换为世界坐标(考虑了摄像机偏移)
            function screenToWorld(sx, sy) {
                const worldX = Math.floor((sx + cameraOffset.x) / BLOCK_SIZE);
                const worldY = Math.floor((sy + cameraOffset.y) / BLOCK_SIZE);
                return { x: worldX, y: worldY };
            }
    
            // --- 辅助函数:设置方块(带边界检查)---
            function setBlockSafe(x, y, type) {
                if (x >= 0 && x < WORLD_WIDTH && y >= 0 && y < WORLD_HEIGHT) {
                    world[x][y] = type;
                }
            }
    
            // --- 辅助函数:获取方块 ---
            function getBlock(x, y) {
                if (x >= 0 && x < WORLD_WIDTH && y >= 0 && y < WORLD_HEIGHT) {
                    return world[x][y];
                }
                return BLOCK_TYPES.AIR; // 越界视为空气
            }
    
            // --- 辅助函数:检查方块是否坚固 ---
            function isSolid(x, y) {
                const blockType = getBlock(x, y);
                // 空气和玻璃不算作完全阻挡移动(玻璃可以被破坏)
                return blockType !== BLOCK_TYPES.AIR && blockType !== BLOCK_TYPES.GLASS;
            }
    
             // --- 辅助函数:模拟左键点击(破坏) ---
            function handleBreakBlock(sx, sy) {
                const { x: worldX, y: worldY } = screenToWorld(sx, sy);
                const targetBlock = getBlock(worldX, worldY);
    
                 // 增加一点交互距离,避免点到玩家自己站的格子上
                 const playerBlockX = Math.floor((player.x * BLOCK_SIZE + player.width / 2) / BLOCK_SIZE);
                 const playerBlockY = Math.floor((player.y * BLOCK_SIZE + player.height / 2) / BLOCK_SIZE);
    
                if (targetBlock !== BLOCK_TYPES.AIR && !(worldX === playerBlockX && worldY === playerBlockY)) {
                    // 简单的破坏逻辑:立即移除方块
                    setBlockSafe(worldX, worldY, BLOCK_TYPES.AIR);
                    // 可以添加延迟、掉落物等效果
                }
            }
    
            // --- 辅助函数:模拟右键点击(放置)---
            function handlePlaceBlock(sx, sy) {
                const { x: targetX, y: targetY } = screenToWorld(sx, sy);
                const clickedBlock = getBlock(targetX, targetY);
    
                if (clickedBlock === BLOCK_TYPES.AIR || clickedBlock === BLOCK_TYPES.GLASS) {
                     // 在点击的位置放置方块(如果点击的是空气或玻璃)
                     setBlockSafe(targetX, targetY, player.selectedBlock);
                } else {
                     // 尝试在点击方块的邻近位置放置
                     // 找出鼠标点击点在被点击方块的哪个方向
                    const playerBlockX = Math.floor((player.x * BLOCK_SIZE + player.width / 2) / BLOCK_SIZE);
                    const playerBlockY = Math.floor((player.y * BLOCK_SIZE + player.height / 2) / BLOCK_SIZE);
    
                     // 找到点击的方块(targetX, targetY)和玩家当前脚下的方块(playerBlockX, playerBlockY)之间的相对位置
                     let placeX = targetX, placeY = targetY;
    
                     // 简单判断:如果点击位置在玩家前方,就在其前方放置
                     // 需要更精确的逻辑来判断放置在哪个邻近格
                     // 这里简化:如果点击的方块不是空气,就在它旁边的第一个空气格放置
                     // 例如,鼠标点击在(tx, ty)方块,找到一个邻近的(nx, ny)是空气,并且(nx, ny)离鼠标点击点(sx, sy)最近
    
                     let closestDistSq = Infinity;
                     let bestPlaceX = -1, bestPlaceY = -1;
    
                     const neighbors = [
                         { dx: 0, dy: -1 }, { dx: 0, dy: 1 }, { dx: -1, dy: 0 }, { dx: 1, dy: 0 }
                     ];
    
                     for (const neighbor of neighbors) {
                        const nx = targetX + neighbor.dx;
                        const ny = targetY + neighbor.dy;
                        if (getBlock(nx, ny) === BLOCK_TYPES.AIR) {
                             // 计算邻近空气格中心到鼠标点击点的距离平方
                             const dx = (nx + 0.5) * BLOCK_SIZE - sx;
                             const dy = (ny + 0.5) * BLOCK_SIZE - sy;
                             const distSq = dx * dx + dy * dy;
                             if (distSq < closestDistSq) {
                                 closestDistSq = distSq;
                                 bestPlaceX = nx;
                                 bestPlaceY = ny;
                             }
                        }
                     }
    
                     if (bestPlaceX !== -1) {
                        setBlockSafe(bestPlaceX, bestPlaceY, player.selectedBlock);
                     }
                }
            }
    
    
            // --- 输入处理 ---
            function handleInput() {
                // 移动
                player.vx = 0;
                if (keysPressed['a'] || keysPressed['arrowleft']) {
                    player.vx -= MOVE_SPEED;
                }
                if (keysPressed['d'] || keysPressed['arrowright']) {
                    player.vx += MOVE_SPEED;
                }
    
                // 跳跃
                if ((keysPressed[' '] || keysPressed['w'] || keysPressed['arrowup']) && player.onGround) {
                    player.vy = JUMP_FORCE;
                    player.onGround = false; // 立即设置为不在地面,防止空中反复跳跃
                }
    
                // 点击处理
                if (mouse.leftPressed) {
                     // 简单的破坏逻辑:长按持续破坏
                     handleBreakBlock(mouse.x, mouse.y);
                }
                if (mouse.rightPressed) {
                    // 简单的放置逻辑:点击一次放置一个
                    handlePlaceBlock(mouse.x, mouse.y);
                    mouse.rightPressed = false; // 防止连续放置,除非再次点击
                }
            }
    
            // --- 更新 ---
            function update() {
                // 1. 应用重力
                if (!player.onGround) {
                    player.vy += GRAVITY;
                }
    
                // 2. 移动和碰撞检测
                let nextX = player.x + player.vx;
                let nextY = player.y + player.vy;
    
                // 水平碰撞检测
                // 检查玩家前方/后方的方块
                const playerLeftBlockX = Math.floor((player.x * BLOCK_SIZE + cameraOffset.x) / BLOCK_SIZE);
                const playerRightBlockX = Math.floor((player.x * BLOCK_SIZE + player.width -1 + cameraOffset.x) / BLOCK_SIZE); // -1 避免刚好在边界上卡住
                const playerTopBlockY = Math.floor((player.y * BLOCK_SIZE + cameraOffset.y) / BLOCK_SIZE);
                const playerBottomBlockY = Math.floor((player.y * BLOCK_SIZE + player.height -1 + cameraOffset.y) / BLOCK_SIZE); // -1 避免刚好在边界上卡住
    
                let nextPlayerLeftBlockX = Math.floor((nextX + cameraOffset.x) / BLOCK_SIZE);
                let nextPlayerRightBlockX = Math.floor((nextX + player.width -1 + cameraOffset.x) / BLOCK_SIZE);
                let nextPlayerTopBlockY = Math.floor((player.y * BLOCK_SIZE + cameraOffset.y) / BLOCK_SIZE); // 垂直速度处理在下面
                let nextPlayerBottomBlockY = Math.floor((player.y * BLOCK_SIZE + player.height -1 + cameraOffset.y) / BLOCK_SIZE);
    
                // 检查左右移动是否撞墙
                if (player.vx > 0 && nextPlayerRightBlockX < WORLD_WIDTH && isSolid(nextPlayerRightBlockX, nextPlayerTopBlockY) || isSolid(nextPlayerRightBlockX, nextPlayerBottomBlockY) ) {
                     // 如果撞墙,停止水平移动,并将玩家推到墙前
                     // nextX = (playerRightBlockX - 1) * BLOCK_SIZE - cameraOffset.x - player.width;
                     player.vx = 0; // 直接停止速度
                } else if (player.vx < 0 && nextPlayerLeftBlockX >= 0 && isSolid(nextPlayerLeftBlockX, nextPlayerTopBlockY) || isSolid(nextPlayerLeftBlockX, nextPlayerBottomBlockY)) {
                     // if (player.vx < 0 && nextPlayerLeftBlockX >= 0 && isSolid(nextPlayerLeftBlockX, playerTopBlockY)) {
                     // nextX = playerLeftBlockX * BLOCK_SIZE - cameraOffset.x;
                     player.vx = 0; // 直接停止速度
                }
    
                 // 更新水平位置
                player.x += player.vx / BLOCK_SIZE; // 速度也需要按比例缩放,这里用 BLOCK_SIZE 作为比例因子
    
    
                // 垂直碰撞检测(重力、跳跃)
                let standingOnBlock = false;
                 nextPlayerBottomBlockY = Math.floor((player.y * BLOCK_SIZE + player.height -1 + cameraOffset.y) / BLOCK_SIZE); // 更新脚下block的Y
                 // 先检查是否还在地面上
                 if (isSolid(player.x, nextPlayerBottomBlockY + 1) || isSolid(player.x + 1, nextPlayerBottomBlockY + 1)) { // 多检查一个像素点以防万一
                     standingOnBlock = true;
                 }
    
    
                // 检查下落是否撞到地面
                 let groundBlockY = Math.floor((player.y * BLOCK_SIZE + player.height + cameraOffset.y) / BLOCK_SIZE);
                 if (player.vy > 0 && groundBlockY < WORLD_HEIGHT && isSolid(player.x, groundBlockY) || isSolid(player.x + 1, groundBlockY) ) {
                     // 撞到地面,停止下落,调整位置
                    // player.y = groundBlockY - player.height / BLOCK_SIZE - 1; // 放到地面上方
                     player.vy = 0;
                     player.onGround = true;
                     // 将玩家精确放置在地块上方
                     player.y = groundBlockY - (player.height / BLOCK_SIZE);
                 } else {
                     player.onGround = false; // 不在地面上
                 }
    
    
                 // 更新垂直位置
                 if (!player.onGround) { // 只有不在地面上时才更新y
                    player.y += player.vy / BLOCK_SIZE; // 同样需要比例缩放
                 }
    
                // 防止玩家移出世界边界 (可以通过逻辑控制,或者在这里限制)
                // player.x = Math.max(0, Math.min(WORLD_WIDTH - player.width / BLOCK_SIZE, player.x));
                // player.y = Math.max(0, player.y); // Y轴向下,一般不限制上限
    
    
                // 更新摄像机偏移,使玩家保持在屏幕中心
                cameraOffset.x = (player.x * BLOCK_SIZE + player.width / 2) - CANVAS_WIDTH / 2;
                cameraOffset.y = (player.y * BLOCK_SIZE + player.height / 2) - CANVAS_HEIGHT / 2;
    
                // 防止摄像机移出世界边界
                // cameraOffset.x = Math.max(0, Math.min(WORLD_WIDTH * BLOCK_SIZE - CANVAS_WIDTH, cameraOffset.x));
                // cameraOffset.y = Math.max(0, Math.min(WORLD_HEIGHT * BLOCK_SIZE - CANVAS_HEIGHT, cameraOffset.y));
            }
    
            // --- 渲染 ---
            function render() {
                // 1. 清除画布
                ctx.fillStyle = BLOCK_COLORS[BLOCK_TYPES.AIR]; // 使用天空蓝色背景
                ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    
                // 2. 绘制世界方块
                // 计算需要在画布上绘制的方块范围
                const startCol = Math.floor(cameraOffset.x / BLOCK_SIZE);
                const endCol = startCol + Math.ceil(CANVAS_WIDTH / BLOCK_SIZE) + 1; // 加1是为了确保覆盖边缘
                const startRow = Math.floor(cameraOffset.y / BLOCK_SIZE);
                const endRow = startRow + Math.ceil(CANVAS_HEIGHT / BLOCK_SIZE) + 1;
    
                for (let x = startCol; x < endCol; x++) {
                    for (let y = startRow; y < endRow; y++) {
                        const blockType = getBlock(x, y);
                        if (blockType !== BLOCK_TYPES.AIR) {
                            ctx.fillStyle = BLOCK_COLORS[blockType];
                            // 计算方块在画布上的屏幕坐标
                            const screenX = x * BLOCK_SIZE - cameraOffset.x;
                            const screenY = y * BLOCK_SIZE - cameraOffset.y;
                            ctx.fillRect(screenX, screenY, BLOCK_SIZE, BLOCK_SIZE);
    
                            // 可选:绘制方块边框
                            // ctx.strokeStyle = '#555';
                            // ctx.lineWidth = 0.5;
                            // ctx.strokeRect(screenX, screenY, BLOCK_SIZE, BLOCK_SIZE);
                        }
                    }
                }
    
                // 3. 绘制玩家
                const playerScreenX = (player.x * BLOCK_SIZE + player.width / 2) - player.width / 2; // 屏幕中心 X
                const playerScreenY = (player.y * BLOCK_SIZE + player.height / 2) - player.height / 2; // 屏幕中心 Y
                ctx.fillStyle = '#FF0000'; // 玩家用红色表示
                // 绘制一个稍微小一点的矩形代表玩家身体,或者一个圆
                ctx.fillRect(
                     (player.x * BLOCK_SIZE) - cameraOffset.x , // 玩家左上角在世界坐标中的位置
                     (player.y * BLOCK_SIZE) - cameraOffset.y ,
                     player.width,
                     player.height
                );
                 // 玩家中心十字准星
                 ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)';
                 ctx.lineWidth = 1;
                 const crosshairSize = 10;
                 const centerX = CANVAS_WIDTH / 2;
                 const centerY = CANVAS_HEIGHT / 2;
                 ctx.beginPath();
                 ctx.moveTo(centerX - crosshairSize, centerY);
                 ctx.lineTo(centerX + crosshairSize, centerY);
                 ctx.moveTo(centerX, centerY - crosshairSize);
                 ctx.lineTo(centerX, centerY + crosshairSize);
                 ctx.stroke();
    
    
                // 4. 显示UI信息 (例如选择的方块) - 已在HTML中显示
    
                // 5. 处理点击操作(在input处理阶段完成,这里只渲染结果)
            }
    
            // --- 游戏循环 ---
            function gameLoop() {
                handleInput();
                update();
                render();
                requestAnimationFrame(gameLoop); // 请求下一帧
            }
    
            // --- 启动游戏 ---
            init();
    
        </script>
    </body>
    </html>
    

    如何使用:

    1. 将上面的所有代码复制到一个文本文件中。
    2. 将文件保存为 .html 扩展名(例如 block_game.html)。
    3. 用任何现代网页浏览器(如Chrome, Firefox, Edge等)打开这个HTML文件。
    4. 游戏将在浏览器窗口中加载。

    游戏说明:

    • 移动: 使用 W/A/S/D 或 方向键 移动。
    • 跳跃: 按下 空格键。
    • 破坏方块: 用鼠标左键点击你想要破坏的方块。 (注意:在2D模式下,点击画布上的方块会被破坏)。
    • 放置方块:
      • 使用数字键 1 到 4 来选择要放置的方块类型(土块、石块、木块、玻璃)。
      • 用鼠标右键点击你想要放置方块的位置。方块会被放置在鼠标点击位置附近的第一个空气格中。
    • 视角: 这是一个2D俯视视角。玩家始终位于屏幕中央,世界围绕玩家移动。

    离线执行:

    这个HTML文件包含了所有的HTML结构、CSS样式和JavaScript逻辑。一旦浏览器加载了这个文件,它就不再需要网络连接即可运行。你可以将其保存在本地,随时随地打开玩。

    局限性与可扩展性:

    • 视角: 这是2D俯视视角,并非Minecraft的3D第一人称。实现3D需要使用WebGL或更复杂的Canvas 2D技巧(如模拟透视)。
    • 物理: 物理系统非常基础,只包含重力和简单的碰撞检测。没有空气动力学、方块坠落等。
    • 世界: 世界生成算法很简单(分层+少量树)。可以使用更复杂的算法(如Perlin噪声)生成更自然的地形。
    • 交互: 破坏和放置是即时的。可以添加动画、声音效果、工具、合成系统、物品栏等。
    • 性能: 对于非常大的世界或复杂的逻辑,Canvas性能可能成为瓶颈。优化可能涉及只渲染可见区域、使用更高效的数据结构等。
    • AI/NPC: 没有其他生物或NPC。
    • 保存: 游戏状态不会被保存。需要使用localStorage等浏览器API来实现存档功能。

    这个例子为你提供了一个基础框架,你可以在此基础上添加更多功能,使其更接近你想要的Minecraft类游戏。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.