小游戏
chase_the_light · · 个人记录
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>明末 · 逐鹿天下</title>
<style>
:root{
--bg:#14100c; --panel:#1f1811; --panel2:#2a2016; --border:#4a3a26;
--gold:#c9a961; --text:#e6dcc8; --dim:#9a8a70;
}
*{margin:0;padding:0;box-sizing:border-box;}
body{background:var(--bg);color:var(--text);font-family:"Songti SC","SimSun","STSong",serif;min-height:100vh;padding:10px;font-size:14px;}
button{font-family:inherit;cursor:pointer;}
#startScreen{position:fixed;inset:0;background:linear-gradient(160deg,#0f0b07,#1d150d 60%,#2a1a0f);display:flex;align-items:flex-start;justify-content:center;z-index:100;overflow-y:auto;padding:16px;}
.start-box{max-width:1100px;width:100%;text-align:center;padding:10px 0;}
.start-box h1{font-size:36px;letter-spacing:12px;color:var(--gold);margin-bottom:4px;}
.start-box .sub{color:var(--dim);letter-spacing:3px;margin-bottom:4px;}
.start-box .intro{color:#b8a888;line-height:1.8;margin:12px auto 16px;max-width:760px;font-size:12.5px;}
.section-label{color:var(--gold);font-size:13px;letter-spacing:4px;margin:14px 0 10px;text-align:left;}
.diff-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:8px;}
.diff-card{background:var(--panel);border:1px solid var(--border);border-radius:4px;padding:10px;cursor:pointer;transition:.2s;text-align:left;}
.diff-card:hover{border-color:var(--gold);}
.diff-card.sel{border-color:var(--gold);background:#33261a;}
.diff-card .dn{font-size:16px;letter-spacing:3px;margin-bottom:5px;}
.diff-card .dd{font-size:11.5px;color:var(--dim);line-height:1.6;}
.faction-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:8px;}
.faction-card{background:var(--panel);border:1px solid var(--border);border-radius:4px;padding:10px;cursor:pointer;transition:.2s;text-align:left;}
.faction-card:hover{background:var(--panel2);border-color:var(--gold);}
.faction-card.sel{border-color:var(--gold);background:#33261a;}
.faction-card .fname{font-size:18px;margin-bottom:5px;letter-spacing:3px;}
.faction-card .fdesc{font-size:11px;color:var(--dim);line-height:1.6;margin-bottom:6px;min-height:48px;}
.faction-card .fstat{font-size:11px;color:#b8a888;line-height:1.6;border-top:1px dashed var(--border);padding-top:5px;}
.faction-card .fstat b{color:var(--gold);font-weight:normal;}
.era-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:8px;}
.era-card{background:var(--panel);border:1px solid var(--border);border-radius:4px;padding:10px;cursor:pointer;transition:.2s;text-align:left;}
.era-card:hover{border-color:var(--gold);background:var(--panel2);}
.era-card .en{font-size:15px;letter-spacing:2px;margin-bottom:4px;color:var(--gold);}
.era-card .ed{font-size:11px;color:var(--dim);line-height:1.6;}
#topbar{background:linear-gradient(180deg,#241b12,#1a1309);border:1px solid var(--border);border-radius:4px;padding:9px 12px;display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;justify-content:space-between;margin-bottom:8px;}
.title-block{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;}
.title-block .t1{font-size:19px;color:var(--gold);letter-spacing:4px;}
.title-block .t2{font-size:11.5px;color:var(--dim);}
.hud{display:flex;flex-wrap:wrap;gap:5px 12px;font-size:12.5px;}
.hud .item{display:flex;align-items:center;gap:4px;}
.hud .item .k{color:var(--dim);font-size:11.5px;}
.hud .item .v{color:var(--text);font-size:14px;}
.ap-dots{display:flex;gap:3px;}
.ap-dot{width:10px;height:10px;border-radius:50%;background:#3a2c1c;border:1px solid var(--border);}
.ap-dot.on{background:var(--gold);}
#layout{display:grid;grid-template-columns:1fr 330px;gap:8px;align-items:start;}
@media(max-width:960px){#layout{grid-template-columns:1fr;}}
.panel{background:var(--panel);border:1px solid var(--border);border-radius:4px;}
.panel-title{padding:7px 12px;border-bottom:1px solid var(--border);color:var(--gold);font-size:13px;letter-spacing:4px;display:flex;justify-content:space-between;align-items:center;}
.panel-body{padding:9px 11px;}
.finance{display:grid;grid-template-columns:repeat(auto-fit,minmax(100px,1fr));gap:6px;margin-bottom:9px;}
.fin-cell{background:var(--panel2);border:1px solid #3a2c1c;border-radius:3px;padding:6px 9px;}
.fin-cell .fl{font-size:10.5px;color:var(--dim);}
.fin-cell .fv{font-size:14.5px;}
.fin-cell .fv.pos{color:#6fbf7a;} .fin-cell .fv.neg{color:#d9544f;}
.pol-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(178px,1fr));gap:7px;}
.pol{background:var(--panel2);border:1px solid #3a2c1c;border-radius:3px;padding:8px 9px;cursor:pointer;transition:.15s;text-align:left;color:inherit;}
.pol:hover:not(:disabled){border-color:var(--gold);background:#33271a;}
.pol:disabled{opacity:.38;cursor:not-allowed;}
.pol .pn{font-size:13px;color:var(--gold);display:flex;justify-content:space-between;}
.pol .pn .ap{font-size:10.5px;color:#8a7550;}
.pol .pd{font-size:11px;color:var(--dim);line-height:1.55;margin-top:4px;}
.pol .pc{font-size:10.5px;color:#a89070;margin-top:4px;}
.pol.war{border-color:#6a3030;background:#2a1a16;}
.pol.war .pn{color:#e08a6a;}
.pol.transfer{border-color:#3a5a3a;background:#1a2a1a;}
.pol.transfer .pn{color:#8ad08a;}
.fac-row{display:grid;grid-template-columns:78px repeat(6,1fr);gap:3px;align-items:center;padding:5px 4px;border-bottom:1px dashed #33261a;font-size:11.5px;cursor:pointer;}
.fac-row.head{color:var(--dim);font-size:10.5px;border-bottom:1px solid var(--border);cursor:default;}
.fac-row.dead{opacity:.3;text-decoration:line-through;}
.fac-row.me{background:#2a2015;border-radius:3px;}
.num{text-align:center;}
#logPanel .panel-body{max-height:460px;overflow-y:auto;}
.log-item{padding:4px 0;border-bottom:1px dashed #2e2318;font-size:12px;line-height:1.65;color:#c8b898;}
.log-item.sys{color:var(--gold);} .log-item.bad{color:#d97a70;}
.log-item.good{color:#7fc08a;} .log-item.war{color:#e0a070;} .log-item.event{color:#88c0e8;}
.btn{background:#33261a;border:1px solid var(--border);color:var(--text);padding:6px 14px;border-radius:3px;font-size:12.5px;transition:.15s;}
.btn:hover{background:#453423;border-color:var(--gold);}
.btn.primary{background:#5a3a1a;border-color:#8a6030;color:#f0dcb0;}
.btn.primary:hover{background:#6e4720;}
.btn.small{font-size:11px;padding:4px 10px;}
#endTurnBtn{width:100%;padding:11px;font-size:14px;letter-spacing:6px;background:linear-gradient(180deg,#6a3f18,#4a2a0e);border:1px solid #8a6030;color:#f5e0b8;border-radius:3px;transition:.2s;}
#endTurnBtn:hover{background:linear-gradient(180deg,#85521f,#5c3411);}
#modal{position:fixed;inset:0;background:#000000cc;display:none;align-items:center;justify-content:center;z-index:200;padding:20px;}
.modal-box{background:var(--panel);border:1px solid var(--gold);border-radius:4px;max-width:600px;width:100%;padding:16px;max-height:86vh;overflow-y:auto;box-shadow:0 0 40px #000;}
.modal-box h3{color:var(--gold);letter-spacing:4px;font-size:16px;margin-bottom:10px;border-bottom:1px solid var(--border);padding-bottom:7px;}
.modal-body{font-size:12.5px;line-height:1.75;color:#c8b898;}
.modal-btns{display:flex;gap:8px;justify-content:flex-end;margin-top:14px;flex-wrap:wrap;}
.target{background:var(--panel2);border:1px solid #3a2c1c;border-radius:3px;padding:9px;margin-bottom:7px;cursor:pointer;transition:.15s;}
.target:hover{border-color:var(--gold);background:#33271a;}
.target .tname{font-size:14px;letter-spacing:2px;margin-bottom:3px;}
.target .tinfo{font-size:11.5px;color:var(--dim);}
.target .todds{font-size:11.5px;margin-top:4px;}
.todds.good{color:#6fbf7a;} .todds.mid{color:#d8b45a;} .todds.bad{color:#d9544f;}
.city-select-row{display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--panel2);border:1px solid #3a2c1c;border-radius:3px;margin-bottom:5px;cursor:pointer;transition:.15s;}
.city-select-row:hover{border-color:var(--gold);}
.city-select-row.checked{background:#3a2c1c;border-color:var(--gold);}
.city-select-row .cb{width:16px;height:16px;border:1px solid var(--dim);border-radius:2px;display:flex;align-items:center;justify-content:center;font-size:12px;color:var(--gold);flex-shrink:0;}
.city-select-row.checked .cb{background:var(--gold);color:#1a1309;}
.city-select-row .cname{flex:1;font-size:13px;}
.city-select-row .cinfo{font-size:11px;color:var(--dim);}
.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:#2a1a10;border:1px solid var(--gold);color:var(--gold);padding:9px 22px;border-radius:3px;font-size:12.5px;z-index:300;animation:tfade 1.8s forwards;letter-spacing:2px;pointer-events:none;}
@keyframes tfade{0%{opacity:0;transform:translate(-50%,12px);}15%{opacity:1;transform:translate(-50%,0);}75%{opacity:1;}100%{opacity:0;}}
.overlay-end{position:fixed;inset:0;background:#000000e0;display:flex;align-items:center;justify-content:center;z-index:250;padding:20px;}
.end-box{text-align:center;max-width:520px;}
.end-box h2{font-size:32px;letter-spacing:12px;margin-bottom:14px;}
.end-box p{color:#b8a888;line-height:1.9;margin-bottom:18px;font-size:13.5px;}
.hint{font-size:11.5px;color:#8a7550;line-height:1.6;margin-top:6px;}
.transfer-input{flex:1;padding:6px 10px;background:#2a1a10;border:1px solid #4a3a26;color:#e6dcc8;font-size:14px;border-radius:3px;font-family:inherit;}
</style>
</head>
<body>
<div id="startScreen">
<div class="start-box">
<h1>逐鹿天下</h1>
<div class="sub">选 择 难 度 · 势 力 · 时 期</div>
<div class="intro">
每座城池有驻军、有岁入;出兵需从各城抽调,每城最多七成。可在自己城池间调兵。
</div>
<div class="section-label">一 · 选择难度</div>
<div class="diff-grid" id="diffChoices"></div>
<div class="section-label">二 · 选择势力</div>
<div class="faction-grid" id="factionChoices"></div>
<div id="eraSection" style="display:none;">
<div class="section-label">三 · 选择时期</div>
<div class="era-grid" id="eraChoices"></div>
</div>
</div>
</div>
<div id="game" style="display:none;">
<div id="topbar">
<div class="title-block">
<div class="t1" id="playerName">明</div>
<div class="t2" id="yearLabel"></div>
</div>
<div class="hud" id="hud"></div>
<div class="hud"><div class="item"><span class="k">行动点</span><div class="ap-dots" id="apDots"></div></div></div>
</div>
<div id="layout">
<div style="display:flex;flex-direction:column;gap:8px;">
<div class="panel">
<div class="panel-title"><span>国 策</span><span style="font-size:10.5px;color:#7a6a50;">点击执行</span></div>
<div class="panel-body">
<div class="finance" id="finance"></div>
<div class="pol-grid" id="polGrid"></div>
</div>
</div>
<div class="panel">
<div class="panel-title"><span>天 下 势 力</span><span style="font-size:10.5px;color:#7a6a50;">点击可查看城池</span></div>
<div class="panel-body" id="factionList"></div>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:8px;">
<div class="panel" id="logPanel">
<div class="panel-title"><span>纪 事</span></div>
<div class="panel-body" id="logBody"></div>
</div>
<button id="endTurnBtn">结 束 此 年</button>
</div>
</div>
</div>
<div id="modal"></div>
<script>
/* =========================================================
基础数据
========================================================= */
const DIFFICULTY = {
easy: { id:'easy', name:'简单', desc:'初始资源充裕,收入加成,敌军进攻意愿低,正面事件偏多。',
initMult:1.5, incomeMult:1.2, aiAggr:0.55, eventGood:0.68 },
normal: { id:'normal', name:'普通', desc:'史实基准。资源、收入、敌军进攻与事件均按标准设定。',
initMult:1.0, incomeMult:1.0, aiAggr:1.0, eventGood:0.50 },
hard: { id:'hard', name:'困难', desc:'初始资源减少,敌军更具侵略性,负面事件偏多。',
initMult:0.7, incomeMult:0.9, aiAggr:1.35, eventGood:0.35 },
hell: { id:'hell', name:'地狱', desc:'资源匮乏,敌军疯狂进攻,天灾人祸不断。',
initMult:0.5, incomeMult:0.8, aiAggr:1.7, eventGood:0.2 }
};
const TAX_LEVELS = [
{name:'轻徭薄赋', mult:0.70, morale:+2},
{name:'常赋', mult:1.00, morale: 0},
{name:'重敛', mult:1.45, morale:-3},
{name:'苛税', mult:2.00, morale:-8}
];
const FACTION_META = {
ming: { name:'明', fullName:'大明', color:'#d05a4a' },
qing: { name:'清', fullName:'大清', color:'#5a9ad0' },
shun: { name:'大顺', fullName:'大顺', color:'#e0a050' },
xi: { name:'大西', fullName:'大西', color:'#a070c0' },
wu: { name:'吴', fullName:'吴三桂', color:'#50b0a0' }
};
/* =========================================================
时期数据
========================================================= */
const ERAS = {
era_1628: {
year:1628, name:'崇祯元年',
desc:'崇祯帝初登基,诛魏忠贤,朝野望治。然辽东后金日强,陕西旱蝗初起,国库已空。',
factions: {
ming: { fullName:'大明', elite:38, morale:45, gentry:70, corruption:65, treasury:200,
cities:[['北京',10,50],['南京',6,40],['西安',4,30],['太原',3,22],['济南',3,24],['开封',3,22],['武昌',3,22],['成都',3,22],['广州',2,25],['杭州',2,28],['福州',2,20],['长沙',2,18]] },
qing: { fullName:'后金', elite:88, morale:60, gentry:40, corruption:20, treasury:60,
cities:[['盛京',3,20],['辽阳',2,15],['抚顺',1.5,10],['广宁',1.5,10]] }
}
},
era_1636: {
year:1636, name:'崇德元年',
desc:'皇太极改国号为清,称帝盛京。八旗铁骑屡破明军,明廷内外交困,流寇渐起。',
factions: {
ming: { fullName:'大明', elite:34, morale:40, gentry:65, corruption:68, treasury:180,
cities:[['北京',12,50],['南京',7,40],['西安',5,30],['太原',4,22],['济南',4,24],['开封',3,22],['武昌',3,22],['成都',4,22],['广州',3,25],['杭州',3,28],['福州',2,20],['长沙',2,18]] },
qing: { fullName:'大清', elite:88, morale:65, gentry:45, corruption:18, treasury:100,
cities:[['盛京',5,25],['辽阳',2,15],['沈阳',2,20],['广宁',1.5,12],['蒙古',1.5,12]] }
}
},
era_1640: {
year:1640, name:'崇祯十三年',
desc:'李自成出商洛山,入河南,赈饥民,均田免赋,从者如云。张献忠转战湖广四川。清军屡次入塞。',
factions: {
ming: { fullName:'大明', elite:30, morale:35, gentry:60, corruption:70, treasury:140,
cities:[['北京',10,50],['南京',6,40],['西安',4,28],['太原',3,20],['济南',3,22],['开封',2.5,18],['武昌',3,20],['成都',3,20],['广州',3,25],['杭州',3,28],['福州',2,18],['长沙',2,16]] },
qing: { fullName:'大清', elite:88, morale:68, gentry:45, corruption:18, treasury:160,
cities:[['盛京',6,28],['辽阳',2,15],['沈阳',2,20],['广宁',1.5,12],['蒙古',2,15],['锦州',1.5,12]] },
shun: { fullName:'大顺', elite:42, morale:55, gentry:25, corruption:30, treasury:60,
cities:[['商洛',2,15],['襄阳',2,18],['洛阳',2,16],['西安',2,18]] },
xi: { fullName:'大西', elite:38, morale:45, gentry:20, corruption:35, treasury:40,
cities:[['谷城',2,12],['川东',1.5,12],['湖广',1.5,12]] }
}
},
era_1644: {
year:1644, name:'甲申之变',
desc:'李自成破北京,帝自缢煤山。清军入关,吴三桂开关迎降。天下鼎沸,群雄逐鹿。',
factions: {
ming: { fullName:'大明', elite:28, morale:30, gentry:55, corruption:72, treasury:80,
cities:[['南京',4,45],['扬州',1.5,28],['杭州',1.5,30],['福州',1,20],['广州',1,25],['武昌',1.5,22],['长沙',1,18],['昆明',0.8,15],['贵阳',0.8,12],['桂林',0.8,14]] },
qing: { fullName:'大清', elite:88, morale:60, gentry:40, corruption:20, treasury:300,
cities:[['北京',4,55],['盛京',2,20],['大同',1.5,18],['济南',1.5,22],['天津',1,15],['辽阳',1,12],['广宁',1,10]] },
shun: { fullName:'大顺', elite:45, morale:50, gentry:20, corruption:45, treasury:1800,
cities:[['西安',5,30],['北京',5,50],['太原',3,20],['开封',3,22],['洛阳',2,18],['襄阳',2,18],['兰州',2,15],['延安',1.5,12],['汉中',1.5,12]] },
xi: { fullName:'大西', elite:40, morale:25, gentry:15, corruption:55, treasury:350,
cities:[['成都',4,25],['重庆',3,22],['保宁',1.5,15],['顺庆',1.5,12]] },
wu: { fullName:'吴三桂', elite:88, morale:45, gentry:60, corruption:35, treasury:60,
cities:[['山海关',3,20],['宁远',1,12]] }
}
},
era_1645: {
year:1645, name:'弘光元年',
desc:'北京已陷,弘光帝立于南京。江北四镇拥兵自重,清军南下在即,大顺已亡,大西据蜀。',
factions: {
ming: { fullName:'南明', elite:32, morale:40, gentry:60, corruption:65, treasury:120,
cities:[['南京',5,45],['扬州',2,28],['杭州',2,30],['福州',2,20],['广州',2,25],['武昌',2,22],['长沙',1.5,18],['桂林',1.5,14]] },
qing: { fullName:'大清', elite:85, morale:55, gentry:35, corruption:25, treasury:400,
cities:[['北京',5,55],['盛京',2,20],['西安',2,28],['太原',2,20],['济南',2,22],['开封',2,20],['天津',1,15],['大同',1.5,18],['洛阳',1,16],['襄阳',1,15],['兰州',1,12],['延安',1,10]] },
xi: { fullName:'大西', elite:38, morale:22, gentry:12, corruption:55, treasury:250,
cities:[['成都',3.5,25],['重庆',2.5,22],['保宁',1.5,15],['顺庆',1.5,12]] }
}
},
era_1673: {
year:1673, name:'三藩之乱',
desc:'吴三桂据云南,称周王,举兵反清。三藩并起,天下震动。然年事已高,后继无人。',
factions: {
qing: { fullName:'大清', elite:70, morale:65, gentry:55, corruption:40, treasury:500,
cities:[['北京',6,60],['盛京',2,22],['南京',3,45],['西安',2.5,32],['广州',2,28],['杭州',2,30],['武昌',2,25],['成都',2,22],['济南',2,24],['太原',1.5,22],['开封',1.5,22],['福州',1.5,20],['长沙',1.5,20],['兰州',1,15],['天津',1,15]] },
wu: { fullName:'吴周', elite:72, morale:55, gentry:45, corruption:35, treasury:200,
cities:[['昆明',3,25],['贵阳',2,18],['桂林',2,16],['长沙',2,20],['成都',2,20]] }
}
}
};
/* =========================================================
游戏状态
========================================================= */
let S = null;
let selectedDiff = 'normal';
let cityIdCounter = 0;
const clamp = (v,a,b) => Math.max(a, Math.min(b, v));
const rnd = (a,b) => a + Math.random()*(b-a);
function makeCity(name, garrison, income){
return { id: ++cityIdCounter, name, garrison, income };
}
// 去重:同一势力内若有同名城池,追加·2 ·3
function dedupeCityNames(f){
if (!f.cities) return;
const seen = new Set();
for (const c of f.cities){
let base = c.name;
// 先去掉已有后缀做基础名
const m = base.match(/^(.+?)·\d+$/);
if (m) base = m[1];
let candidate = base;
let n = 2;
while (seen.has(candidate)){
candidate = `${base}·${n}`;
n++;
}
c.name = candidate;
seen.add(candidate);
}
}
function newGame(factionId, eraId, diffId){
const D = DIFFICULTY[diffId];
const era = ERAS[eraId];
if (!D || !era){ alert('数据错误'); return; }
S = {
year: era.year, turn: 1, maxTurn: 35,
playerId: factionId, ap: 3, maxAp: 3, over: false, log: [],
difficulty: D, eraId,
wuSurrendered: false, rebellionTriggered: false, factionCounter: 0
};
S.factions = {};
for (const id of Object.keys(FACTION_META)){
const meta = FACTION_META[id];
const data = era.factions[id];
if (!data){
S.factions[id] = {
id, name: meta.name, fullName: meta.fullName, color: meta.color,
alive: false, cities: [], elite: 0, morale: 0, corruption: 0, gentry: 0,
treasury: 0, taxLevel: 1, tuntian: 0, army: 0, crisisCount: 0,
lastIncome: 0, lastExpense: 0, lastNet: 0, famine: 0,
isPlayer: id === factionId
};
continue;
}
const f = {
id, name: meta.name, fullName: data.fullName || meta.fullName, color: meta.color,
cities: data.cities.map(c => makeCity(c[0], c[1], c[2])),
elite: data.elite, morale: data.morale, corruption: data.corruption,
gentry: data.gentry, treasury: data.treasury,
taxLevel: 1, tuntian: 0, army: 0, crisisCount: 0,
lastIncome: 0, lastExpense: 0, lastNet: 0, famine: 0,
alive: true, isPlayer: id === factionId
};
if (f.isPlayer) f.treasury = Math.round(f.treasury * D.initMult);
dedupeCityNames(f);
updateArmyCache(f);
S.factions[id] = f;
}
document.getElementById('startScreen').style.display = 'none';
document.getElementById('game').style.display = 'block';
addLog(`【难度】${D.name} 【时期】${era.name} 【势力】${S.factions[factionId].fullName}`, 'sys');
addLog(era.desc, 'sys');
render();
}
/* =========================================================
工具
========================================================= */
function totalArmy(f){
if (!f.cities) return 0;
return f.cities.reduce((s,c)=>s+c.garrison, 0);
}
function updateArmyCache(f){
f.army = totalArmy(f);
}
function addTroops(f, amount){
if (f.cities.length === 0) return;
const per = amount / f.cities.length;
f.cities.forEach(c => c.garrison += per);
updateArmyCache(f);
}
function changeTroops(f, delta){
if (f.cities.length === 0) return;
const per = delta / f.cities.length;
f.cities.forEach(c => { c.garrison = Math.max(0, c.garrison + per); });
updateArmyCache(f);
}
/* =========================================================
经济 / 社会
========================================================= */
function calcIncome(f){
const base = f.cities.reduce((s,c)=>s+c.income, 0);
const tax = TAX_LEVELS[f.taxLevel].mult;
const corr = 1 - f.corruption / 200;
const mor = 0.5 + f.morale / 200;
const gent = 0.85 + f.gentry / 400;
const farm = f.tuntian * 15;
const famine = f.famine > 0 ? 0.5 : 1;
const diff = f.isPlayer ? S.difficulty.incomeMult : 1.0;
return Math.max(0, Math.round((base * tax * corr * mor * gent + farm) * famine * diff));
}
function calcExpense(f){
return Math.round(f.army * 4 + f.cities.length * 2 + 10);
}
function processEconomy(f){
const inc = calcIncome(f);
const exp = calcExpense(f);
f.lastIncome = inc; f.lastExpense = exp; f.lastNet = inc - exp;
f.treasury += f.lastNet;
if (f.treasury < 0){
f.treasury = 0;
f.elite = Math.max(5, f.elite - 5);
f.morale -= 6;
addLog(`【${f.name}】府库空虚,军饷不继,士卒离心。`, 'bad');
if (Math.random() < 0.35 && f.army > 3){
const d = Math.max(1, Math.round(f.army * 0.08));
changeTroops(f, -d);
addLog(`【${f.name}】欠饷哗变,${d} 万士卒逃散。`, 'bad');
}
}
if (f.lastNet < 0 && f.treasury < 20){
f.crisisCount = (f.crisisCount || 0) + 1;
} else if (f.treasury > 100){
f.crisisCount = 0;
}
if (f.crisisCount >= 3){
f.crisisCount = 0;
const d = Math.max(1, Math.round(f.army * 0.1));
changeTroops(f, -d);
f.morale -= 5; f.gentry -= 5;
addLog(`【${f.name}】连年财政困难,军饷积欠,${d} 万士卒哗变逃散。`, 'bad');
if (f.cities.length > 1 && Math.random() < 0.5){
const idx = Math.floor(Math.random() * f.cities.length);
const lost = f.cities.splice(idx, 1)[0];
updateArmyCache(f);
addLog(`【${f.name}】士绅因财政崩溃煽动叛乱,${lost.name} 叛离!`, 'bad');
}
}
if (f.famine > 0) f.famine--;
}
function processSocial(f){
f.morale += TAX_LEVELS[f.taxLevel].morale;
if (f.morale < 30) f.morale -= 2;
f.corruption = Math.min(100, f.corruption + 1.5 + (f.morale < 30 ? 1 : 0));
f.gentry -= 1;
if (f.corruption > 70) f.gentry -= 1;
f.morale = clamp(f.morale, 0, 100);
f.corruption = clamp(f.corruption, 0, 100);
f.gentry = clamp(f.gentry, 0, 100);
if (f.morale < 20 && f.cities.length > 1){
const p = (20 - f.morale) / 100 + 0.08;
if (Math.random() < p){
const idx = Math.floor(Math.random() * f.cities.length);
const lost = f.cities.splice(idx, 1)[0];
updateArmyCache(f);
addLog(`【${f.name}】民变蜂起,${lost.name} 陷于乱民之手!`, 'bad');
}
}
if (f.gentry < 15 && f.cities.length > 1){
const p = (15 - f.gentry) / 100 + 0.06;
if (Math.random() < p){
const idx = Math.floor(Math.random() * f.cities.length);
const lost = f.cities.splice(idx, 1)[0];
updateArmyCache(f);
addLog(`【${f.name}】士绅煽动叛乱,${lost.name} 叛离!`, 'bad');
}
} else if (f.gentry < 30 && f.cities.length > 2){
if (Math.random() < 0.08){
changeTroops(f, -1);
addLog(`【${f.name}】士绅消极抗税,军饷不足,损兵万余。`, 'bad');
}
}
}
/* =========================================================
战斗
========================================================= */
function attackPower(f, troops){
return troops * (f.elite/100) * (0.5 + f.morale/200);
}
function defensePower(f, garrison){
return garrison * (f.elite/100) * (0.5 + f.morale/200) * 1.2;
}
function executeAttack(targetFactionId, targetCityId, sendingCityIds){
const p = S.factions[S.playerId];
const t = S.factions[targetFactionId];
const targetCity = t.cities.find(c => c.id === parseInt(targetCityId));
if (!targetCity){ toast('目标城池不存在'); return; }
if (S.ap < 1){ toast('行动点不足'); return; }
let dispatched = 0;
const senders = [];
for (const cid of sendingCityIds){
const c = p.cities.find(x => x.id === parseInt(cid));
if (!c) continue;
const amount = c.garrison * 0.7;
if (amount <= 0.01) continue;
senders.push({ city: c, amount });
dispatched += amount;
}
if (dispatched < 0.1){ toast('未抽调任何兵力'); return; }
S.ap -= 1;
const atk = attackPower(p, dispatched) * rnd(0.85, 1.15);
const def = defensePower(t, targetCity.garrison) * rnd(0.85, 1.15);
const R = atk / Math.max(0.01, def);
const aLoss = dispatched * clamp(0.5 / (R + 0.5), 0.10, 0.55);
const dLoss = targetCity.garrison * clamp(0.5 * R, 0.10, 0.75);
for (const s of senders) s.city.garrison = Math.max(0, s.city.garrison - s.amount);
let captured = R >= 1.0;
let headline = R >= 1.8 ? '大获全胜' : R >= 1.0 ? '惨胜' : R >= 0.7 ? '失利' : '大败亏输';
addLog(`【战报】${p.name} 调兵 ${dispatched.toFixed(1)} 万攻 ${t.name}·${targetCity.name},${headline}。我军折损 ${aLoss.toFixed(1)} 万,敌损 ${dLoss.toFixed(1)} 万。`,
captured ? 'war' : 'bad');
if (captured){
targetCity.garrison = dispatched - aLoss;
t.cities = t.cities.filter(c => c.id !== targetCity.id);
p.cities.push(targetCity);
dedupeCityNames(p);
dedupeCityNames(t);
updateArmyCache(p); updateArmyCache(t);
addLog(`【战报】${p.name} 克 ${t.name}·${targetCity.name},驻军 ${targetCity.garrison.toFixed(1)} 万。`, 'good');
if (t.cities.length <= 0){
t.alive = false;
addLog(`【${t.fullName}】社稷倾覆,势力覆灭!`, 'sys');
}
render();
setTimeout(() => afterCapture(targetCity), 60);
} else {
targetCity.garrison = Math.max(0.3, targetCity.garrison - dLoss);
updateArmyCache(p); updateArmyCache(t);
render(); checkEnd();
}
}
function afterCapture(capturedCity){
const p = S.factions[S.playerId];
const loot = Math.round(capturedCity.income * 0.6);
showModal('克城之后',
`<p>我军攻入 <b>${capturedCity.name}</b>。是秋毫无犯以收民心,还是纵兵劫掠以充军资?</p>
<p class="hint">· 秋毫无犯:民心 +4,士绅 +3,精锐 +1<br>
· 纵兵劫掠:得银约 ${loot} 万两,民心 -12,士绅 -10,贪腐 +5,精锐 -2</p>`,
[
{label:'秋毫无犯', cls:'primary', onClick:()=>{
p.morale += 4; p.gentry += 3; p.elite = Math.min(100, p.elite+1);
addLog('【军令】入城秋毫无犯,百姓箪食壶浆以迎。', 'good');
render(); if (checkEnd()) return;
setTimeout(offerContinue, 200);
}},
{label:'纵兵劫掠', onClick:()=>{
p.treasury += loot; p.morale -= 12; p.gentry -= 10;
p.corruption = Math.min(100, p.corruption+5);
p.elite = Math.max(5, p.elite-2);
addLog(`【军令】纵兵大掠,得银 ${loot} 万两,然民心大失。`, 'bad');
render(); if (checkEnd()) return;
setTimeout(offerContinue, 200);
}}
]);
}
function offerContinue(){
if (S.over) return;
const p = S.factions[S.playerId];
if (S.ap < 1 || p.army < 0.5) return;
const others = Object.values(S.factions).filter(f => f.alive && f.id !== S.playerId);
if (!others.length) return;
showModal('是否继续进攻?', `<p>尚余行动点 ${S.ap},可继续征讨。</p>`,
[
{label:'继续出征', cls:'primary', onClick:()=>{ startAttack(); }},
{label:'就此收兵', onClick:()=>{ render(); }}
]);
}
/* =========================================================
国策
========================================================= */
const POLICIES = [
{ id:'taxUp', name:'加征赋税', tag:'内政', ap:1, cost:0,
desc:'税率提升一档。国库增收,然民怨渐生,士绅亦怨。',
can: f => f.taxLevel < 3,
run: f => { f.taxLevel++; f.morale -= 6; f.gentry -= 4; f.corruption = Math.min(100, f.corruption + 2);
return `加征赋税,税率升至「${TAX_LEVELS[f.taxLevel].name}」。`; } },
{ id:'taxDown', name:'减免赋税', tag:'内政', ap:1, cost:0,
desc:'税率降低一档。与民休息,民心归附,士绅称颂。',
can: f => f.taxLevel > 0,
run: f => { f.taxLevel--; f.morale += 9; f.gentry += 4;
return `减免赋税,税率降至「${TAX_LEVELS[f.taxLevel].name}」。`; } },
{ id:'conscript', name:'征丁入伍', tag:'军事', ap:1, cost:40,
desc:'强征壮丁三万,分配各城。农事荒废,民怨沸腾,士绅不悦。',
can: f => f.cities.length > 0,
run: f => { addTroops(f, 3); f.morale -= 12; f.gentry -= 3;
return `征丁三万,分配各城,然田间少壮尽去,民怨四起。`; } },
{ id:'levy', name:'募兵', tag:'军事', ap:1, cost:80,
desc:'开募兵之例,应募者给饷,得兵二万。骚扰较轻,耗费颇多。',
can: f => f.cities.length > 0,
run: f => { addTroops(f, 2); f.morale -= 3; f.gentry += 1;
return `出榜募兵,得兵二万,民间稍安。`; } },
{ id:'relief', name:'招抚流民', tag:'内政', ap:1, cost:120,
desc:'开仓赈济,招抚流亡。民心大悦,然耗银颇巨,士绅不悦。',
can: f => f.cities.length > 0,
run: f => { addTroops(f, 1); f.morale += 8; f.gentry -= 4;
return `开仓赈饥,招抚流亡,得兵一万。`; } },
{ id:'disband', name:'裁汰冗兵', tag:'军事', ap:1, cost:20,
desc:'裁撤各城老弱四万,减少军饷,余部精锐提升。',
can: f => totalArmy(f) > 5,
run: f => { changeTroops(f, -4); f.elite = Math.min(100, f.elite + 3); f.morale += 3;
return `裁汰冗兵四万,军饷稍纾,留营者皆精壮。`; } },
{ id:'drill', name:'操练士卒', tag:'军事', ap:1, cost:70,
desc:'严加操练,精锐度提升,然耗费粮饷,民力疲敝。',
can: f => f.cities.length > 0,
run: f => { f.elite = Math.min(100, f.elite + 8); f.morale -= 2;
return `大阅三军,日夜操练,士卒精熟。`; } },
{ id:'reward', name:'犒赏三军', tag:'军事', ap:1, cost:120,
desc:'厚赏各城将士,精锐与民心俱增,吏治亦稍清。',
can: f => f.cities.length > 0,
run: f => { f.elite = Math.min(100, f.elite + 4); f.morale += 5;
f.corruption = Math.max(0, f.corruption - 3);
return `发帑犒军,士卒感奋,欢声雷动。`; } },
{ id:'antiCorruption', name:'整顿吏治', tag:'内政', ap:1, cost:60,
desc:'严查贪墨,澄清吏治。贪腐大降,民心稍安,然士绅惴惴不安。',
can: f => f.corruption > 5,
run: f => { f.corruption = Math.max(0, f.corruption - 12); f.morale += 6; f.gentry -= 15;
return `严饬吏治,罢黜贪墨,然士绅人人自危。`; } },
{ id:'gentryBanquet', name:'结好士绅', tag:'内政', ap:1, cost:100,
desc:'宴请缙绅,优礼士人。士绅满意度提升,然贪腐稍增。',
can: f => f.cities.length > 0,
run: f => { f.gentry += 12; f.corruption = Math.min(100, f.corruption + 3); f.morale -= 2;
return `宴请缙绅,优礼士人,士绅咸感其德。`; } },
{ id:'confiscate', name:'抄没贪墨', tag:'内政', ap:1, cost:0,
desc:'抄查贪官勋贵家产,得银颇丰。贪腐下降,然士绅侧目。',
can: f => f.corruption > 10,
run: f => { const gain = Math.round(f.corruption * 2);
f.treasury += gain; f.corruption = Math.max(0, f.corruption - 6); f.morale += 3; f.gentry -= 8;
return `抄没贪墨之家,得银 ${gain} 万两,然士绅兔死狐悲。`; } },
{ id:'plunder', name:'纵兵劫掠', tag:'内政', ap:1, cost:0,
desc:'放纵各城士卒劫掠地方,得银巨万。然民心尽失,士绅切齿。',
can: f => f.cities.length > 0,
run: f => { const gain = Math.round(f.cities.length * 12);
f.treasury += gain; f.morale -= 18; f.gentry -= 15; f.corruption = Math.min(100, f.corruption + 8);
f.elite = Math.max(5, f.elite - 3);
return `纵兵大掠,得银 ${gain} 万两,士绅切齿。`; } },
{ id:'exam', name:'开科取士', tag:'内政', ap:1, cost:50,
desc:'开科取士,延揽人才。吏治稍清,士林归心。',
can: f => f.cities.length > 0,
run: f => { f.corruption = Math.max(0, f.corruption - 5); f.morale += 5; f.gentry += 8;
return `开科取士,寒门得进,士林归心。`; } },
{ id:'farm', name:'屯田垦荒', tag:'内政', ap:1, cost:80,
desc:'军屯民屯并行,此后每年额外增收。',
can: f => f.tuntian < 5,
run: f => { f.tuntian++; f.morale += 3; f.gentry += 2;
return `大兴屯田,此后岁入可增。`; } },
{ id:'recruitWu', name:'招降吴三桂', tag:'特殊', ap:1, cost:200,
desc:'(仅清朝可用)招降吴三桂,许以王爵。成功后其部众归我,然削藩之患在后。',
can: f => f.id === 'qing' && S.factions.wu && S.factions.wu.alive && !S.wuSurrendered && f.cities.length >= 10,
run: f => {
const wu = S.factions.wu;
wu.cities.forEach(c => f.cities.push(c));
wu.cities = []; wu.alive = false;
dedupeCityNames(f);
updateArmyCache(f); updateArmyCache(wu);
S.wuSurrendered = true;
addLog(`【招降】吴三桂开关迎降,封平西王。然削藩之患,他日必至。`, 'sys');
return `吴三桂归降,其部众尽入我大清。`;
} }
];
/* =========================================================
突发事件
========================================================= */
const EVENTS = [
{ id:'invade', name:'敌军进犯', weight:10, choice:true,
cond:(f)=> f.cities.length > 1,
build:(f)=>{
const idx = Math.floor(Math.random()*f.cities.length);
const target = f.cities[idx];
const loss = Math.max(0.5, target.garrison * 0.4);
return {
text:`敌国兴兵进犯我境,兵锋直指 <b>${target.name}</b>。`,
options:[
{ label:'坚守', hint:`${target.name} 折损约 ${loss.toFixed(1)} 万`,
run:()=>{ target.garrison = Math.max(0, target.garrison - loss); updateArmyCache(f); f.morale += 2;
addLog(`【事件】坚守 ${target.name},折兵 ${loss.toFixed(1)} 万。`, 'event'); } },
{ label:'弃城撤退', hint:`放弃 ${target.name}`,
run:()=>{ f.cities = f.cities.filter(c => c.id !== target.id); updateArmyCache(f);
f.morale -= 6; f.gentry -= 4;
addLog(`【事件】弃守 ${target.name},民心沮丧。`, 'bad'); } }
]
};
}
},
{ id:'refugee', name:'流民潮', weight:8, choice:true,
cond:(f)=> f.cities.length > 0,
build:(f)=>({
text:'大批流民涌入境内,啼饥号寒。',
options:[
{ label:'开仓招抚', hint:'耗银 60 万,民心 +8,兵 +1,士绅 -3',
run:()=>{ if (f.treasury < 60){ addLog('【事件】府库不足,流民散去。', 'bad'); f.morale -= 3; return; }
f.treasury -= 60; f.morale += 8; addTroops(f, 1); f.gentry -= 3;
addLog('【事件】开仓招抚流民,壮者从军。', 'good'); } },
{ label:'驱赶出境', hint:'民心 -6,士绅 +3',
run:()=>{ f.morale -= 6; f.gentry += 3;
addLog('【事件】驱赶流民,哭声震野。', 'bad'); } }
]
})
},
{ id:'gentry', name:'士绅献银', weight:7, choice:true,
cond:(f)=> f.cities.length > 0,
build:(f)=>({
text:'地方士绅为求自保,主动献银劳军。',
options:[
{ label:'接受献银', hint:'得银 90 万,贪腐 +4,士绅 +3',
run:()=>{ f.treasury += 90; f.corruption = Math.min(100, f.corruption+4); f.gentry += 3;
addLog('【事件】士绅献银 90 万两。', 'event'); } },
{ label:'婉言谢绝', hint:'民心 +4,士绅 +6',
run:()=>{ f.morale += 4; f.gentry += 6;
addLog('【事件】谢绝献银,士林称颂。', 'good'); } }
]
})
},
{ id:'famine', name:'天灾', weight:9, auto:true,
cond:(f)=> f.cities.length > 0,
run:(f)=>{ f.famine = 1; f.morale -= 6; f.gentry -= 2;
addLog('【事件】旱蝗为灾,本年岁入减半。', 'bad'); }
},
{ id:'plague', name:'瘟疫', weight:7, auto:true,
cond:(f)=> f.army > 3,
run:(f)=>{ const d = Math.max(0.5, f.army*0.12);
changeTroops(f, -d); f.morale -= 5;
addLog(`【事件】军中瘟疫,减员 ${d.toFixed(1)} 万。`, 'bad'); }
},
{ id:'general', name:'名将归附', weight:6, auto:true,
cond:()=> true,
run:(f)=>{ f.elite = Math.min(100, f.elite+5);
addLog('【事件】名将慕义来投,精锐提升。', 'good'); }
},
{ id:'harvest', name:'风调雨顺', weight:6, auto:true,
cond:()=> true,
run:(f)=>{ f.morale += 5; f.gentry += 2;
addLog('【事件】风调雨顺,年谷丰登。', 'good'); }
},
{ id:'mutiny', name:'边军哗变', weight:8, auto:true,
cond:(f)=> f.corruption > 60 && f.army > 4,
run:(f)=>{ const d = Math.max(0.5, f.army*0.1);
changeTroops(f, -d); f.morale -= 4;
addLog(`【事件】边军哗变,逃散 ${d.toFixed(1)} 万。`, 'bad'); }
},
{ id:'rob', name:'商队遇劫', weight:6, auto:true,
cond:(f)=> f.treasury > 40,
run:(f)=>{ const loss = Math.min(f.treasury, 40);
f.treasury -= loss; addLog(`【事件】商队遇劫,损失银 ${loss} 万两。`, 'bad'); }
},
{ id:'omen', name:'祥瑞', weight:4, auto:true,
cond:()=> true,
run:(f)=>{ f.morale += 6; f.corruption = Math.max(0, f.corruption-2); f.gentry += 3;
addLog('【事件】地方奏报祥瑞,人心振奋。', 'good'); }
},
{ id:'gentryPetition', name:'士绅请愿', weight:7, choice:true,
cond:(f)=> f.cities.length > 0 && f.gentry < 60,
build:(f)=>({
text:'地方士绅联名上书,请求减轻赋税、停止追赃。',
options:[
{ label:'俯允所请', hint:'士绅 +12,民心 +3,税率降一档',
run:()=>{ f.gentry += 12; f.morale += 3; if (f.taxLevel > 0) f.taxLevel--;
addLog('【事件】俯允士绅所请,减税罢赃。', 'good'); } },
{ label:'严词拒绝', hint:'士绅 -10,国库 +60 万两',
run:()=>{ f.gentry -= 10; f.treasury += 60;
addLog('【事件】严词拒绝士绅请愿,府库稍充。', 'event'); } }
]
})
},
{ id:'gentryRevolt', name:'缙绅叛乱', weight:8, choice:true,
cond:(f)=> f.gentry < 25 && f.cities.length > 2,
build:(f)=>({
text:'士绅暗中串联,煽动地方叛乱。',
options:[
{ label:'武力镇压', hint:'折损兵力,士绅 -8,民心 -4',
run:()=>{ const loss = Math.max(0.5, f.army*0.15);
changeTroops(f, -loss); f.gentry -= 8; f.morale -= 4;
addLog(`【事件】武力镇压缙绅叛乱,折兵 ${loss.toFixed(1)} 万。`, 'bad'); } },
{ label:'安抚妥协', hint:'耗银 100 万,士绅 +15,民心 +3',
run:()=>{ if (f.treasury < 100){ f.gentry -= 5; f.morale -= 5;
addLog('【事件】府库不足,无力安抚。', 'bad'); return; }
f.treasury -= 100; f.gentry += 15; f.morale += 3;
addLog('【事件】耗银安抚士绅,乱事遂平。', 'event'); } }
]
})
},
{ id:'volunteer', name:'义军来投', weight:6, auto:true,
cond:(f)=> f.morale > 55,
run:(f)=>{ addTroops(f, 2); f.elite = Math.min(100, f.elite + 2);
addLog('【事件】四方义军慕义来投,得兵二万。', 'good'); }
},
{ id:'tribute', name:'外邦朝贡', weight:4, auto:true,
cond:(f)=> f.cities.length > 6,
run:(f)=>{ f.treasury += 80; f.morale += 3;
addLog('【事件】外邦遣使朝贡,得银 80 万两。', 'good'); }
},
{ id:'weapon', name:'军械革新', weight:5, auto:true,
cond:(f)=> f.treasury > 150,
run:(f)=>{ f.treasury -= 100; f.elite = Math.min(100, f.elite + 6);
addLog('【事件】仿制红夷大炮,精锐提升。', 'good'); }
},
{ id:'locust', name:'蝗灾', weight:7, auto:true,
cond:(f)=> f.cities.length > 1,
run:(f)=>{ f.morale -= 7; f.famine = 1;
addLog('【事件】蝗虫蔽日,本年岁入减半。', 'bad'); }
},
{ id:'sage', name:'招贤纳士', weight:5, choice:true,
cond:()=> true,
build:(f)=>({
text:'有奇士自荐于辕门,言可安邦定国。',
options:[
{ label:'待为上宾', hint:'耗银 50 万,精锐 +3,贪腐 -3,士绅 +5',
run:()=>{ if (f.treasury < 50){ addLog('【事件】府库不足,奇士拂袖而去。', 'bad'); return; }
f.treasury -= 50; f.elite += 3; f.corruption -= 3; f.gentry += 5;
addLog('【事件】待奇士为上宾,军务吏治皆有起色。', 'good'); } },
{ label:'谢而不纳', hint:'士绅 +2',
run:()=>{ f.gentry += 2; addLog('【事件】谢而不纳。', 'event'); } }
]
})
}
];
function rollEvents(){
const p = S.factions[S.playerId];
const D = S.difficulty;
let count = Math.random() < 0.35 ? 0 : (Math.random() < 0.6 ? 1 : 2);
if (count === 0) return [];
const pool = EVENTS.filter(e => { try { return e.cond(p); } catch(err){ return false; } });
const picked = [];
const used = new Set();
for (let i=0; i<count && pool.length > used.size; i++){
const candidates = pool.filter(e => !used.has(e.id));
if (!candidates.length) break;
let total = 0;
const weighted = candidates.map(e => {
let w = e.weight;
const isGood = ['general','harvest','omen','volunteer','tribute','weapon','sage'].includes(e.id);
const isBad = ['famine','plague','mutiny','rob','invade','locust','gentryRevolt'].includes(e.id);
if (isGood) w *= (D.eventGood / 0.5);
if (isBad) w *= ((1 - D.eventGood) / 0.5);
total += w;
return { e, w };
});
let r = Math.random() * total;
let chosen = weighted[0].e;
for (const x of weighted){ r -= x.w; if (r <= 0){ chosen = x.e; break; } }
picked.push(chosen);
used.add(chosen.id);
}
return picked;
}
/* =========================================================
AI
========================================================= */
function aiDecide(f){
if (!f.alive) return;
const D = S.difficulty;
if (f.treasury < 0 || f.lastNet < 0){
if (f.taxLevel < 3 && f.morale > 30) f.taxLevel++;
else if (f.army > 8 && f.lastNet < -80){
changeTroops(f, -Math.max(1, f.army * 0.15)); f.morale += 2;
}
}
if (f.morale < 25 && f.treasury > 120){ f.treasury -= 90; f.morale += 9; }
if (f.gentry < 25 && f.treasury > 120){ f.treasury -= 100; f.gentry += 14; }
if (f.corruption > 70 && f.treasury > 100){ f.treasury -= 80; f.corruption -= 12; f.morale += 4; }
if (f.treasury > 400 && f.elite < 80){ f.treasury -= 110; f.elite = Math.min(100, f.elite + 5); }
if (f.treasury > 300 && f.army < 45){ f.treasury -= 130; addTroops(f, 3); f.morale -= 6; }
if (f.treasury > 500 && f.tuntian < 3){ f.treasury -= 80; f.tuntian++; }
if (f.id === 'qing' && S.factions.wu && S.factions.wu.alive && !S.wuSurrendered && f.cities.length >= 10 && f.treasury > 200){
const wu = S.factions.wu;
wu.cities.forEach(c => f.cities.push(c));
wu.cities = []; wu.alive = false;
dedupeCityNames(f);
updateArmyCache(f); updateArmyCache(wu);
S.wuSurrendered = true;
addLog('【招降】大清招降吴三桂,封平西王。然削藩之患在后。', 'sys');
}
if (Math.random() < 0.5 * D.aiAggr){
const enemies = Object.values(S.factions).filter(x => x.alive && x.id !== f.id);
let bestTarget = null, bestEnemy = null, bestR = 0;
for (const e of enemies){
for (const city of e.cities){
const sendable = f.cities.reduce((sum, c) => sum + c.garrison * 0.7, 0);
const atk = attackPower(f, sendable);
const def = defensePower(e, city.garrison);
const r = atk / Math.max(0.01, def);
if (r > bestR){ bestR = r; bestTarget = city; bestEnemy = e; }
}
}
if (bestTarget && bestR > 1.15){
const sendable = f.cities.reduce((sum, c) => sum + c.garrison * 0.7, 0);
for (const c of f.cities) c.garrison = Math.max(0, c.garrison - c.garrison * 0.7);
const atk = attackPower(f, sendable) * rnd(0.85, 1.15);
const def = defensePower(bestEnemy, bestTarget.garrison) * rnd(0.85, 1.15);
const R = atk / Math.max(0.01, def);
const aLoss = sendable * clamp(0.5/(R+0.5), 0.1, 0.55);
const dLoss = bestTarget.garrison * clamp(0.5*R, 0.1, 0.75);
if (R >= 1.0){
bestTarget.garrison = sendable - aLoss;
bestEnemy.cities = bestEnemy.cities.filter(c => c.id !== bestTarget.id);
f.cities.push(bestTarget);
dedupeCityNames(f);
dedupeCityNames(bestEnemy);
updateArmyCache(f); updateArmyCache(bestEnemy);
addLog(`【战报】${f.name} 攻 ${bestEnemy.name}·${bestTarget.name},克城。`, 'war');
if (bestEnemy.cities.length <= 0){
bestEnemy.alive = false;
addLog(`【${bestEnemy.fullName}】覆灭。`, 'sys');
}
} else {
bestTarget.garrison = Math.max(0.3, bestTarget.garrison - dLoss);
updateArmyCache(f); updateArmyCache(bestEnemy);
addLog(`【战报】${f.name} 攻 ${bestEnemy.name}·${bestTarget.name},未能得手。`, 'war');
}
}
}
}
/* =========================================================
回合结束
========================================================= */
function endTurn(){
if (S.over) return;
const ids = Object.keys(S.factions);
for (const id of ids){
const f = S.factions[id];
if (!f.alive) continue;
processEconomy(f);
processSocial(f);
}
for (const id of ids){
const f = S.factions[id];
if (!f.alive || f.id === S.playerId) continue;
aiDecide(f);
}
S.eventQueue = rollEvents();
S.eventIndex = 0;
processEvents();
}
function processEvents(){
if (S.over) return;
if (S.eventIndex >= S.eventQueue.length){ finishTurn(); return; }
const ev = S.eventQueue[S.eventIndex];
const p = S.factions[S.playerId];
if (ev.choice){
let data;
try { data = ev.build(p); } catch(err){ data = null; }
if (!data){ S.eventIndex++; setTimeout(processEvents, 50); return; }
let html = `<p>${data.text}</p><div style="margin-top:10px;">`;
data.options.forEach((o,i)=>{
html += `<div class="target" data-oi="${i}"><div class="tname">${o.label}</div><div class="tinfo">${o.hint||''}</div></div>`;
});
html += '</div>';
showModal(`【${ev.name}】`, html, []);
document.querySelectorAll('#modal .target').forEach(el=>{
el.onclick = () => {
const o = data.options[parseInt(el.dataset.oi)];
try { o.run(); } catch(err){ console.error(err); }
closeModal();
S.eventIndex++;
render();
if (checkEnd()) return;
setTimeout(processEvents, 100);
};
});
} else {
try { ev.run(p); } catch(err){ console.error(err); }
S.eventIndex++;
render();
if (checkEnd()) return;
setTimeout(processEvents, 100);
}
}
function finishTurn(){
S.year++; S.turn++; S.ap = S.maxAp;
if (S.turn > S.maxTurn){ endGame('time'); return; }
render();
if (checkEnd()) return;
}
function checkEnd(){
if (S.over) return true;
const p = S.factions[S.playerId];
if (!p.alive || p.cities.length <= 0){
endGame('lose');
return true;
}
const others = Object.values(S.factions).filter(f => f.alive && f.id !== S.playerId);
if (others.length === 0){
if (S.playerId === 'qing' && S.wuSurrendered && !S.rebellionTriggered){
triggerWuRebellion();
return false;
}
endGame('win');
return true;
}
return false;
}
function triggerWuRebellion(){
S.rebellionTriggered = true;
const p = S.factions[S.playerId];
const wu = S.factions.wu;
const rebelCount = Math.max(3, Math.floor(p.cities.length * 0.4));
const shuffled = [...p.cities].sort(()=>Math.random()-0.5);
const rebelCities = shuffled.slice(0, rebelCount);
p.cities = p.cities.filter(c => !rebelCities.includes(c));
wu.cities = rebelCities;
dedupeCityNames(p);
dedupeCityNames(wu);
updateArmyCache(p); updateArmyCache(wu);
wu.elite = 78; wu.morale = 65; wu.corruption = 35;
wu.gentry = 55; wu.treasury = 250; wu.alive = true;
wu.isPlayer = false; wu.tuntian = 2;
wu.name = '吴周'; wu.fullName = '吴周'; wu.color = '#50b0a0';
addLog(`【削藩】吴三桂举兵反清,自称周王,天下再度鼎沸!`, 'sys');
showModal('削 藩',
`<p>吴三桂据云南反,三藩并起。天下初定,又生大变。</p>
<p class="hint">吴三桂夺 ${rebelCount} 城,若不速平,必成大患。</p>`,
[{label:'知道了', cls:'primary', onClick:()=>{ render(); }}]);
}
function endGame(type){
if (S.over) return;
S.over = true;
const p = S.factions[S.playerId];
let title, txt, color;
if (type === 'win'){
title = '天下一统'; color = '#c9a961';
txt = `大业已成。${p.fullName} 扫平群雄,混一宇内。凡 ${S.turn} 载。`;
} else if (type === 'lose'){
title = '社稷倾覆'; color = '#a83232';
txt = `${p.fullName} 国土尽丧,城破国亡,宗庙丘墟。`;
} else {
const rank = Object.values(S.factions).filter(f=>f.alive).sort((a,b)=>b.cities.length-a.cities.length);
title = '霸业未竟'; color = '#c9a961';
txt = `三十余载倏忽而过,天下仍未归一。${rank.map(f=>`${f.name}(${f.cities.length}城)`).join('、')} 各据一方。`;
}
const div = document.createElement('div');
div.className = 'overlay-end';
div.innerHTML = `<div class="end-box">
<h2 style="color:${color}">${title}</h2>
<p>${txt}</p>
<button class="btn primary" onclick="location.reload()">重 开 一 局</button>
</div>`;
document.body.appendChild(div);
}
/* =========================================================
渲染
========================================================= */
function colorMorale(v){ if (v>=60) return '#6fbf7a'; if (v>=40) return '#d8b45a'; if (v>=20) return '#e08a50'; return '#d9544f'; }
function colorCorr(v){ if (v<30) return '#6fbf7a'; if (v<60) return '#d8b45a'; return '#d9544f'; }
function colorGentry(v){ if (v>=60) return '#6fbf7a'; if (v>=40) return '#d8b45a'; if (v>=20) return '#e08a50'; return '#d9544f'; }
function render(){
if (!S) return;
const p = S.factions[S.playerId];
if (!p) return;
updateArmyCache(p);
document.getElementById('playerName').textContent = p.fullName;
document.getElementById('playerName').style.color = p.color;
document.getElementById('yearLabel').textContent = `${S.year}年 第 ${S.turn}/${S.maxTurn} 年 ${S.difficulty.name}`;
document.getElementById('hud').innerHTML = `
<div class="item"><span class="k">国库</span><span class="v" style="color:#e8c878">${Math.round(p.treasury)}万</span></div>
<div class="item"><span class="k">城</span><span class="v">${p.cities.length}</span></div>
<div class="item"><span class="k">军</span><span class="v">${p.army.toFixed(1)}万</span></div>
<div class="item"><span class="k">锐</span><span class="v">${Math.round(p.elite)}</span></div>
<div class="item"><span class="k">民心</span><span class="v" style="color:${colorMorale(p.morale)}">${Math.round(p.morale)}</span></div>
<div class="item"><span class="k">士绅</span><span class="v" style="color:${colorGentry(p.gentry)}">${Math.round(p.gentry)}</span></div>
<div class="item"><span class="k">贪腐</span><span class="v" style="color:${colorCorr(p.corruption)}">${Math.round(p.corruption)}</span></div>
`;
const apDots = document.getElementById('apDots');
apDots.innerHTML = '';
for (let i=0;i<S.maxAp;i++){
const d = document.createElement('div');
d.className = 'ap-dot' + (i < S.ap ? ' on' : '');
apDots.appendChild(d);
}
renderFinance(p);
renderPolicies(p);
renderFactions();
renderLog();
}
function renderFinance(p){
const net = p.lastNet || 0;
document.getElementById('finance').innerHTML = `
<div class="fin-cell"><div class="fl">岁入</div><div class="fv pos">${p.lastIncome}</div></div>
<div class="fin-cell"><div class="fl">岁出</div><div class="fv neg">${p.lastExpense}</div></div>
<div class="fin-cell"><div class="fl">岁计</div><div class="fv ${net>=0?'pos':'neg'}">${net>=0?'+':''}${net}</div></div>
<div class="fin-cell"><div class="fl">税率</div><div class="fv">${TAX_LEVELS[p.taxLevel].name}</div></div>
<div class="fin-cell"><div class="fl">屯田</div><div class="fv">${p.tuntian}级</div></div>
${p.famine>0?'<div class="fin-cell"><div class="fl">灾年</div><div class="fv neg">收入减半</div></div>':''}
${p.crisisCount>=1?'<div class="fin-cell"><div class="fl">财政危机</div><div class="fv neg">'+p.crisisCount+'/3</div></div>':''}
${S.wuSurrendered?'<div class="fin-cell"><div class="fl">藩镇</div><div class="fv" style="color:#e0a050">平西王</div></div>':''}
`;
}
function renderPolicies(p){
const grid = document.getElementById('polGrid');
grid.innerHTML = '';
// 出征按钮
const warBtn = document.createElement('button');
warBtn.className = 'pol war';
warBtn.innerHTML = `<div class="pn"><span>⚔ 出 征</span><span class="ap">1 行动点</span></div>
<div class="pd">发兵征讨他方势力。选择目标城池,从各城抽调兵力(每城最多七成)。</div>
<div class="pc">总兵力:${p.army.toFixed(1)} 万</div>`;
warBtn.disabled = S.ap < 1 || S.over || p.army < 0.5;
warBtn.onclick = () => { if (S.ap >= 1) startAttack(); else toast('行动点不足'); };
grid.appendChild(warBtn);
// 调兵按钮
const transferBtn = document.createElement('button');
transferBtn.className = 'pol transfer';
transferBtn.innerHTML = `<div class="pn"><span>⇄ 调 兵</span><span class="ap">1 行动点</span></div>
<div class="pd">在自己城池之间调动驻军。不消耗银两,只消耗行动点。</div>
<div class="pc">城池:${p.cities.length} 座</div>`;
transferBtn.disabled = S.ap < 1 || S.over || p.cities.length < 2;
transferBtn.onclick = () => { if (S.ap >= 1) startTransfer(); else toast('行动点不足'); };
grid.appendChild(transferBtn);
for (const pol of POLICIES){
const cost = Math.round(pol.cost * (1 + p.corruption/100));
const btn = document.createElement('button');
btn.className = 'pol';
let canDo = false;
try { canDo = pol.can(p); } catch(err){ canDo = false; }
btn.disabled = S.ap < pol.ap || !canDo || cost > p.treasury || S.over;
btn.innerHTML = `
<div class="pn"><span>${pol.name}</span><span class="ap">${pol.ap} 行动点</span></div>
<div class="pd">${pol.desc}</div>
<div class="pc">耗银 ${cost} 万两${cost !== pol.cost ? `(贪腐加耗 ${cost-pol.cost})` : ''}</div>
`;
btn.onclick = () => execPolicy(pol, p, cost);
grid.appendChild(btn);
}
}
function execPolicy(pol, f, cost){
if (S.over) return;
if (S.ap < pol.ap){ toast('行动点不足'); return; }
if (cost > f.treasury){ toast('国库不足'); return; }
f.treasury -= cost;
S.ap -= pol.ap;
let msg = '';
try { msg = pol.run(f); } catch(err){ console.error(err); }
if (msg) addLog(`【${f.name}】${msg}`);
render();
}
function renderFactions(){
const box = document.getElementById('factionList');
let html = `<div class="fac-row head">
<div>势力</div><div class="num">城</div><div class="num">军</div>
<div class="num">锐</div><div class="num">民心</div><div class="num">士绅</div><div class="num">贪腐</div>
</div>`;
const list = Object.values(S.factions).sort((a,b)=>{
if (a.isPlayer) return -1;
if (b.isPlayer) return 1;
return b.cities.length - a.cities.length;
});
for (const f of list){
html += `<div class="fac-row ${f.alive?'':'dead'} ${f.isPlayer?'me':''}" data-fid="${f.id}">
<div class="fname" style="color:${f.alive?f.color:'#555'}">${f.fullName}${f.isPlayer?' ★':''}</div>
<div class="num">${f.cities.length}</div>
<div class="num">${f.army.toFixed(1)}</div>
<div class="num">${Math.round(f.elite)}</div>
<div class="num" style="color:${colorMorale(f.morale)}">${Math.round(f.morale)}</div>
<div class="num" style="color:${colorGentry(f.gentry)}">${Math.round(f.gentry)}</div>
<div class="num" style="color:${colorCorr(f.corruption)}">${Math.round(f.corruption)}</div>
</div>`;
}
box.innerHTML = html;
box.querySelectorAll('.fac-row[data-fid]').forEach(row=>{
row.onclick = () => showFactionCities(row.dataset.fid);
});
}
function showFactionCities(fid){
const f = S.factions[fid];
if (!f) return;
let html = `<p style="color:#9a8a70;margin-bottom:8px;">${f.fullName} · 共 ${f.cities.length} 城 · 总兵力 ${f.army.toFixed(1)} 万</p>`;
f.cities.forEach(c=>{
html += `<div class="city-select-row" style="cursor:default;">
<div class="cname" style="color:${f.color}">${c.name}</div>
<div class="cinfo">驻军 ${c.garrison.toFixed(1)} 万 岁入 ${c.income} 万两</div>
</div>`;
});
showModal(`城池 · ${f.fullName}`, html, [{label:'关闭'}]);
}
function renderLog(){
const box = document.getElementById('logBody');
box.innerHTML = S.log.map(l => `<div class="log-item ${l.cls||''}">${l.text}</div>`).join('');
box.scrollTop = box.scrollHeight;
}
function addLog(text, cls){
if (!S) return;
S.log.push({text, cls});
if (S.log.length > 400) S.log.shift();
}
/* =========================================================
调兵 UI
========================================================= */
function startTransfer(){
const p = S.factions[S.playerId];
if (p.cities.length < 2){ toast('至少需要两座城池'); return; }
let html = '<p style="color:#9a8a70;margin-bottom:10px;">选择调出驻军的城池:</p>';
for (const c of p.cities){
html += `<div class="target" data-cid="${c.id}">
<div class="tname">${c.name}</div>
<div class="tinfo">驻军 ${c.garrison.toFixed(1)} 万 岁入 ${c.income} 万两</div>
</div>`;
}
showModal('调 兵 · 第一步 · 选择来源', html, [{label:'取消'}]);
document.querySelectorAll('#modal .target').forEach(el=>{
el.onclick = () => chooseTransferTarget(parseInt(el.dataset.cid));
});
}
function chooseTransferTarget(srcId){
const p = S.factions[S.playerId];
const src = p.cities.find(c => c.id === srcId);
if (!src) return;
let html = `<p style="color:#9a8a70;margin-bottom:8px;">从 <b>${src.name}</b>(驻军 ${src.garrison.toFixed(1)} 万)调出。选择目标城池:</p>`;
for (const c of p.cities){
if (c.id === srcId) continue;
html += `<div class="target" data-cid="${c.id}">
<div class="tname">${c.name}</div>
<div class="tinfo">驻军 ${c.garrison.toFixed(1)} 万 岁入 ${c.income} 万两</div>
</div>`;
}
showModal('调 兵 · 第二步 · 选择目标', html, [
{label:'返回', onClick:()=>{ startTransfer(); }},
{label:'取消'}
]);
document.querySelectorAll('#modal .target').forEach(el=>{
el.onclick = () => chooseTransferAmount(srcId, parseInt(el.dataset.cid));
});
}
function chooseTransferAmount(srcId, dstId){
const p = S.factions[S.playerId];
const src = p.cities.find(c => c.id === srcId);
const dst = p.cities.find(c => c.id === dstId);
if (!src || !dst) return;
const maxMove = src.garrison;
let amount = Math.round(maxMove * 0.5 * 10) / 10;
let html = `<p style="color:#9a8a70;margin-bottom:8px;">从 <b>${src.name}</b> 调往 <b>${dst.name}</b></p>
<p class="hint">可调出最多 ${maxMove.toFixed(1)} 万</p>
<div style="margin:12px 0;display:flex;align-items:center;gap:8px;">
<input type="number" id="amountInput" min="0" max="${maxMove.toFixed(1)}" step="0.1" value="${amount.toFixed(1)}" class="transfer-input">
<span style="font-size:12px;color:#9a8a70;">万</span>
</div>
<div style="display:flex;gap:8px;">
<button class="btn small" id="halfBtn">一半</button>
<button class="btn small" id="allBtn">全部</button>
</div>`;
showModal('调 兵 · 第三步 · 指定数量', html, [
{label:'返回', onClick:()=>{ chooseTransferTarget(srcId); }},
{label:'确认调兵', cls:'primary', onClick:()=>{
if (amount < 0.05){ toast('调动兵力太少'); return; }
if (amount > maxMove) amount = maxMove;
src.garrison -= amount;
dst.garrison += amount;
S.ap -= 1;
updateArmyCache(p);
addLog(`【军令】从 ${src.name} 调兵 ${amount.toFixed(1)} 万至 ${dst.name}。`, 'good');
render();
}},
{label:'取消'}
]);
// 绑定输入
const input = document.getElementById('amountInput');
input.oninput = (e) => { amount = parseFloat(e.target.value) || 0; };
document.getElementById('halfBtn').onclick = () => {
amount = Math.round(maxMove * 0.5 * 10) / 10;
input.value = amount.toFixed(1);
};
document.getElementById('allBtn').onclick = () => {
amount = Math.round(maxMove * 10) / 10;
input.value = amount.toFixed(1);
};
}
/* =========================================================
出征 UI
========================================================= */
let attackTargetFaction = null;
let attackTargetCity = null;
function startAttack(){
const p = S.factions[S.playerId];
const targets = Object.values(S.factions).filter(f => f.alive && f.id !== S.playerId && f.cities.length > 0);
if (!targets.length){ toast('天下已定'); return; }
let html = '<p style="color:#9a8a70;margin-bottom:10px;">选择征讨目标势力:</p>';
for (const t of targets){
html += `<div class="target" data-tid="${t.id}">
<div class="tname" style="color:${t.color}">${t.fullName}</div>
<div class="tinfo">城 ${t.cities.length} 总兵 ${t.army.toFixed(1)}万 锐 ${Math.round(t.elite)} 民心 ${Math.round(t.morale)}</div>
</div>`;
}
showModal('出 征 · 第一步', html, [{label:'取消'}]);
document.querySelectorAll('#modal .target').forEach(el=>{
el.onclick = () => chooseTargetCity(el.dataset.tid);
});
}
function chooseTargetCity(fid){
const p = S.factions[S.playerId];
const t = S.factions[fid];
attackTargetFaction = fid;
const maxSend = p.cities.reduce((sum, c) => sum + c.garrison * 0.7, 0);
let html = `<p style="color:#9a8a70;margin-bottom:8px;">选择攻打 <b style="color:${t.color}">${t.fullName}</b> 的哪座城池(按从所有城抽调 70% 估算):</p>`;
for (const c of t.cities){
const atk = attackPower(p, maxSend);
const def = defensePower(t, c.garrison);
const odds = atk / Math.max(0.01, def);
const cls = odds > 1.3 ? 'good' : odds > 1.0 ? 'mid' : 'bad';
const label = odds > 1.8 ? '大胜可期' : odds > 1.3 ? '略占上风' : odds > 1.0 ? '险胜可期' : odds > 0.7 ? '胜负难料' : '凶多吉少';
html += `<div class="target" data-cid="${c.id}">
<div class="tname" style="color:${t.color}">${c.name}</div>
<div class="tinfo">驻军 ${c.garrison.toFixed(1)} 万 岁入 ${c.income} 万两</div>
<div class="todds ${cls}">胜算:${label}(攻 ${maxSend.toFixed(1)} 万 vs 守 ${c.garrison.toFixed(1)} 万)</div>
</div>`;
}
showModal('出 征 · 第二步 · 选择目标', html, [
{label:'返回', onClick:()=>{ startAttack(); }},
{label:'取消'}
]);
document.querySelectorAll('#modal .target').forEach(el=>{
el.onclick = () => chooseSendingCities(el.dataset.cid);
});
}
function chooseSendingCities(cityId){
const p = S.factions[S.playerId];
const t = S.factions[attackTargetFaction];
const targetCity = t.cities.find(c => c.id === parseInt(cityId));
if (!targetCity){ toast('目标城池不存在'); return; }
attackTargetCity = targetCity;
const checked = new Set();
function calcSend(){
let total = 0;
for (const cid of checked){
const c = p.cities.find(x => x.id === cid);
if (c) total += c.garrison * 0.7;
}
return total;
}
function renderSelector(){
let html = `<p style="color:#9a8a70;margin-bottom:6px;">攻打 <b style="color:${t.color}">${targetCity.name}</b>(守军 ${targetCity.garrison.toFixed(1)} 万)。</p>
<p style="color:#9a8a70;margin-bottom:8px;">从哪些城池抽调兵力?每城最多派出 70%。</p>
<div style="margin-bottom:8px;">
<button class="btn small" id="selectAllBtn">全选</button>
<button class="btn small" id="selectNoneBtn">全不选</button>
</div>
<div id="cityList">`;
for (const c of p.cities){
const isChecked = checked.has(c.id);
html += `<div class="city-select-row ${isChecked?'checked':''}" data-cid="${c.id}">
<div class="cb">${isChecked?'✓':''}</div>
<div class="cname">${c.name}</div>
<div class="cinfo">驻军 ${c.garrison.toFixed(1)} 万 → 可派 ${(c.garrison*0.7).toFixed(1)} 万</div>
</div>`;
}
html += `</div>
<div style="margin-top:10px;padding:8px;background:#2a1a10;border:1px solid #4a3a26;border-radius:3px;text-align:center;">
预计抽调:<b style="color:var(--gold);font-size:15px;">${calcSend().toFixed(1)}</b> 万
</div>`;
showModal('出 征 · 第三步 · 抽调兵力', html, [
{label:'返回', onClick:()=>{ chooseTargetCity(attackTargetFaction); }},
{label:'确认出征', cls:'primary', onClick:()=>{
if (calcSend() < 0.1){ toast('未抽调任何兵力'); return; }
const ids = Array.from(checked);
executeAttack(attackTargetFaction, attackTargetCity.id, ids);
}},
{label:'取消'}
]);
document.querySelectorAll('#cityList .city-select-row').forEach(el=>{
el.onclick = () => {
const cid = parseInt(el.dataset.cid);
if (checked.has(cid)) checked.delete(cid); else checked.add(cid);
renderSelector();
};
});
document.getElementById('selectAllBtn').onclick = () => {
p.cities.forEach(c => checked.add(c.id));
renderSelector();
};
document.getElementById('selectNoneBtn').onclick = () => {
checked.clear();
renderSelector();
};
}
renderSelector();
}
/* =========================================================
弹窗 / 提示
========================================================= */
function showModal(title, bodyHtml, buttons){
const m = document.getElementById('modal');
m.innerHTML = `<div class="modal-box">
<h3>${title}</h3>
<div class="modal-body">${bodyHtml}</div>
<div class="modal-btns"></div>
</div>`;
const btnBox = m.querySelector('.modal-btns');
(buttons||[]).forEach(b=>{
const el = document.createElement('button');
el.className = 'btn ' + (b.cls || '');
el.textContent = b.label;
el.onclick = () => {
closeModal();
if (b.onClick) b.onClick();
};
btnBox.appendChild(el);
});
m.style.display = 'flex';
}
function closeModal(){
const m = document.getElementById('modal');
m.style.display = 'none';
m.innerHTML = '';
}
function toast(msg){
const d = document.createElement('div');
d.className = 'toast';
d.textContent = msg;
document.body.appendChild(d);
setTimeout(()=>d.remove(), 1800);
}
/* =========================================================
开局界面
========================================================= */
(function initStart(){
const dbox = document.getElementById('diffChoices');
for (const id of ['easy','normal','hard','hell']){
const d = DIFFICULTY[id];
const card = document.createElement('div');
card.className = 'diff-card' + (id === 'normal' ? ' sel' : '');
card.innerHTML = `<div class="dn">${d.name}</div><div class="dd">${d.desc}</div>`;
card.onclick = () => {
selectedDiff = id;
document.querySelectorAll('.diff-card').forEach(c=>c.classList.remove('sel'));
card.classList.add('sel');
};
dbox.appendChild(card);
}
const fbox = document.getElementById('factionChoices');
for (const id of ['ming','qing','shun','xi','wu']){
const meta = FACTION_META[id];
let previewEra = null;
for (const era of Object.values(ERAS)){
if (era.factions[id]){ previewEra = era; break; }
}
if (!previewEra) continue;
const d = previewEra.factions[id];
const totalG = d.cities.reduce((s,c)=>s+c[1], 0);
const card = document.createElement('div');
card.className = 'faction-card';
card.innerHTML = `
<div class="fname" style="color:${meta.color}">${meta.fullName}</div>
<div class="fdesc">${getFactionDesc(id)}</div>
<div class="fstat">
城 <b>${d.cities.length}</b> 军 <b>${totalG.toFixed(1)}万</b> 锐 <b>${d.elite}</b><br>
民心 <b>${d.morale}</b> 士绅 <b>${d.gentry}</b> 贪腐 <b>${d.corruption}</b>
</div>`;
card.onclick = () => {
document.querySelectorAll('.faction-card').forEach(c=>c.classList.remove('sel'));
card.classList.add('sel');
showEras(id);
};
fbox.appendChild(card);
}
})();
function getFactionDesc(id){
const descs = {
ming:'崇祯朝,内忧外患,国库空虚,三饷加派,民不聊生。然正统犹在,江南半壁尚存。',
qing:'八旗劲旅,锐不可当。然人口寡少,根基未稳,需防汉人反侧。',
shun:'李自成新入北京,追赃助饷得银千万。然军纪渐弛,拷掠士绅,民心已生疑惧。',
xi:'张献忠据蜀称帝,兵力尚可。然屠戮过甚,川人尽怨,根基浅薄。',
wu:'关宁铁骑,天下精锐,战力冠绝诸军。然孤悬山海关,兵微将寡,进退维谷。'
};
return descs[id] || '';
}
function showEras(factionId){
const eraSection = document.getElementById('eraSection');
const ebox = document.getElementById('eraChoices');
ebox.innerHTML = '';
for (const k of Object.keys(ERAS)){
const era = ERAS[k];
if (!era.factions[factionId]) continue;
const card = document.createElement('div');
card.className = 'era-card';
card.innerHTML = `<div class="en">${era.name}</div><div class="ed">${era.desc}</div>`;
card.onclick = () => { newGame(factionId, k, selectedDiff); };
ebox.appendChild(card);
}
eraSection.style.display = 'block';
eraSection.scrollIntoView({behavior:'smooth', block:'nearest'});
}
document.getElementById('endTurnBtn').addEventListener('click', endTurn);
</script>
</body>
</html>