跳到正文

个人记录

小游戏

chase_the_light约 111 分钟
原文

这是 2026年9月19日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年9月18日
收录
2026年9月19日
更新
2026年11月16日
篇幅
约 111 分钟

版本

  1. v2当前
  2. v1
C++
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>明末 · 逐鹿天下(重制版2)</title>
<style>
:root{
  --bg:#14100c; --panel:#1f1811; --panel2:#2a2016; --border:#4a3a26;
  --gold:#c9a961; --red:#a83232; --green:#4e8c5a; --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","Noto Serif SC",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);text-shadow:0 0 24px #c9a96140;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);transform:translateY(-2px);}
.diff-card.sel{border-color:var(--gold);background:#33261a;box-shadow:0 0 12px #c9a96140;}
.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);transform:translateY(-3px);}
.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:50px;}
.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(200px,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);box-shadow:0 0 6px #c9a96190;}

#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;color:var(--text);}
.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);letter-spacing:1px;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;}
.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;}
.fac-row.head{color:var(--dim);font-size:10.5px;border-bottom:1px solid var(--border);}
.fac-row .fname{font-size:13px;letter-spacing:1px;}
.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;letter-spacing:1px;}
.btn:hover{background:#453423;border-color:var(--gold);}
.btn.primary{background:#5a3a1a;border-color:#8a6030;color:#f0dcb0;}
.btn.primary:hover{background:#6e4720;}
.btn:disabled{opacity:.4;cursor:not-allowed;}
#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);box-shadow:0 0 14px #c9a96140;}
#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;}
.troop-opts{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap;}
.troop-btn{flex:1;min-width:100px;}
.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;}
</style>
</head>
<body>

<div id="startScreen">
  <div class="start-box">
    <h1>逐鹿天下</h1>
    <div class="sub" id="startSub">选 择 难 度 · 势 力 · 时 期</div>
    <div class="intro" id="startIntro">
      崇祯十七年(1644)三月,李自成破北京,帝自缢煤山。四月,清军入关,吴三桂开关迎降。<br>
      天下鼎沸,群雄并起。择一方势力,行政策、理财政、练精兵、收民心,逐鹿中原,一统天下。
    </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">崇祯十七年 · 1644</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></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, short:'轻'},
  {name:'常赋',     mult:1.00, morale: 0, short:'常'},
  {name:'重敛',     mult:1.45, morale:-3, short:'重'},
  {name:'苛税',     mult:2.00, morale:-8, short:'苛'}
];

/* =========================================================
   时期数据(每个时期定义所有势力的初始状态)
   数组格式:[城池, 军队, 精锐, 民心, 贪腐, 国库, 士绅]
========================================================= */
const ERAS = {
  /* ---------- 明 ---------- */
  ming_early: {
    id:'ming_early', faction:'ming', year:1628, name:'崇祯早朝',
    desc:'崇祯帝初登基,诛魏忠贤,朝野望治。然辽东后金日强,陕西旱蝗初起,国库已空。',
    all:{
      ming:[28,70,50,45,55,260,70],
      qing:[3,15,85,60,25,90,45],
      shun:[1,3,32,50,40,15,20],
      xi:[1,2,32,50,40,15,20],
      wu:[2,8,88,55,30,60,65]
    }
  },
  ming_late: {
    id:'ming_late', faction:'ming', year:1644, name:'崇祯末年',
    desc:'崇祯十七年,李自成破北京,帝自缢煤山。清军入关,吴三桂开关迎降。明朝社稷倾覆,江南犹存。',
    all:{
      ming:[20,50,30,25,70,80,50],
      qing:[8,20,85,55,30,300,40],
      shun:[10,40,60,50,45,2000,25],
      xi:[6,20,50,25,60,400,20],
      wu:[2,5,90,45,35,60,60]
    }
  },
  ming_south: {
    id:'ming_south', faction:'ming', year:1645, name:'南明弘光',
    desc:'北京已陷,弘光帝立于南京。江北四镇拥兵自重,清军南下在即,大顺已亡,大西据蜀。',
    all:{
      ming:[12,35,42,40,60,140,58],
      qing:[18,45,85,60,30,420,40],
      shun:[0,0,0,0,0,0,0],
      xi:[8,22,52,28,60,300,20],
      wu:[0,0,0,0,0,0,0]
    }
  },
  /* ---------- 清 ---------- */
  qing_nurhaci: {
    id:'qing_nurhaci', faction:'qing', year:1618, name:'天命年间',
    desc:'努尔哈赤以七大恨告天,起兵攻明。八旗初成,锐气方盛,然人口寡少,根基未固。',
    all:{
      ming:[30,80,55,50,50,300,70],
      qing:[2,8,90,70,15,40,30],
      shun:[0,0,0,0,0,0,0],
      xi:[0,0,0,0,0,0,0],
      wu:[3,12,88,55,30,80,65]
    }
  },
  qing_shunzhi: {
    id:'qing_shunzhi', faction:'qing', year:1644, name:'顺治入关',
    desc:'多尔衮率清军入关,定鼎北京。八旗劲旅,锐不可当。然江南未平,需防汉人反侧。',
    all:{
      ming:[20,50,30,25,70,80,50],
      qing:[8,20,85,55,30,300,40],
      shun:[10,40,60,50,45,2000,25],
      xi:[6,20,50,25,60,400,20],
      wu:[2,5,90,45,35,60,60]
    }
  },
  /* ---------- 大顺 ---------- */
  shun_uprising: {
    id:'shun_uprising', faction:'shun', year:1640, name:'闯王起义',
    desc:'李自成出商洛山,入河南,赈饥民,均田免赋,从者如云。然兵力尚弱,四处流动作战。',
    all:{
      ming:[25,65,45,35,65,130,55],
      qing:[6,20,85,60,25,150,40],
      shun:[3,10,50,55,35,80,25],
      xi:[3,8,50,50,40,60,25],
      wu:[3,10,88,55,30,70,65]
    }
  },
  shun_yongchang: {
    id:'shun_yongchang', faction:'shun', year:1644, name:'永昌元年',
    desc:'李自成破北京,称大顺皇帝。追赃助饷得银千万,然军纪渐弛,拷掠士绅,民心已生疑惧。',
    all:{
      ming:[20,50,30,25,70,80,50],
      qing:[8,20,85,55,30,300,40],
      shun:[10,40,60,50,45,2000,25],
      xi:[6,20,50,25,60,400,20],
      wu:[2,5,90,45,35,60,60]
    }
  },
  /* ---------- 大西 ---------- */
  xi_uprising: {
    id:'xi_uprising', faction:'xi', year:1640, name:'八大王起义',
    desc:'张献忠转战湖广四川,所过残破。兵力尚可,然屠戮过甚,民心不附。',
    all:{
      ming:[25,65,45,35,65,130,55],
      qing:[6,20,85,60,25,150,40],
      shun:[3,10,50,55,35,80,25],
      xi:[3,8,50,50,40,60,25],
      wu:[3,10,88,55,30,70,65]
    }
  },
  xi_dashun: {
    id:'xi_dashun', faction:'xi', year:1644, name:'大顺三年',
    desc:'张献忠据成都称帝,国号大西。川人尽怨,根基浅薄。清军已入关,大顺据北京。',
    all:{
      ming:[20,50,30,25,70,80,50],
      qing:[8,20,85,55,30,300,40],
      shun:[10,40,60,50,45,2000,25],
      xi:[6,20,50,25,60,400,20],
      wu:[2,5,90,45,35,60,60]
    }
  },
  /* ---------- 吴 ---------- */
  wu_shanhaiguan: {
    id:'wu_shanhaiguan', faction:'wu', year:1644, name:'山海关',
    desc:'吴三桂拥关宁铁骑,孤悬山海关。李自成破北京,清军虎视眈眈,进退维谷。',
    all:{
      ming:[20,50,30,25,70,80,50],
      qing:[8,20,85,55,30,300,40],
      shun:[10,40,60,50,45,2000,25],
      xi:[6,20,50,25,60,400,20],
      wu:[2,5,90,45,35,60,60]
    }
  },
  wu_sanfan: {
    id:'wu_sanfan', faction:'wu', year:1673, name:'三藩之乱',
    desc:'吴三桂据云南,称周王,举兵反清。三藩并起,天下震动。然年事已高,后继无人。',
    all:{
      ming:[0,0,0,0,0,0,0],
      qing:[25,50,75,65,40,500,60],
      shun:[0,0,0,0,0,0,0],
      xi:[0,0,0,0,0,0,0],
      wu:[8,25,78,60,40,220,55]
    }
  }
};

const FACTION_BASE = {
  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 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 => true,
    run: f => { f.army += 3; f.morale -= 12; f.gentry -= 3;
      return `征丁三万,军势稍振,然田间少壮尽去,民怨四起。`; } },
  { id:'levy', name:'募兵', tag:'军事', ap:1, cost:80,
    desc:'开募兵之例,应募者给饷。兵力增加,骚扰较轻,然耗费颇多。',
    can: f => true,
    run: f => { f.army += 2; f.morale -= 3; f.gentry += 1;
      return `出榜募兵,应募者踊跃,得兵二万,民间稍安。`; } },
  { id:'relief', name:'招抚流民', tag:'内政', ap:1, cost:120,
    desc:'开仓赈济,招抚流亡。民心大悦,然耗银颇巨,士绅不悦。',
    can: f => true,
    run: f => { f.morale += 8; f.army += 1; f.gentry -= 4;
      return `开仓赈饥,招抚流亡,归附者络绎于道,然士绅恐流民争田。`; } },
  { id:'disband', name:'裁汰冗兵', tag:'军事', ap:1, cost:20,
    desc:'裁撤老弱四万,减少军饷开支,余部精锐度提升。',
    can: f => f.army > 5,
    run: f => { f.army = Math.max(1, f.army - 4); f.elite = Math.min(100, f.elite + 3); f.morale += 3;
      return `裁汰冗兵四万,军饷稍纾,留营者皆精壮。`; } },
  { id:'drill', name:'操练士卒', tag:'军事', ap:1, cost:70,
    desc:'严加操练,精锐度提升,然耗费粮饷,民力疲敝。',
    can: f => true,
    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 => true,
    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 => true,
    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 > 0,
    run: f => { const gain = Math.round(f.cities * 15);
      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 => true,
    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 >= 12,
    run: f => {
      const wu = S.factions.wu;
      f.cities += wu.cities; f.army += wu.army; f.gentry += 5;
      wu.cities = 0; wu.army = 0; wu.alive = false;
      S.wuSurrendered = true;
      addLog(`【招降】吴三桂开关迎降,封平西王,其部众尽归我大清。然削藩之患,他日必至。`, 'sys');
      return `吴三桂归降,其部众尽入我大清。`;
    } }
];

/* =========================================================
   游戏状态
========================================================= */
let S = null;
let selectedDiff = 'normal';
let selectedFaction = null;

const clamp = (v,a,b) => Math.max(a, Math.min(b, v));
const rnd = (a,b) => a + Math.random()*(b-a);

function newGame(factionId, eraId, diffId){
  const D = DIFFICULTY[diffId];
  const era = ERAS[eraId];
  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, base] of Object.entries(FACTION_BASE)){
    const data = era.all[id] || [0,0,0,0,0,0,0];
    const [cities, army, elite, morale, corruption, treasury, gentry] = data;
    if (cities <= 0 && army <= 0){
      S.factions[id] = Object.assign({}, base, {
        id, alive:false, cities:0, army:0, elite:0, morale:0, corruption:0,
        treasury:0, gentry:0, taxLevel:1, tuntian:0,
        lastIncome:0, lastExpense:0, lastNet:0, famine:0,
        isPlayer: id === factionId
      });
      continue;
    }
    const f = Object.assign({}, base, {
      id, alive:true, cities, army, elite, morale, corruption, treasury,
      gentry, taxLevel:1, tuntian:0,
      lastIncome:0, lastExpense:0, lastNet:0, famine:0,
      isPlayer: id === factionId
    });
    if (f.isPlayer){
      f.treasury = Math.round(f.treasury * D.initMult);
    }
    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 calcIncome(f){
  const base  = f.cities * 22;
  const tax   = TAX_LEVELS[f.taxLevel].mult;
  const corr  = 1 - f.corruption / 200;
  const mor   = 0.5 + f.morale / 200;
  const gent  = 0.9 + f.gentry / 250; // 士绅满意度影响收税效率
  const farm  = f.tuntian * 18;
  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){
  const armyPay    = f.army * 4;
  const officialPay = f.cities * 1.5;
  return Math.round(armyPay + officialPay + 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));
      f.army -= d;
      addLog(`【${f.name}】欠饷哗变,${d} 万士卒逃散。`, '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 > 1){
    const p = (20 - f.morale) / 100 + 0.08;
    if (Math.random() < p){
      f.cities -= 1; f.army = Math.max(0, f.army - 2);
      addLog(`【${f.name}】民变蜂起,一城陷于乱民之手!`, 'bad');
    }
  }
  // 士绅叛乱
  if (f.gentry < 15 && f.cities > 1){
    const p = (15 - f.gentry) / 100 + 0.06;
    if (Math.random() < p){
      f.cities -= 1; f.army = Math.max(0, f.army - 1);
      addLog(`【${f.name}】士绅煽动叛乱,一城叛离!`, 'bad');
    }
  } else if (f.gentry < 30 && f.cities > 2){
    if (Math.random() < 0.08){
      f.army = Math.max(0, f.army - 1);
      addLog(`【${f.name}】士绅消极抗税,军饷不足,损兵万余。`, 'bad');
    }
  }
}

/* =========================================================
   战斗 —— 每次只攻一座城
========================================================= */
function attackPower(f, troops){
  return troops * (f.elite/100) * (0.6 + f.morale/150);
}
function defensePower(f, defenders){
  return defenders * (f.elite/100) * (0.6 + f.morale/150) * 1.3;
}
function cityDefenders(f){
  if (f.cities <= 0) return 0;
  const per = f.army / f.cities;
  return Math.max(0.5, Math.min(f.army, per * 1.2));
}
function doAttack(targetId, ratio){
  const p = S.factions[S.playerId];
  const t = S.factions[targetId];
  if (!t || !t.alive) return;
  if (S.ap < 1){ toast('行动点不足'); return; }
  S.ap -= 1;
  const troops = Math.max(1, Math.round(p.army * ratio));
  const defenders = cityDefenders(t);
  const ap = attackPower(p, troops) * rnd(0.85, 1.15);
  const dp = defensePower(t, defenders) * rnd(0.85, 1.15);
  const R = ap / Math.max(0.01, dp);
  const aLossRatio = clamp(0.5 / (R + 0.35), 0.06, 0.65);
  const dLossRatio = clamp(0.5 / (1/R + 0.35), 0.06, 0.65);
  const aLoss = Math.min(troops, Math.round(troops * aLossRatio));
  const dLoss = Math.min(defenders, Math.round(defenders * dLossRatio));
  p.army = Math.max(0, p.army - aLoss);
  t.army = Math.max(0, t.army - dLoss);
  const captured = R >= 1.15;
  let headline = '';
  if (R >= 1.6) headline = '大获全胜';
  else if (R >= 1.15) headline = '惨胜';
  else if (R >= 0.85) headline = '失利';
  else headline = '大败亏输';
  addLog(`【战报】${p.name} 出兵 ${troops} 万攻 ${t.name},${headline}。我军折损 ${aLoss} 万,敌损 ${dLoss} 万。`,
         captured ? 'war' : 'bad');
  if (captured){
    t.cities -= 1; p.cities += 1;
    addLog(`【战报】${p.name} 克 ${t.name} 一城。`, 'good');
    if (t.cities <= 0){
      t.cities = 0; t.alive = false; t.army = 0;
      addLog(`【${t.fullName}】社稷倾覆,势力覆灭!`, 'sys');
    }
    render();
    setTimeout(() => afterCapture(t, 1), 60);
  } else {
    render(); checkEnd();
  }
}
function afterCapture(t, n){
  const p = S.factions[S.playerId];
  const loot = Math.round(n * 18);
  showModal('克城之后',
    `<p>我军攻入城中。是秋毫无犯以收民心,还是纵兵劫掠以充军资?</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(); checkEnd();
        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(); checkEnd();
        setTimeout(offerContinue, 200);
      }}
    ]);
}
function offerContinue(){
  if (S.over) return;
  const p = S.factions[S.playerId];
  if (S.ap < 1 || p.army < 1) 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 EVENTS = [
  // 敌军进犯
  { id:'invade', name:'敌军进犯', weight:10, choice:true,
    cond:(f,S)=> f.cities > 1 && Object.values(S.factions).some(x=>x.alive&&x.id!==f.id),
    build:(f,S)=>{
      const enemies = Object.values(S.factions).filter(x=>x.alive&&x.id!==f.id);
      const e = enemies[Math.floor(Math.random()*enemies.length)];
      const loss = Math.max(1, Math.round(f.army * 0.25));
      return {
        text:`【${e.name}】兴兵进犯我境,兵锋直指一座城池。`,
        options:[
          { label:'坚守', hint:`折损约 ${loss} 万兵力,保城池不失`,
            run:()=>{ f.army = Math.max(0, f.army - loss); f.morale += 2;
              addLog(`【事件】坚守城池,折兵 ${loss} 万,然寸土未失。`, 'event'); } },
          { label:'割地求和', hint:'损失一座城池,保存兵力',
            run:()=>{ f.cities = Math.max(0, f.cities-1); f.morale -= 6; f.gentry -= 4;
              addLog(`【事件】割地求和,失一城,民心沮丧。`, 'bad');
              if (f.cities <= 0 && f.isPlayer) endGame('lose'); } }
        ]
      };
    }
  },
  // 流民潮
  { id:'refugee', name:'流民潮', weight:8, choice:true,
    cond:(f)=> f.cities > 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; f.army += 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 > 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 > 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(1, Math.round(f.army*0.12));
      f.army -= d; f.morale -= 5;
      addLog(`【事件】军中瘟疫流行,减员 ${d} 万,民心惶惶。`, '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(1, Math.round(f.army*0.1));
      f.army -= d; f.morale -= 4;
      addLog(`【事件】边军因欠饷哗变,逃散 ${d} 万,民心震动。`, 'bad'); }
  },
  // 反间计
  { id:'spy', name:'反间计', weight:5, auto:true,
    cond:(f,S)=> Object.values(S.factions).some(x=>x.alive&&x.id!==f.id),
    run:(f,S)=>{
      const enemies = Object.values(S.factions).filter(x=>x.alive&&x.id!==f.id);
      const e = enemies[Math.floor(Math.random()*enemies.length)];
      if (e.cities > 1){
        e.cities -= 1; e.army = Math.max(0, e.army - 2);
        addLog(`【事件】反间计成,${e.name} 内乱,损兵折将失一城。`, 'good');
      } else {
        e.army = Math.max(0, e.army - 2);
        addLog(`【事件】反间计成,${e.name} 损兵二万。`, 'good');
      }
    }
  },
  // 商队遇劫
  { 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 > 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 > 2,
    build:(f)=>({
      text:'士绅暗中串联,煽动地方叛乱,形势危急。',
      options:[
        { label:'武力镇压', hint:'折损兵力,士绅 -8,民心 -4',
          run:()=>{ const loss = Math.max(1, Math.round(f.army*0.15));
            f.army -= loss; f.gentry -= 8; f.morale -= 4;
            addLog(`【事件】武力镇压缙绅叛乱,折兵 ${loss} 万,士绅切齿。`, '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:'warlord', name:'藩镇割据', weight:6, auto:true,
    cond:(f)=> f.cities > 4 && f.gentry < 35,
    run:(f)=>{ f.cities -= 1; f.army = Math.max(0, f.army - 3);
      addLog('【事件】地方藩镇拥兵自重,割据一城,不复听命。', 'bad'); }
  },
  // 义军来投(新增)
  { id:'volunteer', name:'义军来投', weight:6, auto:true,
    cond:(f)=> f.morale > 55,
    run:(f)=>{ f.army += 2; f.elite = Math.min(100, f.elite + 2);
      addLog('【事件】四方义军慕义来投,得兵二万,军势稍振。', 'good'); }
  },
  // 朝贡(新增)
  { id:'tribute', name:'外邦朝贡', weight:4, auto:true,
    cond:(f)=> f.cities > 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:'enemyChaos', name:'敌国内乱', weight:7, auto:true,
    cond:(f,S)=> Object.values(S.factions).some(x=>x.alive&&x.id!==f.id&&x.cities>2),
    run:(f,S)=>{
      const enemies = Object.values(S.factions).filter(x=>x.alive&&x.id!==f.id&&x.cities>2);
      if (!enemies.length) return;
      const e = enemies[Math.floor(Math.random()*enemies.length)];
      // 削弱敌军,不直接夺城
      const loss = Math.max(1, Math.round(e.army * 0.18));
      e.army = Math.max(0, e.army - loss);
      e.elite = Math.max(10, e.elite - 5);
      e.corruption = Math.min(100, e.corruption + 5);
      addLog(`【事件】${e.name} 内部分裂,流民与官军冲突,损兵 ${loss} 万,精锐下降。`, 'good');
    }
  },
  // 流寇立寨(新增,在敌国境内生成小型流寇势力)
  { id:'rebelCamp', name:'流寇立寨', weight:4, auto:true,
    cond:(f,S)=> Object.values(S.factions).some(x=>x.alive&&x.id!==f.id&&x.cities>4),
    run:(f,S)=>{
      const enemies = Object.values(S.factions).filter(x=>x.alive&&x.id!==f.id&&x.cities>4);
      if (!enemies.length) return;
      const e = enemies[Math.floor(Math.random()*enemies.length)];
      // 削弱敌国一城
      e.cities -= 1; e.army = Math.max(0, e.army - 2);
      // 生成流寇势力
      const rid = 'rebel_' + (++S.factionCounter);
      S.factions[rid] = {
        id:rid, name:'流寇', fullName:'流寇', color:'#909090',
        cities:1, army:2, elite:25, morale:45, corruption:30,
        treasury:20, gentry:5, taxLevel:1, tuntian:0, famine:0,
        alive:true, isPlayer:false, lastIncome:0, lastExpense:0, lastNet:0
      };
      addLog(`【事件】${e.name} 境内流民暴动,攻破一城,自成流寇势力。该城守备空虚,可趁机攻取。`, 'good');
    }
  },
  // 水旱蝗疫(新增)
  { id:'locust', name:'蝗灾', weight:7, auto:true,
    cond:(f)=> f.cities > 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 => e.cond(p, S));
  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','spy','volunteer','tribute','weapon','enemyChaos','rebelCamp','sage'].includes(e.id);
      const isBad = ['famine','plague','mutiny','rob','invade','locust','warlord','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){
      const cut = Math.max(1, Math.round(f.army * 0.15));
      f.army -= cut; 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; f.army += 3; f.morale -= 6; }
  if (f.treasury > 500 && f.tuntian < 3){ f.treasury -= 80; f.tuntian++; }
  // 清朝 AI 招降吴三桂
  if (f.id === 'qing' && S.factions.wu && S.factions.wu.alive && !S.wuSurrendered && f.cities >= 12 && f.treasury > 200){
    const wu = S.factions.wu;
    f.cities += wu.cities; f.army += wu.army;
    wu.cities = 0; wu.army = 0; wu.alive = false;
    S.wuSurrendered = true;
    addLog('【招降】大清招降吴三桂,封平西王,其部众尽归。然削藩之患在后。', 'sys');
  }
  // 出征
  if (Math.random() < 0.5 * D.aiAggr){
    const targets = Object.values(S.factions).filter(x => x.alive && x.id !== f.id);
    let best = null, bestR = 0, bestTroops = 0;
    for (const t of targets){
      const troops = Math.round(f.army * 0.7);
      const defenders = cityDefenders(t);
      const r = attackPower(f, troops) / Math.max(0.01, defensePower(t, defenders));
      if (r > bestR){ bestR = r; best = t; bestTroops = troops; }
    }
    if (best && bestR > 1.0){
      const defenders = cityDefenders(best);
      const ap = attackPower(f, bestTroops) * rnd(0.85,1.15);
      const dp = defensePower(best, defenders) * rnd(0.85,1.15);
      const R = ap / Math.max(0.01, dp);
      const aLoss = Math.min(bestTroops, Math.round(bestTroops * clamp(0.5/(R+0.35),0.06,0.65)));
      const dLoss = Math.min(defenders, Math.round(defenders * clamp(0.5/(1/R+0.35),0.06,0.65)));
      f.army -= aLoss; best.army = Math.max(0, best.army - dLoss);
      if (R >= 1.15){
        best.cities -= 1; f.cities += 1;
        addLog(`【战报】${f.name} 攻 ${best.name},克一城。`, 'war');
        if (best.cities <= 0){ best.cities = 0; best.alive = false; best.army = 0;
          addLog(`【${best.fullName}】覆灭。`, 'sys'); }
      } else {
        addLog(`【战报】${f.name} 攻 ${best.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.eventIndex >= S.eventQueue.length){ finishTurn(); return; }
  const ev = S.eventQueue[S.eventIndex];
  const p = S.factions[S.playerId];
  if (ev.choice){
    const data = ev.build(p, S);
    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 = () => {
        closeModal();
        const o = data.options[parseInt(el.dataset.oi)];
        o.run();
        S.eventIndex++;
        render();
        setTimeout(processEvents, 100);
      };
    });
  } else {
    ev.run(p, S);
    S.eventIndex++;
    render();
    setTimeout(processEvents, 100);
  }
}
function finishTurn(){
  S.year++; S.turn++; S.ap = S.maxAp;
  if (S.turn > S.maxTurn){ endGame('time'); return; }
  render();
  checkEnd();
}
function checkEnd(){
  const p = S.factions[S.playerId];
  if (!p.alive || p.cities <= 0){ endGame('lose'); return; }
  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;
    }
    endGame('win');
    return;
  }
  render();
}
function triggerWuRebellion(){
  S.rebellionTriggered = true;
  const p = S.factions[S.playerId];
  const wu = S.factions.wu;
  const rebelCities = Math.max(3, Math.floor(p.cities * 0.4));
  p.cities -= rebelCities;
  wu.cities = rebelCities;
  wu.army = Math.max(12, Math.floor(p.army * 0.3));
  p.army -= wu.army;
  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.lastIncome = 0; wu.lastExpense = 0; wu.lastNet = 0; wu.famine = 0;
  wu.name = '吴周'; wu.fullName = '吴周'; wu.color = '#50b0a0';
  addLog(`【削藩】吴三桂举兵反清,自称周王,天下再度鼎沸!`, 'sys');
  showModal('削 藩',
    `<p>吴三桂据云南反,三藩并起。天下初定,又生大变。</p>
     <p class="hint">吴三桂夺 ${rebelCities} 城,拥兵 ${wu.army} 万,精锐 ${wu.elite}。若不速平,必成大患。</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;
  if (type === 'win'){
    title = '天下一统';
    txt = `大业已成。${p.fullName} 扫平群雄,混一宇内。自${yearName(S.year)},凡 ${S.turn} 载。`;
  } else if (type === 'lose'){
    title = '社稷倾覆';
    txt = `${p.fullName} 城破国亡,宗庙丘墟。乱世之中,终未能逃此劫数。`;
  } else {
    const rank = Object.values(S.factions).filter(f=>f.alive).sort((a,b)=>b.cities-a.cities);
    title = '霸业未竟';
    txt = `三十余载倏忽而过,天下仍未归一。${rank.map(f=>`${f.name}(${f.cities}城)`).join('、')} 各据一方。`;
  }
  const div = document.createElement('div');
  div.className = 'overlay-end';
  div.innerHTML = `<div class="end-box">
    <h2 style="color:${type==='win'?'#c9a961':'#a83232'}">${title}</h2>
    <p>${txt}</p>
    <button class="btn primary" onclick="location.reload()">重 开 一 局</button>
  </div>`;
  document.body.appendChild(div);
}

/* =========================================================
   渲染
========================================================= */
function yearName(y){
  return `${y}年`;
}
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];
  document.getElementById('playerName').textContent = p.fullName;
  document.getElementById('playerName').style.color = p.color;
  document.getElementById('yearLabel').textContent = `${yearName(S.year)} 第 ${S.turn}/${S.maxTurn} 年 ${S.difficulty.name}`;

  const hud = document.getElementById('hud');
  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}</span></div>
    <div class="item"><span class="k">军</span><span class="v">${p.army}万</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 box = document.getElementById('finance');
  const net = p.lastNet || 0;
  box.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>':''}
    ${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} 万</div>`;
  warBtn.disabled = S.ap < 1 || S.over || p.army < 1;
  warBtn.onclick = () => { if (S.ap >= 1) startAttack(); else toast('行动点不足'); };
  grid.appendChild(warBtn);
  for (const pol of POLICIES){
    const cost = Math.round(pol.cost * (1 + p.corruption/100));
    const btn = document.createElement('button');
    btn.className = 'pol';
    const affordable = cost <= p.treasury;
    const canDo = pol.can(p);
    btn.disabled = S.ap < pol.ap || !canDo || !affordable || 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;
  const msg = pol.run(f);
  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 - a.cities;
  });
  for (const f of list){
    html += `<div class="fac-row ${f.alive?'':'dead'} ${f.isPlayer?'me':''}">
      <div class="fname" style="color:${f.alive?f.color:'#555'}">${f.fullName}${f.isPlayer?' ★':''}</div>
      <div class="num">${f.cities}</div>
      <div class="num">${f.army}</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;
}
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 startAttack(){
  const p = S.factions[S.playerId];
  const targets = Object.values(S.factions).filter(f => f.alive && f.id !== S.playerId);
  if (!targets.length){ toast('天下已定'); return; }
  let html = '<p style="color:#9a8a70;margin-bottom:10px;">选择征讨目标(每次只攻一座城,按 70% 兵力估算):</p>';
  for (const t of targets){
    const troops = Math.max(1, Math.round(p.army * 0.7));
    const defenders = cityDefenders(t);
    const odds = attackPower(p, troops) / Math.max(0.01, defensePower(t, defenders));
    const cls = odds > 1.3 ? 'good' : odds > 1.0 ? 'mid' : 'bad';
    const label = odds > 1.6 ? '大胜可期' : odds > 1.15 ? '略占上风' : odds > 1.0 ? '险胜可期' : odds > 0.8 ? '胜负难料' : '凶多吉少';
    html += `<div class="target" data-tid="${t.id}">
      <div class="tname" style="color:${t.color}">${t.fullName} <span style="font-size:11.5px;color:#9a8a70;">守城兵力约 ${Math.round(defenders*10)/10} 万</span></div>
      <div class="tinfo">城 ${t.cities} 总兵 ${t.army}万 锐 ${Math.round(t.elite)} 民心 ${Math.round(t.morale)}</div>
      <div class="todds ${cls}">胜算:${label}</div>
    </div>`;
  }
  showModal('出 征', html, [{label:'取消'}]);
  document.querySelectorAll('#modal .target').forEach(el=>{
    el.onclick = () => chooseTroops(el.dataset.tid);
  });
}
function chooseTroops(tid){
  const p = S.factions[S.playerId];
  let html = `<p style="color:#9a8a70;">可用兵力 ${p.army} 万。投入比例越高,胜算越大,然一旦失利损失亦重。</p>
    <div class="troop-opts">`;
  [0.4, 0.7, 1.0].forEach(r=>{
    const n = Math.max(1, Math.round(p.army * r));
    html += `<button class="btn troop-btn" data-r="${r}">${Math.round(r*100)}%<br><span style="font-size:11px;color:#9a8a70">${n} 万</span></button>`;
  });
  html += '</div>';
  showModal('投入兵力', html, [{label:'取消'}]);
  document.querySelectorAll('#modal .troop-btn').forEach(el=>{
    el.onclick = () => { closeModal(); doAttack(tid, parseFloat(el.dataset.r)); };
  });
}

/* =========================================================
   弹窗 / 提示
========================================================= */
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, d] of Object.entries(DIFFICULTY)){
    const card = document.createElement('div');
    card.className = 'diff-card' + (id === 'normal' ? ' sel' : '');
    card.dataset.diff = id;
    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, f] of Object.entries(FACTION_BASE)){
    const card = document.createElement('div');
    card.className = 'faction-card';
    card.dataset.fid = id;
    const sampleEra = Object.values(ERAS).find(e => e.faction === id);
    const s = sampleEra ? sampleEra.all[id] : [0,0,0,0,0,0,0];
    card.innerHTML = `
      <div class="fname" style="color:${f.color}">${f.fullName}</div>
      <div class="fdesc">${getFactionDesc(id)}</div>
      <div class="fstat">
        城 <b>${s[0]}</b> 军 <b>${s[1]}万</b> 锐 <b>${s[2]}</b><br>
        民心 <b>${s[3]}</b> 士绅 <b>${s[6]}</b> 贪腐 <b>${s[4]}</b>
      </div>`;
    card.onclick = () => {
      selectedFaction = id;
      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 = '';
  const eras = Object.values(ERAS).filter(e => e.faction === factionId);
  for (const era of eras){
    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 = () => {
      const diffId = selectedDiff;
      newGame(factionId, era.id, diffId);
    };
    ebox.appendChild(card);
  }
  eraSection.style.display = 'block';
  eraSection.scrollIntoView({behavior:'smooth', block:'nearest'});
}

document.getElementById('endTurnBtn').addEventListener('click', endTurn);
</script>
</body>
</html>