跳到正文

个人记录

该变量不应为空。

Accepted_MAXN约 165 分钟
原文
文章信息与版本

文章信息

发布
2026年8月24日
收录
2026年8月25日
更新
2026年11月13日
篇幅
约 165 分钟

版本

  1. v1当前
asdf
C++
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>2D我的世界 - 钻石版</title>
<style>
*{margin:0;padding:0;box-sizing:border-box;user-select:none}
body{background:#111;font-family:'Segoe UI',Arial,sans-serif;color:#fff;height:100vh;overflow:hidden;display:flex;justify-content:center;align-items:center}
#gameContainer{position:relative;width:900px;height:600px;box-shadow:0 0 50px rgba(0,0,0,0.8);border:4px solid #333;background:#000;display:none}
canvas{display:block;cursor:crosshair;image-rendering:pixelated}
.top-ui-bar{position:absolute;top:0;left:0;width:100%;height:40px;background:rgba(0,0,0,0.6);border-bottom:1px solid #444;display:flex;align-items:center;justify-content:space-between;padding:0 15px;z-index:50;pointer-events:none}
.ui-left{display:flex;align-items:center;gap:15px;pointer-events:auto}
.hearts{font-size:20px;color:#ff3333;letter-spacing:2px;text-shadow:1px 1px 0 #000}
.hunger-bar{font-size:18px;color:#d4a017;letter-spacing:2px;text-shadow:1px 1px 0 #000}
.mode-badge{font-size:12px;background:#444;padding:2px 6px;border-radius:4px;color:#aaa;border:1px solid #666}
.mode-badge.creative{background:#d35400;color:#fff;border-color:#e67e22}
.mode-badge.spectator{background:#8e44ad;color:#fff;border-color:#9b59b6}
.hotbar-container{position:absolute;bottom:10px;left:50%;transform:translateX(-50%);display:flex;gap:4px;background:rgba(0,0,0,0.6);padding:4px;border-radius:4px;border:2px solid #555;pointer-events:auto;z-index:20}
.slot{width:40px;height:40px;border:2px solid #777;border-radius:4px;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.5);transition:all .1s;position:relative;overflow:hidden}
.slot.active{border-color:#fff;background:rgba(255,255,255,0.2);transform:scale(1.1);z-index:2;box-shadow:0 0 10px rgba(255,255,255,0.3)}
.slot span{position:absolute;top:2px;left:4px;font-size:10px;opacity:.9;color:#fff;text-shadow:1px 1px 0 #000;z-index:2;pointer-events:none}
.slot-preview{width:100%;height:100%;position:absolute;top:0;left:0;background-size:cover;image-rendering:pixelated}
.slot-count{position:absolute;bottom:2px;right:3px;font-size:11px;color:#fff;text-shadow:1px 1px 0 #000;z-index:2;font-weight:bold}
.ingame-hint{position:absolute;top:50px;left:10px;pointer-events:none;z-index:10;text-shadow:1px 1px 0 #000;font-size:12px;color:rgba(255,255,255,0.8)}
.checkpoint-msg{position:absolute;top:20%;left:50%;transform:translateX(-50%);color:#ffd700;font-size:18px;font-weight:bold;text-shadow:1px 1px 0 #000;opacity:0;transition:opacity .5s;pointer-events:none;z-index:20}
.death-msg{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);font-size:30px;color:#ff3333;text-shadow:2px 2px 0 #000;display:none;background:rgba(0,0,0,0.85);padding:30px;border-radius:10px;text-align:center;z-index:200;border:2px solid #555}
.overlay-screen{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);backdrop-filter:blur(3px);z-index:100;display:none;flex-direction:row;align-items:flex-start;justify-content:center;gap:20px;padding-top:30px}
#survivalInventory{flex-direction:row}
#creativeInventory{justify-content:center;padding-top:60px}
.panel-box{background:rgba(60,60,60,0.95);padding:15px;border-radius:8px;border:2px solid #888;display:flex;flex-direction:column;align-items:center;box-shadow:0 10px 30px rgba(0,0,0,0.5)}
.panel-title{margin-bottom:10px;font-size:16px;color:#ddd;text-transform:uppercase;letter-spacing:1px}
.crafting-area{display:flex;align-items:center;margin-bottom:15px}
.grid-2x2{display:grid;grid-template-columns:repeat(2,1fr);gap:4px}
.grid-3x3{display:grid;grid-template-columns:repeat(3,1fr);gap:4px}
.c-slot{width:40px;height:40px;border:2px solid #555;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;cursor:pointer;position:relative}
.c-slot:hover{border-color:#aaa;background:rgba(255,255,255,0.1)}
.arrow{font-size:24px;color:#888;margin:0 15px}
.result-slot{width:45px;height:45px;border:2px solid #ffd700;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;cursor:pointer;position:relative}
.result-slot:hover{background:rgba(255,215,0,0.2)}
.furnace-area{display:flex;align-items:center;margin-bottom:15px}
.furnace-slots{display:flex;flex-direction:column;gap:4px}
.f-progress{width:40px;height:6px;background:#333;border-radius:3px;margin:4px 0;overflow:hidden}
.f-progress-bar{height:100%;background:#ff8c00;width:0%;transition:width .1s}
.inv-grid{display:grid;grid-template-columns:repeat(9,1fr);gap:4px;margin-top:5px}
.i-slot{width:40px;height:40px;border:2px solid #555;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;cursor:pointer;position:relative}
.i-slot:hover{border-color:#fff}
.inv-hotbar{display:grid;grid-template-columns:repeat(9,1fr);gap:4px;margin-top:15px;padding-top:10px;border-top:2px solid #555}
.ih-slot{width:40px;height:40px;border:2px solid #666;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;cursor:pointer;position:relative}
.ih-slot:hover{border-color:#aaa}
.ih-slot.active{border-color:#ffd700}
.armor-slots{display:flex;flex-direction:column;gap:4px;margin-right:10px;border-right:2px solid #555;padding-right:10px}
.armor-slot{width:40px;height:40px;border:2px solid #555;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;cursor:pointer;position:relative}
.armor-slot:hover{border-color:#aaa}
.armor-icon{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);opacity:.3;font-size:20px;pointer-events:none}
.creative-wrapper{width:800px;height:450px;background:rgba(40,40,40,0.95);border:2px solid #666;border-radius:8px;display:flex;flex-direction:column}
.creative-header{padding:10px 20px;background:rgba(0,0,0,0.3);border-bottom:1px solid #555;display:flex;justify-content:space-between;align-items:center}
.creative-search{background:rgba(0,0,0,0.5);border:1px solid #555;color:#fff;padding:5px 10px;border-radius:4px;outline:none}
.creative-grid-container{flex:1;overflow-y:auto;padding:15px;display:grid;grid-template-columns:repeat(auto-fill,minmax(40px,1fr));gap:6px;align-content:start}
.creative-grid-container::-webkit-scrollbar{width:8px}
.creative-grid-container::-webkit-scrollbar-track{background:#222}
.creative-grid-container::-webkit-scrollbar-thumb{background:#555;border-radius:4px}
.item-btn{width:40px;height:40px;border:1px solid #444;background:rgba(0,0,0,0.3);cursor:pointer;position:relative;transition:.1s}
.item-btn:hover{border-color:#fff;transform:scale(1.1);z-index:10;background:rgba(255,255,255,0.1)}
.item-btn img{width:100%;height:100%;image-rendering:pixelated}
.item-tooltip{position:absolute;bottom:105%;left:50%;transform:translateX(-50%);background:#111;color:#fff;padding:4px 8px;font-size:12px;white-space:nowrap;border:1px solid #555;pointer-events:none;opacity:0;transition:opacity .2s;z-index:100}
.item-btn:hover .item-tooltip{opacity:1}
#pauseMenu{z-index:150;background:rgba(0,0,0,0.7);flex-direction:column}
.pause-title{font-size:32px;margin-bottom:30px;color:#fff;text-shadow:2px 2px 0 #000}
.pause-btn{width:220px;padding:12px;margin:8px;font-size:16px;background:#444;border:2px solid #666;color:#fff;cursor:pointer;transition:.2s;text-align:center}
.pause-btn:hover{background:#555;border-color:#888;transform:scale(1.05)}
#mainMenu{position:absolute;top:0;left:0;width:100%;height:100%;background:linear-gradient(to bottom,#4a69bd,#1e3799);z-index:200;display:flex;flex-direction:column;align-items:center;justify-content:center}
.menu-title{font-size:48px;font-weight:bold;color:#fff;text-shadow:4px 4px 0 #000;margin-bottom:40px}
.menu-btn{width:200px;padding:12px;margin:10px;font-size:18px;background:#7f8c8d;border:2px solid #bdc3c7;color:#fff;cursor:pointer;text-align:center;box-shadow:0 4px 0 #2c3e50}
.menu-btn:active{transform:translateY(4px);box-shadow:none}
.menu-btn.green{background:#27ae60;border-color:#2ecc71;box-shadow:0 4px 0 #1e8449}
.submenu{display:none;flex-direction:column;align-items:center;width:100%}
.input-group{margin:10px;text-align:center;color:#eee}
select,input[type="text"]{padding:8px;font-size:16px;border-radius:4px;border:none}
.world-settings-box{background:rgba(0,0,0,0.3);border:1px solid #555;border-radius:8px;padding:15px 25px;margin:10px;text-align:left;min-width:320px}
.world-settings-box h3{margin-bottom:10px;font-size:16px;color:#ffd700;text-align:center}
.setting-row{display:flex;align-items:center;justify-content:space-between;margin:8px 0;font-size:14px}
.setting-row input[type="checkbox"]{width:18px;height:18px;cursor:pointer;accent-color:#27ae60}
#saveList{width:400px;max-height:300px;overflow-y:auto;background:rgba(0,0,0,0.5);border:1px solid #555;margin-bottom:10px}
.save-item{padding:10px;border-bottom:1px solid #444;cursor:pointer;display:flex;justify-content:space-between}
.save-item:hover{background:rgba(255,255,255,0.1)}
.controls-hint{position:absolute;bottom:-40px;width:100%;text-align:center;color:#666;font-size:12px}
.key{display:inline-block;background:#333;padding:2px 6px;border-radius:4px;color:#aaa;border-bottom:2px solid #111}
#debugScreen{position:absolute;top:45px;right:10px;background:rgba(0,0,0,0.7);padding:10px;border-radius:4px;font-size:12px;font-family:monospace;color:#fff;pointer-events:none;z-index:60;display:none;line-height:1.6}
.item-hover-tip{position:fixed;background:#1a1a2e;color:#fff;padding:4px 10px;font-size:12px;border:1px solid #555;border-radius:4px;pointer-events:none;z-index:9999;display:none;white-space:nowrap;text-shadow:1px 1px 0 #000}
#chatOverlay{position:absolute;bottom:50px;left:10px;width:400px;pointer-events:none;z-index:30;display:flex;flex-direction:column;gap:2px}
.chat-msg{font-size:12px;color:#fff;text-shadow:1px 1px 0 #000;padding:2px 6px;background:rgba(0,0,0,0.4);border-radius:3px;word-break:break-all;animation:chatFade 8s forwards}
@keyframes chatFade{0%,70%{opacity:1}100%{opacity:0}}
#chatInputWrap{position:absolute;bottom:50px;left:10px;width:400px;z-index:160;display:none}
#chatInput{width:100%;padding:6px 10px;font-size:13px;background:rgba(0,0,0,0.8);border:1px solid #555;border-radius:4px;color:#fff;outline:none;font-family:'Segoe UI',Arial,sans-serif}
.page-btn{position:absolute;bottom:20px;right:20px;background:#444;border:2px solid #888;color:#fff;padding:10px 20px;border-radius:6px;cursor:pointer;font-size:14px;font-weight:bold;z-index:110;transition:.2s;box-shadow:0 4px 10px rgba(0,0,0,0.5)}
.page-btn:hover{background:#555;border-color:#ffd700;color:#ffd700;transform:scale(1.05)}
.trash-btn{position:absolute;bottom:20px;left:20px;background:#8b0000;border:2px solid #ff4444;color:#fff;padding:10px 20px;border-radius:6px;cursor:pointer;font-size:14px;font-weight:bold;z-index:110;transition:.2s;box-shadow:0 4px 10px rgba(0,0,0,0.5)}
.trash-btn:hover{background:#ff4444;border-color:#ff6666;transform:scale(1.05)}
#chestUI{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(60,60,60,0.95);padding:15px;border-radius:8px;border:2px solid #888;z-index:120;display:none;flex-direction:column;align-items:center;box-shadow:0 10px 30px rgba(0,0,0,0.5)}
.chest-grid{display:grid;grid-template-columns:repeat(9,1fr);gap:4px;margin-top:5px}
.chest-close{margin-top:10px;padding:6px 20px;background:#444;border:1px solid #666;color:#fff;cursor:pointer;border-radius:4px}
.chest-close:hover{background:#555}
</style>
</head>
<body>
<div id="itemHoverTip" class="item-hover-tip"></div>
<div id="mainMenu">
    <div class="menu-title">MINECRAFT 2D 💎</div>
    <div id="mainOptions">
        <div class="menu-btn green" onclick="showCreateWorld()">创建新世界</div>
        <div class="menu-btn" onclick="showLoadWorld()">读取存档</div>
    </div>
    <div id="createOptions" class="submenu">
        <h2 style="margin-bottom:15px;text-shadow:2px 2px 0 #000">创建新世界</h2>
        <div class="input-group"><label>游戏模式:</label><select id="gameMode"><option value="survival">生存模式</option><option value="creative">创造模式</option><option value="spectator">旁观模式</option></select></div>
        <div class="input-group"><label>难度:</label><select id="difficulty"><option value="peaceful">和平</option><option value="normal" selected>普通</option><option value="hard">困难</option></select></div>
        <div class="input-group"><label>世界类型:</label><select id="worldType"><option value="default">默认</option><option value="flat">超平坦</option></select></div>
        <div class="input-group"><label>种子:</label><input type="text" id="seedInput" placeholder="留空随机"></div>
        <div class="world-settings-box"><h3>⚙️ 世界设置</h3>
            <div class="setting-row"><span>时间流逝</span><input type="checkbox" id="optTimeFlow" checked></div>
            <div class="setting-row"><span>短层+虚空</span><input type="checkbox" id="optShortLayer"></div>
            <div class="setting-row"><span>死亡不掉落</span><input type="checkbox" id="optKeepInv"></div>
            <div class="setting-row"><span>开启作弊</span><input type="checkbox" id="optCheats"></div>
            <div class="setting-row"><span>云朵</span><input type="checkbox" id="optClouds" checked></div>
        </div>
        <div style="margin-top:15px"><div class="menu-btn green" onclick="startGame()">生成世界</div><div class="menu-btn" onclick="backToMain()">返回</div></div>
    </div>
    <div id="loadOptions" class="submenu">
        <h2 style="margin-bottom:10px">选择存档</h2>
        <div id="saveList"></div>
        <div class="menu-btn" onclick="backToMain()">返回</div>
    </div>
</div>
<div id="gameContainer">
    <div class="top-ui-bar"><div class="ui-left"><div class="hearts" id="healthDisplay"></div><div class="hunger-bar" id="hungerDisplay"></div><div id="modeBadge" class="mode-badge">SURVIVAL</div></div><div style="font-size:12px;color:#888">ESC菜单 | T聊天 | F3调试</div></div>
    <canvas id="gameCanvas" width="900" height="600"></canvas>
    <div id="debugScreen"></div>
    <div id="chatOverlay"></div>
    <div id="chatInputWrap"><input id="chatInput" type="text" placeholder="输入消息或指令..." autocomplete="off"></div>
    <div class="ingame-hint"><div id="statusText">状态: 正常</div><div style="margin-top:4px">坐标: <span id="coordDisplay">0, 0</span></div><div style="margin-top:4px">时间: <span id="timeDisplay">Day 1</span></div></div>
    <div class="hotbar-container" id="hotbar"></div>
    <div id="checkpointMsg" class="checkpoint-msg">🚩 重生点已更新</div>
    <div id="deathScreen" class="death-msg"><div id="deathReason">你死了</div><div style="font-size:16px;margin-top:10px;color:#fff">按 <span class="key">R</span> 复活</div></div>
    <div id="survivalInventory" class="overlay-screen">
        <div class="panel-box" id="craftPanel">
            <div class="panel-title">合成 / 熔炼</div>
            <div class="crafting-area" id="smallCraftUI"><div class="grid-2x2" id="craftGridSmall"><div class="c-slot"></div><div class="c-slot"></div><div class="c-slot"></div><div class="c-slot"></div></div><div class="arrow">➜</div><div class="result-slot" id="craftResultSmall"></div></div>
            <div class="crafting-area" id="largeCraftUI" style="display:none"><div class="grid-3x3" id="craftGridLarge"></div><div class="arrow">➜</div><div class="result-slot" id="craftResultLarge"></div></div>
            <div class="furnace-area" id="furnaceUI" style="display:none">
                <div class="furnace-slots"><div class="c-slot" id="furnaceInput"></div><div class="c-slot" id="furnaceFuel"></div></div>
                <div style="margin:0 15px;display:flex;flex-direction:column;align-items:center"><div class="f-progress"><div class="f-progress-bar" id="furnaceBar"></div></div><div style="font-size:10px;color:#aaa;margin-top:2px">🔥 熔炼中</div></div>
                <div class="arrow">➜</div><div class="result-slot" id="furnaceOutput"></div>
            </div>
            <div style="margin-top:10px;font-size:12px;color:#aaa">点击物品放入/取出</div>
        </div>
        <div class="panel-box">
            <div class="panel-title">护甲 & 物品栏</div>
            <div style="display:flex;align-items:flex-start">
                <div class="armor-slots">
                    <div class="armor-slot" id="armorHead" onclick="handleArmorClick(0)"><div class="armor-icon">⛑</div></div>
                    <div class="armor-slot" id="armorChest" onclick="handleArmorClick(1)"><div class="armor-icon">👕</div></div>
                    <div class="armor-slot" id="armorLegs" onclick="handleArmorClick(2)"><div class="armor-icon">👖</div></div>
                    <div class="armor-slot" id="armorFeet" onclick="handleArmorClick(3)"><div class="armor-icon">👢</div></div>
                </div>
                <div><div class="inv-grid" id="invGrid"></div><div class="inv-hotbar" id="invHotbar"></div></div>
            </div>
        </div>
        <div class="page-btn" id="btnNextPage" onclick="switchInvPage('creative')" style="display:none">下一页 ➜</div>
        <div class="trash-btn" id="btnTrash" onclick="deleteHeldItem()" style="display:none">🗑️</div>
    </div>
    <div id="creativeInventory" class="overlay-screen"><div class="creative-wrapper"><div class="creative-header"><div class="panel-title" style="margin:0">创造模式物品</div><input type="text" class="creative-search" placeholder="搜索..." onkeyup="filterCreativeItems(this.value)"></div><div class="creative-grid-container" id="creativeGrid"></div><div style="padding:10px;text-align:center;color:#888;font-size:12px;background:rgba(0,0,0,0.3)">左键一组 | 右键一个</div></div>
        <div class="page-btn" id="btnPrevPage" onclick="switchInvPage('survival')">➜ 上一页</div>
        <div class="trash-btn" id="btnTrash2" onclick="deleteHeldItem()">🗑️</div>
    </div>
    <div id="pauseMenu" class="overlay-screen"><div class="pause-title">暂停</div><div class="pause-btn" onclick="saveAndExit()">💾 保存并退出</div><div class="pause-btn" onclick="togglePause()">▶ 继续</div></div>
    <div id="chestUI">
        <div class="panel-title">箱子</div>
        <div class="chest-grid" id="chestGrid"></div>
        <div class="chest-close" onclick="closeChest()">关闭</div>
    </div>
</div>
<div class="controls-hint" id="gameHints" style="display:none"><span class="key">A/D</span>移动 <span class="key">W/S</span>上/下 <span class="key">E</span>背包 <span class="key">T</span>聊天 <span class="key">F3</span>调试 <span class="key">左键</span>挖/攻击 <span class="key">右键</span>放/使用</div>

<script>
// ========== 菜单 ==========
window.showCreateWorld=function(){document.getElementById("mainOptions").style.display="none";document.getElementById("createOptions").style.display="flex"};
window.showLoadWorld=function(){document.getElementById("mainOptions").style.display="none";document.getElementById("loadOptions").style.display="flex";loadSaveList()};
window.backToMain=function(){document.querySelectorAll(".submenu").forEach(el=>el.style.display="none");document.getElementById("mainOptions").style.display="flex"};
window.togglePause=function(){if(player.dead)return;if(document.getElementById("survivalInventory").style.display==="flex"||document.getElementById("creativeInventory").style.display==="flex"){toggleInventory();return}const m=document.getElementById("pauseMenu");isPaused=!isPaused;m.style.display=isPaused?"flex":"none"};
window.saveAndExit=function(){const n=`存档_${new Date().toLocaleTimeString()}`;const d={name:n,date:new Date().toLocaleString(),map:globalMap,player:{x:player.x,y:player.y,hp:player.hp,hunger:player.hunger,saturation:player.saturation,facing:player.facing,flying:player.flying,inBoat:player.inBoat,boatX:player.boatX,boatY:player.boatY},spawn:spawnPoint,type:currentWorldType,mode:gameMode,seed:currentSeed,diff:gameDifficulty,inv:inventorySlots,hotbar:hotbarSlots,time:gameTime,optTimeFlow:worldOptTimeFlow,optShortLayer:worldOptShortLayer,optKeepInv:worldOptKeepInv,cheats:cheatsEnabled,clouds:cloudsEnabled,treesCols:treesGeneratedCols,furnace:furnaceState,armor:armorSlots,chests:chestData};let s=JSON.parse(localStorage.getItem("mc2d_saves_list")||"[]");s.push(n);localStorage.setItem("mc2d_saves_list",JSON.stringify(s));localStorage.setItem(`mc2d_save_${n}`,JSON.stringify(d));location.reload()};

// ========== 核心变量 ==========
const canvas=document.getElementById("gameCanvas"),ctx=canvas.getContext("2d");
const tileSize=32;
let gameTime=0,cameraX=0,cameraY=0,particles=[];
let isDragging=false,dragButton=-1,lastTx=-1,lastTy=-1;
let isPaused=false,mouseGlobalX=0,mouseGlobalY=0,currentSeed=0;
let gameDifficulty='normal',dayCount=1,currentWorldType='default';
let worldOptTimeFlow=true,worldOptShortLayer=false,worldOptKeepInv=false;
let cheatsEnabled=false,cloudsEnabled=true;
let showDebug=false,treesGeneratedCols={},chatOpen=false;
let armorSlots=[null,null,null,null];
let chestData={};
let openChestKey=null;

// ========== 纹理生成 ==========
const textures={};
const WOOL_COLORS=[{id:60,name:"白色羊毛",color:"#FFFFFF"},{id:61,name:"橙色羊毛",color:"#D87F33"},{id:62,name:"品红羊毛",color:"#B24CD8"},{id:63,name:"淡蓝羊毛",color:"#6699D8"},{id:64,name:"黄色羊毛",color:"#E5E533"},{id:65,name:"黄绿羊毛",color:"#7FCC19"},{id:66,name:"粉红羊毛",color:"#F27FA5"},{id:67,name:"灰色羊毛",color:"#4C4C4C"},{id:68,name:"淡灰羊毛",color:"#999999"},{id:69,name:"青色羊毛",color:"#4C7F99"},{id:70,name:"紫色羊毛",color:"#7F3FB2"},{id:71,name:"蓝色羊毛",color:"#334CB2"},{id:72,name:"棕色羊毛",color:"#664C33"},{id:73,name:"绿色羊毛",color:"#667F33"},{id:74,name:"红色羊毛",color:"#993333"},{id:75,name:"黑色羊毛",color:"#191919"}];

function genTex(id,col,type){
    const c=document.createElement('canvas');c.width=c.height=tileSize;const x=c.getContext('2d');
    x.fillStyle=col;x.fillRect(0,0,32,32);
    for(let i=0;i<40;i++){x.fillStyle=Math.random()>.5?"rgba(255,255,255,0.1)":"rgba(0,0,0,0.1)";x.fillRect(Math.random()*32,Math.random()*32,2,2)}
    if(type==='grass'){x.fillStyle="#3da336";x.fillRect(0,0,32,6);for(let i=0;i<8;i++)x.fillRect(Math.random()*28,6,2,4)}
    else if(type==='wood'){x.fillStyle="rgba(0,0,0,0.2)";x.fillRect(4,0,4,32);x.fillRect(12,0,4,32)}
    else if(type==='leaves'){x.fillStyle="rgba(0,0,0,0.2)";for(let i=0;i<10;i++)x.fillRect(Math.random()*28,Math.random()*28,4,4)}
    else if(type==='stone'){x.fillStyle="rgba(0,0,0,0.15)";x.fillRect(5,5,10,6);x.fillRect(18,20,8,5)}
    else if(type==='planks'){x.strokeStyle="rgba(0,0,0,0.2)";x.beginPath();x.moveTo(0,8);x.lineTo(32,8);x.moveTo(0,16);x.lineTo(32,16);x.stroke()}
    else if(type==='coal_ore'){x.fillStyle="#222";x.fillRect(6,6,6,6);x.fillRect(18,14,7,7);x.fillRect(10,22,5,5)}
    else if(type==='iron_ore'){x.fillStyle="#d4a574";x.fillRect(5,5,6,6);x.fillRect(19,12,6,6);x.fillRect(8,23,5,5)}
    else if(type==='diamond_ore'){x.fillStyle="#4af";x.fillRect(5,5,6,6);x.fillRect(19,12,6,6);x.fillRect(8,23,5,5);x.fillStyle="rgba(255,255,255,0.3)";x.fillRect(6,6,3,3);x.fillRect(20,13,3,3)}
    else if(type==='gold'){x.fillStyle="rgba(255,255,255,0.4)";x.fillRect(4,4,8,8);x.fillRect(20,20,8,8)}
    else if(type==='glass'){x.clearRect(0,0,32,32);x.fillStyle="rgba(200,240,255,0.2)";x.fillRect(0,0,32,32);x.strokeStyle="rgba(255,255,255,0.8)";x.lineWidth=2;x.strokeRect(1,1,30,30)}
    else if(type==='stick'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,4,4,24)}
    else if(type==='pickaxe'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,10,4,18);x.fillStyle="#d2b48c";x.fillRect(6,4,20,6)}
    else if(type==='stone_pickaxe'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,10,4,18);x.fillStyle="#888";x.fillRect(6,4,20,6)}
    else if(type==='iron_pickaxe'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,10,4,18);x.fillStyle="#d4d4d4";x.fillRect(6,4,20,6)}
    else if(type==='diamond_pickaxe'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,10,4,18);x.fillStyle="#4af";x.fillRect(6,4,20,6)}
    else if(type==='wood_shovel'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,8,4,20);x.fillStyle="#d2b48c";x.fillRect(10,2,12,8)}
    else if(type==='stone_shovel'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,8,4,20);x.fillStyle="#888";x.fillRect(10,2,12,8)}
    else if(type==='iron_shovel'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,8,4,20);x.fillStyle="#d4d4d4";x.fillRect(10,2,12,8)}
    else if(type==='diamond_shovel'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,8,4,20);x.fillStyle="#4af";x.fillRect(10,2,12,8)}
    else if(type==='wood_sword'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,14,4,14);x.fillStyle="#d2b48c";x.fillRect(13,2,6,14);x.fillStyle="#8b5a2b";x.fillRect(10,14,12,3)}
    else if(type==='stone_sword'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,14,4,14);x.fillStyle="#888";x.fillRect(13,2,6,14);x.fillStyle="#8b5a2b";x.fillRect(10,14,12,3)}
    else if(type==='iron_sword'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,14,4,14);x.fillStyle="#d4d4d4";x.fillRect(13,2,6,14);x.fillStyle="#8b5a2b";x.fillRect(10,14,12,3)}
    else if(type==='diamond_sword'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,14,4,14);x.fillStyle="#4af";x.fillRect(13,2,6,14);x.fillStyle="#8b5a2b";x.fillRect(10,14,12,3)}
    else if(type==='wood_axe'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,12,4,16);x.fillStyle="#d2b48c";x.fillRect(6,4,14,10);x.fillRect(6,4,4,14)}
    else if(type==='stone_axe'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,12,4,16);x.fillStyle="#888";x.fillRect(6,4,14,10);x.fillRect(6,4,4,14)}
    else if(type==='iron_axe'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,12,4,16);x.fillStyle="#d4d4d4";x.fillRect(6,4,14,10);x.fillRect(6,4,4,14)}
    else if(type==='diamond_axe'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.fillRect(14,12,4,16);x.fillStyle="#4af";x.fillRect(6,4,14,10);x.fillRect(6,4,4,14)}
    else if(type==='workbench'){x.fillStyle="#5c3a21";x.fillRect(2,2,28,4);x.fillRect(2,10,28,4);x.fillStyle="#888";x.fillRect(4,4,6,6)}
    else if(type==='furnace'){x.fillStyle="#666";x.fillRect(0,0,32,32);x.fillStyle="#333";x.fillRect(8,10,16,14);x.fillStyle="#ff6600";x.fillRect(10,16,12,6)}
    else if(type==='chest'){x.fillStyle="#8b5a2b";x.fillRect(2,6,28,22);x.fillStyle="#6b3a1b";x.fillRect(2,6,28,4);x.fillStyle="#ffd700";x.fillRect(13,14,6,4)}
    else if(type==='bedrock'){x.fillStyle="#333";x.fillRect(0,0,32,32);x.fillStyle="#555";x.fillRect(4,4,8,8);x.fillRect(16,12,10,10);x.fillRect(8,20,6,6)}
    else if(type==='cloud'){x.clearRect(0,0,32,32);x.fillStyle="rgba(255,255,255,0.6)";x.fillRect(0,0,32,32)}
    else if(type==='boat'){x.clearRect(0,0,32,32);x.fillStyle="#8b5a2b";x.beginPath();x.moveTo(2,12);x.lineTo(6,26);x.lineTo(26,26);x.lineTo(30,12);x.lineTo(26,16);x.lineTo(6,16);x.closePath();x.fill();x.fillStyle="#a0722d";x.fillRect(14,6,4,12)}
    else if(type==='diamond_item'){x.clearRect(0,0,32,32);x.fillStyle="#4af";x.fillRect(8,8,16,16);x.fillStyle="rgba(255,255,255,0.4)";x.fillRect(10,10,6,6)}
    else if(type==='raw_pork'){x.clearRect(0,0,32,32);x.fillStyle="#ffa0a0";x.fillRect(8,8,16,16);x.fillStyle="#ffcccc";x.fillRect(10,10,6,6)}
    else if(type==='cooked_pork'){x.clearRect(0,0,32,32);x.fillStyle="#b5651d";x.fillRect(8,8,16,16);x.fillStyle="#d4944a";x.fillRect(10,10,6,6)}
    else if(type==='raw_beef'){x.clearRect(0,0,32,32);x.fillStyle="#cc3333";x.fillRect(6,10,20,12);x.fillStyle="#ff6666";x.fillRect(8,12,8,4)}
    else if(type==='cooked_beef'){x.clearRect(0,0,32,32);x.fillStyle="#8b4513";x.fillRect(6,10,20,12);x.fillStyle="#a0522d";x.fillRect(8,12,8,4)}
    else if(type==='raw_mutton'){x.clearRect(0,0,32,32);x.fillStyle="#e07070";x.fillRect(8,6,16,20);x.fillStyle="#ffaaaa";x.fillRect(10,8,6,6)}
    else if(type==='cooked_mutton'){x.clearRect(0,0,32,32);x.fillStyle="#a0522d";x.fillRect(8,6,16,20);x.fillStyle="#cd853f";x.fillRect(10,8,6,6)}
    else if(type==='coal_item'){x.clearRect(0,0,32,32);x.fillStyle="#222";x.fillRect(8,8,16,16);x.fillStyle="#444";x.fillRect(10,10,4,4)}
    else if(type==='iron_ingot'){x.clearRect(0,0,32,32);x.fillStyle="#d4d4d4";x.fillRect(6,10,20,12);x.fillStyle="#fff";x.fillRect(8,12,6,3)}
    textures[id]=c;
}

// ========== 方块定义 ==========
const BLOCKS={
0:{name:"空气",solid:false,liquid:false,damage:0,hardness:0},
1:{name:"草地",color:"#49b043",solid:true,tex:'grass',hardness:0.6,drop:2},
2:{name:"泥土",color:"#956239",solid:true,tex:'dirt',hardness:0.5,drop:2},
3:{name:"石头",color:"#7a7a7a",solid:true,tex:'stone',hardness:2,drop:3,tool:'pickaxe',minToolTier:1},
4:{name:"水",color:"rgba(30,144,255,0.6)",solid:false,liquid:true,hardness:0},
5:{name:"岩浆",color:"#ff4500",solid:false,liquid:true,damage:1,glow:true,hardness:0},
6:{name:"原木",color:"#5c4033",solid:true,tex:'wood',hardness:1,drop:6},
7:{name:"木板",color:"#d2b48c",solid:true,tex:'planks',hardness:0.8,drop:7,fuel:600},
8:{name:"沙子",color:"#f4a460",solid:true,hardness:0.5,drop:8},
9:{name:"玻璃",color:"rgba(200,240,255,0.3)",solid:true,tex:'glass',hardness:0.3},
10:{name:"工作台",color:"#8b4513",solid:true,tex:'workbench',hardness:1.5,drop:10,interact:'workbench'},
11:{name:"树叶",color:"#2d8a2d",solid:true,tex:'leaves',hardness:0.2,drop:6},
13:{name:"金块",color:"#ffd700",solid:true,tex:'gold',checkpoint:true,hardness:1.5,drop:13},
16:{name:"煤矿",color:"#555",solid:true,tex:'coal_ore',hardness:2.5,drop:50,tool:'pickaxe',minToolTier:1},
17:{name:"铁矿",color:"#8B7355",solid:true,tex:'iron_ore',hardness:3,drop:17,tool:'pickaxe',minToolTier:2},
18:{name:"钻石矿",color:"#2266aa",solid:true,tex:'diamond_ore',hardness:4,drop:80,tool:'pickaxe',minToolTier:3},
24:{name:"熔炉",color:"#666",solid:true,tex:'furnace',hardness:2,drop:24,interact:'furnace',tool:'pickaxe'},
25:{name:"箱子",color:"#8b5a2b",solid:true,tex:'chest',hardness:1.5,drop:25,interact:'chest'},
32:{name:"基岩",color:"#333",solid:true,tex:'bedrock',hardness:-1,drop:0},
14:{name:"木棍",color:"#8b5a2b",solid:false,item:true,tex:'stick'},
15:{name:"木镐",color:"#d2b48c",solid:false,item:true,tool:'pickaxe',efficiency:3,tier:1,tex:'pickaxe'},
19:{name:"石镐",color:"#888",solid:false,item:true,tool:'pickaxe',efficiency:5,tier:2,tex:'stone_pickaxe'},
29:{name:"铁镐",color:"#d4d4d4",solid:false,item:true,tool:'pickaxe',efficiency:8,tier:3,tex:'iron_pickaxe'},
81:{name:"钻石镐",color:"#4af",solid:false,item:true,tool:'pickaxe',efficiency:16,tier:4,tex:'diamond_pickaxe'},
33:{name:"木铲",color:"#d2b48c",solid:false,item:true,tool:'shovel',efficiency:3,tier:1,tex:'wood_shovel'},
34:{name:"石铲",color:"#888",solid:false,item:true,tool:'shovel',efficiency:5,tier:2,tex:'stone_shovel'},
35:{name:"铁铲",color:"#d4d4d4",solid:false,item:true,tool:'shovel',efficiency:8,tier:3,tex:'iron_shovel'},
82:{name:"钻石铲",color:"#4af",solid:false,item:true,tool:'shovel',efficiency:16,tier:4,tex:'diamond_shovel'},
22:{name:"木斧",color:"#d2b48c",solid:false,item:true,tool:'axe',efficiency:3,tier:1,tex:'wood_axe'},
23:{name:"石斧",color:"#888",solid:false,item:true,tool:'axe',efficiency:5,tier:2,tex:'stone_axe'},
31:{name:"铁斧",color:"#d4d4d4",solid:false,item:true,tool:'axe',efficiency:8,tier:3,tex:'iron_axe'},
83:{name:"钻石斧",color:"#4af",solid:false,item:true,tool:'axe',efficiency:16,tier:4,tex:'diamond_axe'},
20:{name:"木剑",color:"#d2b48c",solid:false,item:true,weapon:true,damage:3,tex:'wood_sword'},
21:{name:"石剑",color:"#888",solid:false,item:true,weapon:true,damage:4,tex:'stone_sword'},
30:{name:"铁剑",color:"#d4d4d4",solid:false,item:true,weapon:true,damage:5,tex:'iron_sword'},
84:{name:"钻石剑",color:"#4af",solid:false,item:true,weapon:true,damage:10,tex:'diamond_sword'},
85:{name:"钻石头盔",color:"#4af",solid:false,item:true,armor:0,defense:6,tex:'diamond_item'},
86:{name:"钻石胸甲",color:"#4af",solid:false,item:true,armor:1,defense:16,tex:'diamond_item'},
87:{name:"钻石护腿",color:"#4af",solid:false,item:true,armor:2,defense:12,tex:'diamond_item'},
88:{name:"钻石靴子",color:"#4af",solid:false,item:true,armor:3,defense:6,tex:'diamond_item'},
50:{name:"煤炭",color:"#222",solid:false,item:true,fuel:800,tex:'coal_item'},
51:{name:"铁锭",color:"#d4d4d4",solid:false,item:true,tex:'iron_ingot'},
80:{name:"钻石",color:"#4af",solid:false,item:true,tex:'diamond_item'},
52:{name:"生猪排",color:"#ffa0a0",solid:false,item:true,food:3,saturation:1.8,cookTo:55,tex:'raw_pork'},
53:{name:"生牛肉",color:"#cc3333",solid:false,item:true,food:3,saturation:1.8,cookTo:56,tex:'raw_beef'},
54:{name:"生羊肉",color:"#e07070",solid:false,item:true,food:2,saturation:1.2,cookTo:57,tex:'raw_mutton'},
55:{name:"熟猪排",color:"#b5651d",solid:false,item:true,food:8,saturation:12.8,tex:'cooked_pork'},
56:{name:"牛排",color:"#8b4513",solid:false,item:true,food:8,saturation:12.8,tex:'cooked_beef'},
57:{name:"熟羊肉",color:"#a0522d",solid:false,item:true,food:6,saturation:9.6,tex:'cooked_mutton'},
27:{name:"船",color:"#8b5a2b",solid:false,item:true,placeable:true,tex:'boat'},
28:{name:"船(放置)",color:"#8b5a2b",solid:false,liquid:false,boat:true,hardness:0.3,drop:27,tex:'boat'},
};
WOOL_COLORS.forEach(w=>BLOCKS[w.id]={name:w.name,color:w.color,solid:true,tex:'wool',hardness:0.8,drop:w.id});
Object.keys(BLOCKS).forEach(k=>{if(k!=0&&!textures[k])genTex(k,BLOCKS[k].color,BLOCKS[k].tex||'default')});
const SMELT_RECIPES={17:51,18:80,52:55,53:56,54:57};

// ========== 地图 ==========
let globalMap={};
function getBlock(x,y){return globalMap[y]?(globalMap[y][x]||0):0}
function setBlock(x,y,id){if(!globalMap[y])globalMap[y]={};globalMap[y][x]=id}

// ========== 玩家 ==========
let player={x:0,y:0,w:24,h:28,vx:0,vy:0,speed:2.8,gravity:0.5,jumpPower:-9,onGround:false,inLiquid:false,hp:10,maxHp:10,hunger:20,maxHunger:20,saturation:5,invTimer:0,dead:false,facing:1,attackCooldown:0,fallStartY:null,hungerTimer:0,healTimer:0,flying:true,lastJumpTime:0,inBoat:false,boatX:-1,boatY:-1};
let gameMode='survival',spawnPoint={x:0,y:0};
let zombies=[],sheeps=[],pigs=[],cows=[];
let zombieSpawnTimer=0;
let hotbarSlots=new Array(9).fill(null),inventorySlots=new Array(27).fill(null);
let craftingGridSmall=[null,null,null,null],craftingGridLarge=new Array(9).fill(null);
let selectedSlotIndex=0,heldItem=null,currentCraftMode='small';
let furnaceState={input:null,fuel:null,output:null,fuelLeft:0,smeltProgress:0,smeltTarget:0};

function initItems(){hotbarSlots=new Array(9).fill(null);inventorySlots=new Array(27).fill(null);craftingGridSmall=[null,null,null,null];craftingGridLarge=new Array(9).fill(null);heldItem=null;zombies=[];sheeps=[];pigs=[];cows=[];furnaceState={input:null,fuel:null,output:null,fuelLeft:0,smeltProgress:0,smeltTarget:0};treesGeneratedCols={};armorSlots=[null,null,null,null];chestData={}}

// ========== 噪声 & 地形 ==========
function hashNoise(x,s){let n=Math.sin(x*127.1+s*311.7)*43758.5453123;return n-Math.floor(n)}
function smoothNoise(x,s){const ix=Math.floor(x),fx=x-ix;return hashNoise(ix,s)+(hashNoise(ix+1,s)-hashNoise(ix,s))*(fx*fx*(3-2*fx))}
function octaveNoise(x,s,o,p){let t=0,f=0.02,a=1,m=0;for(let i=0;i<o;i++){t+=smoothNoise(x*f,s+i*100)*a;m+=a;a*=p;f*=2}return t/m}
function noise2D(x,y,s){const c=x*374761393+y*668265263+s*1274126177;return hashNoise(c,c*0.0000001+1)}
function getTerrainHeight(x,type){if(type==='flat')return 20;return Math.floor(25+(octaveNoise(x,currentSeed,4,0.5)-0.5)*30)}
function getBiome(x){const v=octaveNoise(x,currentSeed+9999,2,0.5);if(v<0.30)return 2;if(v>0.55)return 1;return 0}

// ★ 修改:钻石矿只在底部生成(y>h+25),概率放宽到0.88~0.94
function generateColumn(x,type){
    if(type==='flat'){for(let y=0;y<80;y++){if(y===20)setBlock(x,y,1);else if(y>20&&y<25)setBlock(x,y,2);else if(y>=25&&y<79)setBlock(x,y,3);else if(y===79)setBlock(x,y,32)}return}
    const h=getTerrainHeight(x,type),biome=getBiome(x),seaLevel=30,bedrockY=79;
    for(let y=0;y<80;y++){let id=0;
        if(y===bedrockY)id=32;
        else if(biome===2){const of=Math.min(h+3,seaLevel);if(y===of)id=8;else if(y>of&&y<=seaLevel)id=4;else if(y>seaLevel&&y<bedrockY){if(worldOptShortLayer)id=(y<of+4)?3:0;else{const rh=noise2D(x,y,currentSeed+7777);if(y>of+3&&rh>0.96)id=16;else if(y>of+6&&rh>0.92&&rh<=0.96)id=17;else if(y>of+25&&rh>0.91&&rh<=0.94)id=18;else id=3}}}
        else{if(y===h)id=1;else if(y>h&&y<h+5)id=2;else if(y>=h+5&&y<bedrockY){if(worldOptShortLayer)id=(y<h+7)?3:0;else{const rh=noise2D(x,y,currentSeed+7777);if(y>h+6&&rh>0.96)id=16;else if(y>h+12&&rh>0.92&&rh<=0.96)id=17;else if(y>h+25&&rh>0.91&&rh<=0.94)id=18;else id=3}}}
        setBlock(x,y,id)}
}
function generateTrees(sx,ex,type){
    if(type==='flat'||worldOptShortLayer)return;
    for(let x=sx;x<=ex;x++){if(treesGeneratedCols[x])continue;treesGeneratedCols[x]=true;const biome=getBiome(x);if(biome===2)continue;const tc=biome===1?0.45:0.04;if(hashNoise(x*17,currentSeed+555)>=tc)continue;const h=getTerrainHeight(x,type);if(getBlock(x,h)!==1||getBlock(x,h-1)!==0)continue;const th=4+Math.floor(hashNoise(x,currentSeed+777)*3);for(let i=1;i<=th;i++)setBlock(x,h-i,6);const topY=h-th;for(let lx=-2;lx<=2;lx++)for(let ly=-2;ly<=0;ly++)if(Math.abs(lx)+Math.abs(ly)<3){const leafX=x+lx,leafY=topY+ly;if(getBlock(leafX,leafY)===0)setBlock(leafX,leafY,11)}}
}
function checkExpansion(){const px=Math.floor(player.x/tileSize);let nc=false;for(let x=px-30;x<=px+30;x++)if(!globalMap['_gen_'+x]){generateColumn(x,currentWorldType);globalMap['_gen_'+x]=true;nc=true}if(nc)generateTrees(px-28,px+28,currentWorldType)}

// ========== 输入(★ 已删除F键快速挖掘) ==========
const keys={};
document.addEventListener("keydown",e=>{if(chatOpen)return;keys[e.key.toLowerCase()]=true;if(e.key==="Escape"){if(openChestKey!==null){closeChest();return}togglePause()}if(e.key==="F3"){e.preventDefault();showDebug=!showDebug;document.getElementById("debugScreen").style.display=showDebug?"block":"none"}if(e.key.toLowerCase()==='t'&&!isPaused&&!player.dead){e.preventDefault();openChat();return}const num=parseInt(e.key);if(num>=1&&num<=9){selectedSlotIndex=num-1;updateHotbarUI();updateInvHotbarUI()}if(e.key.toLowerCase()==='e'){if(openChestKey!==null){closeChest();return}toggleInventory()}if(e.key.toLowerCase()==='r'&&player.dead)respawn();if(e.key==='Shift'&&player.inBoat){player.inBoat=false;player.boatX=-1;player.boatY=-1}if(!player.dead&&!isPaused){if(e.key.toLowerCase()==='a')player.facing=-1;if(e.key.toLowerCase()==='d')player.facing=1;if((e.key.toLowerCase()==='w'||e.key===' ')&&gameMode==='creative'){const now=Date.now();if(now-player.lastJumpTime<300){player.flying=!player.flying;player.vy=0;spawnParticles(player.x+player.w/2,player.y+player.h/2,"#fff",8)}player.lastJumpTime=now}}});
document.addEventListener("keyup",e=>{if(!chatOpen)keys[e.key.toLowerCase()]=false});
function getMouseWorldPos(e){const r=canvas.getBoundingClientRect();return{wx:(e.clientX-r.left)+cameraX,wy:(e.clientY-r.top)+cameraY}}

// ========== 聊天 & 指令 ==========
function addChatMsg(text,color){const overlay=document.getElementById("chatOverlay");const div=document.createElement("div");div.className="chat-msg";div.textContent=text;if(color)div.style.color=color;overlay.appendChild(div);while(overlay.children.length>20)overlay.removeChild(overlay.firstChild);setTimeout(()=>{if(div.parentNode)div.parentNode.removeChild(div)},8000)}
function openChat(){chatOpen=true;document.getElementById("chatInputWrap").style.display="block";const inp=document.getElementById("chatInput");inp.value="";inp.focus()}
function closeChat(){chatOpen=false;document.getElementById("chatInputWrap").style.display="none"}
function processCommand(cmd){const parts=cmd.trim().split(/\s+/);if(parts[0]==="/give"){if(!cheatsEnabled){addChatMsg("❌ 作弊未开启","#ff5555");return}if(parts.length<2){addChatMsg("用法: /give <id或名称> [数量]","#ffff55");return}const arg=parts[1];const count=parts.length>=3?parseInt(parts[2]):1;let foundId=null;const numId=parseInt(arg);if(!isNaN(numId)&&BLOCKS[numId])foundId=numId;else{for(const k in BLOCKS){if(BLOCKS[k].name===arg||BLOCKS[k].name.toLowerCase()===arg.toLowerCase()){foundId=parseInt(k);break}}}if(foundId===null||foundId===0){addChatMsg(`❌ 未找到: ${arg}`,"#ff5555");return}addItemToInventory(foundId,count);addChatMsg(`✔ 获得 ${BLOCKS[foundId].name} x${count}`,"#55ff55")}else if(parts[0]==="/gamemode"){if(!cheatsEnabled){addChatMsg("❌ 作弊未开启","#ff5555");return}if(parts.length<2){addChatMsg("用法: /gamemode <survival|creative|spectator>","#ffff55");return}const mode=parts[1];if(mode==='survival'||mode==='creative'||mode==='spectator'){gameMode=mode;player.flying=(gameMode!=='survival');const badge=document.getElementById("modeBadge");badge.innerText=gameMode==='creative'?"CREATIVE":gameMode==='spectator'?"SPECTATOR":"SURVIVAL";badge.className=`mode-badge ${gameMode}`;addChatMsg(`✔ 已切换到 ${gameMode==='creative'?'创造模式':gameMode==='spectator'?'旁观模式':'生存模式'}`,"#55ff55")}else{addChatMsg("❌ 未知模式: "+mode,"#ff5555")}}else{addChatMsg(`未知指令: ${parts[0]}`,"#ffff55")}}
document.getElementById("chatInput").addEventListener("keydown",function(e){e.stopPropagation();if(e.key==="Enter"){const val=this.value.trim();if(val){if(val.startsWith("/"))processCommand(val);else addChatMsg(`<玩家> ${val}`)}closeChat()}else if(e.key==="Escape")closeChat()});
document.getElementById("chatInput").addEventListener("keyup",function(e){e.stopPropagation()});

// ========== Tooltip ==========
const hoverTip=document.getElementById("itemHoverTip");
function attachItemTooltip(el,item){if(!item||!BLOCKS[item.id])return;el.addEventListener("mouseenter",(e)=>{hoverTip.textContent=BLOCKS[item.id].name+(item.count>1?` x${item.count}`:"");hoverTip.style.display="block";hoverTip.style.left=(e.clientX+12)+"px";hoverTip.style.top=(e.clientY-28)+"px"});el.addEventListener("mousemove",(e)=>{hoverTip.style.left=(e.clientX+12)+"px";hoverTip.style.top=(e.clientY-28)+"px"});el.addEventListener("mouseleave",()=>{hoverTip.style.display="none"})}

// ========== 战斗 ==========
function tryAttack(){if(player.attackCooldown>0||player.dead||isPaused||gameMode==='spectator')return;const held=hotbarSlots[selectedSlotIndex];let dmg=1;if(held&&BLOCKS[held.id]?.weapon)dmg=BLOCKS[held.id].damage;const wx=mouseGlobalX+cameraX,wy=mouseGlobalY+cameraY;const allMobs=[...zombies.map(z=>({e:z,arr:'zombie'})),...sheeps.map(s=>({e:s,arr:'sheep'})),...pigs.map(p=>({e:p,arr:'pig'})),...cows.map(c=>({e:c,arr:'cow'}))];for(let m of allMobs){if(Math.abs(wx-(m.e.x+m.e.w/2))<40&&Math.abs(wy-(m.e.y+m.e.h/2))<40){m.e.hp-=dmg;m.e.vx=(m.e.x-player.x)>0?5:-5;m.e.vy=-3;spawnParticles(m.e.x+m.e.w/2,m.e.y+m.e.h/2,"#ff0000",6);if(m.e.hp<=0){spawnParticles(m.e.x+m.e.w/2,m.e.y+m.e.h/2,"#fff",10);if(m.arr==='zombie')zombies=zombies.filter(z=>z!==m.e);else if(m.arr==='sheep'){sheeps=sheeps.filter(s=>s!==m.e);addItemToInventory(60,1+Math.floor(Math.random()*2));addItemToInventory(54,1)}else if(m.arr==='pig'){pigs=pigs.filter(p=>p!==m.e);addItemToInventory(52,1+Math.floor(Math.random()*2))}else if(m.arr==='cow'){cows=cows.filter(c=>c!==m.e);addItemToInventory(53,1+Math.floor(Math.random()*2))}}player.attackCooldown=20;return}}player.attackCooldown=20}

// ========== 挖掘 & 放置(★ 已删除keys['f']判断和fastDig函数) ==========
let miningProgress=0,miningTarget={x:-1,y:-1,id:0};
function handleRightClick(tx,ty){if(player.dead||isPaused||gameMode==='spectator')return;const b=getBlock(tx,ty);
    if(b!==0&&BLOCKS[b]?.interact){
        if(BLOCKS[b].interact==='workbench'){if(document.getElementById("survivalInventory").style.display==="flex"){toggleInventory();return}currentCraftMode='large';isPaused=true;document.getElementById("survivalInventory").style.display="flex";updateInventoryUI();updateInvHotbarUI();checkCrafting();return}
        if(BLOCKS[b].interact==='furnace'){if(document.getElementById("survivalInventory").style.display==="flex"){toggleInventory();return}currentCraftMode='furnace';isPaused=true;document.getElementById("survivalInventory").style.display="flex";updateInventoryUI();updateInvHotbarUI();updateFurnaceUI();return}
        if(BLOCKS[b].interact==='chest'){openChest(tx,ty);return}
    }
    if(b!==0&&BLOCKS[b]?.boat){player.inBoat=true;player.boatX=tx;player.boatY=ty;player.x=tx*tileSize+4;player.y=ty*tileSize-4;player.vy=0;player.vx=0;return}
    const held=hotbarSlots[selectedSlotIndex];
    if(held&&BLOCKS[held.id]?.food&&gameMode==='survival'){const fd=BLOCKS[held.id];if(player.hunger<player.maxHunger||player.hp<player.maxHp){player.hunger=Math.min(player.maxHunger,player.hunger+fd.food);player.saturation=Math.min(player.hunger,player.saturation+fd.saturation);held.count--;if(held.count<=0)hotbarSlots[selectedSlotIndex]=null;updateHotbarUI();updateInvHotbarUI();spawnParticles(player.x+player.w/2,player.y,"#0f0",5);return}}
    if(held&&BLOCKS[held.id]?.placeable&&b===4){setBlock(tx,ty,28);held.count--;if(held.count<=0)hotbarSlots[selectedSlotIndex]=null;updateHotbarUI();updateInvHotbarUI();return}
    placeBlockAt(tx,ty)}
function processTileAction(tx,ty){if(tx===lastTx&&ty===lastTy)return;if(dragButton===0){const b=getBlock(tx,ty);if(b!==0&&BLOCKS[b]?.solid){miningTarget={x:tx,y:ty,id:b};miningProgress=0}}else if(dragButton===2){handleRightClick(tx,ty)}lastTx=tx;lastTy=ty}
function updateMining(){if(gameMode==='spectator')return;if(miningTarget.id!==0){const tx=miningTarget.x,ty=miningTarget.y;const mx=Math.floor((mouseGlobalX+cameraX)/tileSize),my=Math.floor((mouseGlobalY+cameraY)/tileSize);if(mx===tx&&my===ty&&dragButton===0){const bd=BLOCKS[miningTarget.id];if(gameMode==='survival'&&bd.hardness<0){miningTarget.id=0;miningProgress=0;return}let spd=0.02;let toolMatched=false;const held=hotbarSlots[selectedSlotIndex];if(held&&BLOCKS[held.id]?.tool&&bd.tool){const tt=BLOCKS[held.id].tier||1;const rt=bd.minToolTier||1;if(BLOCKS[held.id].tool===bd.tool&&tt>=rt){spd*=BLOCKS[held.id].efficiency;toolMatched=true}}if(gameMode==='creative')spd=bd.hardness>0?bd.hardness*0.5:0.05;else if(!toolMatched&&bd.tool&&bd.minToolTier)spd=0.005;miningProgress+=spd;if(miningProgress>=bd.hardness){spawnParticles(tx*tileSize+16,ty*tileSize+16,bd.color);if(gameMode==='survival'&&bd.drop){if(bd.tool&&bd.minToolTier){if(toolMatched)addItemToInventory(bd.drop,1);else addChatMsg("❌ 需要更高级工具","#ff5555")}else addItemToInventory(bd.drop,1)}setBlock(tx,ty,0);miningTarget.id=0;miningProgress=0}}else{miningTarget.id=0;miningProgress=0}}}
function placeBlockAt(tx,ty){if(gameMode==='spectator')return;let item=heldItem||(hotbarSlots[selectedSlotIndex]?{id:hotbarSlots[selectedSlotIndex].id,count:1}:null);if(!item)return;const prop=BLOCKS[item.id];if(!prop||prop.item)return;if(prop.solid){const pL=Math.floor(player.x/tileSize),pR=Math.floor((player.x+player.w-1)/tileSize),pT=Math.floor(player.y/tileSize),pB=Math.floor((player.y+player.h-1)/tileSize);if(tx>=pL&&tx<=pR&&ty>=pT&&ty<=pB)return}if(getBlock(tx,ty)===0||prop.liquid){setBlock(tx,ty,item.id);if(gameMode==='survival'){if(heldItem){heldItem.count--;if(heldItem.count<=0)heldItem=null}else{hotbarSlots[selectedSlotIndex].count--;if(hotbarSlots[selectedSlotIndex].count<=0)hotbarSlots[selectedSlotIndex]=null}updateInventoryUI();updateHotbarUI();updateInvHotbarUI()}}}

canvas.addEventListener("mousemove",e=>{const r=canvas.getBoundingClientRect();mouseGlobalX=e.clientX-r.left;mouseGlobalY=e.clientY-r.top;if(!player.dead&&!isPaused){const wx=mouseGlobalX+cameraX;if(wx<player.x+player.w/2)player.facing=-1;else player.facing=1}if(isDragging)processTileAction(Math.floor((mouseGlobalX+cameraX)/tileSize),Math.floor((mouseGlobalY+cameraY)/tileSize))});
canvas.addEventListener("mousedown",e=>{if(player.dead||isPaused||chatOpen||document.querySelector(".overlay-screen[style*='flex']")||openChestKey!==null)return;const{wx,wy}=getMouseWorldPos(e);dragButton=e.button;isDragging=true;lastTx=-1;lastTy=-1;const tx=Math.floor(wx/tileSize),ty=Math.floor(wy/tileSize);if(e.button===0)tryAttack();processTileAction(tx,ty)});
window.addEventListener("mouseup",()=>{isDragging=false;dragButton=-1;miningTarget.id=0});
canvas.oncontextmenu=e=>e.preventDefault();

// ========== UI ==========
function updateHotbarUI(){const el=document.getElementById("hotbar");el.innerHTML="";hotbarSlots.forEach((item,i)=>{const s=document.createElement("div");s.className=`slot ${i===selectedSlotIndex?'active':''}`;s.onclick=()=>{selectedSlotIndex=i;updateHotbarUI();updateInvHotbarUI()};let c=`<span>${i+1}</span>`;if(item)c+=`<div class="slot-preview" style="background-image:url(${textures[item.id].toDataURL()});background-size:cover"></div><div class="slot-count">${gameMode==='creative'?'∞':item.count}</div>`;s.innerHTML=c;attachItemTooltip(s,item);el.appendChild(s)})}
function updateInvHotbarUI(){const el=document.getElementById("invHotbar");if(!el)return;el.innerHTML="";hotbarSlots.forEach((item,i)=>{const s=document.createElement("div");s.className=`ih-slot ${i===selectedSlotIndex?'active':''}`;if(item){s.style.backgroundImage=`url(${textures[item.id].toDataURL()})`;s.style.backgroundSize="cover";const d=document.createElement("div");d.className="slot-count";d.innerText=item.count;s.appendChild(d)}s.onclick=(e)=>handleSlotClick(hotbarSlots,i,e.button===2);attachItemTooltip(s,item);el.appendChild(s)})}
function addItemToInventory(id,count){if(gameMode!=='survival')return;for(let i=0;i<27;i++){if(inventorySlots[i]&&inventorySlots[i].id===id&&inventorySlots[i].count<64){inventorySlots[i].count+=count;updateInventoryUI();return}}for(let i=0;i<27;i++){if(!inventorySlots[i]){inventorySlots[i]={id:id,count:count};updateInventoryUI();return}}}
function returnHeldItem(){if(!heldItem)return;for(let i=0;i<27;i++){if(inventorySlots[i]&&inventorySlots[i].id===heldItem.id&&inventorySlots[i].count<64){const sp=64-inventorySlots[i].count;const tk=Math.min(sp,heldItem.count);inventorySlots[i].count+=tk;heldItem.count-=tk;if(heldItem.count<=0){heldItem=null;return}}}for(let i=0;i<9;i++){if(hotbarSlots[i]&&hotbarSlots[i].id===heldItem.id&&hotbarSlots[i].count<64){const sp=64-hotbarSlots[i].count;const tk=Math.min(sp,heldItem.count);hotbarSlots[i].count+=tk;heldItem.count-=tk;if(heldItem.count<=0){heldItem=null;return}}}for(let i=0;i<27;i++){if(!inventorySlots[i]){inventorySlots[i]={...heldItem};heldItem=null;return}}for(let i=0;i<9;i++){if(!hotbarSlots[i]){hotbarSlots[i]={...heldItem};heldItem=null;return}}heldItem=null}

// ========== 护甲 ==========
function handleArmorClick(slotIdx){if(gameMode==='spectator')return;if(heldItem===null&&armorSlots[slotIdx]===null)return;if(heldItem===null){heldItem=armorSlots[slotIdx];armorSlots[slotIdx]=null}else{if(BLOCKS[heldItem.id]?.armor===slotIdx){let old=armorSlots[slotIdx];armorSlots[slotIdx]=heldItem;heldItem=old}else if(armorSlots[slotIdx]===null&&BLOCKS[heldItem.id]?.armor===slotIdx){armorSlots[slotIdx]=heldItem;heldItem=null}else{let t=armorSlots[slotIdx];armorSlots[slotIdx]=heldItem;heldItem=t}}updateInventoryUI();updateInvHotbarUI();updateArmorUI()}
function updateArmorUI(){const names=['armorHead','armorChest','armorLegs','armorFeet'];names.forEach((n,i)=>{const el=document.getElementById(n);const icons=['⛑','👕','👖','👢'];el.innerHTML=`<div class="armor-icon">${icons[i]}</div>`;if(armorSlots[i]){el.style.backgroundImage=`url(${textures[armorSlots[i].id].toDataURL()})`;el.style.backgroundSize="cover"}else{el.style.backgroundImage="none"}})}
function getArmorDefense(){let def=0;armorSlots.forEach(a=>{if(a&&BLOCKS[a.id]?.defense)def+=BLOCKS[a.id].defense});return def}

// ========== 箱子 ==========
function openChest(tx,ty){if(gameMode==='spectator')return;const key=`${tx},${ty}`;if(!chestData[key])chestData[key]=new Array(27).fill(null);openChestKey=key;isPaused=true;document.getElementById("chestUI").style.display="flex";renderChestUI()}
function closeChest(){openChestKey=null;isPaused=false;document.getElementById("chestUI").style.display="none";returnHeldItem()}
function renderChestUI(){const el=document.getElementById("chestGrid");el.innerHTML="";if(!openChestKey||!chestData[openChestKey])return;const slots=chestData[openChestKey];slots.forEach((item,i)=>{const s=document.createElement("div");s.className="i-slot";if(item){s.style.backgroundImage=`url(${textures[item.id].toDataURL()})`;s.style.backgroundSize="cover";const d=document.createElement("div");d.className="slot-count";d.innerText=item.count;s.appendChild(d)}s.onclick=(e)=>handleChestSlotClick(i,e.button===2);attachItemTooltip(s,item);el.appendChild(s)})}
function handleChestSlotClick(idx,right){if(!openChestKey||!chestData[openChestKey])return;const slots=chestData[openChestKey];if(right&&heldItem&&slots[idx])return;if(heldItem===null){heldItem=slots[idx];slots[idx]=null}else{if(slots[idx]===null){slots[idx]=heldItem;heldItem=null}else if(slots[idx].id===heldItem.id){let sp=64-slots[idx].count;if(sp>0){let t=Math.min(sp,heldItem.count);slots[idx].count+=t;heldItem.count-=t;if(heldItem.count<=0)heldItem=null}}else{let t=slots[idx];slots[idx]=heldItem;heldItem=t}}renderChestUI();updateInventoryUI();updateInvHotbarUI()}

// ========== 背包 & 合成 ==========
function toggleInventory(){if(player.dead)return;const si=document.getElementById("survivalInventory"),ci=document.getElementById("creativeInventory");if(si.style.display==="flex"||ci.style.display==="flex"){returnHeldItem();si.style.display="none";ci.style.display="none";isPaused=false;currentCraftMode='small';hoverTip.style.display="none";updateHotbarUI();updateInventoryUI();updateInvHotbarUI();updateArmorUI();return}isPaused=true;currentCraftMode='small';si.style.display="flex";ci.style.display="none";updateInventoryUI();updateInvHotbarUI();updateArmorUI();const craftPanel=document.getElementById("craftPanel");const btnNext=document.getElementById("btnNextPage");const btnTrash=document.getElementById("btnTrash");if(gameMode==='creative'||gameMode==='spectator'){if(craftPanel)craftPanel.style.display="none";if(btnNext)btnNext.style.display="block";if(btnTrash)btnTrash.style.display="block"}else{if(craftPanel)craftPanel.style.display="flex";if(btnNext)btnNext.style.display="none";if(btnTrash)btnTrash.style.display="none";checkCrafting()}}
window.switchInvPage=function(page){const si=document.getElementById("survivalInventory");const ci=document.getElementById("creativeInventory");if(page==='creative'){si.style.display="none";ci.style.display="flex";renderCreativeInventory()}else{ci.style.display="none";si.style.display="flex";updateInventoryUI();updateInvHotbarUI();updateArmorUI()}};
window.deleteHeldItem=function(){if(heldItem){addChatMsg(`🗑️ 已删除 ${BLOCKS[heldItem.id].name} x${heldItem.count}`,"#ff5555");heldItem=null;updateInventoryUI();updateInvHotbarUI()}else addChatMsg("🗑️ 手中没有物品","#ff5555")};
function updateInventoryUI(){const el=document.getElementById("invGrid");el.innerHTML="";inventorySlots.forEach((item,i)=>{const s=document.createElement("div");s.className="i-slot";if(item){s.style.backgroundImage=`url(${textures[item.id].toDataURL()})`;s.style.backgroundSize="cover";const d=document.createElement("div");d.className="slot-count";d.innerText=item.count;s.appendChild(d)}s.onclick=(e)=>handleSlotClick(inventorySlots,i,e.button===2);attachItemTooltip(s,item);el.appendChild(s)})}
function handleSlotClick(arr,idx,right){if(right&&heldItem&&arr[idx])return;if(heldItem===null){heldItem=arr[idx];arr[idx]=null}else{if(arr[idx]===null){arr[idx]=heldItem;heldItem=null}else if(arr[idx].id===heldItem.id){if(gameMode==='survival'){let sp=64-arr[idx].count;if(sp>0){let t=Math.min(sp,heldItem.count);arr[idx].count+=t;heldItem.count-=t;if(heldItem.count<=0)heldItem=null}}}else{let t=arr[idx];arr[idx]=heldItem;heldItem=t}}updateInventoryUI();updateInvHotbarUI();checkCrafting();if(currentCraftMode==='furnace')updateFurnaceUI()}
function checkCrafting(){const s=document.getElementById("smallCraftUI"),l=document.getElementById("largeCraftUI"),f=document.getElementById("furnaceUI");s.style.display="none";l.style.display="none";f.style.display="none";if(currentCraftMode==='large'){l.style.display="flex";renderCraftGrid(l.querySelector(".grid-3x3"),craftingGridLarge,9,"craftResultLarge")}else if(currentCraftMode==='furnace'){f.style.display="flex";updateFurnaceUI()}else{s.style.display="flex";renderCraftGrid(s.querySelector(".grid-2x2"),craftingGridSmall,4,"craftResultSmall")}}
function renderCraftGrid(container,data,size,resId){container.innerHTML="";data.forEach((item,idx)=>{const s=document.createElement("div");s.className="c-slot";if(item){s.style.backgroundImage=`url(${textures[item.id].toDataURL()})`;s.style.backgroundSize="cover";const d=document.createElement("div");d.className="slot-count";d.innerText=item.count;s.appendChild(d)}s.onclick=(e)=>handleCraftSlotClick(data,idx,e.button===2);attachItemTooltip(s,item);container.appendChild(s)});calculateResult(data,size,resId)}
function handleCraftSlotClick(grid,idx,right){if(heldItem===null){heldItem=grid[idx];grid[idx]=null}else{if(grid[idx]===null){grid[idx]={id:heldItem.id,count:1};if(gameMode==='survival'){heldItem.count--;if(heldItem.count<=0)heldItem=null}}else if(grid[idx].id===heldItem.id){if(grid[idx].count<64){grid[idx].count++;if(gameMode==='survival'){heldItem.count--;if(heldItem.count<=0)heldItem=null}}}else{let t=grid[idx];grid[idx]={id:heldItem.id,count:1};if(gameMode==='survival'){heldItem.count--;if(heldItem.count<=0)heldItem=t;else heldItem=t}else heldItem=t}}updateInventoryUI();checkCrafting()}
function isPat(ids,pat){if(ids.length!==pat.length)return false;for(let i=0;i<ids.length;i++){if(pat[i]===-1)continue;if(pat[i]===-2){if(ids[i]<60||ids[i]>75)return false;continue}if(pat[i]===0&&ids[i]!==0)return false;if(pat[i]>0&&ids[i]!==pat[i])return false}return true}
function mirrorIds(ids){if(ids.length===4)return[ids[1],ids[0],ids[3],ids[2]];if(ids.length===9)return[ids[2],ids[1],ids[0],ids[5],ids[4],ids[3],ids[8],ids[7],ids[6]];return ids}
function calculateResult(grid,size,resId){let result=null;const ids=grid.map(i=>i?i.id:0);const ne=ids.filter(x=>x!==0).length;const mids=mirrorIds(ids);
    if(size===4){if(ne===1&&ids.includes(6))result={id:7,count:4};else if(ne===2&&((ids[0]===7&&ids[2]===7)||(ids[1]===7&&ids[3]===7)))result={id:14,count:4};else if(ids.every(x=>x===7))result={id:10,count:1}}
    if(size===9){
        if(!result&&ne===2){for(let c=0;c<3;c++)for(let r=0;r<2;r++)if(ids[r*3+c]===7&&ids[(r+1)*3+c]===7)result={id:14,count:4}}
        else if(!result&&isPat(ids,[7,7,7,0,14,0,0,14,0]))result={id:15,count:1};
        else if(!result&&isPat(ids,[0,7,0,0,7,0,0,14,0]))result={id:33,count:1};
        else if(!result&&isPat(ids,[0,7,0,0,14,0,0,14,0]))result={id:22,count:1};
        else if(!result&&isPat(ids,[0,7,0,0,7,0,0,7,0]))result={id:20,count:1};
        else if(!result&&isPat(ids,[3,3,3,0,14,0,0,14,0]))result={id:19,count:1};
        else if(!result&&isPat(ids,[0,3,0,0,14,0,0,14,0]))result={id:34,count:1};
        else if(!result&&(isPat(ids,[0,3,3,0,14,3,0,14,0])||isPat(mids,[0,3,3,0,14,3,0,14,0])))result={id:23,count:1};
        else if(!result&&isPat(ids,[0,3,0,0,3,0,0,14,0]))result={id:21,count:1};
        else if(!result&&isPat(ids,[51,51,51,0,14,0,0,14,0]))result={id:29,count:1};
        else if(!result&&isPat(ids,[0,51,0,0,14,0,0,14,0]))result={id:35,count:1};
        else if(!result&&(isPat(ids,[0,51,51,0,14,51,0,14,0])||isPat(mids,[0,51,51,0,14,51,0,14,0])))result={id:31,count:1};
        else if(!result&&isPat(ids,[0,51,0,0,51,0,0,14,0]))result={id:30,count:1};
        else if(!result&&isPat(ids,[80,80,80,0,14,0,0,14,0]))result={id:81,count:1};
        else if(!result&&isPat(ids,[0,80,0,0,14,0,0,14,0]))result={id:82,count:1};
        else if(!result&&(isPat(ids,[0,80,80,0,14,80,0,14,0])||isPat(mids,[0,80,80,0,14,80,0,14,0])))result={id:83,count:1};
        else if(!result&&isPat(ids,[0,80,0,0,80,0,0,14,0]))result={id:84,count:1};
        else if(!result&&isPat(ids,[80,80,80,80,0,80,0,0,0]))result={id:85,count:1};
        else if(!result&&isPat(ids,[80,0,80,80,80,80,80,80,80]))result={id:86,count:1};
        else if(!result&&isPat(ids,[80,80,80,80,0,80,80,0,80]))result={id:87,count:1};
        else if(!result&&isPat(ids,[0,0,0,80,0,80,80,0,80]))result={id:88,count:1};
        else if(!result&&isPat(ids,[-2,-2,-2,7,7,7,0,0,0]))result={id:21,count:1};
        else if(!result&&isPat(ids,[3,3,3,3,0,3,3,3,3]))result={id:24,count:1};
        else if(!result&&isPat(ids,[7,7,7,7,0,7,7,7,7]))result={id:25,count:1};
        else if(!result&&(isPat(ids,[0,0,0,7,0,7,7,7,7])||isPat(ids,[7,0,7,7,7,7,0,0,0])))result={id:27,count:1};
    }
    const rs=document.getElementById(resId);rs.innerHTML="";if(result){rs.style.backgroundImage=`url(${textures[result.id].toDataURL()})`;rs.style.backgroundSize="cover";const d=document.createElement("div");d.className="slot-count";d.innerText=result.count;rs.appendChild(d);attachItemTooltip(rs,{id:result.id,count:result.count});rs.onclick=()=>{for(let i=0;i<grid.length;i++){if(grid[i]){grid[i].count--;if(grid[i].count<=0)grid[i]=null}}addItemToInventory(result.id,result.count);checkCrafting();updateInventoryUI();updateInvHotbarUI()}}else{rs.style.backgroundImage="none";rs.onclick=null}}

// ========== 熔炉 ==========
function updateFurnaceUI(){const inS=document.getElementById("furnaceInput"),fuS=document.getElementById("furnaceFuel"),outS=document.getElementById("furnaceOutput");[inS,fuS,outS].forEach(s=>{s.innerHTML="";s.style.backgroundImage="none"});if(furnaceState.input){inS.style.backgroundImage=`url(${textures[furnaceState.input.id].toDataURL()})`;inS.style.backgroundSize="cover";const d=document.createElement("div");d.className="slot-count";d.innerText=furnaceState.input.count;inS.appendChild(d)}if(furnaceState.fuel){fuS.style.backgroundImage=`url(${textures[furnaceState.fuel.id].toDataURL()})`;fuS.style.backgroundSize="cover";const d=document.createElement("div");d.className="slot-count";d.innerText=furnaceState.fuel.count;fuS.appendChild(d)}if(furnaceState.output){outS.style.backgroundImage=`url(${textures[furnaceState.output.id].toDataURL()})`;outS.style.backgroundSize="cover";const d=document.createElement("div");d.className="slot-count";d.innerText=furnaceState.output.count;outS.appendChild(d)}inS.onclick=(e)=>handleFurnaceSlotClick('input',e.button===2);fuS.onclick=(e)=>handleFurnaceSlotClick('fuel',e.button===2);outS.onclick=(e)=>handleFurnaceSlotClick('output',e.button===2);attachItemTooltip(inS,furnaceState.input);attachItemTooltip(fuS,furnaceState.fuel);attachItemTooltip(outS,furnaceState.output);document.getElementById("furnaceBar").style.width=furnaceState.smeltTarget>0?`${(furnaceState.smeltProgress/furnaceState.smeltTarget)*100}%`:"0%"}
function handleFurnaceSlotClick(slot,right){if(slot==='output'){if(heldItem===null&&furnaceState.output){heldItem={...furnaceState.output};furnaceState.output=null}else if(heldItem&&furnaceState.output&&heldItem.id===furnaceState.output.id&&heldItem.count<64){const tk=Math.min(64-heldItem.count,furnaceState.output.count);heldItem.count+=tk;furnaceState.output.count-=tk;if(furnaceState.output.count<=0)furnaceState.output=null}}else{const key=slot;if(heldItem===null){if(furnaceState[key]){heldItem={...furnaceState[key]};furnaceState[key]=null}}else{if(!furnaceState[key]){furnaceState[key]={...heldItem};heldItem=null}else if(furnaceState[key].id===heldItem.id&&furnaceState[key].count<64){const tk=Math.min(64-furnaceState[key].count,heldItem.count);furnaceState[key].count+=tk;heldItem.count-=tk;if(heldItem.count<=0)heldItem=null}else{const t={...furnaceState[key]};furnaceState[key]={...heldItem};heldItem=t}}}updateFurnaceUI();updateInventoryUI();updateInvHotbarUI()}
function updateFurnaceLogic(){if(currentCraftMode!=='furnace')return;const inputId=furnaceState.input?furnaceState.input.id:null;const recipe=inputId!=null?SMELT_RECIPES[inputId]:undefined;if(recipe!==undefined){if(furnaceState.smeltTarget===0)furnaceState.smeltTarget=200;if(furnaceState.fuelLeft>0){furnaceState.fuelLeft--;furnaceState.smeltProgress++;if(furnaceState.smeltProgress>=furnaceState.smeltTarget){furnaceState.smeltProgress=0;furnaceState.smeltTarget=0;furnaceState.input.count--;if(furnaceState.input.count<=0)furnaceState.input=null;if(!furnaceState.output)furnaceState.output={id:recipe,count:1};else if(furnaceState.output.id===recipe&&furnaceState.output.count<64)furnaceState.output.count++;if(furnaceState.input&&SMELT_RECIPES[furnaceState.input.id]!==undefined)furnaceState.smeltTarget=200}}else if(furnaceState.fuel&&BLOCKS[furnaceState.fuel.id]?.fuel){furnaceState.fuelLeft=BLOCKS[furnaceState.fuel.id].fuel;furnaceState.fuel.count--;if(furnaceState.fuel.count<=0)furnaceState.fuel=null}else{if(furnaceState.smeltProgress>0)furnaceState.smeltProgress=Math.max(0,furnaceState.smeltProgress-1)}}else{furnaceState.smeltProgress=0;furnaceState.smeltTarget=0}updateFurnaceUI()}

function renderCreativeInventory(){const g=document.getElementById("creativeGrid");g.innerHTML="";Object.keys(BLOCKS).filter(k=>k!=0).map(k=>parseInt(k)).sort((a,b)=>a-b).forEach(id=>{const b=document.createElement("div");b.className="item-btn";b.dataset.name=BLOCKS[id].name;const img=document.createElement("img");img.src=textures[id].toDataURL();b.appendChild(img);const tt=document.createElement("div");tt.className="item-tooltip";tt.innerText=BLOCKS[id].name;b.appendChild(tt);b.onmousedown=(e)=>{e.preventDefault();heldItem={id:id,count:e.button===0?64:1};hotbarSlots[selectedSlotIndex]=heldItem;updateHotbarUI()};g.appendChild(b)})}
function filterCreativeItems(q){q=q.toLowerCase();document.querySelectorAll(".item-btn").forEach(i=>{i.style.display=i.dataset.name.toLowerCase().includes(q)?"block":"none"})}

// ========== 碰撞 ==========
function resolveEntityCollision(ent,isH){const pts=[{x:ent.x,y:ent.y},{x:ent.x+ent.w-0.1,y:ent.y},{x:ent.x,y:ent.y+ent.h-0.1},{x:ent.x+ent.w-0.1,y:ent.y+ent.h-0.1}];for(let p of pts){const bx=Math.floor(p.x/tileSize),by=Math.floor(p.y/tileSize),bid=getBlock(bx,by);if(BLOCKS[bid]&&BLOCKS[bid].solid){if(isH){if(ent.vx>0)ent.x=bx*tileSize-ent.w;else ent.x=(bx+1)*tileSize;ent.vx=0}else{if(ent.vy>0){ent.y=by*tileSize-ent.h;ent.onGround=true}else ent.y=(by+1)*tileSize;ent.vy=0}return}}}
function checkCreativeCollision(nx,ny){const pts=[{x:nx,y:ny},{x:nx+player.w-0.1,y:ny},{x:nx,y:ny+player.h-0.1},{x:nx+player.w-0.1,y:ny+player.h-0.1}];for(let p of pts){const bx=Math.floor(p.x/tileSize),by=Math.floor(p.y/tileSize),bid=getBlock(bx,by);if(BLOCKS[bid]&&BLOCKS[bid].solid)return true}return false}

// ========== 生物 ==========
function spawnPassiveMob(arr,max,w,h,hp){if(arr.length>=max||Math.random()>0.002)return;const side=Math.random()>0.5?1:-1;const dist=20+Math.floor(Math.random()*30);const sx=Math.floor(player.x/tileSize)+side*dist;let sy=0;while(getBlock(sx,sy)===0&&sy<80)sy++;if(sy>0&&sy<70&&getBlock(sx,sy)===1)arr.push({x:sx*tileSize,y:(sy-2)*tileSize,w,h,vx:0,vy:0,hp,onGround:false,moveTimer:0,dir:1})}
function updatePassiveMob(arr){arr.forEach(s=>{s.vy+=0.5;s.moveTimer++;if(s.moveTimer>120){s.moveTimer=0;s.dir=Math.random()>0.5?1:-1;if(Math.random()>0.6)s.dir=0}s.vx=s.dir*0.6;const fx=Math.floor((s.x+(s.dir>0?s.w:0))/tileSize),fy=Math.floor((s.y+s.h)/tileSize);if(s.onGround&&s.dir!==0&&getBlock(fx,fy-1)!==0&&BLOCKS[getBlock(fx,fy-1)]?.solid)s.vy=-7;s.x+=s.vx;resolveEntityCollision(s,true);s.y+=s.vy;s.onGround=false;resolveEntityCollision(s,false);if(s.y>5000)s.hp=0});return arr.filter(s=>s.hp>0)}
function updateZombies(){if(gameMode!=='survival'||gameDifficulty==='peaceful'){zombies=[];return}const isNight=(gameTime%1)>0.5;const maxZ=gameDifficulty==='hard'?30:12;if(isNight&&zombies.length<maxZ){zombieSpawnTimer++;const rate=gameDifficulty==='hard'?80:180;if(zombieSpawnTimer>rate){zombieSpawnTimer=0;const side=Math.random()>0.5?1:-1;const dist=30+Math.floor(Math.random()*20);const zx=Math.floor(player.x/tileSize)+side*dist;let zy=0;while(getBlock(zx,zy)===0&&zy<80)zy++;if(zy>0&&zy<70)zombies.push({x:zx*tileSize,y:(zy-2)*tileSize,w:24,h:28,vx:0,vy:0,hp:10,onGround:false,attackTimer:0})}}if(!isNight){zombies.forEach(z=>{const py=Math.floor(z.y/tileSize);if(py<30&&Math.abs(z.x-player.x)<600)z.hp-=0.1});zombies=zombies.filter(z=>z.hp>0)}zombies.forEach(z=>{const dx=player.x-z.x;const dir=dx>0?1:-1;z.vx=dir*1.2;z.vy+=0.5;if(z.onGround&&z.vx!==0){const checkX=dir>0?z.x+z.w+2:z.x-2;const bx=Math.floor(checkX/tileSize);const footBy=Math.floor((z.y+z.h-1)/tileSize);const bodyBy=Math.floor((z.y+z.h*0.5)/tileSize);const headBy=Math.floor(z.y/tileSize);if(BLOCKS[getBlock(bx,footBy)]?.solid&&!BLOCKS[getBlock(bx,bodyBy)]?.solid&&!BLOCKS[getBlock(bx,headBy)]?.solid){z.vy=-8;z.onGround=false}}z.x+=z.vx;resolveEntityCollision(z,true);z.y+=z.vy;z.onGround=false;resolveEntityCollision(z,false);if(Math.abs(dx)<30&&Math.abs(player.y-z.y)<30){z.attackTimer++;if(z.attackTimer>60){z.attackTimer=0;if(player.invTimer<=0){let dmg=Math.max(1,2-getArmorDefense()*0.1);player.hp-=dmg;player.invTimer=30;player.vy=-5;player.vx=dir*5;spawnParticles(player.x+player.w/2,player.y+player.h/2,"#ff0000",5);if(player.hp<=0)die("被僵尸击败")}}}if(z.y>5000)z.hp=0});zombies=zombies.filter(z=>z.hp>0)}

// ========== 饥饿 ==========
function updateHunger(){if(gameMode!=='survival'||player.dead)return;player.hungerTimer++;let drainRate=1200;if(Math.abs(player.vx)>0.1||Math.abs(player.vy)>0.1)drainRate=600;if(player.hungerTimer>=drainRate){player.hungerTimer=0;if(player.saturation>0)player.saturation=Math.max(0,player.saturation-1);else if(player.hunger>0)player.hunger--}if(player.hunger>=18&&player.hp<player.maxHp){player.healTimer++;if(player.healTimer>=80){player.healTimer=0;player.hp=Math.min(player.maxHp,player.hp+1);spawnParticles(player.x+player.w/2,player.y,"#0f0",3)}}else player.healTimer=0;if(player.hunger<=0){player.healTimer++;if(player.healTimer>=80){player.healTimer=0;player.hp--;if(player.hp<=0)die("饿死了")}}}

// ========== 启动 ==========
window.startGame=function(){try{const seed=document.getElementById("seedInput").value;currentSeed=seed?parseInt(seed):Math.floor(Math.random()*100000);currentWorldType=document.getElementById("worldType").value;gameMode=document.getElementById("gameMode").value;gameDifficulty=document.getElementById("difficulty").value;worldOptTimeFlow=document.getElementById("optTimeFlow").checked;worldOptShortLayer=document.getElementById("optShortLayer").checked;worldOptKeepInv=document.getElementById("optKeepInv").checked;cheatsEnabled=document.getElementById("optCheats").checked;cloudsEnabled=document.getElementById("optClouds").checked;globalMap={};initItems();gameTime=0;dayCount=1;currentCraftMode='small';player.x=0;player.y=0;player.vx=0;player.vy=0;player.hp=10;player.hunger=20;player.saturation=5;player.dead=false;player.facing=1;player.attackCooldown=0;player.fallStartY=null;player.hungerTimer=0;player.healTimer=0;player.inBoat=false;player.boatX=-1;player.boatY=-1;player.lastJumpTime=0;player.flying=(gameMode!=='survival');for(let x=-30;x<=30;x++){generateColumn(x,currentWorldType);globalMap['_gen_'+x]=true}generateTrees(-28,28,currentWorldType);let by=0;while(getBlock(0,by)===0&&by<100)by++;spawnPoint.x=0;spawnPoint.y=(by-2)*tileSize;player.x=spawnPoint.x;player.y=spawnPoint.y;cameraY=player.y-canvas.height/2;if(gameMode==='creative')hotbarSlots[0]={id:81,count:1};document.getElementById("mainMenu").style.display="none";document.getElementById("gameContainer").style.display="block";document.getElementById("gameHints").style.display="block";document.getElementById("deathScreen").style.display="none";const badge=document.getElementById("modeBadge");badge.innerText=gameMode==='creative'?"CREATIVE":gameMode==='spectator'?"SPECTATOR":"SURVIVAL";badge.className=`mode-badge ${gameMode}`;addChatMsg(`世界已生成 | 模式:${gameMode} | 种子:${currentSeed}`,"#aaffaa");updateHotbarUI();loop()}catch(e){console.error("启动出错:",e);alert("启动出错")}};

// ========== 主循环 ==========
function update(){if(player.dead)return;if(currentCraftMode==='furnace')updateFurnaceLogic();if(isPaused)return;if(worldOptTimeFlow){gameTime+=0.0000556;dayCount=Math.floor(gameTime)+1}if(player.attackCooldown>0)player.attackCooldown--;const cx=player.x+player.w/2,cy=player.y+player.h/2;const cb=getBlock(Math.floor(cx/tileSize),Math.floor(cy/tileSize));const fb=getBlock(Math.floor(cx/tileSize),Math.floor((player.y+player.h)/tileSize));player.inLiquid=BLOCKS[cb]?.liquid||BLOCKS[fb]?.liquid;
    if(gameMode==='spectator'){let fs=keys["shift"]?7:4,dx=0,dy=0;if(keys["a"])dx=-fs;if(keys["d"])dx=fs;if(keys["w"])dy=-fs;if(keys["s"])dy=fs;player.x+=dx;player.y+=dy;player.vx=dx;player.vy=dy;player.fallStartY=null}
    else if(player.inBoat){if(player.boatX>=0&&getBlock(player.boatX,player.boatY)===28){let boatSpd=3.5;player.vx=0;if(keys["a"])player.vx=-boatSpd;if(keys["d"])player.vx=boatSpd;player.vy=0;player.x+=player.vx;const ptx=Math.floor((player.x+player.w/2)/tileSize);let waterY=-1;for(let wy=0;wy<80;wy++){if(getBlock(ptx,wy)===4){waterY=wy;break}}if(waterY>=0)player.y=waterY*tileSize-4;else{player.inBoat=false;player.boatX=-1}player.fallStartY=null}else{player.inBoat=false;player.boatX=-1}}
    else{if(!player.onGround&&player.fallStartY===null&&player.vy>0)player.fallStartY=player.y;if(player.onGround&&player.fallStartY!==null){const fd=(player.y-player.fallStartY)/tileSize;if(fd>5){const dmg=Math.max(1,Math.floor((fd-5)/5)+1-getArmorDefense()*0.2);player.hp-=dmg;player.invTimer=20;spawnParticles(player.x+player.w/2,player.y+player.h,"#aaa",10);if(player.hp<=0)die(`摔落了${Math.floor(fd)}格`)}player.fallStartY=null}if(player.onGround)player.fallStartY=null;if(gameMode==='creative'){if(player.flying){let fs=keys["shift"]?7:4,dx=0,dy=0;if(keys["a"])dx=-fs;if(keys["d"])dx=fs;if(keys["w"])dy=-fs;if(keys["s"])dy=fs;if(dx!==0&&!checkCreativeCollision(player.x+dx,player.y))player.x+=dx;if(dy!==0&&!checkCreativeCollision(player.x,player.y+dy))player.y+=dy;player.vx=dx;player.vy=dy;player.fallStartY=null}else{let spd=player.speed;player.vx=0;if(keys["a"])player.vx=-spd;if(keys["d"])player.vx=spd;if((keys["w"]||keys[" "])&&player.onGround){player.vy=player.jumpPower;player.onGround=false}player.vy+=player.gravity;player.x+=player.vx;resolveEntityCollision(player,true);player.y+=player.vy;player.onGround=false;resolveEntityCollision(player,false)}}else{let spd=player.inLiquid?player.speed*0.4:player.speed;player.vx=0;if(keys["a"])player.vx=-spd;if(keys["d"])player.vx=spd;if(keys["w"]||keys[" "]){if(player.onGround&&!player.inLiquid){player.vy=player.jumpPower;player.onGround=false}else if(player.inLiquid)player.vy=-3}if(player.inLiquid){player.vy+=player.gravity*0.15;if(player.vy>2)player.vy=2}else player.vy+=player.gravity;player.x+=player.vx;resolveEntityCollision(player,true);player.y+=player.vy;player.onGround=false;resolveEntityCollision(player,false)}}
    cameraX+=(player.x-canvas.width/2+player.w/2-cameraX)*0.1;cameraY+=(player.y-canvas.height/2+player.h/2-cameraY)*0.1;checkExpansion();updateMining();updateZombies();updateHunger();spawnPassiveMob(sheeps,15,24,24,5);sheeps=updatePassiveMob(sheeps);spawnPassiveMob(pigs,12,22,20,5);pigs=updatePassiveMob(pigs);spawnPassiveMob(cows,12,26,26,5);cows=updatePassiveMob(cows);if(gameMode==='survival'&&player.y>80*tileSize){die("坠入虚空");return}if(gameMode==='survival'){if(player.invTimer>0)player.invTimer--;if((BLOCKS[cb]?.damage||BLOCKS[fb]?.damage)&&player.invTimer===0){player.hp--;player.invTimer=60;player.vy=-8;if(player.hp<=0)die("被岩浆吞噬")}if(BLOCKS[cb]?.checkpoint||BLOCKS[fb]?.checkpoint){if(spawnPoint.x!==Math.floor(player.x)||spawnPoint.y!==Math.floor(player.y)){spawnPoint.x=player.x;spawnPoint.y=player.y;showCheckpointMsg()}}}particles.forEach(p=>{p.x+=p.vx;p.y+=p.vy;p.vy+=0.3;p.life--});particles=particles.filter(p=>p.life>0);document.getElementById("healthDisplay").innerText=gameMode==='spectator'?"👁️":gameMode==='creative'?"∞":"❤".repeat(Math.max(0,player.hp));document.getElementById("hungerDisplay").innerText=(gameMode==='creative'||gameMode==='spectator')?"":"🍗".repeat(Math.max(0,Math.ceil(player.hunger/2)));document.getElementById("coordDisplay").innerText=`${Math.floor(player.x/32)}, ${Math.floor(player.y/32)}`;const isNight=(gameTime%1)>0.5;document.getElementById("timeDisplay").innerText=`Day ${dayCount} ${isNight?'🌙':'☀️'}${!worldOptTimeFlow?' ⏸':''}`;if(showDebug){const px=Math.floor(player.x/tileSize);const biomeNames=['plains','forest','ocean'];document.getElementById("debugScreen").innerHTML=`X:${player.x.toFixed(1)} Y:${player.y.toFixed(1)}<br>Biome:${biomeNames[getBiome(px)]||'?'}<br>Mode:${gameMode}<br>Mobs:Z:${zombies.length} S:${sheeps.length} P:${pigs.length} C:${cows.length}<br>Armor Def:${getArmorDefense()}<br>Seed:${currentSeed}`}}

function render(){const tod=gameTime%1;let sky;if(!worldOptTimeFlow)sky="#87CEEB";else if(tod<0.4)sky="#87CEEB";else if(tod<0.5)sky="#FF8C42";else if(tod<0.9)sky="#0a0a2e";else sky="#FF8C42";ctx.fillStyle=sky;ctx.fillRect(0,0,canvas.width,canvas.height);if(cloudsEnabled){ctx.fillStyle="rgba(255,255,255,0.6)";const cloudSpeed=gameTime*10;const sc=Math.floor(cameraX/tileSize)-5;const ec=sc+(canvas.width/tileSize)+10;for(let x=sc;x<=ec;x++){const n=hashNoise(x*0.1,currentSeed+888);if(n>0.6){const cx=x*tileSize-cameraX+cloudSpeed%(tileSize*100);const cy=50+hashNoise(x,currentSeed+999)*60;ctx.fillRect(cx,cy,tileSize,tileSize);ctx.fillRect(cx+tileSize,cy,tileSize,tileSize);ctx.fillRect(cx+tileSize*2,cy,tileSize,tileSize);ctx.fillRect(cx+tileSize,cy-tileSize,tileSize,tileSize)}}}const sc=Math.floor(cameraX/tileSize),ec=sc+(canvas.width/tileSize)+2,sr=Math.floor(cameraY/tileSize),er=sr+(canvas.height/tileSize)+2;for(let y=sr;y<=er;y++)for(let x=sc;x<=ec;x++){const b=getBlock(x,y);if(b===0)continue;const dx=x*tileSize-cameraX,dy=y*tileSize-cameraY;if(BLOCKS[b]?.glow){ctx.shadowColor="#ff4500";ctx.shadowBlur=20}else ctx.shadowBlur=0;if(textures[b])ctx.drawImage(textures[b],dx,dy);else{ctx.fillStyle=BLOCKS[b].color;ctx.fillRect(dx,dy,tileSize,tileSize)}ctx.shadowBlur=0}if(miningTarget.id!==0&&gameMode!=='spectator'){const tx=miningTarget.x,ty=miningTarget.y;const mx=Math.floor((mouseGlobalX+cameraX)/tileSize),my=Math.floor((mouseGlobalY+cameraY)/tileSize);if(mx===tx&&my===ty&&dragButton===0){const bd=BLOCKS[miningTarget.id];if(bd&&bd.hardness>0){const pct=Math.min(1,miningProgress/bd.hardness);const dx=tx*tileSize-cameraX,dy=ty*tileSize-cameraY;ctx.fillStyle="rgba(0,0,0,0.6)";ctx.fillRect(dx,dy+28,32,4);ctx.fillStyle="#7CFC00";ctx.fillRect(dx,dy+28,32*pct,4)}}}sheeps.forEach(s=>{const sx=s.x-cameraX,sy=s.y-cameraY;ctx.fillStyle="#fff";ctx.fillRect(sx,sy,s.w,s.h);ctx.fillStyle="#333";ctx.fillRect(sx+(s.dir>=0?16:4),sy+4,3,3)});pigs.forEach(p=>{const sx=p.x-cameraX,sy=p.y-cameraY;ctx.fillStyle="#f4a0b0";ctx.fillRect(sx,sy,p.w,p.h);ctx.fillStyle="#333";ctx.fillRect(sx+(p.dir>=0?16:4),sy+4,2,2)});cows.forEach(c=>{const sx=c.x-cameraX,sy=c.y-cameraY;ctx.fillStyle="#8B4513";ctx.fillRect(sx,sy,c.w,c.h);ctx.fillStyle="#fff";ctx.fillRect(sx+4,sy+4,8,8);ctx.fillStyle="#333";ctx.fillRect(sx+(c.dir>=0?20:4),sy+4,3,3)});zombies.forEach(z=>{const sx=z.x-cameraX,sy=z.y-cameraY;ctx.fillStyle="#4a7a3d";ctx.fillRect(sx,sy,z.w,z.h);ctx.fillStyle="#f00";ctx.fillRect(sx+4,sy+6,5,5);ctx.fillRect(sx+15,sy+6,5,5);const hp=z.hp/10;ctx.fillStyle="#333";ctx.fillRect(sx,sy-6,z.w,3);ctx.fillStyle="#f00";ctx.fillRect(sx,sy-6,z.w*hp,3)});particles.forEach(p=>{ctx.fillStyle=p.color;ctx.globalAlpha=p.life/30;ctx.fillRect(p.x-cameraX,p.y-cameraY,p.size,p.size)});ctx.globalAlpha=1;if(!player.dead){const sx=player.x-cameraX,sy=player.y-cameraY;if(gameMode==='spectator'){ctx.globalAlpha=0.4}else if(player.invTimer>0&&Math.floor(Date.now()/50)%2===0){ctx.globalAlpha=0.5}ctx.fillStyle=gameMode==='spectator'?"#aa88ff":"#FF0000";ctx.fillRect(sx,sy,player.w,player.h);ctx.fillStyle=gameMode==='spectator'?"#fff":"#000";if(player.facing===1)ctx.fillRect(sx+14,sy+6,4,4);else ctx.fillRect(sx+6,sy+6,4,4);ctx.globalAlpha=1}requestAnimationFrame(loop)}

function spawnParticles(x,y,color,count=5){for(let i=0;i<count;i++)particles.push({x,y,vx:(Math.random()-0.5)*4,vy:(Math.random()-0.5)*4,life:20+Math.random()*10,color,size:2+Math.random()*3})}
function die(reason){player.dead=true;document.getElementById("deathReason").innerText=reason||"你死了";document.getElementById("deathScreen").style.display="block";if(!worldOptKeepInv&&gameMode==='survival'){hotbarSlots.fill(null);inventorySlots.fill(null);heldItem=null;updateHotbarUI();updateInventoryUI()}}
function respawn(){player.dead=false;player.hp=player.maxHp;player.hunger=player.maxHunger;player.saturation=5;player.x=spawnPoint.x;player.y=spawnPoint.y;player.vx=0;player.vy=0;player.invTimer=60;document.getElementById("deathScreen").style.display="none"}
function showCheckpointMsg(){const msg=document.getElementById("checkpointMsg");msg.style.opacity=1;setTimeout(()=>msg.style.opacity=0,2000)}
function loadSaveList(){const list=document.getElementById("saveList");list.innerHTML="";const saves=JSON.parse(localStorage.getItem("mc2d_saves_list")||"[]");if(saves.length===0){list.innerHTML="<div style='padding:10px;color:#888'>暂无存档</div>";return}saves.reverse().forEach(name=>{const div=document.createElement("div");div.className="save-item";div.innerHTML=`<span>${name}</span><span style="color:#888;font-size:12px">加载</span>`;div.onclick=()=>loadGame(name);list.appendChild(div)})}
function loadGame(name){const dataStr=localStorage.getItem(`mc2d_save_${name}`);if(!dataStr)return;const data=JSON.parse(dataStr);globalMap=data.map;currentWorldType=data.type;gameMode=data.mode;currentSeed=data.seed;gameDifficulty=data.diff;gameTime=data.time;dayCount=Math.floor(gameTime)+1;worldOptTimeFlow=data.optTimeFlow;worldOptShortLayer=data.optShortLayer;worldOptKeepInv=data.optKeepInv;cheatsEnabled=data.cheats;cloudsEnabled=data.clouds;treesGeneratedCols=data.treesCols||{};furnaceState=data.furnace||{input:null,fuel:null,output:null,fuelLeft:0,smeltProgress:0,smeltTarget:0};armorSlots=data.armor||[null,null,null,null];chestData=data.chests||{};spawnPoint=data.spawn;inventorySlots=data.inv;hotbarSlots=data.hotbar;player.x=data.player.x;player.y=data.player.y;player.hp=data.player.hp;player.hunger=data.player.hunger;player.saturation=data.player.saturation;player.facing=data.player.facing;player.flying=data.player.flying;player.inBoat=data.player.inBoat;player.boatX=data.player.boatX;player.boatY=data.player.boatY;player.dead=false;Object.keys(BLOCKS).forEach(k=>{if(k!=0&&!textures[k])genTex(k,BLOCKS[k].color,BLOCKS[k].tex||'default')});document.getElementById("mainMenu").style.display="none";document.getElementById("gameContainer").style.display="block";document.getElementById("gameHints").style.display="block";document.getElementById("deathScreen").style.display="none";const badge=document.getElementById("modeBadge");badge.innerText=gameMode==='creative'?"CREATIVE":gameMode==='spectator'?"SPECTATOR":"SURVIVAL";badge.className=`mode-badge ${gameMode}`;updateHotbarUI();updateInventoryUI();updateArmorUI();loop()}
function loop(){update();render()}
</script>
</body>
</html>
原文