汉末三国之君临天下
by ChromeOtter724204 lines178.1 KB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>汉末三国之君临天下</title>
<style>
/* ==== 全局 ==== */
*{box-sizing:border-box;margin:0;padding:0;font-family:"Microsoft YaHei","PingFang SC",sans-serif;-webkit-tap-highlight-color:transparent}
html,body{width:100%;height:100%;overflow:hidden;background:#0a0e1b;color:#eef}
button{font-family:inherit}
/* ==== 标题屏 ==== */
#titleScreen{position:fixed;inset:0;z-index:100;display:flex;flex-direction:column;align-items:center;justify-content:center;background:radial-gradient(ellipse at 50% 40%,#1e2f4f,#0a0e1b);padding:20px;overflow-y:auto}
#titleScreen .title-wrap{display:flex;flex-direction:column;align-items:center;max-height:100%;padding:10px 0}
#titleScreen{position:fixed;inset:0;z-index:100;display:flex;flex-direction:column;align-items:center;justify-content:center;background:radial-gradient(ellipse at 50% 40%,#1e2f4f,#0a0e1b);padding:20px}
#titleScreen h1{font-size:34px;color:#ffe066;text-shadow:0 0 20px rgba(255,224,102,0.5);letter-spacing:4px;margin-bottom:8px}
#titleScreen .sub{color:#8fa;font-size:13px;letter-spacing:6px;margin-bottom:30px}
#titleScreen .menu-btn{border:2px solid #c9a227;background:rgba(20,28,48,0.9);color:#ffe066;padding:12px 36px;font-size:16px;border-radius:6px;margin:6px;cursor:pointer;letter-spacing:2px;min-width:260px}
#titleScreen .title-block{margin:10px 0;width:320px;max-width:90vw}
#titleScreen .block-label{color:#8fa;font-size:11px;letter-spacing:3px;margin-bottom:6px;text-align:center}
#titleScreen .scenario-list,#titleScreen .force-list,#titleScreen .diff-list{display:flex;flex-direction:column;gap:6px}
#titleScreen .pick-item{border:1px solid #3a5a8a;background:rgba(15,28,52,0.9);color:#cfe;border-radius:6px;padding:8px 12px;cursor:pointer;display:flex;align-items:center;gap:10px;transition:all 0.15s;font-size:12px;text-align:left}
#titleScreen .pick-item:hover{border-color:#c9a227;background:rgba(30,50,90,0.9)}
#titleScreen .pick-item.sel{border-color:#c9a227;background:linear-gradient(135deg,rgba(201,162,39,0.25),rgba(201,162,39,0.08));color:#ffe066;box-shadow:0 0 12px rgba(201,162,39,0.3)}
#titleScreen .pick-item .pi-banner{width:14px;height:14px;border-radius:3px;flex-shrink:0;border:1px solid rgba(255,255,255,0.3)}
#titleScreen .pick-item .pi-name{font-weight:bold;font-size:13px;flex-shrink:0;min-width:52px}
#titleScreen .pick-item .pi-desc{color:#9ab;font-size:10px;flex:1;line-height:1.4}
#titleScreen .pick-item .pi-cap{color:#ffd479;font-size:11px;font-weight:bold;flex-shrink:0}
#titleScreen .pick-item.diff .pi-desc{color:#cfe;font-size:11px}
#titleScreen .menu-btn:active{background:#c9a227;color:#0a0e1b}
#titleScreen .credits{position:absolute;bottom:16px;color:#556;font-size:11px}
#titleScreen .portrait-row{display:flex;gap:16px;margin-bottom:20px}
#titleScreen .portrait-row img{width:64px;height:78px;border:2px solid #c9a227;border-radius:8px;image-rendering:pixelated}
/* ==== 顶部资源栏 ==== */
#topBar{height:44px;background:#0a0e1b;display:flex;align-items:center;padding:0 10px;gap:8px;border-bottom:1px solid #203258;flex-shrink:0;overflow-x:auto;white-space:nowrap}
#topBar .turn{color:#ffe066;font-size:12px;font-weight:bold;flex-shrink:0}
#resBar{font-size:12px;color:#cfe;flex-shrink:0}
.top-btn{border:1px solid #3a5a8a;background:#12203c;color:#fff;padding:5px 8px;border-radius:4px;font-size:11px;cursor:pointer;flex-shrink:0}
.top-btn:active{background:#c9a227;color:#0a0e1b}
/* ==== 主体 ==== */
#app{flex:1;display:flex;flex-direction:column;overflow:hidden;height:calc(100% - 44px);min-height:0}
.view{display:none;flex:1;flex-direction:column;overflow:hidden}
.view.active{display:flex}
/* ==== 战略地图 ==== */
#mapView{position:relative;flex:1;overflow:hidden;cursor:crosshair}
#mapCanvas{display:block;width:100%;height:100%;touch-action:none}
/* 缩放控制按钮 */
#mapZoomCtrl{position:absolute;right:10px;bottom:10px;display:flex;flex-direction:column;gap:6px;z-index:50}
#mapZoomCtrl button{width:36px;height:36px;border:none;border-radius:6px;background:rgba(10,14,27,0.85);border:1px solid #25427a;color:#ffe066;font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;user-select:none;-webkit-user-select:none}
#mapZoomCtrl button:hover{background:rgba(30,50,90,0.9)}
#mapZoomCtrl button:active{transform:scale(0.92)}
#mapZoomCtrl .zoom-reset{font-size:11px;font-weight:bold}
#mapZoomInfo{position:absolute;left:10px;bottom:10px;z-index:50;background:rgba(10,14,27,0.8);border:1px solid #25427a;border-radius:4px;padding:3px 8px;color:#8899bb;font-size:11px;pointer-events:none}
/* ==== 战斗 ==== */
#battleView{position:relative;flex:1;overflow:hidden;background:#0a0a0a;touch-action:none;-webkit-user-select:none;user-select:none;min-height:300px}
#battleCanvas{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none}
/* ===== 搜打撤战斗 HUD ===== */
#sdeHUD{position:absolute;inset:0;pointer-events:none;font-size:12px;z-index:5}
#sdeHUD>*{pointer-events:none}
#sdeTop{position:absolute;top:0;left:0;right:0;display:flex;align-items:center;gap:10px;padding:8px 12px;background:linear-gradient(180deg,rgba(8,11,20,0.95),rgba(8,11,20,0.4));}
#sdeObj{color:#ffe066;font-size:13px;font-weight:bold;flex:1;text-shadow:1px 1px 2px #000}
#sdeTimer{color:#ffe066;font-size:20px;font-weight:bold;min-width:52px;text-align:center;text-shadow:0 0 8px rgba(255,224,102,0.5)}
#sdePause{pointer-events:auto;border:1px solid #c9a227;background:rgba(20,28,48,0.9);color:#ffe066;width:32px;height:32px;border-radius:5px;cursor:pointer;font-size:13px}
#sdeLeft{position:absolute;top:52px;left:10px;width:200px}
#sdePortrait{width:44px;height:56px;border:2px solid #c9a227;border-radius:4px;background:rgba(0,0,0,0.5) center/cover no-repeat #1a1f2e;margin-bottom:6px;box-shadow:0 0 10px rgba(0,0,0,0.6)}
#sdeHpBar,#sdeStamBar{position:relative;height:12px;border:1px solid #444;border-radius:3px;background:rgba(0,0,0,0.6);margin:3px 0}
#sdeHpFill{height:100%;background:linear-gradient(90deg,#c0392b,#e07b3a);transition:width 0.15s}
#sdeStamFill{height:100%;background:linear-gradient(90deg,#2a6a8a,#5ad0e0);transition:width 0.15s}
#sdeHpTxt,#sdeStamBar::after{position:absolute;top:0;left:0;width:100%;text-align:center;font-size:10px;line-height:12px;color:#fff;text-shadow:1px 1px 1px #000}
#sdeHpTxt{font-size:10px}
#sdeStamBar::after{content:'体力';}
#sdeThreat{font-size:11px;color:#5f5;margin-top:3px;text-shadow:1px 1px 2px #000}
#sdeRight{position:absolute;top:52px;right:10px;width:150px}
#sdeLoot{background:rgba(8,11,20,0.85);border:1px solid #3a5a8a;border-radius:5px;padding:6px 8px;min-height:28px;max-height:120px;overflow-y:auto;line-height:1.5}
#sdeLoot.empty{color:#778;font-size:11px}
#sdeLoot.has{color:#cfe}
#sdeLoot .lt{display:inline-block;background:rgba(201,162,39,0.15);border:1px solid #5a4820;border-radius:3px;padding:1px 5px;margin:2px;font-size:11px;color:#ffe066}
#sdeLoot .lt.mid{background:rgba(192,200,212,0.15);border-color:#5a6070;color:#dde}
#sdeLoot .lt.big{background:rgba(255,224,102,0.22);border-color:#c9a227;color:#fff;box-shadow:0 0 6px rgba(255,224,102,0.5);font-weight:bold}
#sdeLoot .lt i{color:#aab;font-style:normal;font-size:10px}
#sdeSquad{margin-top:8px}
.sq{display:flex;align-items:center;gap:6px;margin:3px 0}
.sq-ico{width:20px;height:20px;background:rgba(40,70,120,0.8);border:1px solid #5a7ab0;border-radius:3px;color:#bcd;text-align:center;line-height:18px;font-size:11px}
.sq-bar{flex:1;height:8px;background:rgba(0,0,0,0.6);border-radius:2px;border:1px solid #334}
.sq-bar i{display:block;height:100%;background:linear-gradient(90deg,#2a8a3a,#5ae06a);transition:width 0.2s}
/* 虚拟摇杆 */
#sdeJoy{position:absolute;left:26px;bottom:34px;width:104px;height:104px;border:2px solid rgba(255,224,102,0.45);border-radius:50%;background:rgba(10,14,27,0.45);pointer-events:auto;touch-action:none}
#sdeJoy.active{border-color:#ffe066;background:rgba(201,162,39,0.2)}
#sdeJoyKnob{position:absolute;left:50%;top:50%;width:42px;height:42px;margin:-21px 0 0 -21px;border-radius:50%;background:radial-gradient(circle at 35% 35%,#ffe066,#8a6a10);box-shadow:0 2px 8px rgba(0,0,0,0.6);pointer-events:none}
/* 攻击键 */
#sdeBtns{position:absolute;right:22px;bottom:34px;display:flex;gap:12px;align-items:flex-end}
#sdeBtns button{pointer-events:auto;border:none;border-radius:50%;cursor:pointer;box-shadow:0 3px 10px rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;color:#0a0e1b;font-weight:bold;touch-action:none}
#sdeBtns button:active{transform:scale(0.9)}
#sdeBtnAtk{width:78px;height:78px;background:radial-gradient(circle at 35% 35%,#ff7a5a,#a82020)}
#sdeBtnDef{width:60px;height:60px;background:radial-gradient(circle at 35% 35%,#7ab0e0,#1f4a7a)}
#sdeBtnRoll{width:60px;height:60px;background:radial-gradient(circle at 35% 35%,#a0d0a0,#2a6a32)}
#sdeBtns button span{font-size:15px}
/* 提示层 */
#sdeCenterTip,#sdePickupTip,#sdeExtractTip{position:absolute;left:50%;transform:translateX(-50%);text-align:center;pointer-events:none;transition:opacity 0.2s}
#sdeCenterTip{top:24%;background:rgba(8,11,20,0.92);border:1px solid #c9a227;border-radius:6px;padding:10px 22px;color:#ffe066;font-size:15px;text-shadow:1px 1px 2px #000}
#sdeCenterTip b{font-size:17px;display:block;margin-bottom:3px}
#sdeCenterTip span{color:#cfe;font-size:12px}
#sdePickupTip{bottom:150px;background:rgba(8,11,20,0.9);border:1px solid #ffe066;border-radius:14px;padding:6px 14px;color:#fff;font-size:13px}
#sdeExtractTip{top:14%;background:rgba(20,60,30,0.9);border:1px solid #5f5;border-radius:4px;padding:5px 12px;color:#bff}
.hidden{opacity:0 !important}
/* 小地图 */
#sdeMinimap{position:absolute;top:52px;right:170px;width:150px;height:150px;border:2px solid #c9a227;border-radius:6px;background:rgba(8,11,20,0.9);overflow:hidden}
#sdeMinimap canvas{display:block}
#sdeCompass{position:absolute;top:210px;right:196px;width:0;height:0}
/* 移动端适配 */
@media(max-width:640px){
#sdeLeft{width:150px;top:46px}
#sdePortrait{width:34px;height:44px}
#sdeRight{width:110px;top:46px}
#sdeLoot{font-size:10px;padding:4px}
#sdeMinimap{width:100px;height:100px;right:124px;top:46px}
#sdeObj{font-size:11px}
#sdeTimer{font-size:16px}
#sdeJoy{width:88px;height:88px;left:14px;bottom:22px}
#sdeJoyKnob{width:34px;height:34px;margin:-17px 0 0 -17px}
#sdeBtns{right:12px;bottom:22px;gap:8px}
#sdeBtnAtk{width:66px;height:66px}
#sdeBtnDef,#sdeBtnRoll{width:52px;height:52px}
#sdePickupTip{bottom:120px;font-size:12px}
}
/* ==== 日志 ==== */
#logPanel{height:110px;background:#080b14;border-top:1px solid #203258;display:flex;flex-direction:column;flex-shrink:0}
#logPanel .head{display:flex;justify-content:space-between;align-items:center;padding:4px 10px;background:#0d1428;border-bottom:1px solid #1a2540}
#logPanel .head span{font-size:12px;color:#ffe066}
#logPanel .clear{border:none;background:none;color:#8aa;font-size:11px;cursor:pointer}
#logList{flex:1;overflow-y:auto;padding:6px 10px;font-size:12px;line-height:1.7}
#logList div{border-bottom:1px solid rgba(255,255,255,0.04);padding:1px 0}
#logList .warn{color:#f88}
/* ==== 提示条 ==== */
#toast{position:fixed;top:54px;left:50%;transform:translateX(-50%);background:rgba(10,14,27,0.95);border:1px solid #c9a227;color:#ffe066;padding:8px 16px;border-radius:4px;font-size:13px;z-index:200;opacity:0;transition:opacity 0.3s;pointer-events:none;max-width:80%}
#toast.show{opacity:1}
/* ==== 城市菜单浮层 ==== */
#cityMenu{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:150;background:rgba(12,18,35,0.97);border:2px solid #c9a227;border-radius:10px;padding:18px 22px;min-width:300px;max-width:90vw;max-height:85vh;overflow-y:auto;box-shadow:0 0 40px rgba(0,0,0,0.8)}
#cityMenu h3{color:#ffe066;font-size:16px;margin-bottom:4px}
#cityMenu .info{color:#aac;font-size:12px;line-height:1.8;margin-bottom:12px}
#cityMenu .act-btn{display:block;width:100%;text-align:left;border:1px solid #3a5a8a;background:#12203c;color:#fff;padding:8px 12px;border-radius:5px;margin:4px 0;font-size:13px;cursor:pointer}
#cityMenu .act-btn:active{background:#c9a227;color:#0a0e1b}
#cityMenu .act-btn:disabled{opacity:0.4;cursor:not-allowed}
#cityMenu .close-x{position:absolute;top:8px;right:12px;background:none;border:none;color:#c9a227;font-size:20px;cursor:pointer}
#cityMenu .menu-section{margin:10px 0 4px;padding-bottom:4px;border-bottom:1px solid #2a3a5a;color:#7a90b5;font-size:11px;letter-spacing:1px}
#cityMenu .act-btn{display:block;width:100%;text-align:left;border:1px solid #3a5a8a;background:#12203c;color:#fff;padding:9px 12px;border-radius:5px;margin:4px 0;font-size:13px;cursor:pointer;position:relative;overflow:hidden;transition:background 0.15s}
#cityMenu .act-btn:hover{background:#1a3058}
#cityMenu .act-btn:active{background:#c9a227;color:#0a0e1b}
#cityMenu .act-btn:disabled{opacity:0.35;cursor:not-allowed}
#cityMenu .act-btn .btn-ico{margin-right:6px}
#cityMenu .act-btn .btn-hot{position:absolute;right:8px;top:50%;transform:translateY(-50%);font-size:11px;color:#7a90b5}
#cityMenu .act-btn.battle{background:linear-gradient(135deg,#4a1520,#2a0e16);border-color:#8a3030;font-weight:bold}
#cityMenu .act-btn.battle:hover{background:linear-gradient(135deg,#6a1f2e,#3a141f)}
#cityMenu .act-btn.scout{background:linear-gradient(135deg,#0e3a2a,#0a2a1e);border-color:#1f6a45}
#cityMenu .hero-list{max-height:140px;overflow-y:auto;margin:6px 0}
#cityMenu .hero-row{display:flex;align-items:center;gap:6px;padding:3px 0;border-bottom:1px solid #1a2a45;font-size:12px}
#cityMenu .hero-row .hname{color:#ffe066;min-width:48px}
#cityMenu .hero-row .hstat{color:#9ab;font-size:11px}
#cityMenu .hero-row input[type=radio]{accent-color:#c9a227}
#cityMenu .target-list{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0}
#cityMenu .target-chip{border:1px solid #3a5a8a;background:#0f1c34;color:#fff;padding:4px 10px;border-radius:14px;font-size:12px;cursor:pointer}
#cityMenu .target-chip.selected{border-color:#c9a227;background:#c9a227;color:#0a0e1b;font-weight:bold}
#cityMenu .target-chip:hover{border-color:#c9a227}
#cityMenu .cost-tag{display:inline-block;background:#0a1428;border:1px solid #2a3a5a;border-radius:3px;padding:1px 6px;font-size:11px;color:#aab;margin-left:4px}
</style>
</head>
<body>
<div id="titleScreen">
<div class="title-wrap">
<div class="portrait-row">
<img id="ptStrategist" alt=""><img id="ptWarrior" alt=""><img id="ptRuler" alt="">
</div>
<h1>汉末三国之君临天下</h1>
<div class="sub">战 略 · 搜 打 撤 双 模 式</div>
<!-- 剧本选择 -->
<div class="title-block" id="blkScenario">
<div class="block-label">选择剧本</div>
<div class="scenario-list" id="scenarioList"></div>
</div>
<!-- 势力选择 -->
<div class="title-block" id="blkForce" style="display:none">
<div class="block-label">选择势力</div>
<div class="force-list" id="forceList"></div>
</div>
<!-- 难度选择 -->
<div class="title-block" id="blkDiff" style="display:none">
<div class="block-label">选择难度</div>
<div class="diff-list" id="diffList"></div>
</div>
<button class="menu-btn" id="btnNew" style="display:none">开 始 霸 业</button>
<button class="menu-btn" id="btnContinue">读 取 存 档</button>
<button class="menu-btn" id="btnHelp">游 戏 说 明</button>
<div class="credits">45 城 · 三国志 11 式武将五维 · 搜打撤战斗</div>
</div>
</div>
<div id="app">
<div id="topBar">
<span class="turn" id="turnInfo">公元 189 年</span>
<span id="resBar"></span>
<button class="top-btn" id="btnNext">▶ 下一月</button>
<button class="top-btn" id="btnHeroes">武将</button>
<button class="top-btn" id="btnTech">科技</button>
<button class="top-btn" id="btnDiplomacy">外交</button>
<button class="top-btn" id="btnReports">战报</button>
<button class="top-btn" id="btnMenu">菜单</button>
<button class="top-btn" id="btnTitle">标题</button>
</div>
<div id="cityMenu" style="display:none"></div>
<div class="view active" id="mapView">
<canvas id="mapCanvas"></canvas>
<div id="mapZoomInfo">缩放 100%</div>
<div id="mapZoomCtrl">
<button id="zoomIn" title="放大">+</button>
<button id="zoomReset" class="zoom-reset" title="重置">100%</button>
<button id="zoomOut" title="缩小">-</button>
</div>
</div>
<div class="view" id="battleView">
<canvas id="battleCanvas"></canvas>
</div>
<div id="logPanel">
<div class="head"><span>📜 事件日志</span><button class="clear" id="btnClearLog">清空</button></div>
<div id="logList"></div>
</div>
</div>
<div id="toast"></div>
<script>
if(typeof CanvasRenderingContext2D==='undefined'){
CanvasRenderingContext2D = function(){};
CanvasRenderingContext2D.prototype = {};
}
/* === 视觉层模块(人物模型 + 2D 画面)===
*/
/* ============================================================
视觉层升级模块(注入到主 HTML 用)
- Portrait : 为每个武将程序化生成独特像素立绘(按势力/职业/五维)
- Sprite : 2D 人物精灵绘制(身体、头部、武器、马匹)
- CityArt : 城池、地形、旗帜视觉升级
============================================================ */
(function(){
'use strict';
/* ---------- 1. 字符串哈希(把武将名/势力名变成稳定随机数种子) ---------- */
function hashStr(s){
let h = 2166136261 >>> 0;
for(let i=0;i<s.length;i++){ h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
return h;
}
function mulberry32(seed){
let t = seed >>> 0;
return function(){
t = (t + 0x6D2B79F5) >>> 0;
let r = t;
r = Math.imul(r ^ (r >>> 15), r | 1);
r ^= r + Math.imul(r ^ (r >>> 7), r | 61);
return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
};
}
/* ---------- 2. 势力主题色(旗帜/服饰/城池) ---------- */
const FORCE_THEME = {
'player':'魏', 'player2':'魏',
'曹氏':'魏', '魏':'魏', '汉':'汉',
'袁绍':'袁', '公孙':'公孙', '刘表':'刘', '刘璋':'刘', '张鲁':'张',
'士燮':'士', '羌':'羌', '袁术':'袁', '孙策':'吴', '吴':'吴',
'陶谦':'陶', '刘岱':'刘', '孔融':'孔',
};
const THEME_COLORS = {
'魏':{banner:'#1f4fa8', dark:'#0e2a64', trim:'#d9b24a', cloth:'#2b4d8a', clothDark:'#1a335c'},
'汉':{banner:'#c9a227', dark:'#7a6210', trim:'#f4e2b0', cloth:'#b8942a', clothDark:'#7a6210'},
'袁':{banner:'#a83232', dark:'#5c1414', trim:'#e8c864', cloth:'#8a2a2a', clothDark:'#5c1414'},
'公孙':{banner:'#4a8a3c', dark:'#254a1c', trim:'#d0e0a0', cloth:'#3c7030', clothDark:'#254a1c'},
'刘':{banner:'#3c7a9a', dark:'#1c4054', trim:'#bfe0f0', cloth:'#336686', clothDark:'#1c4054'},
'张':{banner:'#8a4a9a', dark:'#4a1c5a', trim:'#e0bff0', cloth:'#703a80', clothDark:'#4a1c5a'},
'士':{banner:'#c08030', dark:'#6a4010', trim:'#f0d0a0', cloth:'#a06020', clothDark:'#6a4010'},
'羌':{banner:'#6a5a3a', dark:'#3a2e18', trim:'#c9a877', cloth:'#5a4a2a', clothDark:'#3a2e18'},
'吴':{banner:'#3aa8a8', dark:'#1a5454', trim:'#bfe8e8', cloth:'#2c8a8a', clothDark:'#1a5454'},
'陶':{banner:'#a89060', dark:'#544820', trim:'#e8d8b0', cloth:'#8a7040', clothDark:'#544820'},
'孔':{banner:'#7a8a9a', dark:'#3c4654', trim:'#d0d8e0', cloth:'#607080', clothDark:'#3c4654'},
};
function themeOf(force){ return THEME_COLORS[FORCE_THEME[force]||'汉'] || THEME_COLORS['汉']; }
/* ---------- 3. 职业(决定立绘构图:武将/军师/君主/文官) ---------- */
const ROLE = {
warrior:'武', vanguard:'武', spearman:'武', archer:'武', cavalry:'骑',
strategist:'文', adviser:'文', civil:'文',
ruler:'君', monarch:'君',
};
function roleOf(hero){
if(hero.portrait==='ruler') return '君';
if(hero.portrait==='strategist') return '文';
// 按五维自动判定
const s = hero.stats;
if(s[1] >= 90 && s[1] >= s[2]+15) return '武';
if(s[2] >= 88) return '文';
if((hero.force==='player') && ['曹操','刘备','孙策','袁绍','袁术','刘表','刘璋','公孙','士燮'].includes(hero.name)) return '君';
if(s[1] >= 80) return '武';
if(s[2] >= 78) return '文';
return s[1]>=s[2] ? '武' : '文';
}
/* ============================================================
4. Portrait 立绘生成器
输出:180x220 像素立绘 Canvas;每个武将独一无二
============================================================ */
const Portrait = {
W:180, H:220,
/* 取立绘(带缓存) */
get(hero){
hero._portraitKey = hero._portraitKey || (hero.name+'|'+hero.force);
if(hero._cachedPortrait){
// 检查是否需要刷新(势力变化)
if(hero._cachedKey === hero._portraitKey) return hero._cachedPortrait;
}
const c = document.createElement('canvas');
c.width = this.W; c.height = this.H;
this.draw(c, hero);
const url = c.toDataURL('image/png');
hero._cachedPortrait = url;
hero._cachedKey = hero._portraitKey;
return url;
},
draw(canvas, hero){
const ctx = canvas.getContext('2d');
const W=this.W, H=this.H;
const th = themeOf(hero.force);
const role = roleOf(hero);
const rnd = mulberry32(hashStr(hero.name + '|' + hero.force));
const s = hero.stats;
// 背景:势力色渐变 + 光晕
const bg = ctx.createLinearGradient(0,0,0,H);
bg.addColorStop(0, th.dark);
bg.addColorStop(0.55, th.clothDark);
bg.addColorStop(1, '#0a0e1b');
ctx.fillStyle = bg; ctx.fillRect(0,0,W,H);
// 中央光晕
const glow = ctx.createRadialGradient(W/2, H*0.42, 10, W/2, H*0.42, 95);
glow.addColorStop(0, 'rgba(255,255,255,0.20)');
glow.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = glow; ctx.fillRect(0,0,W,H);
// 底部装饰纹理
ctx.fillStyle = 'rgba(0,0,0,0.25)';
for(let i=0;i<6;i++){ ctx.fillRect(0, H-18+i*3, W, 1); }
// 配色(个人差异化)
const skinLight = 150+rnd()*30|0, skinMid = 120+rnd()*25|0, skinDark = 95+rnd()*20|0;
const skin = `rgb(${skinLight-10},${skinLight-6},${skinLight-18})`;
const hairColor = ['#1a1208','#2a1a0c','#150d06','#221710'][rnd()*4|0];
const clothMain = th.cloth;
const clothDark = th.clothDark;
const trim = th.trim;
// 铠甲 / 布料细节
const hasArmor = role==='武';
const armorPlate = role==='君' ? '#c9a227' : (rnd()<0.5 ? '#9aa6b4' : '#8a7a5a');
// 头部坐标
const hx = W/2, hy = 62, hr = 22;
// 肩宽(体形按统率)
const shoulder = 30 + (s[0]-70)*0.28;
const bodyTop = hy + hr - 4;
ctx.save();
// 披风(背后)
ctx.fillStyle = th.banner;
ctx.beginPath();
ctx.moveTo(hx-shoulder-4, bodyTop);
ctx.lineTo(hx+shoulder+4, bodyTop);
ctx.lineTo(hx+shoulder+14, H-24);
ctx.lineTo(hx-shoulder-14, H-24);
ctx.closePath();
ctx.fill();
// 披风褶皱
ctx.strokeStyle = th.dark; ctx.lineWidth = 1.5;
for(let i=-1;i<=1;i++){
ctx.beginPath();
ctx.moveTo(hx + i*12, bodyTop+4);
ctx.quadraticCurveTo(hx + i*20, H*0.72, hx + i*16 + (rnd()*6-3), H-26);
ctx.stroke();
}
// 躯干(铠甲或袍服)
if(hasArmor){
// 身甲
ctx.fillStyle = clothMain;
roundRect(ctx, hx-shoulder, bodyTop, shoulder*2, 62, 8); ctx.fill();
// 护心镜
ctx.fillStyle = armorPlate;
ctx.beginPath(); ctx.ellipse(hx, bodyTop+24, 16, 20, 0,0,Math.PI*2); ctx.fill();
ctx.strokeStyle = trim; ctx.lineWidth = 2; ctx.stroke();
// 胸甲分片
ctx.strokeStyle = clothDark; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(hx, bodyTop+8); ctx.lineTo(hx, bodyTop+56); ctx.stroke();
ctx.beginPath(); ctx.moveTo(hx-16, bodyTop+22); ctx.quadraticCurveTo(hx, bodyTop+30, hx+16, bodyTop+22); ctx.stroke();
// 肩甲
ctx.fillStyle = armorPlate;
ctx.beginPath(); ctx.ellipse(hx-shoulder+2, bodyTop+4, 10, 13, 0,0,Math.PI*2); ctx.fill();
ctx.beginPath(); ctx.ellipse(hx+shoulder-2, bodyTop+4, 10, 13, 0,0,Math.PI*2); ctx.fill();
ctx.strokeStyle = trim; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.ellipse(hx-shoulder+2, bodyTop+4, 10, 13, 0,0,Math.PI*2); ctx.stroke();
ctx.beginPath(); ctx.ellipse(hx+shoulder-2, bodyTop+4, 10, 13, 0,0,Math.PI*2); ctx.stroke();
}else if(role==='君'){
// 龙袍
ctx.fillStyle = th.banner;
roundRect(ctx, hx-shoulder, bodyTop, shoulder*2, 70, 8); ctx.fill();
// 龙纹(简化波浪)
ctx.strokeStyle = trim; ctx.lineWidth = 1.5;
for(let yy=bodyTop+14; yy<bodyTop+64; yy+=14){
ctx.beginPath();
ctx.moveTo(hx-shoulder+8, yy);
ctx.quadraticCurveTo(hx, yy+7, hx+shoulder-8, yy);
ctx.stroke();
}
// 腰带
ctx.fillStyle = trim;
roundRect(ctx, hx-shoulder+2, bodyTop+44, shoulder*2-4, 8, 3); ctx.fill();
}else{ // 文官袍服
ctx.fillStyle = clothMain;
roundRect(ctx, hx-shoulder+2, bodyTop, (shoulder-2)*2, 72, 6); ctx.fill();
// 交领
ctx.fillStyle = clothDark;
ctx.beginPath();
ctx.moveTo(hx, bodyTop+2);
ctx.lineTo(hx-shoulder+8, bodyTop+34);
ctx.lineTo(hx, bodyTop+20);
ctx.lineTo(hx+shoulder-8, bodyTop+34);
ctx.closePath(); ctx.fill();
// 腰带
ctx.fillStyle = trim;
roundRect(ctx, hx-shoulder+4, bodyTop+46, (shoulder-4)*2, 6, 2); ctx.fill();
}
// 颈部
ctx.fillStyle = skin;
roundRect(ctx, hx-6, hy+hr-8, 12, 12, 4); ctx.fill();
// 头部
ctx.fillStyle = skin;
ctx.beginPath(); ctx.arc(hx, hy, hr, 0, Math.PI*2); ctx.fill();
ctx.strokeStyle = `rgb(${skinDark},${skinDark-4},${skinDark-14})`; ctx.lineWidth = 1.5; ctx.stroke();
// 发髻/冠(按角色)
if(role==='君'){
// 天子冠冕 / 平天冠
ctx.fillStyle = '#c9a227';
roundRect(ctx, hx-20, hy-hr-2, 40, 12, 3); ctx.fill();
ctx.fillStyle = '#0a0e1b';
for(let i=-2;i<=2;i++){
ctx.fillRect(hx+i*7-1, hy-hr-14, 2, 14);
}
ctx.fillStyle = '#c9a227';
ctx.fillRect(hx-22, hy-hr-2, 44, 4);
}else if(role==='文'){
// 文冠(进贤冠)
ctx.fillStyle = hairColor;
ctx.beginPath();
ctx.moveTo(hx-18, hy-hr+2);
ctx.quadraticCurveTo(hx, hy-hr-16, hx+18, hy-hr+2);
ctx.closePath(); ctx.fill();
ctx.fillStyle = th.banner;
roundRect(ctx, hx-16, hy-hr-6, 32, 8, 3); ctx.fill();
ctx.strokeStyle = trim; ctx.lineWidth=1; ctx.strokeRect(hx-16, hy-hr-6, 32, 8);
}else{
// 武将兜鍪 / 束发
ctx.fillStyle = hairColor;
ctx.beginPath();
ctx.arc(hx, hy-hr+4, hr-2, Math.PI, 0);
ctx.lineTo(hx+hr-4, hy-hr+10);
ctx.lineTo(hx-hr+4, hy-hr+10);
ctx.closePath(); ctx.fill();
// 盔缨
ctx.fillStyle = th.banner;
ctx.beginPath();
ctx.moveTo(hx, hy-hr-2);
ctx.lineTo(hx+5, hy-hr-14);
ctx.lineTo(hx-5, hy-hr-2);
ctx.closePath(); ctx.fill();
// 护颊
ctx.fillStyle = armorPlate;
ctx.fillRect(hx-hr-2, hy-6, 6, 16);
ctx.fillRect(hx+hr-4, hy-6, 6, 16);
}
// 眉毛(按武力高低决定浓淡/角度)
ctx.strokeStyle = hairColor; ctx.lineWidth = 2.4;
const browAng = (s[1]-70)*0.012;
[-1,1].forEach(side=>{
ctx.beginPath();
const bx = hx + side*8;
ctx.moveTo(bx-6, hy-6 + side*browAng*4);
ctx.quadraticCurveTo(bx, hy-9 + side*browAng*5, bx+6, hy-5);
ctx.stroke();
});
// 眼睛(按智力决定大小/神采)
const eyeOpen = s[2]>=85 ? 1 : 0.75;
ctx.fillStyle = '#0a0e1b';
[-1,1].forEach(side=>{
const ex = hx + side*8, ey = hy+2;
ctx.beginPath();
ctx.ellipse(ex, ey, 3, 3.2*eyeOpen, 0, 0, Math.PI*2); ctx.fill();
// 高光
ctx.fillStyle='#fff';
ctx.fillRect(ex+1, ey-1.4, 1.2, 1.2);
ctx.fillStyle='#0a0e1b';
});
// 胡须(按年龄/魅力,武力型多胡)
if(role==='武' && s[1]>=85){
ctx.strokeStyle = hairColor; ctx.lineWidth = 1.6;
ctx.beginPath();
ctx.moveTo(hx-7, hy+9);
ctx.quadraticCurveTo(hx-4, hy+16, hx, hy+11);
ctx.quadraticCurveTo(hx+4, hy+16, hx+7, hy+9);
ctx.stroke();
// 须尖
ctx.beginPath();
ctx.moveTo(hx, hy+11); ctx.lineTo(hx, hy+17);
ctx.stroke();
}else if(role==='君'){
ctx.strokeStyle = hairColor; ctx.lineWidth = 1.4;
ctx.beginPath();
ctx.moveTo(hx-6, hy+10); ctx.lineTo(hx-3, hy+15);
ctx.moveTo(hx+6, hy+10); ctx.lineTo(hx+3, hy+15);
ctx.stroke();
}
// 嘴
ctx.strokeStyle = `rgb(${skinDark},${skinDark-6},${skinDark-16})`; ctx.lineWidth = 1.4;
ctx.beginPath();
ctx.moveTo(hx-4, hy+13); ctx.quadraticCurveTo(hx, hy+15, hx+4, hy+13); ctx.stroke();
// 手持武器(武将)
if(role==='武'){
const wp = s[1]>=95 ? '#d0d0d8' : '#8a7a5a'; // 神兵亮色
ctx.strokeStyle = wp; ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(hx+shoulder-2, bodyTop+40);
ctx.lineTo(hx+shoulder+26, bodyTop-6);
ctx.stroke();
// 枪缨 / 剑格
if(s[1]>=92){
ctx.fillStyle = '#c0392b';
ctx.beginPath();
ctx.moveTo(hx+shoulder+22, bodyTop-4);
ctx.lineTo(hx+shoulder+30, bodyTop-10);
ctx.lineTo(hx+shoulder+24, bodyTop+2);
ctx.closePath(); ctx.fill();
}else{
ctx.fillStyle = '#c9a227';
ctx.fillRect(hx+shoulder-3, bodyTop+34, 6, 4);
}
}else if(role==='文'){
// 手执书卷
ctx.strokeStyle = '#e8d8b0'; ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(hx+shoulder-6, bodyTop+34, 9, Math.PI*0.2, Math.PI*1.8);
ctx.stroke();
ctx.strokeStyle = '#a89060'; ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(hx+shoulder-6, bodyTop+34, 9, Math.PI*0.2, Math.PI*1.8);
ctx.stroke();
}
// 底部铭牌:势力名
ctx.fillStyle = 'rgba(0,0,0,0.45)';
roundRect(ctx, 12, H-16, W-24, 11, 5); ctx.fill();
ctx.fillStyle = trim;
ctx.font = '10px "Microsoft YaHei",sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline='middle';
ctx.fillText((hero.force==='player'?'曹氏':hero.force), W/2, H-10);
ctx.restore();
},
};
/* ---------- 圆角矩形工具(全局可用)---------- */
function roundRect(ctx, x, y, w, h, r){
if(w<0) { x+=w; w=-w; }
if(h<0) { y+=h; h=-h; }
r = Math.min(r, w/2, h/2);
ctx.beginPath();
ctx.moveTo(x+r, y);
ctx.lineTo(x+w-r, y);
ctx.quadraticCurveTo(x+w, y, x+w, y+r);
ctx.lineTo(x+w, y+h-r);
ctx.quadraticCurveTo(x+w, y+h, x+w-r, y+h);
ctx.lineTo(x+r, y+h);
ctx.quadraticCurveTo(x, y+h, x, y+h-r);
ctx.lineTo(x, y+r);
ctx.quadraticCurveTo(x, y, x+r, y);
ctx.closePath();
}
// 挂到全局,供 IIFE 外部模块使用
globalThis.roundRect = roundRect;
if(!CanvasRenderingContext2D.prototype.roundRect){
CanvasRenderingContext2D.prototype.roundRect = function(x,y,w,h,r){
roundRect(this,x,y,w,h,r);
return this;
};
}
/* ============================================================
5. Sprite 人物精灵(战斗场景 / 大地图用)
参数化绘制:骑兵、步卒、弓手、武将、文官
============================================================ */
const Sprite = {
_ik: 0,
/* 通用单位:type 决定外观,force 决定配色,facing 朝向弧度 */
unit(ctx, x, y, opt){
opt = opt||{};
const type = opt.type||'步卒'; // 步卒/弓手/戟兵/骑兵/武将/文官
const role = opt.role||'武'; // 武/文/君
const force = opt.force||'player';
const facing = opt.facing||0;
const size = opt.size||16;
const hpRatio = (opt.hpRatio==null)?1:opt.hpRatio;
const th = themeOf(force);
const rnd = opt._rnd || mulberry32(hashStr((opt.seed||'')+x+y));
ctx.save();
ctx.translate(x, y);
ctx.rotate(facing);
const s = size;
const bodyColor = th.cloth;
const dark = th.clothDark;
const trim = th.trim;
const armor = role==='武' ? '#9aa6b4' : th.banner;
// ===== 骑兵 =====
if(type==='骑兵'){
// 马身
const mw = s*1.9, mh = s*1.05;
// 马腿(简单摆动)
const leg = Math.sin(opt._t||0)*2;
ctx.fillStyle = dark;
ctx.fillRect(-mw*0.30, mh*0.34, 3, 8+leg);
ctx.fillRect(-mw*0.10, mh*0.34, 3, 8-leg);
ctx.fillRect( mw*0.14, mh*0.34, 3, 8+leg);
ctx.fillRect( mw*0.30, mh*0.34, 3, 8-leg);
// 马体
ctx.fillStyle = th.banner;
roundRect(ctx, -mw/2, -mh/2, mw, mh, mh*0.4); ctx.fill();
// 马鬃
ctx.fillStyle = '#1a1208';
ctx.beginPath();
ctx.moveTo(-mw*0.14, -mh*0.5);
ctx.quadraticCurveTo(0, -mh*0.8, mw*0.14, -mh*0.5);
ctx.lineTo(mw*0.06, -mh*0.2);
ctx.quadraticCurveTo(0, -mh*0.5, -mw*0.06, -mh*0.2);
ctx.closePath(); ctx.fill();
// 马尾
ctx.strokeStyle = '#1a1208'; ctx.lineWidth = 2.5;
ctx.beginPath();
ctx.moveTo(-mw/2, -mh*0.1);
ctx.quadraticCurveTo(-mw/2-5, 0, -mw/2-2, mh*0.2);
ctx.stroke();
// 马头
ctx.fillStyle = th.banner;
roundRect(ctx, mw*0.32, -mh*0.4, mw*0.26, mh*0.5, 4); ctx.fill();
// 马耳
ctx.fillStyle = '#1a1208';
ctx.beginPath();
ctx.moveTo(mw*0.5, -mh*0.42); ctx.lineTo(mw*0.52, -mh*0.62); ctx.lineTo(mw*0.56, -mh*0.4); ctx.closePath(); ctx.fill();
ctx.beginPath();
ctx.moveTo(mw*0.58, -mh*0.42); ctx.lineTo(mw*0.60, -mh*0.60); ctx.lineTo(mw*0.64, -mh*0.4); ctx.closePath(); ctx.fill();
// 骑手躯干
const riderX = mw*0.05, riderTop = -mh*0.5 - s*0.55;
ctx.fillStyle = bodyColor;
roundRect(ctx, riderX-s*0.34, riderTop, s*0.68, s*0.6, 3); ctx.fill();
// 铠甲片
if(role==='武'){
ctx.fillStyle = armor;
ctx.fillRect(riderX-s*0.24, riderTop+s*0.1, s*0.48, s*0.22);
ctx.strokeStyle = trim; ctx.lineWidth = 1;
ctx.strokeRect(riderX-s*0.24, riderTop+s*0.1, s*0.48, s*0.22);
}
// 披风
ctx.fillStyle = th.banner;
ctx.beginPath();
ctx.moveTo(riderX-s*0.34, riderTop+s*0.1);
ctx.quadraticCurveTo(riderX-s*0.6, riderTop+s*0.5, riderX-s*0.5, riderTop+s*0.85);
ctx.lineTo(riderX-s*0.2, riderTop+s*0.85);
ctx.quadraticCurveTo(riderX-s*0.1, riderTop+s*0.5, riderX-s*0.34, riderTop+s*0.1);
ctx.closePath(); ctx.fill();
// 头部
const headY = riderTop + s*0.05;
ctx.fillStyle = '#e8c99a';
ctx.beginPath(); ctx.arc(riderX, headY, s*0.26, 0, Math.PI*2); ctx.fill();
// 兜鍪
ctx.fillStyle = armor;
ctx.beginPath();
ctx.arc(riderX, headY-s*0.04, s*0.26, Math.PI, 0); ctx.fill();
// 盔缨
ctx.fillStyle = th.banner;
ctx.beginPath();
ctx.moveTo(riderX, headY-s*0.3);
ctx.lineTo(riderX+2.5, headY-s*0.5);
ctx.lineTo(riderX-2.5, headY-s*0.3);
ctx.closePath(); ctx.fill();
// 枪/马槊
ctx.strokeStyle = role==='武' ? '#d0d0d8' : '#8a7a5a';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(riderX+s*0.3, riderTop+s*0.3);
ctx.lineTo(riderX+s*1.5, riderTop-s*0.6);
ctx.stroke();
// 枪缨
ctx.fillStyle = '#c0392b';
ctx.beginPath();
ctx.moveTo(riderX+s*1.42, riderTop-s*0.54);
ctx.lineTo(riderX+s*1.58, riderTop-s*0.68);
ctx.lineTo(riderX+s*1.46, riderTop-s*0.46);
ctx.closePath(); ctx.fill();
}
// ===== 步卒 / 弓手 / 戟兵 / 武将 =====
else{
const isArcher = type==='弓手';
const isHalberd = type==='戟兵';
const isHero = role==='君' || (opt.hero && role==='武');
const bw = s*0.8, bh = s*1.5;
const bodyTop = -bh*0.55;
// 阴影
ctx.fillStyle = 'rgba(0,0,0,0.28)';
ctx.beginPath(); ctx.ellipse(0, s*0.5, s*0.5, s*0.18, 0,0,Math.PI*2); ctx.fill();
// 披风
ctx.fillStyle = th.banner;
ctx.beginPath();
ctx.moveTo(-bw*0.5, bodyTop+s*0.05);
ctx.quadraticCurveTo(-bw*0.85, bodyTop+s*0.5, -bw*0.6, bodyTop+s*0.9);
ctx.lineTo(-bw*0.2, bodyTop+s*0.9);
ctx.quadraticCurveTo(-bw*0.1, bodyTop+s*0.5, -bw*0.5, bodyTop+s*0.05);
ctx.closePath(); ctx.fill();
// 躯干
ctx.fillStyle = bodyColor;
roundRect(ctx, -bw/2, bodyTop, bw, bh*0.9, 3); ctx.fill();
// 铠甲/袍服细节
if(role==='武'){
ctx.fillStyle = armor;
ctx.fillRect(-bw*0.3, bodyTop+s*0.1, bw*0.6, s*0.32);
ctx.strokeStyle = trim; ctx.lineWidth = 1;
ctx.strokeRect(-bw*0.3, bodyTop+s*0.1, bw*0.6, s*0.32);
// 肩甲
ctx.fillStyle = armor;
ctx.beginPath(); ctx.arc(-bw*0.5, bodyTop+s*0.05, s*0.16,0,Math.PI*2); ctx.fill();
ctx.beginPath(); ctx.arc( bw*0.5, bodyTop+s*0.05, s*0.16,0,Math.PI*2); ctx.fill();
}else if(role==='君'){
ctx.strokeStyle = trim; ctx.lineWidth = 1;
for(let yy=bodyTop+s*0.12; yy<bodyTop+s*0.7; yy+=s*0.16){
ctx.beginPath();
ctx.moveTo(-bw*0.4, yy);
ctx.quadraticCurveTo(0, yy+s*0.08, bw*0.4, yy);
ctx.stroke();
}
ctx.fillStyle = trim;
ctx.fillRect(-bw*0.45, bodyTop+s*0.66, bw*0.9, s*0.1);
}else{ // 文官
ctx.fillStyle = dark;
ctx.beginPath();
ctx.moveTo(0, bodyTop);
ctx.lineTo(-bw*0.4, bodyTop+s*0.42);
ctx.lineTo(0, bodyTop+s*0.24);
ctx.lineTo(bw*0.4, bodyTop+s*0.42);
ctx.closePath(); ctx.fill();
ctx.fillStyle = trim;
ctx.fillRect(-bw*0.45, bodyTop+s*0.66, bw*0.9, s*0.08);
}
// 头部
const headY = bodyTop - s*0.02;
ctx.fillStyle = '#e8c99a';
ctx.beginPath(); ctx.arc(0, headY, s*0.3, 0, Math.PI*2); ctx.fill();
// 冠/盔
if(role==='武'){
ctx.fillStyle = '#1a1208';
ctx.beginPath();
ctx.arc(0, headY-s*0.02, s*0.3, Math.PI, 0); ctx.fill();
ctx.fillStyle = armor;
ctx.beginPath();
ctx.arc(0, headY-s*0.02, s*0.3, Math.PI, 0); ctx.fill();
// 护颊
ctx.fillRect(-s*0.3, headY-s*0.04, s*0.1, s*0.2);
ctx.fillRect( s*0.2, headY-s*0.04, s*0.1, s*0.2);
ctx.fillStyle = th.banner;
ctx.beginPath();
ctx.moveTo(0, headY-s*0.32);
ctx.lineTo(s*0.08, headY-s*0.5);
ctx.lineTo(-s*0.08, headY-s*0.32);
ctx.closePath(); ctx.fill();
}else if(role==='君'){
ctx.fillStyle = '#c9a227';
roundRect(ctx, -s*0.32, headY-s*0.34, s*0.64, s*0.16, 2); ctx.fill();
ctx.fillStyle = '#0a0e1b';
for(let i=-2;i<=2;i++) ctx.fillRect(i*s*0.1-0.5, headY-s*0.5, 1, s*0.18);
}else{
ctx.fillStyle = '#2a1a0c';
ctx.beginPath();
ctx.moveTo(-s*0.3, headY-s*0.02);
ctx.quadraticCurveTo(0, headY-s*0.34, s*0.3, headY-s*0.02);
ctx.closePath(); ctx.fill();
ctx.fillStyle = th.banner;
roundRect(ctx, -s*0.26, headY-s*0.12, s*0.52, s*0.1, 2); ctx.fill();
}
// 眼
ctx.fillStyle = '#0a0e1b';
ctx.fillRect(-s*0.14, headY-s*0.02, 1.6, 2);
ctx.fillRect( s*0.06, headY-s*0.02, 1.6, 2);
// 武器
if(isArcher){
// 弓
ctx.strokeStyle = '#8a6a3a'; ctx.lineWidth = 1.6;
ctx.beginPath();
ctx.arc(s*0.7, bodyTop+s*0.3, s*0.5, -1.0, 1.0);
ctx.stroke();
ctx.strokeStyle = '#e8d8b0'; ctx.lineWidth = 0.8;
ctx.beginPath();
ctx.arc(s*0.7, bodyTop+s*0.3, s*0.4, -0.9, 0.9);
ctx.stroke();
}else if(isHalberd){
ctx.strokeStyle = '#8a7a5a'; ctx.lineWidth = 1.8;
ctx.beginPath();
ctx.moveTo(s*0.42, bodyTop+s*0.55);
ctx.lineTo(s*0.42, bodyTop-s*0.85);
ctx.stroke();
// 戟刃
ctx.fillStyle = '#c0c0c8';
ctx.beginPath();
ctx.moveTo(s*0.42, bodyTop-s*0.85);
ctx.lineTo(s*0.42+s*0.34, bodyTop-s*0.95);
ctx.lineTo(s*0.42+s*0.1, bodyTop-s*0.72);
ctx.lineTo(s*0.42+s*0.34, bodyTop-s*0.6);
ctx.lineTo(s*0.42, bodyTop-s*0.66);
ctx.closePath(); ctx.fill();
}else if(role==='文'){
// 书卷
ctx.strokeStyle = '#e8d8b0'; ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(s*0.4, bodyTop+s*0.35, s*0.22, 0.3, Math.PI-0.3);
ctx.stroke();
}else{
// 长枪/剑
const wp = isHero ? '#d0d0d8' : '#9aa0a8';
ctx.strokeStyle = wp; ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(s*0.4, bodyTop+s*0.5);
ctx.lineTo(s*1.4, bodyTop-s*0.7);
ctx.stroke();
if(isHero){
ctx.fillStyle = '#c0392b';
ctx.beginPath();
ctx.moveTo(s*1.32, bodyTop-s*0.64);
ctx.lineTo(s*1.48, bodyTop-s*0.78);
ctx.lineTo(s*1.34, bodyTop-s*0.58);
ctx.closePath(); ctx.fill();
}
}
}
// 血条(受伤时显示)
if(hpRatio<1){
const w = s*1.6;
ctx.rotate(-facing);
ctx.fillStyle = 'rgba(0,0,0,0.6)';
ctx.fillRect(-w/2, -s*1.7, w, 4);
ctx.fillStyle = hpRatio>0.5 ? '#5f5' : (hpRatio>0.25?'#fd3':'#f55');
ctx.fillRect(-w/2, -s*1.7, w*hpRatio, 4);
}
ctx.restore();
},
/* 玩家专属:带头衔光环 */
player(ctx, x, y, opt){
opt = opt||{};
const role = opt.role||'武';
const facing = opt.facing||0;
const s = opt.size||18;
// 脚下光环
ctx.save();
ctx.translate(x,y);
const pulse = 0.5 + 0.5*Math.sin((opt._t||0)*0.12);
ctx.strokeStyle = role==='君' ? `rgba(201,162,39,${0.5+pulse*0.3})`
: `rgba(120,200,255,${0.4+pulse*0.3})`;
ctx.lineWidth = 2;
ctx.beginPath(); ctx.ellipse(0, s*0.5, s*0.9, s*0.3, 0,0,Math.PI*2); ctx.stroke();
ctx.restore();
this.unit(ctx, x, y, opt);
},
};
/* ============================================================
6. 城池视觉升级(战略地图用)
============================================================ */
const CityArt = {
/* 城池:日式天守阁风格城郭,带势力旗 */
city(ctx, c, opt){
opt = opt||{};
const own = opt.own;
const sel = opt.sel;
const th = themeOf(c.force);
const x=c.x, y=c.y;
const r = own?18:14;
ctx.save();
ctx.translate(x, y);
// 阴影
ctx.fillStyle = 'rgba(0,0,0,0.35)';
ctx.beginPath(); ctx.ellipse(0, r*0.6, r*1.1, r*0.4, 0,0,Math.PI*2); ctx.fill();
// 旗帜(在最上层,先画在后方)
ctx.save();
ctx.translate(r*0.3, -r-10);
// 旗杆
ctx.fillStyle = '#3a2a14';
ctx.fillRect(-1, -r*0.4, 2.5, r*0.6);
// 旗面
ctx.fillStyle = th.banner;
roundRect(ctx, 1.5, -r*0.4, r*1.1, r*0.7, 2); ctx.fill();
ctx.strokeStyle = th.trim; ctx.lineWidth = 1;
roundRect(ctx, 1.5, -r*0.4, r*1.1, r*0.7, 2);
// 旗上标记
ctx.fillStyle = th.trim;
ctx.font = `bold ${r*0.5}px sans-serif`;
ctx.textAlign='center'; ctx.textBaseline='middle';
ctx.fillText(th.banner==='#c9a227'?'汉':(own?'魏':th.banner==='#a83232'?'袁':th.banner==='#3c7a9a'?'吴':th.banner==='#3aa8a8'?'吴':'·'),
1.5+r*0.55, -r*0.05);
ctx.restore();
// 城郭主体
// 石垣(台基)
ctx.fillStyle = '#6a6a72';
roundRect(ctx, -r-3, -r*0.3, (r+3)*2, r*0.55, 3); ctx.fill();
ctx.fillStyle = '#4a4a52';
for(let i=-r-2;i<=r+1;i+=5){
ctx.fillRect(i, -r*0.3, 2, r*0.55);
}
// 天守(白墙黑瓦)
const tw = r*1.3, th2 = r*1.1;
const top = -r*0.3 - th2;
// 瓦顶(黑)
ctx.fillStyle = '#2a2a32';
ctx.beginPath();
ctx.moveTo(-tw/2-4, top+6);
ctx.lineTo(-tw/2+2, top-4);
ctx.lineTo(tw/2-2, top-4);
ctx.lineTo(tw/2+4, top+6);
ctx.closePath(); ctx.fill();
// 墙体(白)
ctx.fillStyle = '#f0ead6';
roundRect(ctx, -tw/2, top+5, tw, th2-4, 2); ctx.fill();
// 楼层线
ctx.strokeStyle = '#c9c2ac'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(-tw/2+2, top+th2*0.5); ctx.lineTo(tw/2-2, top+th2*0.5); ctx.stroke();
// 城门
ctx.fillStyle = '#3a2a14';
roundRect(ctx, -r*0.3, top+th2*0.55, r*0.6, th2*0.38, 2); ctx.fill();
// 门钉
ctx.fillStyle = '#c9a227';
ctx.fillRect(-r*0.14, top+th2*0.66, 2, 2);
ctx.fillRect( r*0.1, top+th2*0.66, 2, 2);
// 轮廓
ctx.strokeStyle = sel ? '#ffe066' : 'rgba(255,255,255,0.9)';
ctx.lineWidth = sel?3:1.5;
ctx.beginPath();
ctx.moveTo(-tw/2-4, top+6);
ctx.lineTo(-tw/2+2, top-4);
ctx.lineTo(tw/2-2, top-4);
ctx.lineTo(tw/2+4, top+6);
ctx.lineTo(tw/2, top+6);
ctx.lineTo(tw/2, top+th2+2);
ctx.lineTo(-tw/2, top+th2+2);
ctx.lineTo(-tw/2, top+6);
ctx.closePath(); ctx.stroke();
// 选中光环
if(sel){
ctx.beginPath(); ctx.arc(0,0,r+7,0,Math.PI*2);
ctx.strokeStyle = 'rgba(255,224,102,0.85)'; ctx.lineWidth = 2; ctx.stroke();
// 旋转指示点
const a = (opt._t||0)*0.04;
ctx.fillStyle = '#ffe066';
ctx.beginPath();
ctx.arc(Math.cos(a)*(r+7), Math.sin(a)*(r+7), 2.5, 0,Math.PI*2); ctx.fill();
}
// 名称
ctx.fillStyle = '#fff';
ctx.font = '12px "Microsoft YaHei",sans-serif';
ctx.textAlign='center'; ctx.textBaseline='alphabetic';
ctx.strokeStyle = 'rgba(0,0,0,0.85)'; ctx.lineWidth = 3;
ctx.strokeText(c.id, 0, r+16);
ctx.fillText(c.id, 0, r+16);
// 守军小标记
ctx.font = '9px sans-serif';
ctx.fillStyle = own?'#8f8':'#faa';
ctx.fillText((opt.troops==null?'':opt.troops), 0, r+27);
ctx.restore();
},
/* 地形:山脉、河流、森林,分层绘制 */
terrain(ctx, W, H){
// 山脉(层叠剪影)
const ranges = [
{color:'rgba(90,104,130,0.35)', pts:[[180,80],[240,50],[300,110],[360,70],[430,120],[490,80],[560,130],[600,100],[550,180],[480,170],[410,200],[330,175],[260,205],[190,180]], dir:'up'},
{color:'rgba(70,84,110,0.30)', pts:[[120,420],[180,390],[250,430],[330,400],[420,440],[500,410],[560,450],[520,510],[440,500],[350,530],[260,510],[180,530],[120,490]], dir:'down'},
];
ranges.forEach(rg=>{
ctx.fillStyle = rg.color;
ctx.beginPath();
ctx.moveTo(rg.pts[0][0], rg.pts[0][1]);
for(let i=1;i<rg.pts.length;i++) ctx.lineTo(rg.pts[i][0], rg.pts[i][1]);
if(rg.dir==='up'){ ctx.lineTo(rg.pts[rg.pts.length-1][0],0); ctx.lineTo(rg.pts[0][0],0); }
else { ctx.lineTo(rg.pts[rg.pts.length-1][0],H); ctx.lineTo(rg.pts[0][0],H); }
ctx.closePath(); ctx.fill();
});
// 森林点缀(长江以南)
const trees = [[360,470],[390,490],[420,480],[460,500],[490,485],[520,505],[400,520],[440,530],[480,525]];
trees.forEach(t=>{
ctx.fillStyle = 'rgba(40,80,45,0.5)';
ctx.beginPath();
ctx.moveTo(t[0], t[1]-6);
ctx.lineTo(t[0]-5, t[1]+3);
ctx.lineTo(t[0]+5, t[1]+3);
ctx.closePath(); ctx.fill();
});
// 河流(黄河/长江意向,更柔和)
ctx.strokeStyle = 'rgba(110,170,230,0.45)'; ctx.lineWidth = 9; ctx.lineCap='round';
ctx.beginPath();
ctx.moveTo(40,330);
ctx.bezierCurveTo(160,300, 240,360, 340,360);
ctx.bezierCurveTo(420,360, 460,420, 520,560);
ctx.stroke();
ctx.strokeStyle = 'rgba(150,200,245,0.35)'; ctx.lineWidth = 4;
ctx.beginPath();
ctx.moveTo(40,330);
ctx.bezierCurveTo(160,300, 240,360, 340,360);
ctx.bezierCurveTo(420,360, 460,420, 520,560);
ctx.stroke();
// 支流
ctx.strokeStyle = 'rgba(110,170,230,0.30)'; ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(140,520);
ctx.bezierCurveTo(240,510, 300,490, 350,470);
ctx.stroke();
// 海岸(东南)
ctx.fillStyle = 'rgba(120,150,180,0.10)';
ctx.beginPath();
ctx.moveTo(560,400);
ctx.lineTo(620,410);
ctx.lineTo(620,560);
ctx.lineTo(540,560);
ctx.lineTo(520,500);
ctx.closePath(); ctx.fill();
},
};
/* ---------- 暴露到全局 ---------- */
globalThis.Portrait = Portrait;
globalThis.Sprite = Sprite;
globalThis.CityArt = CityArt;
globalThis.themeOf = themeOf;
globalThis.roleOf = roleOf;
})();
// ---------- 可选剧本 ----------
// 每个剧本定义起始年份与势力归属,玩家开局可选其一
const SCENARIOS = [
{id:'s189', name:'群雄讨董', year:189, season:'秋',
desc:'公元 189 年,董卓入京废立皇帝。十八路诸侯群起讨董,天下进入群雄割据时代。',
forces:['曹氏','袁绍','公孙','刘表','刘璋','张鲁','士燮','羌','孙策','袁术','陶谦','刘岱','孔融','汉']},
{id:'s194', name:'中原争霸', year:194, season:'春',
desc:'公元 194 年,吕布趁乱袭取兖州,曹操与吕布激战濮阳。各方势力重新洗牌。',
forces:['曹氏','吕布','袁绍','公孙','刘表','孙策','袁术','陶谦','刘岱','孔融','汉']},
{id:'s200', name:'官渡之战', year:200, season:'秋',
desc:'公元 200 年,袁曹决战官渡。以弱胜强的经典战役,天下大势在此一举。',
forces:['曹氏','袁绍','刘备','刘表','刘璋','孙策','张鲁','士燮']},
{id:'s208', name:'赤壁之战', year:208, season:'冬',
desc:'公元 208 年,曹操南下荆州,孙刘联军火烧赤壁,三分天下之势初成。',
forces:['曹氏','刘备','孙权','刘璋','张鲁','士燮']},
];
// ---------- 可选势力(玩家可选) ----------
// 每个势力定义起始城、君主、武将池、初始资源加成
const PLAYER_FORCES = {
'曹氏':{name:'曹氏', theme:'魏', city:'许昌', ruler:'曹操', color:'#3a6ab5',
desc:'挟天子以令诸侯。武将如云,骑兵精锐,据中原四战之地。',
startGold:2600, startFood:3400, startIron:60, startHorse:60,
caps:['曹操','夏侯惇','夏侯渊','曹仁','张辽','许褚','典韦','徐晃','张郃','乐进','于禁','曹洪','曹休','曹真','李典','庞德','文聘','司马懿','邓艾','王双','郝昭']},
'袁绍':{name:'袁绍', theme:'袁', city:'邺', ruler:'袁绍', color:'#c05050',
desc:'四世三公,门生故吏遍天下。冀州沃野千里,兵多将广。',
startGold:3000, startFood:3800, startIron:40, startHorse:50,
caps:['颜良','文丑','田丰','沮授','张郃','高览','淳于琼','蒋义渠']},
'公孙':{name:'公孙', theme:'公孙', city:'蓟', ruler:'公孙瓒', color:'#5a9a48',
desc:'白马义从,边塞劲旅。善骑兵突击,威震塞外。',
startGold:1800, startFood:2600, startIron:30, startHorse:90,
caps:['公孙瓒','赵云','严纲','田楷','关靖']},
'孙策':{name:'孙策', theme:'吴', city:'吴', ruler:'孙策', color:'#3aa8a8',
desc:'小霸王转战江东,父兄基业。水军强悍,据长江天险。',
startGold:2200, startFood:2800, startIron:35, startHorse:55,
caps:['孙策','周瑜','太史慈','程普','黄盖','韩当','朱治','蒋钦','周泰','陈武','董袭']},
'刘备':{name:'刘备', theme:'刘', city:'陈留', ruler:'刘备', color:'#3c7a9a',
desc:'汉室宗亲,仁德之名远播。虽兵微将寡,关张之勇天下无双。',
startGold:1400, startFood:2200, startIron:25, startHorse:40,
caps:['关羽','张飞','赵云','简雍','孙乾','糜竺','陈到']},
'袁术':{name:'袁术', theme:'袁', city:'寿春', ruler:'袁术', color:'#b04040',
desc:'袁氏嫡子,兵粮充足。僭号称帝,欲先据淮南。',
startGold:2800, startFood:3200, startIron:35, startHorse:45,
caps:['纪灵','桥蕤','张勋','雷薄','陈兰','乐就']},
'刘表':{name:'刘表', theme:'刘', city:'襄阳', ruler:'刘表', color:'#4a7a9a',
desc:'坐拥荆州八郡,带甲十万。地处四战之地,需善外交。',
startGold:2400, startFood:3400, startIron:40, startHorse:45,
caps:['黄祖','蒯越','蔡瑁','文聘','甘宁','霍峻','魏延']},
'马腾':{name:'马腾', theme:'羌', city:'武威', ruler:'马腾', color:'#7a6a4a',
desc:'西凉羌汉杂处,铁骑剽悍。据凉州天险,可问鼎关中。',
startGold:1600, startFood:2400, startIron:55, startHorse:100,
caps:['马腾','韩遂','马超','庞德','马岱','成宜','侯选']},
};
// ---------- 难度配置 ----------
const DIFFICULTIES = {
easy: {name:'仁君', atkMul:0.8, defMul:0.9, resMul:1.2, aiAggro:0.6, desc:'敌人较弱,资源充足,适合初次体验'},
normal:{name:'霸主', atkMul:1.0, defMul:1.0, resMul:1.0, aiAggro:1.0, desc:'标准体验,攻防资源均平衡'},
hard: {name:'枭雄', atkMul:1.25, defMul:1.15, resMul:0.85,aiAggro:1.4, desc:'敌人更强,资源紧张,AI 更主动扩张'},
};
// ---------- 三国志 11 式数据(权威资料:三国志 11 威力加强版 / 游侠网专题) ----------
// 45 城:沿用你已有的城池名与区域划分,补全坐标、特产、资源
const CITIES = [
{id:'武威', x:61, y:164, region:'凉州', spec:'马', force:'羌', pop:45, food:70, gold:25, defense:80},
{id:'张掖', x:107, y:116, region:'凉州', spec:'马', force:'羌', pop:30, food:55, gold:20, defense:70},
{id:'敦煌', x:159, y:156, region:'凉州', spec:'马', force:'羌', pop:35, food:50, gold:40, defense:75},
{id:'西平', x:113, y:204, region:'凉州', spec:'马', force:'羌', pop:32, food:60, gold:22, defense:72},
{id:'长安', x:276, y:270, region:'司隶', spec:'关中豪族', force:'汉', pop:95, food:90, gold:80, defense:95},
{id:'洛阳', x:339, y:279, region:'司隶', spec:'土豪', force:'汉', pop:100, food:85, gold:100, defense:100},
{id:'晋阳', x:315, y:215, region:'并州', spec:'铁', force:'汉', pop:55, food:50, gold:45, defense:78},
{id:'上党', x:299, y:151, region:'并州', spec:'铁', force:'汉', pop:42, food:48, gold:30, defense:74},
{id:'雁门', x:379, y:227, region:'并州', spec:'铁', force:'汉', pop:28, food:35, gold:25, defense:68},
{id:'蓟', x:524, y:121, region:'幽州', spec:'铁', force:'公孙', pop:58, food:55, gold:35, defense:78},
{id:'北平', x:459, y:119, region:'幽州', spec:'铁', force:'公孙', pop:45, food:45, gold:30, defense:72},
{id:'襄平', x:490, y:63, region:'幽州', spec:'铁', force:'公孙', pop:38, food:40, gold:40, defense:70},
{id:'邺', x:360, y:168, region:'冀州', spec:'土豪', force:'袁绍', pop:80, food:80, gold:70, defense:88},
{id:'南皮', x:423, y:176, region:'冀州', spec:'土豪', force:'袁绍', pop:50, food:55, gold:35, defense:76},
{id:'常山', x:395, y:115, region:'冀州', spec:'土豪', force:'袁绍', pop:40, food:45, gold:28, defense:72},
{id:'信都', x:501, y:242, region:'冀州', spec:'土豪', force:'袁绍', pop:35, food:40, gold:25, defense:70},
{id:'北海', x:550, y:184, region:'青州', spec:'水军', force:'孔融', pop:48, food:55, gold:25, defense:72},
{id:'乐安', x:486, y:179, region:'青州', spec:'水军', force:'孔融', pop:40, food:50, gold:22, defense:70},
{id:'东莱', x:566, y:248, region:'青州', spec:'水军', force:'孔融', pop:36, food:48, gold:28, defense:68},
{id:'下邳', x:465, y:298, region:'徐州', spec:'商', force:'陶谦', pop:60, food:70, gold:40, defense:78},
{id:'彭城', x:403, y:290, region:'徐州', spec:'商', force:'陶谦', pop:52, food:65, gold:35, defense:74},
{id:'濮阳', x:440, y:238, region:'兖州', spec:'水军', force:'刘岱', pop:45, food:55, gold:30, defense:74},
{id:'陈留', x:528, y:303, region:'兖州', spec:'土豪', force:'刘岱', pop:42, food:50, gold:32, defense:72},
{id:'任城', x:361, y:340, region:'兖州', spec:'土豪', force:'刘岱', pop:32, food:42, gold:24, defense:68},
{id:'许昌', x:425, y:351, region:'豫州', spec:'土豪', force:'汉', pop:70, food:75, gold:60, defense:85},
{id:'汝南', x:490, y:358, region:'豫州', spec:'土豪', force:'汉', pop:55, food:65, gold:40, defense:78},
{id:'陈', x:451, y:410, region:'豫州', spec:'商', force:'汉', pop:40, food:50, gold:30, defense:72},
{id:'襄阳', x:385, y:404, region:'荆州', spec:'土豪', force:'刘表', pop:75, food:80, gold:55, defense:88},
{id:'江陵', x:414, y:463, region:'荆州', spec:'商', force:'刘表', pop:60, food:75, gold:45, defense:82},
{id:'长沙', x:351, y:458, region:'荆州', spec:'商', force:'刘表', pop:55, food:70, gold:50, defense:78},
{id:'零陵', x:372, y:516, region:'荆州', spec:'商', force:'刘表', pop:40, food:55, gold:35, defense:72},
{id:'桂阳', x:398, y:574, region:'荆州', spec:'商', force:'刘表', pop:38, food:52, gold:38, defense:70},
{id:'武陵', x:439, y:523, region:'荆州', spec:'商', force:'刘表', pop:36, food:50, gold:32, defense:70},
{id:'寿春', x:543, y:479, region:'扬州', spec:'商', force:'袁术', pop:55, food:60, gold:45, defense:78},
{id:'庐江', x:583, y:428, region:'扬州', spec:'商', force:'袁术', pop:42, food:52, gold:35, defense:72},
{id:'建业', x:517, y:419, region:'扬州', spec:'水军', force:'袁术', pop:48, food:58, gold:40, defense:75},
{id:'吴', x:606, y:490, region:'扬州', spec:'水军', force:'孙策', pop:50, food:60, gold:42, defense:76},
{id:'会稽', x:557, y:368, region:'扬州', spec:'水军', force:'孙策', pop:44, food:55, gold:38, defense:72},
{id:'庐陵', x:479, y:471, region:'扬州', spec:'商', force:'孙策', pop:38, food:50, gold:32, defense:70},
{id:'成都', x:227, y:490, region:'益州', spec:'蜀', force:'刘璋', pop:80, food:95, gold:60, defense:90},
{id:'梓潼', x:263, y:364, region:'益州', spec:'蜀', force:'刘璋', pop:40, food:60, gold:35, defense:76},
{id:'江州', x:244, y:427, region:'益州', spec:'蜀', force:'刘璋', pop:42, food:62, gold:32, defense:74},
{id:'永安', x:309, y:410, region:'益州', spec:'蜀', force:'刘璋', pop:35, food:55, gold:30, defense:72},
{id:'汉中', x:290, y:475, region:'益州', spec:'马', force:'张鲁', pop:45, food:60, gold:38, defense:80},
{id:'番禺', x:544, y:585, region:'交州', spec:'土特产', force:'士燮', pop:40, food:55, gold:45, defense:68},
{id:'交趾', x:471, y:585, region:'交州', spec:'土特产', force:'士燮', pop:36, food:52, gold:42, defense:66},
{id:'合浦', x:506, y:532, region:'交州', spec:'土特产', force:'士燮', pop:32, food:50, gold:38, defense:64},
];
// 去重(上一步北海2 占位)
const CITY_MAP = {};
const CITIES_CLEAN = CITIES.filter(c=>c.pop>0);
CITIES_CLEAN.forEach(c=>CITY_MAP[c.id]=c);
// 城市间邻接(用于行军与搜打撤地图连通)
const ROUTES = [
['长安','洛阳'],['长安','汉中'],['长安','西平'],['西平','武威'],['武威','张掖'],['张掖','敦煌'],
['长安','晋阳'],['晋阳','雁门'],['雁门','北平'],['北平','襄平'],['晋阳','邺'],['上党','邺'],['上党','洛阳'],
['洛阳','许昌'],['洛阳','陈留'],['陈留','濮阳'],['濮阳','邺'],['邺','南皮'],['南皮','北平'],
['邺','常山'],['常山','信都'],['信都','陈留'],['陈留','彭城'],['彭城','下邳'],['下邳','北海'],
['北海','东莱'],['北海','乐安'],['乐安','下邳'],['下邳','寿春'],['寿春','庐江'],['庐江','建业'],
['建业','吴'],['吴','会稽'],['会稽','庐陵'],['庐陵','番禺'],['番禺','合浦'],['合浦','交趾'],['交趾','番禺'],
['寿春','许昌'],['许昌','汝南'],['汝南','陈'],['陈','彭城'],['汝南','江陵'],['江陵','长沙'],
['长沙','零陵'],['零陵','桂阳'],['桂阳','长沙'],['桂阳','番禺'],['江陵','武陵'],['武陵','长沙'],
['江陵','江州'],['江州','成都'],['成都','梓潼'],['梓潼','汉中'],['汉中','成都'],['汉中','永安'],
['永安','江陵'],['梓潼','江州'],['江州','永安'],
];
// 武将(五维:统率/武力/智力/政治/魅力;适性:骑兵SABCDE 枪兵 戟兵 弩兵 兵器 水军)
const HEROES = [
{name:'曹操', force:'player', portrait:'ruler', stats:[96,72,91,94,95], apt:{骑兵:'S',枪兵:'B',戟兵:'A',弩兵:'B',兵器:'B',水军:'C'}},
{name:'夏侯惇',force:'player', portrait:'warrior', stats:[90,93,65,70,78], apt:{骑兵:'S',枪兵:'A',戟兵:'B',弩兵:'C',兵器:'B',水军:'C'}},
{name:'夏侯渊',force:'player', portrait:'warrior', stats:[86,90,60,55,68], apt:{骑兵:'S',枪兵:'B',戟兵:'A',弩兵:'A',兵器:'C',水军:'C'}},
{name:'曹仁', force:'player', portrait:'warrior', stats:[90,85,65,72,80], apt:{骑兵:'A',枪兵:'S',戟兵:'S',弩兵:'B',兵器:'B',水军:'B'}},
{name:'张辽', force:'player', portrait:'warrior', stats:[95,92,78,65,85], apt:{骑兵:'S',枪兵:'A',戟兵:'A',弩兵:'B',兵器:'C',水军:'C'}},
{name:'徐晃', force:'player', portrait:'warrior', stats:[88,89,65,60,74], apt:{骑兵:'A',枪兵:'S',戟兵:'A',弩兵:'B',兵器:'B',水军:'C'}},
{name:'张郃', force:'player', portrait:'warrior', stats:[89,86,72,62,76], apt:{骑兵:'S',枪兵:'A',戟兵:'A',弩兵:'A',兵器:'C',水军:'C'}},
{name:'乐进', force:'player', portrait:'warrior', stats:[82,86,55,48,66], apt:{骑兵:'A',枪兵:'A',戟兵:'B',弩兵:'B',兵器:'C',水军:'C'}},
{name:'于禁', force:'player', portrait:'warrior', stats:[87,75,70,68,72], apt:{骑兵:'A',枪兵:'S',戟兵:'A',弩兵:'B',兵器:'B',水军:'B'}},
{name:'许褚', force:'player', portrait:'warrior', stats:[75,98,35,30,62], apt:{骑兵:'B',枪兵:'A',戟兵:'S',弩兵:'C',兵器:'C',水军:'C'}},
{name:'典韦', force:'player', portrait:'warrior', stats:[72,99,30,25,60], apt:{骑兵:'C',枪兵:'A',戟兵:'S',弩兵:'C',兵器:'B',水军:'C'}},
{name:'荀彧', force:'player', portrait:'strategist', stats:[82,35,97,95,96], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'郭嘉', force:'player', portrait:'strategist', stats:[78,30,98,75,88], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'程昱', force:'player', portrait:'strategist', stats:[78,45,92,80,72], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'贾诩', force:'player', portrait:'strategist', stats:[76,38,97,78,80], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'荀攸', force:'player', portrait:'strategist', stats:[80,38,95,82,82], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'刘晔', force:'player', portrait:'strategist', stats:[72,55,90,80,68], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'A',兵器:'S',水军:'C'}},
{name:'满宠', force:'player', portrait:'strategist', stats:[78,58,82,86,72], apt:{骑兵:'B',枪兵:'B',戟兵:'A',弩兵:'B',兵器:'B',水军:'C'}},
{name:'曹洪', force:'player', portrait:'warrior', stats:[72,80,52,58,65], apt:{骑兵:'A',枪兵:'B',戟兵:'B',弩兵:'C',兵器:'C',水军:'C'}},
{name:'曹休', force:'player', portrait:'warrior', stats:[82,82,68,62,74], apt:{骑兵:'S',枪兵:'A',戟兵:'B',弩兵:'B',兵器:'C',水军:'C'}},
{name:'曹真', force:'player', portrait:'warrior', stats:[88,80,72,70,80], apt:{骑兵:'S',枪兵:'A',戟兵:'A',弩兵:'B',兵器:'B',水军:'C'}},
{name:'李典', force:'player', portrait:'warrior', stats:[80,75,68,72,78], apt:{骑兵:'A',枪兵:'A',戟兵:'A',弩兵:'B',兵器:'B',水军:'B'}},
{name:'臧霸', force:'player', portrait:'warrior', stats:[78,84,60,55,68], apt:{骑兵:'A',枪兵:'B',戟兵:'A',弩兵:'B',兵器:'C',水军:'B'}},
{name:'文聘', force:'player', portrait:'warrior', stats:[82,80,65,60,74], apt:{骑兵:'B',枪兵:'A',戟兵:'A',弩兵:'B',兵器:'C',水军:'S'}},
{name:'吕虔', force:'player', portrait:'warrior', stats:[74,72,68,72,70], apt:{骑兵:'A',枪兵:'B',戟兵:'B',弩兵:'B',兵器:'B',水军:'C'}},
{name:'庞德', force:'player', portrait:'warrior', stats:[85,93,65,55,75], apt:{骑兵:'S',枪兵:'A',戟兵:'A',弩兵:'B',兵器:'C',水军:'C'}},
{name:'司马懿',force:'player', portrait:'strategist', stats:[96,45,98,96,94], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'陈群', force:'player', portrait:'strategist', stats:[70,30,85,95,90], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'毛玠', force:'player', portrait:'strategist', stats:[68,28,80,90,78], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'邓艾', force:'player', portrait:'warrior', stats:[92,78,88,82,82], apt:{骑兵:'A',枪兵:'S',戟兵:'A',弩兵:'A',兵器:'B',水军:'C'}},
{name:'钟会', force:'player', portrait:'strategist', stats:[86,62,94,82,86], apt:{骑兵:'B',枪兵:'A',戟兵:'B',弩兵:'B',兵器:'B',水军:'C'}},
{name:'诸葛诞',force:'player', portrait:'warrior', stats:[82,75,72,70,76], apt:{骑兵:'A',枪兵:'A',戟兵:'S',弩兵:'B',兵器:'B',水军:'C'}},
{name:'王双', force:'player', portrait:'warrior', stats:[70,92,40,30,58], apt:{骑兵:'A',枪兵:'A',戟兵:'B',弩兵:'C',兵器:'S',水军:'C'}},
{name:'郝昭', force:'player', portrait:'warrior', stats:[84,75,72,68,74], apt:{骑兵:'B',枪兵:'S',戟兵:'S',弩兵:'A',兵器:'A',水军:'C'}},
{name:'孙礼', force:'player', portrait:'warrior', stats:[78,80,60,58,68], apt:{骑兵:'A',枪兵:'A',戟兵:'B',弩兵:'B',兵器:'C',水军:'C'}},
{name:'秦朗', force:'player', portrait:'warrior', stats:[76,78,55,50,64], apt:{骑兵:'A',枪兵:'B',戟兵:'B',弩兵:'C',兵器:'C',水军:'C'}},
{name:'吴质', force:'player', portrait:'strategist', stats:[65,35,82,78,70], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'蒋济', force:'player', portrait:'strategist', stats:[72,38,88,82,75], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'高堂隆',force:'player', portrait:'strategist', stats:[60,28,82,80,68], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'辛毗', force:'player', portrait:'strategist', stats:[68,35,85,78,74], apt:{骑兵:'C',枪兵:'C',戟兵:'C',弩兵:'C',兵器:'C',水军:'C'}},
{name:'杨阜', force:'player', portrait:'strategist', stats:[74,45,84,78,76], apt:{骑兵:'C',枪兵:'B',戟兵:'B',弩兵:'B',兵器:'B',水军:'C'}},
{name:'田豫', force:'player', portrait:'warrior', stats:[84,80,72,65,74], apt:{骑兵:'S',枪兵:'A',戟兵:'A',弩兵:'B',兵器:'C',水军:'C'}},
{name:'牵招', force:'player', portrait:'warrior', stats:[82,82,70,60,72], apt:{骑兵:'S',枪兵:'A',戟兵:'A',弩兵:'B',兵器:'C',水军:'C'}},
{name:'王凌', force:'player', portrait:'warrior', stats:[80,78,68,66,72], apt:{骑兵:'A',枪兵:'A',戟兵:'A',弩兵:'B',兵器:'B',水军:'B'}},
{name:'毌丘俭',force:'player', portrait:'warrior', stats:[86,80,74,70,78], apt:{骑兵:'A',枪兵:'A',戟兵:'A',弩兵:'A',兵器:'B',水军:'C'}},
{name:'诸葛恪',force:'player', portrait:'strategist', stats:[84,62,90,80,82], apt:{骑兵:'B',枪兵:'A',戟兵:'B',弩兵:'B',兵器:'B',水军:'S'}},
{name:'文鸯', force:'player', portrait:'warrior', stats:[78,97,55,45,72], apt:{骑兵:'S',枪兵:'A',戟兵:'S',弩兵:'C',兵器:'C',水军:'C'}},
];
// AI 势力武将(简化,用于非玩家势力)
const AI_HEROES = {
'袁绍':[{name:'颜良',stats:[82,96,58,40,72]},{name:'文丑',stats:[80,94,55,38,70]},{name:'田丰',stats:[72,35,95,78,76]},{name:'沮授',stats:[76,30,94,75,74]},{name:'张郃',stats:[89,86,72,62,76]}],
'公孙':[{name:'公孙瓒',stats:[86,90,60,52,80]},{name:'赵云',stats:[95,98,78,60,95]},{name:'严纲',stats:[70,80,50,40,58]}],
'刘表':[{name:'黄祖',stats:[72,78,50,45,60]},{name:'蒯越',stats:[68,35,88,80,72]},{name:'蔡瑁',stats:[70,76,58,62,68]}],
'刘璋':[{name:'张任',stats:[86,88,70,60,76]},{name:'严颜',stats:[82,85,65,60,74]},{name:'吴懿',stats:[74,78,55,52,66]}],
'张鲁':[{name:'张卫',stats:[68,72,62,65,60]},{name:'阎圃',stats:[60,35,82,72,66]}],
'士燮':[{name:'士燮',stats:[70,40,82,88,85]},{name:'士壹',stats:[62,72,50,48,60]}],
'羌': [{name:'迷当大王',stats:[72,85,50,35,65]},{name:'俄何烧戈',stats:[68,82,40,30,58]}],
'汉': [{name:'汉献帝',stats:[30,20,60,50,85]},{name:'皇甫嵩',stats:[92,82,78,75,88]}],
'陶谦':[{name:'陶谦',stats:[55,45,72,80,78]},{name:'曹豹',stats:[65,76,50,45,60]}],
'刘岱':[{name:'刘岱',stats:[58,55,68,72,66]},{name:'桥瑁',stats:[52,62,58,60,60]}],
'孔融':[{name:'孔融',stats:[45,30,85,90,92]},{name:'武安国',stats:[60,85,35,30,50]}],
'袁术':[{name:'纪灵',stats:[72,88,48,42,62]},{name:'桥蕤',stats:[65,78,45,40,55]}],
'孙策':[{name:'孙策',stats:[93,95,70,65,92]},{name:'周瑜',stats:[95,72,98,85,97]},{name:'太史慈',stats:[86,96,62,55,82]},{name:'程普',stats:[84,85,68,65,78]},{name:'黄盖',stats:[82,88,65,60,78]}],
};
// 装备(三国志 11 式,可搜刮/缴获)
const EQUIP_TYPES = ['剑','枪','戟','弓','盾','盔','甲','马','书','宝'];
const EQUIP_NAMES = {
剑:['倚天剑','青釭剑','古锭刀','七星剑'], 枪:['丈八蛇矛','龙胆枪','神威烈水枪'],
戟:['方天画戟','虎牢戟'], 弓:['李广弓','养由基弓','黄忠弓'], 盾:['八卦阵盾','玄铁盾'],
盔:['诸葛巾','紫金冠','铁盔'], 甲:['白银铠','黑金铠','明光铠'], 马:['赤兔马','的卢','绝影','爪黄飞电'],
书:['孙子兵法','六韬','孟德新书','太平要术'], 宝:['玉玺','铜雀','玉如意'],
};
const EQUIP_STAT = { 剑:2,枪:3,戟:4,弓:3,盾:2,盔:1,甲:3,马:3,书:2,宝:2 };
// ---------- 工具函数 ----------
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
const rand=(a,b)=>a+Math.random()*(b-a);
const randi=(a,b)=>Math.floor(rand(a,b+1));
const choice=arr=>arr[Math.floor(Math.random()*arr.length)];
const dist2=(a,b)=>{const dx=a.x-b.x,dy=a.y-b.y;return dx*dx+dy*dy;};
// ---------- 游戏状态 ----------
const APT_RANK = {'S':5,'A':4,'B':3,'C':2,'D':1,'E':0};
var state, ui, battle, loot, audio, view, persist;
// 同时挂到 globalThis,确保 vm context 可访问
globalThis.state = state;
// ---------- 音频:Web Audio API(无外部资源,懒初始化)----------
audio = {
ctx:null, master:null, inited:false,
init(){
if(this.inited) return;
try{
const AC = globalThis.AudioContext||globalThis.webkitAudioContext;
if(!AC) return;
this.ctx = new AC();
this.master = this.ctx.createGain();
this.master.gain.value = 0.25;
this.master.connect(this.ctx.destination);
this.inited = true;
}catch(e){ this.ctx=null; }
},
resume(){
// 用户交互后恢复(部分浏览器 suspended)
if(this.ctx && this.ctx.state==='suspended'){
this.ctx.resume().catch(()=>{});
}
},
beep(freq,dur,type='square',vol=0.3){
if(!this.ctx) return;
try{
const o=this.ctx.createOscillator(), g=this.ctx.createGain();
o.type=type; o.frequency.value=freq;
g.gain.value=vol;
o.connect(g); g.connect(this.master);
o.start();
g.gain.exponentialRampToValueAtTime(0.001,this.ctx.currentTime+dur);
o.stop(this.ctx.currentTime+dur);
}catch(e){}
},
hit(){ this.beep(120,0.12,'sawtooth',0.4); },
// 敌人 AI 类型配置
_enemyAI(type){
if(type==='斥候') return {mode:'flank', fleeAt:0.25, ranged:false};
if(type==='弓手') return {mode:'kite', fleeAt:0.4, ranged:true, range:170, cd:90};
if(type==='戟兵') return {mode:'tank', fleeAt:0.15, ranged:false};
return {mode:'chase', fleeAt:0.3, ranged:false};
},
shoot(){ this.beep(680,0.06,'square',0.2); },
coin(){ this.beep(880,0.08,'triangle',0.3); setTimeout(()=>this.beep(1175,0.1,'triangle',0.3),70); },
pickup(){ this.beep(520,0.1,'triangle',0.3); },
alert(){ this.beep(180,0.3,'sawtooth',0.4); },
fanfare(){ [523,659,784,1047].forEach((f,i)=>setTimeout(()=>this.beep(f,0.18,'triangle',0.35),i*120)); },
defeat(){ [300,250,200,150].forEach((f,i)=>setTimeout(()=>this.beep(f,0.2,'sawtooth',0.35),i*150)); },
ui(){ this.beep(440,0.05,'triangle',0.2); },
};
// ---------- 存档(只存纯数据字段)----------
function sanitizeForSave(obj){
// 深度克隆,去掉 canvas/Image/函数等非序列化对象
return JSON.parse(JSON.stringify(obj, (k,v)=>{
if(v instanceof Node || v instanceof HTMLCanvasElement) return undefined;
if(typeof v==='function') return undefined;
return v;
}));
}
persist = {
KEY:'hanmo_sanguo_save_v1',
save(){
try{
const data = sanitizeForSave({
cities: state.cities, heroes: state.heroes,
month: state.month, year: state.year, season: state.season,
turn: state.turn, resources: state.resources,
playerForce: state.playerForce, playerCity: state.playerCity,
log: state.log.slice(-30), reports: state.reports.slice(-8),
tech: state.tech, diplomacy: state.diplomacy,
battleWon: state.battleWon,
});
localStorage.setItem(this.KEY, JSON.stringify(data));
}catch(e){ console.warn('save failed', e); }
},
load(){
try{ const s=localStorage.getItem(this.KEY); return s?JSON.parse(s):null; }catch(e){ return null; }
},
clear(){ try{ localStorage.removeItem(this.KEY); }catch(e){} }
};
// ---------- 武将管理 ----------
function calcMaxTroops(h){
// 统率*10 + 武力*5,最低 500
const s = h.stats;
return clamp(Math.floor(s[0]*10 + s[1]*5), 500, 9999);
}
function makeHero(tpl, force, city){
const mt = calcMaxTroops(tpl);
return {
name:tpl.name, force, city, portrait:tpl.portrait,
stats:tpl.stats.slice(), apt:JSON.parse(JSON.stringify(tpl.apt||{})),
hp:100, maxHp:100,
troops: Math.floor(mt*0.6), // 初始带 60% 兵力
maxTroops: mt,
loyalty:80, exp:0, level:1,
weapon:null, armor:null, helm:null, horse:null, book:null, treasure:null,
};
}
function heroStat(h,idx){ // 基础 + 装备加成
let v=h.stats[idx];
const all=[h.weapon,h.armor,h.helm,h.horse,h.book,h.treasure];
all.forEach(it=>{ if(it) v+= EQUIP_STAT[it.type]||0; });
return v;
}
const STAT_NAMES=['统率','武力','智力','政治','魅力'];
// ---------- 初始化 ----------
function newGame(opts){
opts = opts||{};
const scenario = SCENARIOS.find(s=>s.id===opts.scenario)||SCENARIOS[0];
const pForce = PLAYER_FORCES[opts.force]||PLAYER_FORCES['曹氏'];
const diff = DIFFICULTIES[opts.diff]||DIFFICULTIES.normal;
const cities={};
CITIES_CLEAN.forEach(c=>{
cities[c.id]={
id:c.id, name:c.id, x:c.x, y:c.y, region:c.region, spec:c.spec,
force:c.force, pop:c.pop, food:c.food, gold:c.gold, defense:c.defense,
loyalty:70, build:{农场:0,市场:0,兵营:0,城墙:0,工坊:0},
garrison:0,
};
});
// 邻接
CITIES_CLEAN.forEach(c=>cities[c.id].neighbors=[]);
ROUTES.forEach(([a,b])=>{
if(cities[a]&&cities[b]){ cities[a].neighbors.push(b); cities[b].neighbors.push(a); }
});
const heroes={};
HEROES.forEach(h=>{
// 仅当武将在当前所选势力池中,才归玩家
const inPool = pForce.caps.includes(h.name);
heroes[h.name]=makeHero(h, inPool?'player':'汉', inPool?pForce.city:null);
});
Object.keys(AI_HEROES).forEach(f=>{
AI_HEROES[f].forEach(h=>{
const tpl={name:h.name,portrait: h.stats[1]>h.stats[2]?'warrior':'strategist', stats:h.stats, apt:{}};
['骑兵','枪兵','戟兵','弩兵','兵器','水军'].forEach(t=>{
tpl.apt[t]=choice(['S','A','B','C']);
});
heroes[h.name]=makeHero(tpl,f,null);
});
});
// 给 AI 势力配武将
const forceCity={};
Object.keys(cities).forEach(k=>{
const f=cities[k].force;
if(f==='player') return;
if(!forceCity[f]) forceCity[f]=[];
forceCity[f].push(k);
});
Object.keys(forceCity).forEach(f=>{
const list=Object.values(heroes).filter(h=>h.force===f);
list.forEach((h,i)=>{ h.city=forceCity[f][i%forceCity[f].length]; });
});
state={
cities, heroes,
playerForce:'player',
playerCity:pForce.city,
difficulty:diff,
scenario:scenario.id,
resources:{ gold:pForce.startGold, food:pForce.startFood, horse:pForce.startHorse, iron:pForce.startIron, silk:30 },
month:0, year:scenario.year, season:scenario.season,
turn:1,
view:'map',
selectedCity:null, selectedHero:null,
selectedArmy:null,
moveTarget:null,
log:[],
reports:[],
tech:{ 征兵术:1, 农耕术:1, 交易术:1, 练兵术:1 },
diplomacy:{},
events:[],
battleWon:0,
startedAt:Date.now(),
};
// 玩家起兵:将 playerCity 归属玩家势力
if(state.cities[state.playerCity]){
state.cities[state.playerCity].force = state.playerForce;
}
// 初始驻军
Object.keys(cities).forEach(k=>{
const c=cities[k];
c.garrison = c.force==='player'? randi(800,1500): randi(400,1200);
});
// 确保玩家武将有初始兵力
Object.values(heroes).filter(h=>h.force==='player').forEach(h=>{
if(h.troops===0 || h.maxTroops===0){
h.maxTroops = calcMaxTroops(h);
h.troops = Math.floor(h.maxTroops*0.6);
}
});
logMsg('【游戏开始】公元 '+scenario.year+' 年,'+scenario.name+'。你扮演 '+pForce.name+' 势力,起兵于 '+pForce.city+'。');
logMsg('难度:'+diff.name+'。提示:点击城池查看详情,点击「出征」选择目标进入搜打撤战场。');
persist.clear();
}
function logMsg(txt){
const t=`第${state.turn}月 · ${txt}`;
state.log.push(t);
if(state.log.length>80) state.log.shift();
// 同步到日志面板
const list=document.getElementById('logList');
if(list){
const div=document.createElement('div');
div.textContent=t;
list.appendChild(div);
list.scrollTop=list.scrollHeight;
}
}
// ---------- 战略逻辑 ----------
function cityOutput(c){
const b=c.build;
const foodOut = Math.floor(c.food*(1+b['农场']*0.2)*(1+state.tech['农耕术']*0.1));
const goldOut = Math.floor(c.gold*(1+b['市场']*0.2)*(1+state.tech['交易术']*0.1));
const troopMax = 2000 + b['兵营']*1500 + c.pop*15 + state.tech['征兵术']*500;
const recruit = Math.floor((c.pop*0.05 + b['兵营']*10)*(1+state.tech['征兵术']*0.15));
return {foodOut, goldOut, troopMax, recruit};
}
function heroesInCity(cityId, force){
return Object.values(state.heroes).filter(h=>h.city===cityId && (!force||h.force===force));
}
function cityTroops(cityId){
return heroesInCity(cityId).reduce((s,h)=>s+h.troops,0) + (state.cities[cityId].garrison||0);
}
function cityMaxTroops(cityId){
return heroesInCity(cityId).reduce((s,h)=>s+h.maxTroops,0);
}
function getForce(forceId){
const cs=Object.values(state.cities).filter(c=>c.force===forceId);
return cs;
}
function processMonth(){
state.month++; state.turn++;
const yr=189+Math.floor((state.month-1)/12);
state.year=yr;
const seasons=['春','夏','秋','冬'];
state.season=seasons[Math.floor((state.month-1)%12/3)];
Object.values(state.cities).forEach(c=>{
const o=cityOutput(c);
if(c.force===state.playerForce){
state.resources.food+=o.foodOut;
state.resources.gold+=o.goldOut;
// 自动征兵(若有空闲容量)
const heroes=heroesInCity(c.id,state.playerForce);
let foodUsed=0;
heroes.forEach(h=>{
if(h.troops<h.maxTroops && state.resources.food>200){
const need=Math.min(o.recruit, h.maxTroops-h.troops);
const cost=Math.floor(need*0.4);
if(state.resources.food>=cost){
h.troops+=need; state.resources.food-=cost; foodUsed+=cost;
}
}
});
if(heroes.length===0){
c.garrison=clamp(c.garrison+o.recruit,0,c.pop*30);
}
}else{
c.garrison=clamp(c.garrison+o.recruit,0,c.pop*30);
}
});
// AI 扩张
aiTurn();
// 事件
if(Math.random()<0.15){
const evs=['民乱','丰收','瘟疫','天灾','流民来投','名士来访'];
const e=choice(evs);
state.events.push(e);
if(state.cities[state.playerCity]){
if(e==='丰收'){ state.resources.food+=300; logMsg('丰收:粮草 +300'); }
if(e==='流民来投'){ state.resources.gold+=100; logMsg('流民来投:获得流民,黄金 +100'); }
if(e==='民乱'){ logMsg('民乱:民心下降,注意稳定。'); }
if(e==='名士来访'){ logMsg('名士来访:声望提升,可考虑登庸。'); }
}
}
// 粮草消耗
const playerTroops=Object.values(state.heroes).filter(h=>h.force===state.playerForce).reduce((s,h)=>s+h.troops,0);
const upkeep=Math.floor(playerTroops*0.05);
state.resources.food=Math.max(0,state.resources.food-upkeep);
if(state.resources.food<200) logMsg('⚠ 粮草告急,请尽快补充!');
state.reports=state.reports.slice(0,8);
persist.save();
}
function aiTurn(){
const forces={};
Object.values(state.cities).forEach(c=>{
if(c.force===state.playerForce) return;
if(!forces[c.force]) forces[c.force]=[];
forces[c.force].push(c);
});
Object.keys(forces).forEach(f=>{
const my=forces[f];
my.forEach(c=>{
const targets=c.neighbors.map(n=>state.cities[n]).filter(n=>n&&n.force!==f&&Math.random()<0.18);
targets.forEach(t=>{
const ta=heroesInCity(t.id,f)[0];
if(ta && cityTroops(c.id)>cityTroops(t.id)*0.7){
doBattle(choice(heroesInCity(c.id,f)), t, true);
}
});
});
});
}
function doBattle(attacker, targetCity, isAI){
const aHeroes=heroesInCity(attacker.city, attacker.force);
const dHeroes=heroesInCity(targetCity.id, targetCity.force);
const aPower=aHeroes.reduce((s,h)=>s+h.stats[0]+h.stats[1]+h.troops*0.05,0);
const dPower=dHeroes.reduce((s,h)=>s+h.stats[0]+h.stats[1]+h.troops*0.05,0) + targetCity.defense*2 + targetCity.garrison*0.05;
const aWin=aPower>dPower*0.85;
const ratio=clamp(aPower/(dPower||1),0.3,3);
if(aWin){
if(!isAI){
logMsg(`${attacker.name} 攻破 ${targetCity.id}!缴获部分资源。`);
const steal=Math.floor(targetCity.gold*0.3);
state.resources.gold+=steal;
targetCity.garrison=Math.floor(targetCity.garrison*0.3);
generateLoot(attacker.city, targetCity.id, ratio);
if(ratio>1.5 || targetCity.garrison<300){
targetCity.force=attacker.force;
targetCity.garrison=Math.floor(cityTroops(attacker.city)*0.4);
heroesInCity(attacker.city,attacker.force).forEach(h=>h.city=targetCity.id);
logMsg(`🏆 占领 ${targetCity.id}!`);
audio.fanfare();
state.battleWon++;
}else{
audio.coin();
}
}else{
if(targetCity.force===state.playerForce){
logMsg(`⚠ ${attacker.force} 的 ${attacker.name} 进攻 ${targetCity.id},我军击退敌军。`);
targetCity.garrison=Math.floor(targetCity.garrison*0.8);
}
}
}else{
if(!isAI){
logMsg(`${attacker.name} 进攻 ${targetCity.id} 受挫,损兵折将。`);
aHeroes.forEach(h=>h.troops=Math.floor(h.troops*0.6));
audio.defeat();
}
}
state.reports.unshift({
turn:state.turn, attacker:attacker.name, target:targetCity.id, win:aWin, ratio
});
}
// ---------- 搜打撤:战利品生成 ----------
function generateLoot(fromCity, toCityId, ratio){
const count=randi(3,7);
const items=[];
for(let i=0;i<count;i++){
const type=choice(EQUIP_TYPES);
const name=choice(EQUIP_NAMES[type]);
const rarity=randi(1,3);
items.push({type,name,rarity,used:false});
}
state.currentLoot={
from:fromCity, to:toCityId, items,
insurance: items.filter(()=>Math.random()<0.4),
timeLeft:180,
escaped:false,
evacuated:false,
cityFrom:fromCity,
};
ui.openLoot();
}
// ---------- UI ----------
ui = {
$:(id)=>document.getElementById(id),
init(){
this.bindTopBtns();
this.bindMapInput();
this.bindTitleBtns();
this.bindCityMenu();
if(state && state.resources) this.renderTop();
this.renderLog();
},
bindCityMenu(){
const menu=this.$('cityMenu');
if(!menu) return;
// 事件委托:所有按钮点击
menu.addEventListener('click', e=>this._onCityMenuClick(e));
// radio 变更
menu.addEventListener('change', e=>{
if(e.target.name==='heroSel'){
this._selectedHero=e.target.value;
this._refreshCityMenu();
}
});
},
renderLog(){
const list=this.$('logList');
if(!list||!state) return;
list.innerHTML='';
state.log.slice(-40).forEach(t=>{
const div=document.createElement('div');
div.textContent=t;
list.appendChild(div);
});
list.scrollTop=list.scrollHeight;
},
bindTopBtns(){
const ids=['btnNext','btnHeroes','btnTech','btnDiplomacy','btnReports','btnMenu','btnTitle'];
ids.forEach(id=>{
const el=this.$(id);
if(el) el.addEventListener('click',()=>this.onTopBtn(id));
});
const cl=this.$('btnClearLog');
if(cl) cl.addEventListener('click',()=>{
state.log=[];
const list=this.$('logList');
if(list) list.innerHTML='';
});
},
bindTitleBtns(){
this.$('btnNew').addEventListener('click',()=>{
if(!titleSel.scenario || !titleSel.force || !titleSel.diff){
alert('请先选择剧本、势力和难度。'); return;
}
audio.init(); audio.resume();
hideTitle();
newGame({scenario:titleSel.scenario, force:titleSel.force, diff:titleSel.diff});
ui.renderTop();
view.resize();
view.render();
this.renderLog();
});
this.$('btnContinue').addEventListener('click',()=>{
const sv=persist.load();
if(sv){
audio.init(); audio.resume();
hideTitle();
newGame();
Object.assign(state, sv);
state.log=sv.log||[];
// 恢复英雄 maxTroops
Object.values(state.heroes).forEach(h=>{
if(!h.maxTroops) h.maxTroops=calcMaxTroops(h);
if(h.troops>h.maxTroops) h.troops=h.maxTroops;
});
ui.renderTop(); view.resize(); view.render(); this.renderLog();
}else{
alert('暂无存档。');
}
});
this.$('btnHelp').addEventListener('click',()=>{
alert('【汉末三国之君临天下】\n\n◆ 战略地图\n· 点击城池查看/操作(出征、征兵、建设、开发、搜索)\n· 顶部「▶下一月」推进时间,资源自动产出\n· 右上「武将/科技/外交/战报」查看势力\n\n◆ 搜打撤战斗\n· 出征/搜索进入 2D 战场,清剿敌军并搜刮战利品\n· 收集装备(受背包负重限制)\n· 走到右下角「撤离点」按 E 撤离,撤离成功才保留战利品\n· 死亡或超时:装备有概率掉落\n\n◆ 胜利:统一天下,或达成你的霸业目标。');
});
},
bindMapInput(){
const mv=this.$('mapView');
if(!mv) return;
mv.addEventListener('click',e=>{
// 首次点城池给个提示
if(!state._tipped){
state._tipped=true;
setTimeout(()=>logMsg('💡 提示:点城池后选「出征」即可进入搜打撤战场。滚轮可缩放地图。'),2000);
}
this.onMapClick(e);
});
mv.addEventListener('touchstart',e=>{ e.preventDefault(); this.onMapTouch(e); },{passive:false});
},
renderTop(){
if(!state||!state.resources) return;
const el=this.$('resBar'); if(el){
const r=state.resources;
el.innerHTML=`🪙${r.gold|0} 🍚${r.food|0} 🐴${r.horse} ⚙${r.iron} 🎗${r.silk} 📅 第${state.turn}月(${state.season})`; }
const ti=this.$('turnInfo'); if(ti) ti.textContent=`公元 ${state.year} 年`;
},
onTopBtn(id){
audio.init(); audio.resume(); audio.ui();
if(id==='btnNext'){ processMonth(); this.renderTop(); view.render(); this.renderLog(); }
if(id==='btnMenu'){ this.openMenu(); }
if(id==='btnDiplomacy'){ this.openDiplomacy(); }
if(id==='btnTech'){ this.openTech(); }
if(id==='btnHeroes'){ this.openHeroes(); }
if(id==='btnReports'){ this.openReports(); }
if(id==='btnTitle'){ showTitle(); }
},
openMenu(){
const act=prompt('菜单:\n1. 保存\n2. 返回标题\n3. 重新开始');
if(act==='1'){ persist.save(); alert('已保存。'); }
if(act==='3'){ if(confirm('重新开始?')){ newGame(); view.render(); this.renderTop(); } }
},
openDiplomacy(){
const forces={};
Object.values(state.cities).forEach(c=>{
if(c.force===state.playerForce) return;
if(!forces[c.force]) forces[c.force]={city:0, total:0};
forces[c.force].city++; forces[c.force].total+=c.gold+c.pop;
});
let txt='=== 外交 ===\n';
Object.keys(forces).forEach(f=>{
const rel=state.diplomacy[f]||0;
txt+=`${f}:城${forces[f].city}座,关系 ${rel>0?'友好':rel<0?'敌对':'中立'}\n`;
});
txt+='\n输入势力名可与其结盟(需 1000 金):';
const f=prompt(txt);
if(f && forces[f] && state.resources.gold>=1000){
state.resources.gold-=1000;
state.diplomacy[f]=1;
logMsg(`与 ${f} 结盟。`);
alert('结盟成功。');
this.renderTop();
}
},
openTech(){
let txt='=== 科技 ===\n';
Object.keys(state.tech).forEach(t=>{ txt+=`${t} Lv.${state.tech[t]}(升级 800 金)\n`; });
const t=prompt(txt+'\n输入科技名升级:');
if(t && state.tech[t]!==undefined && state.resources.gold>=800){
state.resources.gold-=800; state.tech[t]++; logMsg(`${t} 升至 ${state.tech[t]} 级。`); alert('升级成功。'); this.renderTop();
}
},
openHeroes(){
const hs=Object.values(state.heroes).filter(h=>h.force===state.playerForce);
let txt='=== 武将 ===\n';
hs.forEach(h=>{
txt+=`${h.name} [${h.city||'无'}]\n 统${h.stats[0]} 武${h.stats[1]} 智${h.stats[2]} 政${h.stats[3]} 魅${h.stats[4]}\n 兵力 ${h.troops}/${h.maxTroops} 忠诚${h.loyalty}\n`;
});
alert(txt);
},
openReports(){
let txt='=== 战报 ===\n';
state.reports.forEach(r=>{
txt+=`第${r.turn}月 ${r.attacker} → ${r.target} ${r.win?'胜':'败'}(力比${r.ratio.toFixed(2)})\n`;
});
if(!state.reports.length) txt+='暂无战报。';
alert(txt);
},
// 地图交互
onMapClick(e){
const rect=this.$('mapView').getBoundingClientRect();
const p=view.screenToMap(e.clientX-rect.left, e.clientY-rect.top);
this.hitCity(p.x, p.y);
},
onMapTouch(e){
if(e.touches.length===0) return;
const t=e.touches[0];
const rect=this.$('mapView').getBoundingClientRect();
const p=view.screenToMap(t.clientX-rect.left, t.clientY-rect.top);
if(view._pendingClick!==false){ this.hitCity(p.x, p.y); }
},
hitCity(x,y){
// 拖拽中忽略
if(view._pendingClick===false) return;
const hitR = 22/Math.max(state.viewScale||1, 0.5);
let hit=null,hd=Infinity;
Object.values(state.cities).forEach(c=>{
const d=Math.sqrt((c.x-x)**2+(c.y-y)**2);
if(d<hitR && d<hd){ hd=d; hit=c; }
});
if(hit){
audio.init(); audio.resume(); audio.ui();
if(state.moveTarget){
if(hit.id===state.moveTarget){
const fromId=state.selectedCity;
state.moveTarget=null;
state.selectedCity=null;
this.startBattle(fromId, hit.id);
return;
}else{
// 点击非目标城,取消出征模式
state.moveTarget=null;
state.selectedCity=null;
}
}
state.selectedCity=hit.id;
this.openCity(hit.id);
}
},
_selectedHero:null,
_selectedTarget:null,
openCity(cityId){
const c=state.cities[cityId];
if(!c) return;
const o=cityOutput(c);
// 城池属于玩家,或者城池内有玩家武将(刚占领/驻军),都视为己方可操作
const own = (c.force===state.playerForce) || (heroesInCity(cityId, state.playerForce).length>0);
const hs=heroesInCity(cityId);
state.selectedCity=cityId;
this._selectedHero=hs.length?hs[0].name:null;
this._selectedTarget=null;
this._renderCityMenu(c, own, hs, o);
const menu=this.$('cityMenu');
if(menu){ menu.style.display='block'; }
view.render();
},
// 生成一个按钮的 HTML(用 data-action 替代内联 onclick)
_actBtn(action, param, label, cls, disabled){
const dis = disabled ? ' disabled' : '';
const dt = param!==undefined ? ' data-param="'+param+'"' : '';
return '<button class="act-btn '+cls+'" data-action="'+action+'"'+dt+dis+'>'+label+'</button>';
},
_renderCityMenu(c, own, hs, o){
const el=this.$('cityMenu');
if(!el) return;
const forceColor = c.force===state.playerForce ? '#6fe07a' : (c.force==='汉'?'#d7d7d7':(c.force==='魏'?'#6a9bff':(c.force==='吴'?'#ffb95a':'#d97a7a')));
let html='<button class="close-x" data-action="close">×</button>';
html+='<h3>'+c.id+' <span style="font-size:11px;color:'+forceColor+'">['+c.force+'·'+c.region+']</span></h3>';
html+='<div class="info">';
html+='特产 '+c.spec+' 城墙 '+c.defense+' 守军 '+cityTroops(c.id)+'<br>';
html+='月产 粮 '+o.foodOut+' / 金 '+o.goldOut+' 最大驻军 '+o.troopMax;
html+='</div>';
if(own){
// 武将选择
if(hs.length){
html+='<div class="menu-section">出征武将(点击选择)</div>';
html+='<div class="hero-list">';
hs.forEach(h=>{
const sel = this._selectedHero===h.name ? ' checked' : '';
html+='<label class="hero-row" style="cursor:pointer'+sel+';position:relative">';
html+='<input type="radio" name="heroSel" value="'+h.name+'" '+(sel?'checked':'')+' data-action="select-hero" data-param="'+h.name+'">';
html+='<span class="hname">'+h.name+'</span>';
html+='<span class="hstat">统'+h.stats[0]+' 武'+h.stats[1]+' 智'+h.stats[2]+'</span>';
html+='<span class="hstat" style="margin-left:auto">兵 '+h.troops+'/'+h.maxTroops+'</span>';
html+='</label>';
});
html+='</div>';
}else{
html+='<div class="menu-section">城内无武将</div>';
}
// ===== 搜打撤战斗 - 最醒目的入口 =====
html+='<div class="menu-section">⚔ 搜打撤战斗模式</div>';
const canBattle = hs.length>0;
html+=this._actBtn('march', c.id, '<span class="btn-ico">⚔</span>出征 — 进入搜打撤战场 <span class="btn-hot">Enter</span>', 'battle', !canBattle);
html+=this._actBtn('scout', c.id, '<span class="btn-ico">🔍</span>潜行搜索 — 敌境搜刮 <span class="btn-hot">Scout</span>', 'scout', !canBattle);
html+=this._actBtn('raid', c.id, '<span class="btn-ico">⚡</span>快速遭遇 — 随机事件战', '', !canBattle);
// 内政
html+='<div class="menu-section">🏛 内政</div>';
html+=this._actBtn('recruit', c.id, '<span class="btn-ico">🛡</span>征兵 <span class="cost-tag">200金</span>', '', state.resources.gold<200);
html+=this._actBtn('build', c.id, '<span class="btn-ico">🏗</span>建设 <span class="cost-tag">300金</span>', '', state.resources.gold<300);
html+=this._actBtn('develop', c.id, '<span class="btn-ico">🌾</span>开发 <span class="cost-tag">400金</span>', '', state.resources.gold<400);
if(hs.length){
html+='<div class="menu-section">📦 调度</div>';
html+=this._actBtn('move', c.id, '<span class="btn-ico">➤</span>移动武将到邻城', '', false);
}
}else{
html+='<div class="menu-section">🏴 敌方城池</div>';
html+='<div class="info" style="color:#d97a7a">此城非我方所有,需先派军出征攻克。</div>';
if(hs.length){
html+='<div class="hero-list">';
hs.forEach(h=>{
html+='<div class="hero-row"><span class="hname">'+h.name+'</span><span class="hstat">统'+h.stats[0]+' 武'+h.stats[1]+' 智'+h.stats[2]+' 兵'+h.troops+'</span></div>';
});
html+='</div>';
}
const playerHere = heroesInCity(c.id,state.playerForce).length>0;
html+=this._actBtn('attack-city', c.id, '<span class="btn-ico">⚔</span>攻打此城 <span class="btn-hot">Enter</span>', 'battle', !playerHere);
}
el.innerHTML=html;
},
// 事件委托:点击弹窗内的按钮
_onCityMenuClick(e){
const btn = e.target.closest('[data-action]');
if(!btn) return;
const action = btn.dataset.action;
const param = btn.dataset.param;
switch(action){
case 'close': this.closeCityMenu(); break;
case 'select-hero': this._selectedHero=param; this._refreshCityMenu(); break;
case 'march': this.confirmMarch(param); break;
case 'attack-city': this.confirmAttackCity(param); break;
case 'scout': this.confirmScout(param); break;
case 'raid': this.confirmRaid(param); break;
case 'recruit': this.doRecruit(param); break;
case 'build': this.doBuild(param); break;
case 'develop': this.doDevelop(param); break;
case 'move': this.doMove(param); break;
case 'select-target': this._selectedTarget=param; this._updateTargetChips(); break;
case 'do-march': this._execMarch(); break;
case 'build-exec': this._doBuildExec(param, parseInt(btn.dataset.idx)); break;
case 'move-exec': this._doMoveExec(param, btn.dataset.toid); break;
case 'back': this._refreshCityMenu(); break;
}
},
_updateTargetChips(){
const menu=this.$('cityMenu');
if(!menu) return;
// 只更新 chip 的选中状态,不重新渲染整个菜单
const chips=menu.querySelectorAll('[data-action="select-target"]');
chips.forEach(ch=>{
if(ch.dataset.param===this._selectedTarget){
ch.classList.add('selected');
}else{
ch.classList.remove('selected');
}
});
},
_refreshCityMenu(){
const cityId=state.selectedCity;
if(!cityId) return;
const c=state.cities[cityId];
this._renderCityMenu(c, c.force===state.playerForce, heroesInCity(cityId), cityOutput(c));
},
closeCityMenu(){
const menu=ui.$('cityMenu');
if(menu) menu.style.display='none';
state.selectedCity=null;
state.moveTarget=null;
view.render();
},
// 从敌方城池点击"攻打此城":直接以该城为目标
confirmAttackCity(cityId){
const target=state.cities[cityId];
if(!target){ logMsg('目标城池无效。'); return; }
// 找己方势力中离目标最近的城作为出发城
const ownCities=Object.keys(state.cities).filter(k=>state.cities[k].force===state.playerForce);
if(!ownCities.length){ logMsg('无可出征的己方城池。'); return; }
// 找有武将的己方城
const ownWithHero=ownCities.filter(k=>heroesInCity(k,state.playerForce).length>0);
const fromCities=ownWithHero.length?ownWithHero:ownCities;
// 选离目标最近的
let best=null, bestD=Infinity;
fromCities.forEach(k=>{
const c=state.cities[k];
const d=Math.abs(c.x-target.x)+Math.abs(c.y-target.y);
if(d<bestD){ bestD=d; best=k; }
});
if(!best){ logMsg('无可出征的武将。'); return; }
state.selectedCity=best;
state.moveTarget=cityId;
this._selectedTarget=cityId;
// 直接进入出征确认(复用 confirmMarch 的目标选择逻辑)
// 但只保留目标=被点击的城
const el=this.$('cityMenu');
if(!el) return;
const c=state.cities[best];
const lead=heroesInCity(best,state.playerForce)[0];
const marchCost=Math.floor(lead.troops*0.8);
lead.troops=marchCost;
logMsg('⚔ '+lead.name+' 率军出征 '+target.id+'!');
audio.fanfare();
battle.start({
leader:lead,
from:best, to:cityId,
attackerTroops: lead.troops,
defenderTroops: cityTroops(cityId),
defenderCity: target,
});
},
// 出征确认:选择目标城
confirmMarch(cityId){
const c=state.cities[cityId];
const hs=heroesInCity(cityId);
if(!hs.length){ logMsg('该城无武将可出征。'); return; }
const targets=c.neighbors.filter(n=>{
const nc=state.cities[n];
return nc && nc.force!==state.playerForce;
});
if(!targets.length){
logMsg(c.id+' 周边无可攻击的目标。');
return;
}
state.selectedCity=cityId;
state.moveTarget=cityId;
if(!this._selectedTarget || !targets.includes(this._selectedTarget)) this._selectedTarget=targets[0];
const el=this.$('cityMenu');
if(!el) return;
let html='<button class="close-x" data-action="close">×</button>';
html+='<h3>⚔ 出征 · '+c.id+'</h3>';
html+='<div class="info">选择出征目标:</div>';
html+='<div class="target-list">';
targets.forEach(t=>{
const tc=state.cities[t];
const troops=cityTroops(t);
const sel=this._selectedTarget===t?' selected':'';
html+='<div class="target-chip'+sel+'" data-action="select-target" data-param="'+t+'">'+t+'<br><span style="font-size:10px;opacity:0.8">守军 '+troops+'</span></div>';
});
html+='</div>';
html+=this._actBtn('do-march', '', '<span class="btn-ico">⚔</span>出征!进入搜打撤战场', 'battle', false);
el.innerHTML=html;
},
_execMarch(){
const fromId=state.selectedCity;
const toId=this._selectedTarget;
state.moveTarget=null;
if(!fromId || !toId){ logMsg('出征信息不完整。'); return; }
this.closeCityMenu();
this.startBattle(fromId, toId);
},
// 快速遭遇:不指定城池,生成随机野外遭遇战
confirmRaid(cityId){
const c=state.cities[cityId];
const lead=choice(heroesInCity(cityId));
if(!lead){ logMsg('该城无武将。'); return; }
logMsg('⚡ '+lead.name+' 遭遇流寇游军!');
audio.ui();
this.closeCityMenu();
battle.start({
leader:lead, from:cityId, to:cityId,
attackerTroops: Math.floor(lead.troops*0.6),
defenderTroops: randi(300,800),
defenderCity: c,
isRaid:true,
});
},
confirmScout(cityId){
// 搜索 = 随机选一个邻城作为目标,进入搜打撤但敌方较弱
const c=state.cities[cityId];
const targets=c.neighbors.filter(n=>state.cities[n]);
if(!targets.length){ logMsg('周边无可搜索区域。'); return; }
const t=choice(targets);
logMsg(`🔍 ${choice(heroesInCity(cityId)).name} 率轻骑潜入 ${t} 周边搜索!`);
audio.ui();
this.closeCityMenu();
// 搜索模式:敌方兵力减半,撤离难度低
const origTroops=cityTroops(t);
const scoutBattle=()=>{
const lead=choice(heroesInCity(cityId));
const battleTroops=Math.floor(lead.troops*0.5);
battle.start({
leader:lead, from:cityId, to:t,
attackerTroops: battleTroops,
defenderTroops: Math.floor(origTroops*0.4),
defenderCity: state.cities[t],
isScout:true,
});
};
scoutBattle();
},
doRecruit(cityId){
const c=state.cities[cityId];
const cost=200;
if(state.resources.gold<cost){ logMsg('黄金不足。'); return; }
state.resources.gold-=cost;
const hs=heroesInCity(cityId);
hs.forEach(h=>h.troops=clamp(h.troops+randi(200,500),0,h.maxTroops||2000));
if(!hs.length) c.garrison+=randi(300,600);
logMsg(`${c.id} 征兵完成。`);
audio.coin(); this.renderTop(); this._refreshCityMenu();
},
doBuild(cityId){
const c=state.cities[cityId];
const types=['农场','市场','兵营','城墙','工坊'];
const labels=['1.农场(+粮)','2.市场(+金)','3.兵营(+驻军)','4.城墙(+防御)','5.工坊(+装备)'];
// 弹出简易选择
const btns=labels.map((l,i)=>`<button class="act-btn" data-action="build-exec" data-param="${cityId}" data-idx="${i}">${l}</button>`).join('');
const el=ui.$('cityMenu');
if(!el) return;
if(state.resources.gold<300){ logMsg('黄金不足。'); return; }
el.innerHTML=`<button class="close-x" onclick="ui._refreshCityMenu()">×</button><h3>🏗 建设 · ${c.id}</h3><div class="info">选择建设项目(每项 300 金,当前金 ${state.resources.gold})</div>${btns}<button class="act-btn" onclick="ui._refreshCityMenu()">← 返回</button>`;
},
_doBuildExec(cityId, idx){
const c=state.cities[cityId];
const types=['农场','市场','兵营','城墙','工坊'];
const key=types[idx];
if(state.resources.gold<300){ logMsg('黄金不足。'); return; }
state.resources.gold-=300;
c.build[key]=(c.build[key]||0)+1;
logMsg(`${c.id} ${key} 升至 Lv.${c.build[key]}`);
audio.coin(); this.renderTop(); this._refreshCityMenu();
},
doDevelop(cityId){
const c=state.cities[cityId];
const cost=400;
if(state.resources.gold<cost){ logMsg('黄金不足。'); return; }
state.resources.gold-=cost;
c.pop+=randi(5,15);
logMsg(`${c.id} 开发完成,人口 +${c.pop-state.cities[cityId].pop+c.pop-state.cities[cityId].pop>=0?'':'+'}${Math.abs(c.pop-(c.pop-randi(5,15)))}`);
this.renderTop(); this._refreshCityMenu();
},
doMove(cityId){
const c=state.cities[cityId];
const hs=heroesInCity(cityId);
if(!hs.length) return;
const el=ui.$('cityMenu');
if(!el) return;
let html=`<button class="close-x" onclick="ui._refreshCityMenu()">×</button><h3>➤ 移动武将</h3>`;
html+=`<div class="target-list">`;
c.neighbors.forEach(n=>{
const nc=state.cities[n]; if(!nc) return;
html+=`<button class="target-chip" style="margin:4px" data-action="move-exec" data-param="${cityId}" data-toid="${n}">${n}<br><span style="font-size:10px;opacity:0.7">${nc.force}</span></button>`;
});
html+=`</div>`;
html+=`<button class="act-btn" data-action="back">← 返回</button>`;
el.innerHTML=html;
},
_doMoveExec(fromId, toId){
const c=state.cities[fromId];
const hs=heroesInCity(fromId);
if(!hs.length) return;
const h=hs[0];
h.city=toId;
logMsg(`${h.name} 移驻 ${toId}。`);
audio.ui();
state.selectedCity=toId;
this._renderCityMenu(state.cities[toId], state.cities[toId].force===state.playerForce, heroesInCity(toId), cityOutput(state.cities[toId]));
},
startBattle(fromId, toId){
const c=state.cities[fromId];
const hs=heroesInCity(fromId,state.playerForce);
if(!hs.length){ logMsg('该城无武将可出征。'); return; }
let lead=hs.find(h=>h.name===this._selectedHero)||hs[0];
const marchCost=Math.floor(lead.troops*0.8);
lead.troops=marchCost;
logMsg(`⚔ ${lead.name} 率军出征 ${state.cities[toId].id||toId}!`);
audio.fanfare();
battle.start({
leader:lead,
from:fromId, to:toId,
attackerTroops: lead.troops,
defenderTroops: cityTroops(toId),
defenderCity: state.cities[toId],
});
},
openLoot(){ loot.start(state.currentLoot); },
};
// ---------- 战略地图渲染 ----------
view = {
cv:null, ctx:null, W:960, H:640,
// 用户缩放状态
userZoom:1, panX:0, panY:0,
minZoom:0.5, maxZoom:4,
lastTouchDist:0, lastTouchMid:null, lastTouchMidY:0,
init(){
this.cv=ui.$('mapCanvas');
this.ctx=this.cv.getContext('2d');
this.bindZoom();
this.resize();
globalThis.addEventListener('resize',()=>this.resize());
state.viewScale=1; state.viewOffset={x:0,y:0};
},
bindZoom(){
const mv=ui.$('mapView');
if(!mv) return;
// 滚轮缩放
mv.addEventListener('wheel', e=>{
e.preventDefault();
const rect=this.cv.getBoundingClientRect();
const cx=e.clientX-rect.left, cy=e.clientY-rect.top;
const factor = e.deltaY < 0 ? 1.12 : 1/1.12;
this.applyZoom(factor, cx, cy);
}, {passive:false});
// 中键拖拽平移
let dragging=false, dragStart={x:0,y:0}, panStart={x:0,y:0};
mv.addEventListener('mousedown', e=>{
if(e.button===1){ e.preventDefault(); dragging=true; dragStart={x:e.clientX,y:e.clientY}; panStart={x:this.panX,y:this.panY}; }
});
mv.addEventListener('mousemove', e=>{
if(!dragging) return;
this.panX=panStart.x+(e.clientX-dragStart.x);
this.panY=panStart.y+(e.clientY-dragStart.y);
this.render();
});
globalThis.addEventListener('mouseup', ()=>{ dragging=false; });
// 触摸:双指缩放 + 单指拖拽
mv.addEventListener('touchstart', e=>{
if(e.touches.length===2){
e.preventDefault();
const t1=e.touches[0], t2=e.touches[1];
this.lastTouchDist=Math.hypot(t1.clientX-t2.clientX, t1.clientY-t2.clientY);
this.lastTouchMid=(t1.clientX+t2.clientX)/2;
this.lastTouchMidY=(t1.clientY+t2.clientY)/2;
} else if(e.touches.length===1){
const t=e.touches[0];
this._downPos={x:t.clientX,y:t.clientY};
this._pendingClick=true;
this._touchPanStart={x:this.panX, y:this.panY};
}
}, {passive:false});
mv.addEventListener('touchmove', e=>{
e.preventDefault();
if(e.touches.length===2){
const t1=e.touches[0], t2=e.touches[1];
const dist=Math.hypot(t1.clientX-t2.clientX, t1.clientY-t2.clientY);
const midX=(t1.clientX+t2.clientX)/2, midY=(t1.clientY+t2.clientY)/2;
const rect=this.cv.getBoundingClientRect();
if(this.lastTouchDist>0){
const cx=midX-rect.left, cy=midY-rect.top;
const factor=dist/this.lastTouchDist;
this.applyZoom(factor, cx, cy);
}
if(this.lastTouchMid!=null){
this.panX += midX-this.lastTouchMid;
this.panY += midY-this.lastTouchMidY;
this.render();
}
this.lastTouchDist=dist;
this.lastTouchMid=midX;
this.lastTouchMidY=midY;
} else if(e.touches.length===1 && this._pendingClick!==false){
const t=e.touches[0];
const dx=t.clientX-this._downPos.x, dy=t.clientY-this._downPos.y;
if(Math.abs(dx)>6 || Math.abs(dy)>6){
this._pendingClick=false;
this.panX=this._touchPanStart.x+dx;
this.panY=this._touchPanStart.y+dy;
this.render();
}
}
}, {passive:false});
mv.addEventListener('touchend', ()=>{ this.lastTouchDist=0; this.lastTouchMid=null; });
// 缩放按钮
ui.$('zoomIn').addEventListener('click', ()=>{
const rect=this.cv.getBoundingClientRect();
this.applyZoom(1.3, rect.width/2, rect.height/2);
if(audio.init) audio.init(); if(audio.ui) audio.ui();
});
ui.$('zoomOut').addEventListener('click', ()=>{
const rect=this.cv.getBoundingClientRect();
this.applyZoom(1/1.3, rect.width/2, rect.height/2);
if(audio.init) audio.init(); if(audio.ui) audio.ui();
});
ui.$('zoomReset').addEventListener('click', ()=>{
this.userZoom=1; this.panX=0; this.panY=0;
this.updateZoomInfo();
this.render();
if(audio.init) audio.init(); if(audio.ui) audio.ui();
});
},
zoomIn(){ this.applyZoom(1.3, this.viewW/2, this.viewH/2); },
zoomOut(){ this.applyZoom(1/1.3, this.viewW/2, this.viewH/2); },
resetZoom(){ this.userZoom=1; this.panX=0; this.panY=0; this.clampPan(); this.render(); },
applyZoom(factor, cx, cy){
const newZoom = clamp(this.userZoom*factor, this.minZoom, this.maxZoom);
const realFactor = newZoom/this.userZoom;
this.panX = cx - (cx-this.panX)*realFactor;
this.panY = cy - (cy-this.panY)*realFactor;
this.userZoom = newZoom;
this.clampPan();
this.updateZoomInfo();
this.render();
},
clampPan(){
const w=this.viewW, h=this.viewH;
const fitScale=Math.min(w/this.W, h/this.H);
const curScale=fitScale*this.userZoom;
const scaledW=this.W*curScale, scaledH=this.H*curScale;
if(scaledW<=w){ this.panX=(w-scaledW)/2; }
else { this.panX=clamp(this.panX, w-scaledW, 0); }
if(scaledH<=h){ this.panY=(h-scaledH)/2; }
else { this.panY=clamp(this.panY, h-scaledH, 0); }
},
updateZoomInfo(){
const el=ui.$('mapZoomInfo');
if(el) el.textContent='缩放 '+Math.round(this.userZoom*100)+'%';
},
resize(){
const box=ui.$('mapView');
if(!box) return;
const w=box.clientWidth||960, h=box.clientHeight||640;
const dpr=globalThis.devicePixelRatio||1;
this.cv.width=w*dpr; this.cv.height=h*dpr;
this.cv.style.width=w+'px'; this.cv.style.height=h+'px';
this.ctx.setTransform(dpr,0,0,dpr,0,0);
this.viewW=w; this.viewH=h;
this.clampPan();
this.render();
},
screenToMap(sx, sy){
const w=this.viewW, h=this.viewH;
const fitScale=Math.min(w/this.W, h/this.H);
const ox=(w-this.W*fitScale)/2, oy=(h-this.H*fitScale)/2;
return {
x:(sx-ox-this.panX)/(fitScale*this.userZoom),
y:(sy-oy-this.panY)/(fitScale*this.userZoom)
};
},
render(){
if(!this.ctx) return;
const {ctx}=this;
const w=this.viewW, h=this.viewH;
if(!w || !h) return;
state._tick = (state._tick||0)+1;
ctx.clearRect(0,0,w,h);
const g=ctx.createLinearGradient(0,0,0,h);
g.addColorStop(0,'#1e2f4f'); g.addColorStop(0.5,'#1a2a48'); g.addColorStop(1,'#14203a');
ctx.fillStyle=g; ctx.fillRect(0,0,w,h);
ctx.save();
const fitScale=Math.min(w/this.W, h/this.H);
const scale=fitScale*this.userZoom;
state.viewScale=scale;
const ox=(w-this.W*fitScale)/2, oy=(h-this.H*fitScale)/2;
state.viewOffset={x:-ox/fitScale, y:-oy/fitScale};
ctx.translate(ox+this.panX, oy+this.panY);
ctx.scale(scale, scale);
this.drawTerrain(ctx);
ctx.strokeStyle='rgba(255,255,255,0.25)';
ctx.lineWidth=1.5/this.userZoom;
ROUTES.forEach(([a,b])=>{
const ca=state.cities[a],cb=state.cities[b];
if(!ca||!cb) return;
ctx.beginPath(); ctx.moveTo(ca.x,ca.y); ctx.lineTo(cb.x,cb.y); ctx.stroke();
});
Object.values(state.cities).forEach(c=>this.drawCity(ctx,c));
if(state.moveTarget && state.selectedCity){
const c=state.cities[state.selectedCity];
if(c){
c.neighbors.forEach(n=>{
const t=state.cities[n]; if(!t) return;
ctx.strokeStyle='#ffe066'; ctx.lineWidth=2/this.userZoom; ctx.setLineDash([6,4]);
ctx.beginPath(); ctx.moveTo(c.x,c.y); ctx.lineTo(t.x,t.y); ctx.stroke();
ctx.setLineDash([]);
});
}
}
ctx.restore();
},
drawTerrain(ctx){
window.CityArt.terrain(ctx, this.W, this.H);
},
drawCity(ctx,c){
const own=c.force===state.playerForce;
const sel=state.selectedCity===c.id;
window.CityArt.city(ctx, c, {
own, sel,
troops: cityTroops(c.id),
_t: (state._tick||0),
zoom: this.userZoom,
});
},
};
// ============================================================
// 搜打撤战斗系统 v2
// · 第三人称追尾 2D,真实物理移动(无"滑冰"感)
// · 大型多房间"战后废弃城池"地图 + 多个出生点
// · 三国主题物资分级:大金 / 中金 / 小金 + 暗区式高价值战略物品
// · 四兵种随行部曲(小弟/兵力),独立 AI 协同作战
// · 近战重击 / 蓄力 / 格挡 / 翻滚 i-frames / 远程射击 全键位
// · 多类敌人 AI(斥候包抄 / 弓手风筝 / 戟兵冲锋 / 武将精英 / 伏兵)
// · 撤离读条、威胁度、物资带出、死亡掉落
// ============================================================
// ============================================================
// 搜打撤物资表:三国主题 · 大金 / 中金 / 小金 / 补给 分级
// 大金 = 暗区"大金",最高价值战略物品,搜索耗时、携出得分最高
// ============================================================
const SDE_LOOT_TABLE = {
'大金':[
{name:'传国玉玺', type:'宝', weight:3, rarity:5, val:120, ico:'玺', desc:'秦制传国玉玺,得之可正大统'},
{name:'九锡礼器', type:'宝', weight:3, rarity:5, val:110, ico:'锡', desc:'九锡全套,加九锡者位极人臣'},
{name:'天子剑', type:'weapon', weight:2, rarity:5, val:90, ico:'剑', desc:'尚方斩马剑,天子所赐'},
{name:'赤霄剑', type:'weapon', weight:2, rarity:5, val:95, ico:'剑', desc:'高祖斩白蛇之赤霄'},
{name:'青釭剑', type:'weapon', weight:2, rarity:5, val:90, ico:'剑', desc:'削铁如泥的名剑'},
{name:'魏王金印', type:'宝', weight:2, rarity:5, val:100, ico:'印', desc:'魏王之印,号令一方'},
{name:'和氏璧', type:'宝', weight:2, rarity:5, val:115, ico:'璧', desc:'天下所共传之宝璧'},
{name:'诸葛连弩', type:'weapon', weight:3, rarity:5, val:85, ico:'弩', desc:'损益连弩,一发十矢'},
{name:'孟德新书', type:'book', weight:2, rarity:5, val:80, ico:'书', desc:'魏武兵法,用兵奇略'},
{name:'太平要术', type:'book', weight:2, rarity:5, val:85, ico:'术', desc:'南华老仙所授仙书'},
{name:'金缕玉衣', type:'armor', weight:3, rarity:5, val:100, ico:'衣', desc:'诸侯王殓服,金缕玉片'},
{name:'夜照玉狮子',type:'horse', weight:3, rarity:5, val:90, ico:'骥', desc:'日行千里的骏马'},
],
'中金':[
{name:'虎符', type:'宝', weight:1, rarity:4, val:45, ico:'符', desc:'调兵遣将的兵符'},
{name:'鱼鳞铠', type:'armor', weight:2, rarity:4, val:38, ico:'铠', desc:'铁片连缀的鱼鳞甲'},
{name:'明光铠', type:'armor', weight:2, rarity:4, val:40, ico:'铠', desc:'护心镜光可鉴人'},
{name:'环首刀', type:'weapon', weight:1, rarity:4, val:34, ico:'刀', desc:'汉制环首长刀'},
{name:'方天画戟', type:'weapon', weight:2, rarity:4, val:42, ico:'戟', desc:'吕布所用方天画戟'},
{name:'羽葆幢', type:'宝', weight:1, rarity:4, val:36, ico:'幢', desc:'主将仪仗之幢'},
{name:'吴侯印绶', type:'宝', weight:1, rarity:4, val:38, ico:'绶', desc:'江东孙氏印绶'},
{name:'屯田策', type:'book', weight:1, rarity:4, val:30, ico:'策', desc:'许下屯田之策'},
{name:'绝影', type:'horse', weight:2, rarity:4, val:40, ico:'影', desc:'大宛良驹,绝影之名'},
{name:'紫金冠', type:'helm', weight:1, rarity:4, val:28, ico:'冠', desc:'紫金束发冠'},
{name:'孙子兵法', type:'book', weight:1, rarity:4, val:32, ico:'兵', desc:'兵家圣典十三篇'},
{name:'轒辒车', type:'weapon', weight:2, rarity:4, val:36, ico:'车', desc:'攻城之冲车'},
],
'小金':[
{name:'绢帛', type:'宝', weight:1, rarity:2, val:12, ico:'帛', desc:'上等绢帛若干匹'},
{name:'铜钱', type:'宝', weight:1, rarity:1, val:8, ico:'钱', desc:'五铢铜钱一袋'},
{name:'铁蒺藜', type:'weapon', weight:1, rarity:1, val:6, ico:'藜', desc:'撒地阻骑的铁蒺藜'},
{name:'皮甲', type:'armor', weight:1, rarity:1, val:10, ico:'甲', desc:'牛皮缝制的札甲'},
{name:'藤牌', type:'armor', weight:1, rarity:1, val:7, ico:'盾', desc:'御箭的藤编盾'},
{name:'环刀', type:'weapon', weight:1, rarity:2, val:11, ico:'刀', desc:'寻常步卒佩刀'},
{name:'札甲片', type:'armor', weight:1, rarity:1, val:6, ico:'片', desc:'可补缀甲衣的甲片'},
{name:'战马缰', type:'horse', weight:1, rarity:2, val:10, ico:'辔', desc:'辔头与缰绳'},
{name:'竹简兵书', type:'book', weight:1, rarity:2, val:9, ico:'简', desc:'兵法竹简残卷'},
{name:'皮靴', type:'helm', weight:1, rarity:1, val:5, ico:'靴', desc:'行军皮靴'},
{name:'旌旗残幅', type:'宝', weight:1, rarity:1, val:7, ico:'旗', desc:'残破的军旗'},
{name:'弩箭束', type:'weapon', weight:1, rarity:1, val:8, ico:'矢', desc:'蹶张弩之箭'},
],
'补给':[
{name:'军粮', type:'food', weight:1, rarity:1, val:4, ico:'粮', desc:'粟米饭团,可充饥'},
{name:'药囊', type:'potion', weight:1, rarity:2, val:14, ico:'药', desc:'金创散,可疗伤'},
{name:'火折子', type:'宝', weight:1, rarity:1, val:3, ico:'火', desc:'夜间照明的火折'},
{name:'水囊', type:'food', weight:1, rarity:1, val:3, ico:'水', desc:'清水一囊'},
{name:'箭矢', type:'weapon', weight:1, rarity:1, val:5, ico:'矢', desc:'羽箭二十支'},
],
};
const SDE_TIER_COLOR = {'大金':'#ffe066','中金':'#c0c8d4','小金':'#c9a227','补给':'#6a8a5a'};
const rnd01 = ()=>Math.random();
battle = {
cv:null, ctx:null, running:false, paused:false, timer:0, lastTs:0,
world:null, // 地图数据
player:null, squad:[], // 随行部曲
enemies:[], bullets:[], projectiles:[], pickups:[], particles:[], decals:[],
extracts:[], activeExtract:null,
collected:[], invWeight:0, maxWeight:8,
kills:0, threat:0, timeLeft:0, escaped:false, death:false,
escapeProgress:0,
keys:{}, touching:false, touch:null,
// 出生点相关
spawnPoints:[], spawnIdx:0,
// 镜头
cam:{x:0,y:0,tx:0,ty:0},
// 战斗配置
cfg:null, toCity:null, leader:null, mapType:null,
// 结算
result:null,
// 触摸控制状态
joy:null, atkBtn:null, defBtn:null, rollBtn:null,
// 攻击输入
meleeCd:0, chargedAt:0, charging:false, shootCd:0, defCd:0, rollCd:0,
// 拾取提示
nearPickup:null, toast:null,
init(){
this.cv=ui.$('battleCanvas');
if(!this.cv){ console.warn('battleCanvas not found'); return; }
this.ctx=this.cv.getContext('2d');
this.resize();
globalThis.addEventListener('resize',()=>this.resize());
this.bindInput();
this._ensureOverlay();
},
// ---------- 触摸 UI 覆盖层(虚拟摇杆 + 攻击键) ----------
_ensureOverlay(){
if(document.getElementById('sdeHUD')) return;
const hud=document.createElement('div');
hud.id='sdeHUD';
hud.innerHTML=`
<div id="sdeTop">
<div id="sdeObj">目标:搜刮物资并撤离</div>
<div id="sdeTimer">0:00</div>
<button id="sdePause" title="暂停">❚❚</button>
</div>
<div id="sdeLeft">
<div id="sdePortrait"></div>
<div id="sdeHpBar"><div id="sdeHpFill"></div><span id="sdeHpTxt">0/0</span></div>
<div id="sdeStamBar"><div id="sdeStamFill"></div></div>
<div id="sdeThreat">威胁 0%</div>
</div>
<div id="sdeRight">
<div id="sdeLoot" class="empty">未携带物资</div>
<div id="sdeSquad"></div>
</div>
<div id="sdeJoy"><div id="sdeJoyKnob"></div></div>
<div id="sdeBtns">
<button id="sdeBtnRoll" title="翻滚(Shift/空格)"><span>翻</span></button>
<button id="sdeBtnDef" title="格挡(Q)"><span>挡</span></button>
<button id="sdeBtnAtk" title="攻击(J/点击)"><span>攻</span></button>
</div>
<div id="sdeExtractTip" class="hidden"></div>
<div id="sdeCenterTip" class="hidden"></div>
<div id="sdePickupTip" class="hidden"></div>
<div id="sdeCompass"></div>
<div id="sdeMinimap"><canvas id="sdeMinimapCv" width="150" height="150"></canvas></div>
`;
document.getElementById('battleView').appendChild(hud);
this._bindOverlay();
},
_bindOverlay(){
const joy=document.getElementById('sdeJoy');
const knob=document.getElementById('sdeJoyKnob');
const atk=document.getElementById('sdeBtnAtk');
const def=document.getElementById('sdeBtnDef');
const roll=document.getElementById('sdeBtnRoll');
const pause=document.getElementById('sdePause');
let joyId=null, joyCx=0, joyCy=0, joyR=0;
const onJoyStart=e=>{
const r=joy.getBoundingClientRect();
joyCx=r.left+r.width/2; joyCy=r.top+r.height/2; joyR=r.width/2;
const _t=(e.touches?e.touches[0]:e);
joyId=(e.touches&&e.touches[0])?e.touches[0].identifier:null;
joy.classList.add('active');
onJoyMove(e);
e.preventDefault&&e.preventDefault();
};
const onJoyMove=e=>{
if(!joyId && e.touches) return;
let t=null;
if(e.touches){
for(const x of e.touches){ if(x.identifier===joyId){ t=x; break; } }
}else{ t=e; }
if(!t) return;
let dx=t.clientX-joyCx, dy=t.clientY-joyCy;
const len=Math.sqrt(dx*dx+dy*dy);
const max=joyR*0.85;
if(len>max){ dx=dx/len*max; dy=dy/len*max; }
knob.style.transform=`translate(${dx}px,${dy}px)`;
this.joy={x:len>6?dx/max:0, y:len>6?dy/max:0, mag:Math.min(1,len/max)};
};
const onJoyEnd=()=>{ joyId=null; this.joy=null; knob.style.transform=''; joy.classList.remove('active'); };
joy.addEventListener('touchstart',onJoyStart,{passive:false});
joy.addEventListener('touchmove',onJoyMove,{passive:false});
joy.addEventListener('touchend',onJoyEnd,{passive:false});
joy.addEventListener('touchcancel',onJoyEnd,{passive:false});
atk.addEventListener('touchstart',e=>{ e.preventDefault(); this._inputAtk(true); },{passive:false});
atk.addEventListener('touchend',e=>{ e.preventDefault(); this._inputAtk(false); },{passive:false});
def.addEventListener('touchstart',e=>{ e.preventDefault(); this._inputDef(true); },{passive:false});
def.addEventListener('touchend',e=>{ e.preventDefault(); this._inputDef(false); },{passive:false});
roll.addEventListener('touchstart',e=>{ e.preventDefault(); this._doRoll(); },{passive:false});
pause.addEventListener('click',()=>{ this.paused=!this.paused; });
},
_inputAtk(down){
if(!this.running) return;
if(down){
// 按下:开始蓄力(远程武将直接射击)
this.charging=true; this.chargedAt=this.timer;
const role=this.leader&&this.leader.portrait;
const isRanged=(role==='strategist');
if(isRanged) this._shoot();
else this._melee();
}else{
this.charging=false;
}
},
_inputDef(down){
if(!this.running) return;
this.player.defending=down;
},
_doRoll(){
if(!this.running) return;
if((this.rollCd||0)>0) return;
const p=this.player;
let dx=0,dy=0;
if(this.joy){ dx=this.joy.x; dy=this.joy.y; }
else { const k=this.keys||{};
if(k['ArrowRight']||k['d']) dx=1; else if(k['ArrowLeft']||k['a']) dx=-1;
if(k['ArrowUp']||k['w']) dy=-1; else if(k['ArrowDown']||k['s']) dy=1;
}
const l=Math.sqrt(dx*dx+dy*dy)||1;
p.rollVx=dx/l*6.5; p.rollVy=dy/l*6.5; p.rolling=14; p.invuln=16;
this.rollCd=45; audio.dodge&&audio.dodge();
},
// ---------- 主循环 ----------
loop(ts){
if(!this.running) return;
if(!this.lastTs) this.lastTs=ts;
const dt=Math.min(48, ts-this.lastTs);
this.lastTs=ts;
if(!this.paused){
this.timer+=dt;
this.update(dt);
this.draw();
}
requestAnimationFrame(t=>this.loop(t));
},
// ---------- 开始一场搜打撤 ----------
start(cfg){
switchView('battle');
this.resize();
if(!this.viewW||!this.viewH){
this.resize();
}
state.view='battle';
this.cfg=cfg||{};
this.leader=this.cfg.leader;
if(!this.leader){ console.warn('battle.start: no leader'); return; }
this.toCity=this.cfg.defenderCity||null;
// 地图
const wType=this.cfg.mapType||this._pickMapType();
this.mapType=wType;
const dur=clamp(180- (state.difficulty?state.difficulty.atkMul*0:0)*0, 180, 300);
this.world=this._genWorld(wType, this.cfg);
// 出生点
this.spawnPoints=this.world.spawns;
this.spawnIdx=this.cfg.spawnIdx||0;
const sp=this.spawnPoints[this.spawnIdx%this.spawnPoints.length];
// 玩家
const lead=this.leader;
const baseHp=90+lead.stats[1]*1.4+lead.stats[0]*0.6;
const role=(lead.portrait==='strategist')?'文':(lead.portrait==='ruler')?'君':'武';
this.player={
x:sp.x, y:sp.y, vx:0, vy:0,
facing:0,
size:15,
hp:baseHp, maxHp:baseHp,
stamina:100, maxStamina:100,
ammo:role==='文'?24:0, maxAmmo:role==='文'?24:0,
invWeight:0, maxWeight:8,
defending:false, blocking:0,
rolling:0, rollVx:0, rollVy:0, invuln:0,
// 战斗属性
meleeDmg: 8 + lead.stats[1]*0.22,
rangedDmg: 6 + lead.stats[1]*0.15,
knockback: 1.6,
attackRange: role==='文'? 220 : 46,
attackAngle: role==='文'? 0.35 : 1.5,
role,
};
this.squad=this._genSquad(lead);
this.invWeight=0; this.maxWeight=8;
// 物资(按点位表生成,大金/中金/小金)
this.pickups=this._genLoot(this.world);
// 撤离点(默认全部关闭,满足条件后开启一个最近的)
this.extracts=this.world.extracts.map(e=>({...e, active:false, used:false}));
this.activeExtract=null;
// 敌人(分批刷,主出生区 + 后续威胁刷)
this.enemies=[]; this.bullets=[]; this.projectiles=[]; this.particles=[]; this.decals=[];
this.kills=0; this.threat=0;
this.collected=[];
this.timeLeft=this.world.timeLimit||300;
this.escaped=false; this.death=false; this.result=null;
this.escapeProgress=0; this.paused=false; this.lastTs=0;
this.cam={x:sp.x,y:sp.y,tx:sp.x,ty:sp.y};
this._spawnWave(0);
// 镜头锁定玩家
this._focusCamera(true);
logMsg('🗺 进入战场:'+wType+(this.toCity?'('+this.toCity.id+' 外围)':'(野外)'));
logMsg('🎯 目标:搜刮 '+this.world.lootHint+',前往撤离点撤离。');
// 开局提示
this._centerTip('⚔ 搜打撤 · '+wType,'搜刮 → 战斗 → 撤离,物资死亡会掉落', 2600);
audio.init(); audio.resume();
// 启动主循环(之前遗漏 running=true,导致 loop 首次判断即退出,画面全黑)
this.running = true;
this.lastTs = 0;
requestAnimationFrame(t=>this.loop(t));
},
_pickMapType(){
// 核心主题:战后废弃城池;辅以官道/密林/渡口作为外围搜刮区
const core=['废弃城池','火烧连营','破寨','古战场'];
const t=choice(core);
return t;
},
// ---------- 世界生成:大地图 + 房间/走廊 + 出生点 + 撤离点 ----------
_genWorld(type, cfg){
const TILE=64;
const COLS=26, ROWS=20; // 26*64=1664, 20*64=1280
const W=COLS*TILE, H=ROWS*TILE;
// 用 2D 网格:0=空地 1=墙 2=矮掩体 3=水/湿地 4=火堆 5=可破坏木门
const grid=[];
for(let y=0;y<ROWS;y++){ grid.push(new Array(COLS).fill(1)); }
const rnd=()=>{ this._seed=(this._seed*1103515245+12345)&0x7fffffff; return this._seed/0x7fffffff; };
const seedStr=(type+(cfg&&cfg.defenderCity?cfg.defenderCity.id:'')+(cfg&&cfg.isRaid?'r':'')+(state&&state.turn||0));
this._seed=0; for(const ch of seedStr) this._seed=(this._seed*31+ch.charCodeAt(0))&0xffff;
const rooms=[];
const roomCount = type==='废弃城池'?9 : type==='火烧连营'?8 : type==='破寨'?8 : 10;
// 边界留 1 格
for(let i=0;i<roomCount;i++){
const rw=4+Math.floor(rnd()*5); // 4..8
const rh=3+Math.floor(rnd()*4); // 3..6
const rx=2+Math.floor(rnd()*(COLS-rw-4));
const ry=2+Math.floor(rnd()*(ROWS-rh-4));
rooms.push({x:rx,y:ry,w:rw,h:rh, cx:rx+rw/2|0, cy:ry+rh/2|0});
}
// 挖房间
rooms.forEach(r=>{ for(let y=r.y;y<r.y+r.h;y++) for(let x=r.x;x<r.x+r.w;x++) grid[y][x]=0; });
// 走廊连接(相邻房间)
for(let i=1;i<rooms.length;i++){
const a=rooms[i-1], b=rooms[i];
this._carveCorridor(grid, a.cx, a.cy, b.cx, b.cy, rnd);
}
// 区域特征
const features=[];
if(type==='火烧连营'){ // 大面积火堆,靠近掉血
for(let i=0;i<18;i++){
const rr=rooms[Math.floor(rnd()*rooms.length)];
const fx=rr.x+1+Math.floor(rnd()*(rr.w-2));
const fy=rr.y+1+Math.floor(rnd()*(rr.h-2));
features.push({type:'fire', x:fx*TILE+TILE/2, y:fy*TILE+TILE/2, r:TILE*0.9, dmg:2});
grid[fy][fx]=4;
}
}
if(type==='破寨'||type==='废弃城池'){ // 可破坏木门
rooms.forEach(r=>{
if(rnd()<0.35){
// 在房间一侧中间开一个门
const side=Math.floor(rnd()*4);
let dx=0,dy=0;
if(side===0) dx=r.x; else if(side===1) dx=r.x+r.w-1; else if(side===2) dy=r.y; else dy=r.y+r.h-1;
const px=(dx||r.cx)*TILE+TILE/2, py=(dy||r.cy)*TILE+TILE/2;
features.push({type:'door', x:px, y:py, hp:40, maxHp:40, w:TILE*0.8, h:TILE*0.8});
grid[dy||r.cy][dx||r.cx]=5;
}
});
}
// 出生点:分布在 3 个不同区域(地图一角 + 两处边缘房间)
const spawns=[
{x:rooms[0].cx*TILE+TILE/2, y:rooms[0].cy*TILE+TILE/2, name:'东废墟'},
{x:rooms[Math.floor(rooms.length*0.4)].cx*TILE+TILE/2, y:rooms[Math.floor(rooms.length*0.4)].cy*TILE+TILE/2, name:'中庭'},
{x:rooms[Math.floor(rooms.length*0.75)].cx*TILE+TILE/2, y:rooms[Math.floor(rooms.length*0.75)].cy*TILE+TILE/2, name:'北门'},
];
// 撤离点:地图对角 + 一侧
const extracts=[
{x:rooms[rooms.length-1].cx*TILE+TILE/2, y:rooms[rooms.length-1].cy*TILE+TILE/2, name:'北门马道'},
{x:rooms[Math.floor(rooms.length*0.6)].cx*TILE+TILE/2, y:rooms[Math.floor(rooms.length*0.6)].cy*TILE+TILE/2, name:'西门残道'},
];
// 物资点位:每个房间 1-2 个
const lootSpots=[];
rooms.forEach(r=>{
const n=1+Math.floor(rnd()*2);
for(let i=0;i<n;i++){
lootSpots.push({ x:r.x*TILE+TILE+Math.floor(rnd()*(r.w-2)*TILE),
y:r.y*TILE+TILE+Math.floor(rnd()*(r.h-2)*TILE),
room:r });
}
});
// 掩体(矮墙)
const cover=[];
rooms.forEach(r=>{
if(rnd()<0.5){
cover.push({x:(r.x+1)*TILE, y:r.cy*TILE, w:TILE*0.9, h:14});
}
});
return {
type, TILE, COLS, ROWS, W, H, grid, rooms, features,
spawns, extracts, lootSpots, cover,
timeLimit: 300,
lootHint: type==='废弃城池'?'传国玉玺等高价值宝物':'军资辎重',
// 区域威胁权重(影响刷怪)
ambushRooms: rooms.slice(Math.floor(rooms.length*0.5)),
};
},
_carveCorridor(grid, x1,y1,x2,y2, rnd){
let x=x1, y=y1;
let horiz=rnd()<0.5;
while(x!==x2||y!==y2){
if(horiz && x!==x2){ x+= x<x2?1:-1; }
else if(!horiz && y!==y2){ y+= y<y2?1:-1; }
else if(x!==x2){ x+= x<x2?1:-1; }
else { y+= y<y2?1:-1; }
if(y>=0&&y<grid.length&&x>=0&&x<grid[0].length){ grid[y][x]=0; }
if(y-1>=0&&x>=0&&x<grid[0].length&&grid[y-1][x]===1) grid[y-1][x]=0;
if(x-1>=0&&y>=0&&y<grid.length&&grid[y][x-1]===1) grid[y][x-1]=0;
horiz=!horiz;
}
},
// ---------- 部曲(随行小弟)生成 ----------
_genSquad(lead){
const list=[];
// 最多 3 名随行,按玩家武将统率决定
const n=clamp(Math.floor(lead.stats[0]/30), 1, 3);
const types=['步卒','戟兵','弓手','斥候'];
for(let i=0;i<n;i++){
const t=types[i%types.length];
list.push({
id:'sq'+i,
type:t, x:lead.x||0, y:(lead.y||0)+20+i*16,
vx:0,vy:0, size:13,
hp:40+lead.stats[1]*0.4, maxHp:40+lead.stats[1]*0.4,
speed: t==='斥候'?2.4:1.7,
dmg: t==='戟兵'?12: t==='弓手'?9: 8,
cd:0, atkRange: t==='弓手'?190: 30,
target:null, state:'follow',
hpFlash:0,
});
}
return list;
},
// ---------- 物资:三国主题 + 大金/中金/小金分级 ----------
_genLoot(world){
const items=SDE_LOOT_TABLE;
const out=[];
// 按点位表生成,保证每张地图物资固定
let i=0;
world.lootSpots.forEach(spot=>{
// 该点位的稀有度池(越深入越富)
const _deep=spot.room.index!==undefined?spot.room.index/world.rooms.length:rnd01();
const _rr=rnd01();
let tier;
if(_rr<0.10) tier='大金';
else if(_rr<0.30) tier='中金';
else if(_rr<0.60) tier='小金';
else tier='补给';
const pool=items[tier];
const def=pool[Math.floor(rnd01()*pool.length)];
const px=spot.x, py=spot.y;
out.push({
id:'loot'+(i++),
x:px, y:py,
tier, def,
w:def.weight||1,
size: tier==='大金'?16: tier==='中金'?14: 12,
bob:rnd01()*Math.PI*2,
// 可搜索次数(大金需 2 秒搜索)
searchT: tier==='大金'?2.0: tier==='中金'?1.2: 0.6,
searched:0, searching:false, searchBy:null,
});
});
return out;
},
// ---------- 刷怪 ----------
_spawnWave(phase){
const diff=state.difficulty||DIFFICULTIES.normal;
const mul=diff.atkMul;
// 阶段 0:出生区周围基础敌人
const baseCount=3+Math.floor(mul*2);
for(let i=0;i<baseCount;i++) this._spawnEnemyAt(mul, 'edge');
// 伏兵房
if(this.world.ambushRooms){
this.world.ambushRooms.forEach(r=>{ r._triggered=false; });
}
},
_spawnEnemyAt(mul, where){
const W=this.world.W, H=this.world.H;
let x,y;
if(where==='edge'){
const edge=Math.floor(rnd01()*4);
if(edge===0){x=W+30;y=rnd01()*H;}
else if(edge===1){x=-30;y=rnd01()*H;}
else if(edge===2){x=rnd01()*W;y=-30;}
else {x=rnd01()*W;y=H+30;}
}else{
// 在指定房间内
const rr=where.room||choice(this.world.rooms);
x=(rr.x+0.5+rnd01()*0.4)*this.world.TILE;
y=(rr.y+0.5+rnd01()*0.4)*this.world.TILE;
}
this._spawnEnemy(mul, x, y);
},
_spawnEnemy(mul, x, y){
const types=['步卒','戟兵','弓手','斥候'];
const t=x!==undefined&&y!==undefined?choice(types):choice(types);
const role=t==='弓手'?'弓':t==='斥候'?'斥':'步';
const isElite=this.threat>0.5 && rnd01()<0.12;
const isCommander=this.kills>6 && rnd01()<0.08;
const baseHp = isCommander?120:isElite?70: t==='斥候'?24: t==='弓手'?28: 38;
const e={
x:x||0, y:y||0, vx:0, vy:0, size:isCommander?20:isElite?16:13,
hp:Math.floor(baseHp*mul), maxHp:Math.floor(baseHp*mul),
speed:(t==='斥候'?1.9:t==='弓手'?1.3:t==='戟兵'?1.0:1.35)*(isElite?1.15:1),
type:t, role,
dmg: isCommander?16: isElite?11: t==='戟兵'?12: t==='弓手'?8: 7,
cd:0, atkRange: t==='弓手'?210: t==='戟兵'?40: 28,
facing:0,
state:'hunt', target:null,
fleeAt: t==='斥候'?0.2: t==='弓手'?0.35: 0.15,
ranged: t==='弓手',
side: rnd01()<0.5?1:-1,
hpFlash:0,
// 精英/武将
isElite, isCommander,
name: isCommander?choice(['华雄','颜良','文丑','高顺','张辽']):null,
summonCd: isCommander?180:0,
};
this.enemies.push(e);
return e;
},
// ---------- 输入 ----------
bindInput(){
const keys=this.keys={};
globalThis.addEventListener('keydown',e=>{
keys[e.key]=true;
const prevent=['ArrowUp','ArrowDown','ArrowLeft','ArrowRight',' ','Tab'];
if(prevent.includes(e.key)) e.preventDefault&&e.preventDefault();
if(!this.running) return;
if(e.key==='j'||e.key==='J'||e.key==='f'||e.key==='F') this._inputAtk(true);
if(e.key==='q'||e.key==='Q') this._inputDef(true);
if(e.key===' '||e.key==='Shift') this._doRoll();
if(e.key==='e'||e.key==='E') this._tryInteract();
if(e.key==='g'||e.key==='G') this._dropLoot();
});
globalThis.addEventListener('keyup',e=>{
keys[e.key]=false;
if(!this.running) return;
if(e.key==='j'||e.key==='J'||e.key==='f'||e.key==='F') this._inputAtk(false);
if(e.key==='q'||e.key==='Q') this._inputDef(false);
});
// 鼠标 / 触摸射击与移动
let touchId=null;
this.cv.addEventListener('touchstart',e=>{
e.preventDefault();
const r=this.cv.getBoundingClientRect();
const t=e.changedTouches[0];
touchId=t.identifier;
this.touch={x:t.clientX-r.left, y:t.clientY-r.top};
this.touching=true;
this._tryInteract();
},{passive:false});
this.cv.addEventListener('touchmove',e=>{
e.preventDefault();
for(const t of e.changedTouches){
if(t.identifier===touchId){
const r=this.cv.getBoundingClientRect();
this.touch={x:t.clientX-r.left, y:t.clientY-r.top};
}
}
},{passive:false});
this.cv.addEventListener('touchend',e=>{
e.preventDefault();
this.touching=false;
this.touch=null;
},{passive:false});
this.cv.addEventListener('mousedown',e=>{
const r=this.cv.getBoundingClientRect();
this.touch={x:e.clientX-r.left, y:e.clientY-r.top};
this.touching=true;
this._tryInteract();
});
globalThis.addEventListener('mouseup',()=>{ this.touching=false; });
},
_tryInteract(){
if(!this.running) return;
// 拾取 / 搜索物资
const near=this._nearestPickup();
if(near && near.dist<40){
this._beginSearch(near.p);
return;
}
// 撤离
const ex=this._nearestExtract();
if(ex && ex.dist<60 && ex.e.active){
// 在 update 中处理读条
}
},
_dropLoot(){
// 丢弃一件已携带物资(腾出负重)
if(!this.collected.length) return;
const it=this.collected.pop();
this.invWeight=Math.max(0,this.invWeight-(it.weight||1));
// 掉落在玩家脚下
this.pickups.push({
id:'drop'+Math.random().toString(36).slice(2),
x:this.player.x, y:this.player.y+20,
tier: it.tier||'小金', def:it, w:it.weight||1, size:12,
bob:0, searchT:0, searched:99, searching:false,
});
this._toast('丢弃了 '+it.name);
},
// ---------- 攻击 ----------
_melee(){
if((this.meleeCd||0)>0) return;
const p=this.player;
const isRanged=(p.role==='文');
if(isRanged){ this._shoot(); return; }
this.meleeCd=22;
p.swing=8; // 攻击动画帧
audio.swing&&audio.swing();
const ang=p.facing;
const range=p.attackRange, half=p.attackAngle;
// 判定锥形内敌人
this.enemies.forEach(e=>{
const dx=e.x-p.x, dy=e.y-p.y;
const dist=Math.sqrt(dx*dx+dy*dy);
if(dist<range+e.size){
const a=Math.atan2(dy,dx);
let diff=a-ang; while(diff>Math.PI) diff-=Math.PI*2; while(diff<-Math.PI) diff+=Math.PI*2;
if(Math.abs(diff)<half){
let dmg=p.meleeDmg*(1+(this.charging?0.6:0));
if(e.defending&&!this.charging) dmg*=0.45;
e.hp-=dmg; e.hpFlash=8;
e.vx+=Math.cos(a)*p.knockback*2; e.vy+=Math.sin(a)*p.knockback*2;
this.spawnParticles(e.x,e.y,'#ff6',6);
this._dmgNum(e.x,e.y,dmg);
if(e.hp<=0){ this.kills++; this.threat=clamp(this.threat-0.05,0,1); this._spawnCorpse(e); }
}
}
});
// 可破坏木门
this.world.features.forEach(f=>{
if(f.type!=='door'||f._dead) return;
const dx=f.x-p.x, dy=f.y-p.y;
if(Math.sqrt(dx*dx+dy*dy)<range+f.w/2){
f.hp-=p.meleeDmg*0.8;
if(f.hp<=0){ f._dead=true; this._addDecal(f.x,f.y,'#5a3a1a',40); }
}
});
// 近战挥砍残影
this.particles.push({x:p.x+Math.cos(ang)*range*0.5, y:p.y+Math.sin(ang)*range*0.5,
vx:0,vy:0,life:6,color:'rgba(255,240,200,0.6)',size:range*0.6,arc:true,ang,half});
this.charging=false;
},
_shoot(){
if((this.shootCd||0)>0) return;
const p=this.player;
if(p.ammo<=0){ audio.dry&&audio.dry(); this._toast('箭矢已尽'); return; }
this.shootCd=14; p.ammo--; audio.shoot();
let dx=Math.cos(p.facing), dy=Math.sin(p.facing);
if(this.touch&&this.touching){
const _r=this.cv.getBoundingClientRect();
dx=(this.touch.x+r.left)-(p.x-this.cam.x); // 世界坐标方向
// 用屏幕中心到触摸点
}
this.projectiles.push({
x:p.x, y:p.y, vx:dx*7, vy:dy*7, life:90, dmg:p.rangedDmg, from:'player', size:4,
});
},
_dmgNum(x,y,n){
this.particles.push({x,y,vx:0,vy:-0.6,life:28,color:'#ffe066',txt:Math.round(n)+'',num:true});
},
_spawnCorpse(e){
this._addDecal(e.x,e.y,'#3a1010',20);
},
_addDecal(x,y,color,s){ this.decals.push({x,y,color,life:600,s,max:s}); },
// ---------- 搜索物资 ----------
_nearestPickup(){
let best=null, bd=Infinity;
this.pickups.forEach(p=>{
if(!p||p._taken) return;
const d=Math.sqrt((p.x-this.player.x)**2+(p.y-this.player.y)**2);
if(d<bd){ bd=d; best={p,d}; }
});
return best;
},
_beginSearch(p){
if(this.invWeight>=this.maxWeight){ this._toast('负重已满,无法携带更多物资'); return; }
p.searching=true; p.searchBy='player';
p._searchT=(p._searchT||p.searchT);
},
_finishSearch(p){
p._taken=true;
const def=p.def;
const item={
id:p.id, name:def.name, type:def.type, tier:p.tier,
weight:def.weight||1, rarity:def.rarity||1,
desc:def.desc||'', val:def.val||1,
};
// 大金需要空出对应负重
if(this.invWeight+item.weight<=this.maxWeight){
this.collected.push(item);
this.invWeight+=item.weight;
audio.pickup();
this._toast('获得 '+p.tier+':'+item.name, def.rarity>=3?'gold':'');
logMsg('📦 搜得 '+p.tier+'【'+item.name+'】'+(item.desc?':'+item.desc:''));
// 高价值物品触发危险(吸引敌人)
if(def.rarity>=3){ this.threat=clamp(this.threat+0.25,0,1); this._spawnEnemyAt(state.difficulty.atkMul, 'edge'); }
}else{
this._toast('负重已满,只能看不能带');
}
this.pickups=this.pickups.filter(x=>x!==p);
},
// ---------- 撤离 ----------
_nearestExtract(){
let best=null,bd=Infinity;
this.extracts.forEach(e=>{
const d=Math.sqrt((e.x-this.player.x)**2+(e.y-this.player.y)**2);
if(d<bd){ bd=d; best={e,d}; }
});
return best;
},
_openExtract(){
// 开启撤离点(携带任意物资或清剿足够威胁后)
const ex=this._nearestExtract();
if(!ex) return;
if(!ex.e.active){
ex.e.active=true;
this.activeExtract=ex.e;
audio.ui();
this._centerTip('🚪 撤离点已开启','进入光圈按住 E 或点击撤离读条 3 秒',2200);
logMsg('🚪 撤离点【'+ex.e.name+'】已开启!');
}
},
// ---------- 每帧更新 ----------
update(dt){
if(!this.player||!this.world) return;
const p=this.player;
const dts=dt/16.6667;
const diff=state.difficulty||DIFFICULTIES.normal;
// ---- 输入 → 期望速度 ----
let ix=0, iy=0;
const K=this.keys||{};
if(this.joy){ ix=this.joy.x; iy=this.joy.y; }
else {
if(K['ArrowRight']||K['d']||K['D']) ix+=1;
if(K['ArrowLeft']||K['a']||K['A']) ix-=1;
if(K['ArrowUp']||K['w']||K['W']) iy-=1;
if(K['ArrowDown']||K['s']||K['S']) iy+=1;
}
const il=Math.sqrt(ix*ix+iy*iy);
if(il>1){ ix/=il; iy/=il; }
// 朝向(跟随输入或瞄准)
let aimX=ix, aimY=iy;
if(this.touching&&this.touch){
// 朝向触摸点(屏幕→世界)
aimX=(this.touch.x)-(p.x-this.cam.x);
aimY=(this.touch.y)-(p.y-this.cam.y);
const al=Math.sqrt(aimX*aimX+aimY*aimY)||1; aimX/=al; aimY/=al;
}
if(aimX||aimY) p.facing=Math.atan2(iy||aimY, ix||aimX);
// ---- 翻滚 ----
if(p.rolling>0){
p.rolling-=dts;
p.x+=p.rollVx*dts; p.y+=p.rollVy*dts;
p.invuln=Math.max(p.invuln-dts,0);
}else{
// 正常移动:响应迅速,避免"滑冰"和"泥潭"
const speed=p.defending?1.4:3.8;
const accel=p.defending?0.30:0.42;
const friction=p.defending?0.90:0.93;
const tvx=ix*speed, tvy=iy*speed;
p.vx+=(tvx-p.vx)*accel;
p.vy+=(tvy-p.vy)*accel;
p.vx*=friction; p.vy*=friction;
if(Math.abs(p.vx)<0.02) p.vx=0;
if(Math.abs(p.vy)<0.02) p.vy=0;
let nx=p.x+p.vx*dts, ny=p.y+p.vy*dts;
// 墙体碰撞(AABB 滑动)
const rad=p.size;
nx=this._collideAxis(nx, p.y, rad, 'x');
ny=this._collideAxis(p.x, ny, rad, 'y');
p.x=clamp(nx, rad, this.world.W-rad);
p.y=clamp(ny, rad, this.world.H-rad);
}
if((this.rollCd||0)>0) this.rollCd-=dts;
if(p.invuln>0) p.invuln-=dts;
if((this.meleeCd||0)>0) this.meleeCd-=dts;
if((this.shootCd||0)>0) this.shootCd-=dts;
if(p.swing>0) p.swing-=dts;
if(p.defending){ p.blocking=8; p.stamina=Math.max(0,p.stamina-0.3*dts); }
else { p.defending=false; p.stamina=Math.min(p.maxStamina,p.stamina+0.15*dts); }
// ---- 自动开火(触摸时持续射击)----
if(this.touching&&p.role==='文'&&(this.shootCd||0)<=0) this._shoot();
// ---- 搜索进度 ----
const np=this._nearestPickup();
this.nearPickup=(np&&np.dist<44)?np.p:null;
if(this.nearPickup&&this.nearPickup.searching){
// 只有玩家在附近才推进
const d=Math.sqrt((this.nearPickup.x-p.x)**2+(this.nearPickup.y-p.y)**2);
if(d<44){
this.nearPickup._searchT-=dt/1000;
if(this.nearPickup._searchT<=0) this._finishSearch(this.nearPickup);
}else{
this.nearPickup.searching=false; this.nearPickup._searchT=this.nearPickup.searchT;
}
}else if(this.nearPickup){
this.nearPickup.searching=false; this.nearPickup._searchT=this.nearPickup.searchT;
}
// ---- 伏兵触发(进入未触发房间)----
this.world.rooms.forEach(r=>{
if(r._triggered) return;
if(this.player.x>r.x*this.world.TILE && this.player.x<(r.x+r.w)*this.world.TILE &&
this.player.y>r.y*this.world.TILE && this.player.y<(r.y+r.h)*this.world.TILE){
r._triggered=true;
const remain=this.world.ambushRooms.includes(r);
if(remain){
const cnt=2+Math.floor(this.threat*4);
this._centerTip('⚠ 遭遇伏兵!','清剿 '+cnt+' 名敌军',1600);
for(let i=0;i<cnt;i++) this._spawnEnemyAt(diff.atkMul,{room:r});
audio.alert();
}
}
});
// ---- 敌人 AI ----
this._updateEnemies(dts, diff);
// ---- 部曲 AI ----
this._updateSquad(dts);
// ---- 投射物 ----
this.projectiles=this.projectiles.filter(b=>{
if(!b) return false;
b.x+=b.vx*dts; b.y+=b.vy*dts; b.life-=dts;
if(b.x<0||b.x>this.world.W||b.y<0||b.y>this.world.H) return false;
if(b.from==='player'){
for(const e of this.enemies){
if(Math.sqrt((b.x-e.x)**2+(b.y-e.y)**2)<e.size+b.size){
let dmg=b.dmg*(e.defending?0.5:1);
e.hp-=dmg; e.hpFlash=6;
this.spawnParticles(b.x,b.y,'#ff6',5);
this._dmgNum(e.x,e.y,dmg);
if(e.hp<=0){ this.kills++; this._spawnCorpse(e); }
return false;
}
}
}else{
if(Math.sqrt((b.x-p.x)**2+(b.y-p.y)**2)<p.size+b.size){
if(p.invuln<=0&&!p.defending){ this._hurtPlayer(b.dmg); }
else if(p.defending){ /* 格挡 */ }
return false;
}
this.squad.forEach(s=>{
if(Math.sqrt((b.x-s.x)**2+(b.y-s.y)**2)<s.size+b.size&&s.hp>0){ s.hp-=b.dmg; s.hpFlash=6; }
});
}
return b.life>0;
});
// ---- 火堆/地形伤害 ----
this.world.features.forEach(f=>{
if(f.type==='fire'&&!f._dead){
const d=Math.sqrt((f.x-p.x)**2+(f.y-p.y)**2);
if(d<f.r+p.size){
if(p.invuln<=0) this._hurtPlayer(f.dmg*dts/16);
}
}
});
// ---- 粒子 ----
this.particles.forEach(pt=>{
if(pt.num){ pt.y+=pt.vy*dts; pt.life-=dts; return; }
pt.x+=pt.vx*dts; pt.y+=pt.vy*dts; pt.vx*=0.9; pt.vy*=0.9; pt.life-=dts;
});
this.particles=this.particles.filter(pt=>pt.life>0);
this.decals.forEach(d=>d.life--);
this.decals=this.decals.filter(d=>d.life>0);
this.enemies=this.enemies.filter(e=>e.hp>0);
this.squad=this.squad.filter(s=>s.hp>0);
// ---- 动态补怪(威胁压迫)----
if(this.enemies.length<3 && this.threat<0.9 && this.timer>120){
const cap=3+Math.floor(this.threat*5);
if(this.enemies.length<cap && rnd01()<0.02) this._spawnEnemyAt(diff.atkMul,'edge');
}
// 武将召唤小兵
this.enemies.forEach(e=>{
if(e.isCommander&&(e.summonCd||0)<=0&&this.enemies.length<8){
e.summonCd=300;
for(let i=0;i<2;i++){
const m=this._spawnEnemy(diff.atkMul*0.7, e.x+(i?20:-20), e.y+20);
if(m) m.size=11;
}
}
if(e.summonCd>0) e.summonCd-=dts;
});
// ---- 撤离点开启条件:携带物资 / 清剿 / 时间过半 ----
const hasLoot=this.collected.length>0||this.invWeight>0;
const cleared=this.enemies.length<=2&&this.threat<0.6;
if(!this.activeExtract && (hasLoot||cleared||this.timeLeft<this.world.timeLimit*0.4)) this._openExtract();
// ---- 撤离读条 ----
const ex=this._nearestExtract();
let inExtract=false;
if(ex&&ex.e.active&&ex.dist<56){
inExtract=true;
this.escapeProgress+=dt/1000;
if(this.escapeProgress>=3){ this._doEscape(); }
}else{
this.escapeProgress=Math.max(0,this.escapeProgress-dt/1500);
}
// ---- 计时 ----
this.timeLeft=Math.max(0,this.world.timeLimit-this.timer/1000);
if(this.timeLeft<=0){ this._doTimeout(); }
// ---- 镜头跟随 ----
this._focusCamera(false, dts);
// ---- 死亡 ----
if(p.hp<=0&&!this.death){ this._doDeath(); }
// ---- HUD 刷新 ----
this._updateHUD();
},
_updateEnemies(dts, diff){
const p=this.player;
this.enemies.forEach(e=>{
const dx=p.x-e.x, dy=p.y-e.y;
const l=Math.sqrt(dx*dx+dy*dy)||1;
e.facing=Math.atan2(dy,dx);
if(e.hpFlash>0) e.hpFlash-=dts;
// 发现部曲则攻击部曲
let target=p;
let td=l;
this.squad.forEach(s=>{
if(s.hp<=0) return;
const d=Math.sqrt((s.x-e.x)**2+(s.y-e.y)**2);
if(d<td){ td=d; target=s; }
});
if(e.ranged){ // 弓手:保持距离
const ideal=e.atkRange-40;
if(td<ideal-30){ e.x-=dx/td*e.speed*dts; e.y-=dy/td*e.speed*dts; }
else if(td>ideal+30){ e.x+=dx/td*e.speed*0.6*dts; e.y+=dy/td*e.speed*0.6*dts; }
e.cd-=dts;
if(td<e.atkRange&&e.cd<=0){
const a=Math.atan2(target.y-e.y,target.x-e.x);
this.projectiles.push({x:e.x,y:e.y,vx:Math.cos(a)*4,vy:Math.sin(a)*4,life:110,dmg:e.dmg*0.7,from:'enemy',size:4});
e.cd=90; audio.enemyShoot&&audio.enemyShoot();
}
}else if(e.type==='斥候'){ // 侧翼包抄
const px=-dy/td, py=dx/td;
e.x+=(dx/td*0.6+px*0.55*e.side)*e.speed*dts;
e.y+=(dy/td*0.6+py*0.55*e.side)*e.speed*dts;
e.cd-=dts;
if(td<e.atkRange&&e.cd<=0){
if(target===p&&p.invuln<=0&&!p.defending) this._hurtPlayer(e.dmg);
else if(target!==p) target.hp-=e.dmg;
e.cd=40; audio.hit();
}
}else{ // 戟兵/步卒 冲锋
// 绕过墙体(简单分离:朝玩家直线,碰撞交给全局)
const tvx=dx/td*e.speed, tvy=dy/td*e.speed;
e.vx+=(tvx-e.vx)*0.2; e.vy+=(tvy-e.vy)*0.2;
e.vx*=0.85; e.vy*=0.85;
let nx=e.x+e.vx*dts, ny=e.y+e.vy*dts;
nx=this._collideAxis(nx,e.y,e.size,'x');
ny=this._collideAxis(e.x,ny,e.size,'y');
e.x=clamp(nx,0,this.world.W); e.y=clamp(ny,0,this.world.H);
e.cd-=dts;
if(td<e.atkRange&&e.cd<=0){
if(target===p){
if(p.invuln<=0&&!p.defending) this._hurtPlayer(e.dmg);
else if(p.defending){ /* 被格挡 */ }
}else{ target.hp-=e.dmg; }
e.cd=50; audio.hit();
this.spawnParticles(target.x,target.y,'#f55',5);
}
}
// 武将精英光环
if(e.isCommander&&this.timer%4<2){
this.particles.push({x:e.x,y:e.y,vx:0,vy:0,life:4,color:'rgba(255,80,80,0.4)',size:e.size+10});
}
// 低血量退却
const ratio=e.hp/e.maxHp;
if(ratio<e.fleeAt&&!e.ranged&&!e.isCommander){
e.x-=dx/td*e.speed*1.2*dts; e.y-=dy/td*e.speed*1.2*dts;
}
});
},
_updateSquad(dts){
const p=this.player;
this.squad.forEach((s,i)=>{
// 跟随玩家,保持阵型
const ax=p.x+Math.cos(p.facing+Math.PI*0.6+i*0.6)*55;
const ay=p.y+Math.sin(p.facing+Math.PI*0.6+i*0.6)*55;
const dx=ax-s.x, dy=ay-s.y;
const l=Math.sqrt(dx*dx+dy*dy)||1;
if(l>6){
s.x+=dx/l*Math.min(s.speed,l/8)*dts;
s.y+=dy/l*Math.min(s.speed,l/8)*dts;
}
s.x=this._collideAxis(s.x,s.y,s.size,'x');
s.y=this._collideAxis(s.x,s.y,s.size,'y');
// 找最近敌人攻击
let best=null,bd=9999;
this.enemies.forEach(e=>{ const d=Math.sqrt((e.x-s.x)**2+(e.y-s.y)**2); if(d<bd){bd=d;best=e;} });
if(best&&bd<s.atkRange+10&&(s.cd||0)<=0){
if(s.ranged){
const a=Math.atan2(best.y-s.y,best.x-s.x);
this.projectiles.push({x:s.x,y:s.y,vx:Math.cos(a)*4,vy:Math.sin(a)*4,life:90,dmg:s.dmg*0.6,from:'squad',size:3});
}else{
best.hp-=s.dmg; best.hpFlash=5;
this.spawnParticles(best.x,best.y,'#ff8',4);
if(best.hp<=0){ this.kills++; }
}
s.cd=s.ranged?70:38;
}
if(s.cd>0) s.cd-=dts;
if(s.hpFlash>0) s.hpFlash-=dts;
});
},
_collideAxis(nx,ny,rad,axis){
const T=this.world.TILE;
const cands=[];
const gx=Math.floor(nx/T), gy=Math.floor(ny/T);
for(let yy=gy-1;yy<=gy+1;yy++)for(let xx=gx-1;xx<=gx+1;xx++){
if(yy<0||yy>=this.world.ROWS||xx<0||xx>=this.world.COLS) continue;
const v=this.world.grid[yy][xx];
if(v===1){ cands.push({x:xx*T,y:yy*T,w:T,h:T}); } // 墙
}
// 掩体(矮,可越过但减速)
if(axis==='x'){
for(const c of cands){
if(nx+rad>c.x&&nx-rad<c.x+c.w&&ny+rad>c.y&&ny-rad<c.y+c.h){
nx= nx< c.x+T/2 ? c.x-rad : c.x+c.w+rad;
}
}
}else{
for(const c of cands){
if(nx+rad>c.x&&nx-rad<c.x+c.w&&ny+rad>c.y&&ny-rad<c.y+c.h){
ny= ny< c.y+T/2 ? c.y-rad : c.y+c.h+rad;
}
}
}
return axis==='x'?nx:ny;
},
_hurtPlayer(dmg){
const p=this.player;
if(p.invuln>0) return;
p.hp-=dmg;
p.invuln=30;
p.hpFlash=8;
this.spawnParticles(p.x,p.y,'#f55',10);
audio.hit();
// 镜头抖动
this.cam.shake=10;
},
spawnParticles(x,y,color,n){
for(let i=0;i<n;i++){
const a=rnd01()*Math.PI*2, s=1+rnd01()*3;
this.particles.push({x,y,vx:Math.cos(a)*s,vy:Math.sin(a)*s,life:14+rnd01()*12,color,size:2+rnd01()*2});
}
},
// ---------- 镜头 ----------
_focusCamera(snap, dts){
const p=this.player;
const vw=this.viewW, vh=this.viewH;
let tx=p.x-vw/2, ty=p.y-vh/2;
// 限制镜头在世界内(若世界小于视口则居中)
const limitX=Math.max(0,this.world.W-vw), limitY=Math.max(0,this.world.H-vh);
tx=clamp(tx,0,limitX||0); ty=clamp(ty,0,limitY||0);
if(snap){
this.cam.x=tx; this.cam.y=ty;
}else{
// 相机跟踪更紧(0.25 = 较快跟随,减少眩晕感)
const kk=clamp(dts*0.25,0,1);
this.cam.x+=(tx-this.cam.x)*kk;
this.cam.y+=(ty-this.cam.y)*kk;
}
if(this.cam.shake>0){
this.cam.x+=(rnd01()-0.5)*this.cam.shake;
this.cam.y+=(rnd01()-0.5)*this.cam.shake;
this.cam.shake*=0.85;
if(this.cam.shake<0.5) this.cam.shake=0;
}
},
// ---------- 绘制 ----------
draw(){
if(!this.ctx||!this.world) return;
const ctx=this.ctx; const w=this.viewW, h=this.viewH;
if(!w||!h) return;
const T=this.world.TILE;
const camx=this.cam.x, camy=this.cam.y;
ctx.save();
ctx.clearRect(0,0,w,h);
// 背景(深墨)
ctx.fillStyle='#111a2a'; ctx.fillRect(0,0,w,h);
// 只绘制视口内 tile
const x0=clamp(Math.floor(camx/T)-1,0,this.world.COLS-1);
const y0=clamp(Math.floor(camy/T)-1,0,this.world.ROWS-1);
const x1=clamp(Math.ceil((camx+w)/T)+1,0,this.world.COLS);
const y1=clamp(Math.ceil((camy+h)/T)+1,0,this.world.ROWS);
for(let yy=y0;yy<y1;yy++){
for(let xx=x0;xx<x1;xx++){
const v=this.world.grid[yy][xx];
const px=xx*T-camx, py=yy*T-camy;
if(v===1){ // 城墙/废墟
ctx.fillStyle='#2a2530'; ctx.fillRect(px,py,T,T);
ctx.fillStyle='#3a3340'; ctx.fillRect(px+2,py+2,T-4,T-4);
ctx.fillStyle='#1c1822';
ctx.fillRect(px+8,py+10,T*0.3,T*0.4);
ctx.fillRect(px+T*0.55,py+T*0.2,T*0.3,T*0.4);
}else{ // 地面
const dark2=((xx+yy)&1)?'#2c3444':'#27303f';
ctx.fillStyle=dark2; ctx.fillRect(px,py,T,T);
// 碎石/瓦砾
const r=(xx*73+yy*31)&7;
ctx.fillStyle='rgba(0,0,0,0.18)';
ctx.fillRect(px+r*3%T,py+(r*5)%T,3,3);
}
if(v===5){ // 木门(未破坏)
ctx.fillStyle='#6a4422'; ctx.fillRect(px,py,T,T);
ctx.strokeStyle='#3a2410'; ctx.lineWidth=2;
ctx.beginPath(); ctx.moveTo(px+T/2,py); ctx.lineTo(px+T/2,py+T); ctx.stroke();
ctx.beginPath(); ctx.moveTo(px,py+T/2); ctx.lineTo(px+T,py+T/2); ctx.stroke();
}
}
}
// 掩体
this.world.cover.forEach(c=>{
const px=c.x-camx, py=c.y-camy;
if(px<-c.w||py<-20||px>w||py>h) return;
ctx.fillStyle='#4a4230'; ctx.fillRect(px,py,c.w,c.h);
ctx.strokeStyle='#6a5a30'; ctx.strokeRect(px,py,c.w,c.h);
});
// 区域提示(房间名,调试用)
// 火堆
this.world.features.forEach(f=>{
if(f.type!=='fire'||f._dead) return;
const px=f.x-camx, py=f.y-camy;
const pulse=0.5+0.5*Math.sin(this.timer*0.1);
ctx.fillStyle=`rgba(255,${80+pulse*60},0,${0.4+pulse*0.2})`;
ctx.beginPath(); ctx.arc(px,py,f.r,0,Math.PI*2); ctx.fill();
ctx.fillStyle=`rgba(255,200,80,${0.6+pulse*0.3})`;
ctx.beginPath(); ctx.arc(px,py,f.r*0.5,0,Math.PI*2); ctx.fill();
});
// 出生点标记(已用,淡)
// 撤离点
this.extracts.forEach(e=>{
if(!e.active) return;
const px=e.x-camx, py=e.y-camy;
const pulse=0.5+0.5*Math.sin(this.timer*0.12);
ctx.save();
ctx.fillStyle=`rgba(120,220,140,${0.15+pulse*0.12})`;
ctx.beginPath(); ctx.arc(px,py,52,0,Math.PI*2); ctx.fill();
ctx.strokeStyle=`rgba(140,255,170,${0.6+pulse*0.4})`;
ctx.lineWidth=3; ctx.setLineDash([8,6]);
ctx.beginPath(); ctx.arc(px,py,48,0,Math.PI*2); ctx.stroke(); ctx.setLineDash([]);
// 门楼
ctx.fillStyle='#2a6a32';
roundRect(ctx,px-18,py-22,36,24,3); ctx.fill();
ctx.fillStyle='#c9a227';
ctx.fillRect(px-12,py-14,24,14);
ctx.fillStyle='#ffe066'; ctx.fillRect(px-9,py-11,18,8);
ctx.fillStyle='#5f5'; ctx.font='11px sans-serif'; ctx.textAlign='center';
ctx.fillText('撤离',px,py-26);
ctx.restore();
});
// 血迹 decal
this.decals.forEach(d=>{
const px=d.x-camx, py=d.y-camy;
ctx.fillStyle=d.color; ctx.globalAlpha=clamp(d.life/400,0,0.5);
ctx.beginPath(); ctx.ellipse(px,py,d.s,d.s*0.6,0,0,Math.PI*2); ctx.fill();
ctx.globalAlpha=1;
});
// 物资
this.pickups.forEach(p=>{
const px=p.x-camx, py=p.y-camy;
if(px<-30||py<-30||px>w+30||py>h+30) return;
const bob=Math.sin(this.timer*0.08+p.bob)*2;
ctx.save();
ctx.translate(px,py+bob);
// 光晕
const col=SDE_TIER_COLOR[p.tier]||'#c9a227';
ctx.fillStyle=col; ctx.globalAlpha=p.searching?0.35:0.18;
ctx.beginPath(); ctx.arc(0,0,p.size*1.9,0,Math.PI*2); ctx.fill();
ctx.globalAlpha=1;
// 主体
ctx.fillStyle=col;
roundRect(ctx,-p.size*0.7,-p.size*0.6,p.size*1.4,p.size*1.2,p.size*0.2); ctx.fill();
ctx.strokeStyle='rgba(0,0,0,0.7)'; ctx.lineWidth=1.5;
ctx.strokeRect(-p.size*0.7,-p.size*0.6,p.size*1.4,p.size*1.2);
// 图标
ctx.fillStyle='#fff'; ctx.font='bold 9px sans-serif'; ctx.textAlign='center'; ctx.textBaseline='middle';
ctx.fillText(p.def.ico||'?',0,-1);
ctx.textBaseline='alphabetic';
// 名称
ctx.fillStyle='#fff'; ctx.font='9px sans-serif';
ctx.fillText(p.def.name,0,p.size+10);
// 稀有度边框
if(p.def.rarity>=3){
ctx.strokeStyle='#ffe066'; ctx.lineWidth=2;
ctx.strokeRect(-p.size*0.7-2,-p.size*0.6-2,p.size*1.4+4,p.size*1.2+4);
}
ctx.restore();
// 搜索进度环
if(p.searching){
const r=clamp(1-(p._searchT||0)/(p.searchT||1),0,1);
ctx.save();
ctx.strokeStyle='rgba(255,255,255,0.4)'; ctx.lineWidth=3;
ctx.beginPath(); ctx.arc(px,py+bob,p.size+6,0,Math.PI*2); ctx.stroke();
ctx.strokeStyle='#7f7'; ctx.beginPath();
ctx.arc(px,py+bob,p.size+6,-Math.PI/2,-Math.PI/2+r*Math.PI*2); ctx.stroke();
ctx.restore();
}
});
// 敌人
this.enemies.forEach(e=>{
const px=e.x-camx, py=e.y-camy;
if(px<-30||py<-30||px>w+30||py>h+30) return;
const flash=e.hpFlash>0?'rgba(255,255,255,0.5)':'rgba(0,0,0,0)';
window.Sprite.unit(ctx, px, py, {
type:e.type, role:e.role, force:(this.toCity&&this.toCity.force)||'袁绍',
facing:e.facing, size:e.size, hpRatio:e.hp/e.maxHp,
_t:this.timer, seed:e.type+e.size, flash,
});
// 武将名
if(e.isCommander){
ctx.fillStyle='#f55'; ctx.font='bold 10px sans-serif'; ctx.textAlign='center';
ctx.fillText('★ '+e.name,px,py-e.size-12);
}
// 血条
const ratio=e.hp/e.maxHp;
ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(px-e.size,py-e.size-8,e.size*2,3);
ctx.fillStyle=ratio>0.5?'#5f5':'#f55';
ctx.fillRect(px-e.size,py-e.size-8,e.size*2*ratio,3);
});
// 部曲
this.squad.forEach(s=>{
const px=s.x-camx, py=s.y-camy;
window.Sprite.unit(ctx, px, py, {
type:s.type, role:s.type==='弓手'?'弓':'步', force:'player',
facing:Math.atan2(this.player.y-s.y,this.player.x-s.x),
size:s.size, hpRatio:s.hp/s.maxHp, _t:this.timer, seed:'sq'+s.type,
});
ctx.fillStyle='rgba(0,0,0,0.6)'; ctx.fillRect(px-s.size,py-s.size-7,s.size*2,3);
ctx.fillStyle='#5af'; ctx.fillRect(px-s.size,py-s.size-7,s.size*2*(s.hp/s.maxHp),3);
});
// 玩家
const p=this.player;
const pflash=(p.invuln>0&&Math.floor(this.timer/3)%2)?'rgba(255,255,255,0.6)':'null';
const px=p.x-camx, py=p.y-camy;
window.Sprite.player(ctx, px, py, {
type:p.role==='文'?'弓':p.role==='君'?'骑兵':'戟兵',
role:p.role, force:state.playerForce,
facing:p.facing, size:p.size, hpRatio:p.hp/p.maxHp,
_t:this.timer, seed:'player', flash:pflash,
});
// 翻滚残影
if(p.rolling>0){
ctx.fillStyle='rgba(120,200,255,0.4)';
ctx.beginPath(); ctx.arc(px,py,p.size*0.9,0,Math.PI*2); ctx.fill();
}
// 格挡盾
if(p.defending){
const sx=px+Math.cos(p.facing)*p.size, sy=py+Math.sin(p.facing)*p.size;
ctx.strokeStyle='#c9a227'; ctx.lineWidth=3;
ctx.beginPath(); ctx.arc(sx,sy,p.size*0.8,0,Math.PI*2); ctx.stroke();
}
// 投射物
this.projectiles.forEach(b=>{
if(!b) return;
const bx=b.x-camx, by=b.y-camy;
ctx.fillStyle=b.from==='player'?'#ff6':b.from==='squad'?'#7cf':'#f55';
ctx.beginPath(); ctx.arc(bx,by,b.size,0,Math.PI*2); ctx.fill();
ctx.strokeStyle=b.from==='player'?'rgba(255,220,100,0.5)':'rgba(255,80,80,0.5)';
ctx.lineWidth=2;
ctx.beginPath(); ctx.moveTo(bx-b.vx*1.2,by-b.vy*1.2); ctx.lineTo(bx,by); ctx.stroke();
});
// 粒子
this.particles.forEach(pt=>{
if(pt.num){
ctx.fillStyle=pt.color; ctx.font='bold 11px sans-serif'; ctx.textAlign='center';
ctx.globalAlpha=clamp(pt.life/28,0,1);
ctx.fillText(pt.txt,pt.x-camx,pt.y-camy);
ctx.globalAlpha=1;
return;
}
ctx.fillStyle=pt.color; ctx.globalAlpha=clamp(pt.life/20,0,1);
if(pt.arc){
ctx.save();
ctx.translate(pt.x-camx,pt.y-camy); ctx.rotate(pt.ang);
ctx.fillRect(-pt.size/2,-pt.size/2,pt.size,pt.size*0.35);
ctx.restore();
}else{
ctx.fillRect(pt.x-camx-2,pt.y-camy-2,pt.size,pt.size);
}
ctx.globalAlpha=1;
});
// 搜索提示
if(this.nearPickup&&!this.nearPickup._taken){
const npx=this.nearPickup.x-camx, npy=this.nearPickup.y-camy;
ctx.fillStyle='#ffe066'; ctx.font='11px sans-serif'; ctx.textAlign='center';
const t=this.nearPickup.searching?('搜索中…'+Math.ceil(this.nearPickup._searchT)+'s'):('点击/按E搜刮【'+this.nearPickup.def.name+'】');
ctx.fillText(t,npx,npy-this.nearPickup.size-16);
}
// 撤离读条
const ex=this._nearestExtract();
if(ex&&ex.e.active&&ex.dist<56){
const bx=ex.e.x-camx-40, by=ex.e.y-camy+40, bw=80;
ctx.fillStyle='rgba(0,0,0,0.7)'; ctx.fillRect(bx-2,by-2,bw+4,14);
ctx.fillStyle='rgba(120,220,140,0.95)'; ctx.fillRect(bx,by,bw*clamp(this.escapeProgress/3,0,1),10);
ctx.strokeStyle='#7f7'; ctx.strokeRect(bx,by,bw,10);
ctx.fillStyle='#fff'; ctx.font='10px sans-serif'; ctx.textAlign='center';
ctx.fillText('撤离中',ex.e.x-camx,by+9);
}
ctx.restore();
// 小地图
this._drawMinimap();
},
_drawMinimap(){
const cv=document.getElementById('sdeMinimapCv');
if(!cv) return;
const ctx=cv.getContext('2d');
const W=cv.width, H=cv.height;
ctx.clearRect(0,0,W,H);
ctx.fillStyle='rgba(10,14,27,0.9)';
roundRect(ctx,0,0,W,H,6); ctx.fill();
const sx=W/this.world.W, sy=H/this.world.H;
// 墙体
ctx.fillStyle='#3a3340';
for(let y=0;y<this.world.ROWS;y++)for(let x=0;x<this.world.COLS;x++){
if(this.world.grid[y][x]===1) ctx.fillRect(x*sx|0,y*sy|0,Math.max(1,sx|0),Math.max(1,sy|0));
}
// 撤离点
this.extracts.forEach(e=>{
ctx.fillStyle=e.active?'#5f5':'#888';
ctx.fillRect(e.x*sx|0,e.y*sy|0,3,3);
});
// 物资
this.pickups.forEach(p=>{
ctx.fillStyle=(SDE_TIER_COLOR[p.tier]||'#c9a227');
ctx.fillRect(p.x*sx|0,p.y*sy|0,2,2);
});
// 敌人
ctx.fillStyle='#f55';
this.enemies.forEach(e=>ctx.fillRect(e.x*sx|0,e.y*sy|0,2,2));
// 部曲
ctx.fillStyle='#5af';
this.squad.forEach(s=>ctx.fillRect(s.x*sx|0,s.y*sy|0,2,2));
// 玩家
const p=this.player;
ctx.fillStyle='#ffe066';
ctx.beginPath(); ctx.arc(p.x*sx,p.y*sy,3,0,Math.PI*2); ctx.fill();
// 视口框
ctx.strokeStyle='rgba(255,224,102,0.5)'; ctx.lineWidth=1;
ctx.strokeRect(this.cam.x*sx,this.cam.y*sy,this.viewW*sx,this.viewH*sy);
},
// ---------- HUD ----------
_updateHUD(){
const p=this.player;
if(!p) return;
const $=(id)=>document.getElementById(id);
const hpFill=$('sdeHpFill'), hpTxt=$('sdeHpTxt');
if(hpFill) hpFill.style.width=clamp(p.hp/p.maxHp*100,0,100)+'%';
if(hpTxt) hpTxt.textContent=Math.ceil(p.hp)+'/'+Math.ceil(p.maxHp);
const stFill=$('sdeStamFill');
if(stFill) stFill.style.width=clamp(p.stamina/p.maxStamina*100,0,100)+'%';
const th=$('sdeThreat');
if(th){ th.textContent='威胁 '+Math.ceil(this.threat*100)+'%'; th.style.color=this.threat>0.66?'#f55':this.threat>0.33?'#fd3':'#5f5'; }
// 立绘
const port=$('sdePortrait');
if(port&&this.leader&&!port._done){
try{
const im=new Image();
im.src=window.Portrait.get(this.leader);
im.onload=()=>{ port.style.backgroundImage='url('+im.src+')'; port._done=true; };
}catch(e){}
}
// 计时
const t=$('sdeTimer');
if(t){ const s=Math.ceil(this.timeLeft); t.textContent=Math.floor(s/60)+':'+((s%60)+'').padStart(2,'0'); t.style.color=s<60?'#f55':'#ffe066'; }
// 目标
const obj=$('sdeObj');
if(obj){
if(this.activeExtract) obj.textContent='目标:前往撤离点('+this.invWeight+'/'+this.maxWeight+')';
else if(this.collected.length>0) obj.textContent='目标:已搜得物资,撤离点即将开启';
else obj.textContent='目标:搜刮物资(大金/中金/小金)';
}
// 物资栏
const loot=$('sdeLoot');
if(loot){
if(!this.collected.length){ loot.className='empty'; loot.textContent='未携带物资(负重 0/'+this.maxWeight+')'; }
else{
loot.className='has';
loot.innerHTML=this.collected.map((c,i)=>`<span class="lt ${c.tier==='大金'?'big':c.tier==='中金'?'mid':''}" title="${c.desc||c.name}">${c.def?c.def.ico:''}${c.name}<i>${c.weight}</i></span>`).join('');
}
}
// 部曲
const sq=$('sdeSquad');
if(sq){
sq.innerHTML=this.squad.map(s=>`<div class="sq"><span class="sq-ico">${s.type[0]}</span><div class="sq-bar"><i style="width:${clamp(s.hp/s.maxHp*100,0,100)}%"></i></div></div>`).join('');
}
// 拾取提示
const pk=$('sdePickupTip');
if(pk){
if(this.nearPickup&&!this.nearPickup._taken){
pk.classList.remove('hidden');
pk.textContent=(this.nearPickup.searching?'搜索中…':'点击 / 按 E 搜刮')+':'+this.nearPickup.def.name;
}else{ pk.classList.add('hidden'); }
}
},
_toast(msg){ this._centerTip('',msg,1400, true); },
_centerTip(title, sub, ms, isToast){
const el=document.getElementById(isToast?'sdeCenterTip':'sdeCenterTip');
if(!el) return;
el.classList.remove('hidden');
el.innerHTML=title?'<b>'+title+'</b>'+(sub?'<br><span>'+sub+'</span>':''):'<span>'+sub+'</span>';
clearTimeout(this._tipTm);
this._tipTm=setTimeout(()=>el.classList.add('hidden'),ms||2000);
},
// ---------- 结束处理 ----------
_doEscape(){
if(this.escaped) return;
this.escaped=true; this.running=false;
audio.fanfare();
const survived=clamp(this.player.hp/this.player.maxHp,0,1);
const diff=state.difficulty||DIFFICULTIES.normal;
const timeBonus=clamp(this.timeLeft/this.world.timeLimit,0,1);
// 战利品价值(大金加分)
const val=this.collected.reduce((s,c)=>s+(c.val||1)*(c.tier==='大金'?5:c.tier==='中金'?2.5:1),0);
const score=Math.floor(this.kills*15*survived*2 + timeBonus*120 + val*8 + (this.squad.filter(s=>s.hp>0).length)*30);
const goldBonus=Math.floor((this.kills*12+score*0.3+val*4)*diff.resMul);
state.resources.gold+=goldBonus;
// 入库存(保留更高稀有度)
const slotOf={剑:'weapon',枪:'weapon',戟:'weapon',弓:'weapon',甲:'armor',盔:'helm',马:'horse',书:'book',宝:'treasure'};
this.collected.forEach(it=>{
const h=this.leader; if(!h) return;
const slot=slotOf[it.type];
if(slot&&(!h[slot]||(it.rarity||0)>=(h[slot].rarity||0))) h[slot]=it;
});
const rare=this.collected.filter(i=>i.rarity>=3).length;
const big=this.collected.filter(i=>i.tier==='大金').length;
const mid=this.collected.filter(i=>i.tier==='中金').length;
const small=this.collected.filter(i=>i.tier==='小金').length;
const won=this.kills>=3&&survived>0.5;
if(won&&this.toCity) doBattle(this.leader,this.toCity,false);
logMsg(`✅ 撤离成功!评分 ${score}|击杀 ${this.kills}|存活 ${(survived*100|0)}%|用时 ${Math.floor((this.world.timeLimit-this.timeLeft)/60)}分${Math.floor(this.world.timeLimit-this.timeLeft)%60}秒`);
logMsg(`📦 带出:大金 ${big} 中金 ${mid} 小金 ${small}|🪙 黄金 +${goldBonus}`+(rare?`|缴获稀有装备 ${rare} 件`:''));
switchView('map');
setTimeout(()=>{ ui.renderTop(); view.render(); ui.renderLog(); },100);
},
_doTimeout(){
if(this.escaped) return;
this.escaped=true; this.running=false;
audio.defeat();
logMsg('⏰ 战斗超时,未能撤离,物资全部遗落。');
switchView('map');
setTimeout(()=>{ ui.renderTop(); view.render(); ui.renderLog(); },100);
},
_doDeath(){
if(this.death) return;
this.death=true; this.running=false;
audio.defeat();
// 死亡掉落:身上装备 + 随行部曲全灭
const h=this.leader;
let dropN=0;
if(h){
['weapon','armor','helm','horse','book','treasure'].forEach(k=>{
if(h[k]&&Math.random()<0.5){ h[k]=null; dropN++; }
});
h.troops=Math.floor(h.troops*0.5);
}
this.squad.forEach(s=>s.hp=0);
logMsg(`💀 ${h?h.name:'主将'} 阵亡!${dropN?('损失装备 '+dropN+' 件,'):''}随行部曲全灭,物资遗落。`);
switchView('map');
setTimeout(()=>{ ui.renderTop(); view.render(); ui.renderLog(); },100);
},
// ---------- 尺寸 ----------
resize(){
const box=ui.$('battleView');
if(!box||!this.cv) return;
box.style.display='flex';
box.offsetHeight;
let w=box.clientWidth, h=box.clientHeight;
if(!w||!h){
const rect=box.getBoundingClientRect();
w=rect.width||(globalThis.innerWidth||800);
h=rect.height||(globalThis.innerHeight||600);
}
w=Math.max(w,320); h=Math.max(h,240);
const dpr=globalThis.devicePixelRatio||1;
try{
this.cv.width=Math.round(w*dpr); this.cv.height=Math.round(h*dpr);
this.cv.style.width=w+'px'; this.cv.style.height=h+'px';
this.cv.style.position='absolute';
this.cv.style.left='0';
this.cv.style.top='0';
this.ctx.setTransform(dpr,0,0,dpr,0,0);
}catch(e){ return; }
this.viewW=w; this.viewH=h;
if((w<400||h<300) && !this._resizeRetry){
this._resizeRetry=true;
globalThis.requestAnimationFrame(()=>{ this._resizeRetry=false; this.resize(); });
}
},
};
// ---------- 视图切换 ----------
function switchView(name){
state.view = name;
const mapView = document.getElementById('mapView');
const battleView = document.getElementById('battleView');
if(!mapView || !battleView) return;
if(name==='battle'){
mapView.classList.remove('active');
mapView.style.display = 'none';
battleView.classList.add('active');
battleView.style.display = 'flex';
battleView.offsetHeight;
if(battle && battle.resize){
battle.resize();
globalThis.requestAnimationFrame(()=>{ if(battle.resize) battle.resize(); });
}
}else{
battleView.classList.remove('active');
battleView.style.display = 'none';
mapView.classList.add('active');
mapView.style.display = 'flex';
if(view && view.resize) view.resize();
}
}
// ---------- 战利品结算(简化,战斗内已完成核心逻辑)----------
loot = {
start(data){
// 预留:可在战斗结束后弹出战利品清单
if(!data) return;
},
};
// ---------- 标题屏 ----------
let titleSel = {scenario:null, force:null, diff:null};
function showTitle(){
const ts = document.getElementById('titleScreen');
const app = document.getElementById('app');
if(ts) ts.style.display = 'flex';
if(app) app.style.display = 'none';
titleSel = {scenario:null, force:null, diff:null};
document.getElementById('blkScenario').style.display = 'block';
document.getElementById('blkForce').style.display = 'none';
document.getElementById('blkDiff').style.display = 'none';
document.getElementById('btnNew').style.display = 'none';
// 标题立绘
const cast=[
{name:'曹操', force:'player', portrait:'ruler', stats:[96,72,91,94,95]},
{name:'郭嘉', force:'player', portrait:'strategist', stats:[78,30,98,75,88]},
{name:'许褚', force:'player', portrait:'warrior', stats:[75,98,35,30,62]},
];
const ids=['ptStrategist','ptWarrior','ptRuler'];
cast.forEach((h,i)=>{
const img=document.getElementById(ids[i]);
if(!img) return;
try{ img.src = window.Portrait.get(h); }
catch(e){ requestAnimationFrame(()=>{ try{ img.src=window.Portrait.get(h); }catch(err){} }); }
});
renderScenarioList();
}
function renderScenarioList(){
const box = document.getElementById('scenarioList');
box.innerHTML='';
SCENARIOS.forEach(s=>{
const row = document.createElement('div');
row.className='pick-item';
row.innerHTML = '<span class="pi-name">'+s.name+'</span>'
+ '<span class="pi-desc">'+s.desc+'</span>'
+ '<span class="pi-cap">'+s.year+'年</span>';
row.onclick = ()=>{
titleSel.scenario = s.id;
[...box.children].forEach(c=>c.classList.remove('sel'));
row.classList.add('sel');
// 根据剧本筛选可用势力
renderForceList(s);
document.getElementById('blkForce').style.display='block';
document.getElementById('blkDiff').style.display='none';
document.getElementById('btnNew').style.display='none';
titleSel.force=null; titleSel.diff=null;
};
box.appendChild(row);
});
}
function renderForceList(scenario){
const box = document.getElementById('forceList');
box.innerHTML='';
const forces = scenario.forces.filter(f=>PLAYER_FORCES[f]);
if(!forces.length) forces.push(...Object.keys(PLAYER_FORCES));
forces.forEach(f=>{
const pf = PLAYER_FORCES[f];
const row = document.createElement('div');
row.className='pick-item';
row.innerHTML = '<span class="pi-banner" style="background:'+pf.color+'"></span>'
+ '<span class="pi-name">'+pf.name+'</span>'
+ '<span class="pi-desc">'+pf.desc+'</span>';
row.onclick = ()=>{
titleSel.force = f;
[...box.children].forEach(c=>c.classList.remove('sel'));
row.classList.add('sel');
renderDiffList();
document.getElementById('blkDiff').style.display='block';
document.getElementById('btnNew').style.display='none';
titleSel.diff=null;
};
box.appendChild(row);
});
}
function renderDiffList(){
const box = document.getElementById('diffList');
box.innerHTML='';
Object.keys(DIFFICULTIES).forEach(k=>{
const d = DIFFICULTIES[k];
const row = document.createElement('div');
row.className='pick-item diff';
row.innerHTML = '<span class="pi-name">'+d.name+'</span>'
+ '<span class="pi-desc">'+d.desc+'</span>';
row.onclick = ()=>{
titleSel.diff = k;
[...box.children].forEach(c=>c.classList.remove('sel'));
row.classList.add('sel');
document.getElementById('btnNew').style.display='block';
};
box.appendChild(row);
});
}
function hideTitle(){
const ts = document.getElementById('titleScreen');
const app = document.getElementById('app');
if(ts) ts.style.display = 'none';
if(app) app.style.display = 'flex';
}
// ---------- 主循环与启动 ----------
function main(){
newGame();
ui.init();
view.init();
battle.init();
showTitle();
// 自动月推进(演示用)
setInterval(()=>{
if(state && state.view==='map' && document.getElementById('titleScreen').style.display==='none'){
processMonth();
view.render();
ui.renderTop();
ui.renderLog();
}
}, 25000);
}
// 暴露到全局(便于测试与外部访问)
globalThis.state = state;
globalThis.ui = ui;
globalThis.battle = battle;
globalThis.view = view;
globalThis.persist = persist;
globalThis.audio = audio;
globalThis.newGame = newGame;
globalThis.logMsg = logMsg;
globalThis.showTitle = showTitle;
globalThis.hideTitle = hideTitle;
globalThis.switchView = switchView;
globalThis.heroesInCity = heroesInCity;
globalThis.cityTroops = cityTroops;
globalThis.processMonth = processMonth;
globalThis.doBattle = doBattle;
globalThis.makeHero = makeHero;
globalThis.calcMaxTroops = calcMaxTroops;
globalThis.cityOutput = cityOutput;
globalThis.onload = main;
</script>
</body>
</html>
Game Source: 汉末三国之君临天下
Creator: ChromeOtter72
Libraries: none
Complexity: complex (4204 lines, 178.1 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: game-chromeotter72-mv6engps" to link back to the original. Then publish at arcadelab.ai/publish.