feat: 摸鱼棋乐 — 象棋/五子棋/军棋三合一网页棋类游戏

- 象棋:完整规则引擎 + α-β 搜索 AI(三档难度)
- 五子棋:攻防评分 AI(困难档会堵活四连四)
- 军棋:标准 5x12 陆战棋翻棋(行营/大本营/铁路/山界),暗棋定色
- 通用:双人同屏、残局挑战、悔棋、存档(手动+每分钟自动覆盖)、刷新续局、战绩排行、倒计时、离开提醒、AI 教练
- 部署:纯 Node.js + Docker,数据卷持久化,存档/战绩按游戏独立文件
This commit is contained in:
personal82555 committed 2026-10-08 15:27:10 +08:00
commit b143766643
56 files changed
+3672

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
node_modules
data
ref
tests
*.log
.git
README.md
+5
View File
@@ -0,0 +1,5 @@
node_modules/
data/
ref/
*.log
.DS_Store
+9
View File
@@ -0,0 +1,9 @@
FROM node:20-alpine
WORKDIR /app
COPY package.json .
RUN npm install --omit=dev --registry=https://registry.npmmirror.com
COPY server.js .
COPY app app
EXPOSE 7025
ENV PORT=7025
CMD ["node", "server.js"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 摸鱼棋乐 (moyu-qile)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+110
View File
@@ -0,0 +1,110 @@
# 🐟 摸鱼棋乐(moyu-qile)
> 益智 · 摸鱼 · 小憩 —— 象棋 / 五子棋 / 军棋(陆战棋翻棋)三合一网页棋类游戏,纯 Node.js 自研,无外部依赖,Docker 一键部署。
浏览器打开就能玩,**手机 / 平板 / 电脑**都适配:不需要装 App、不需要注册账号、局域网零延迟、数据全部留在自己家里。
![games](https://img.shields.io/badge/games-%E8%B1%A1%E6%A3%8B%20%7C%20%E4%BA%94%E5%AD%90%E6%A3%8B%20%7C%20%E5%86%9B%E6%A3%8B-blue) ![node](https://img.shields.io/badge/node-%3E%3D20-green) ![license](https://img.shields.io/badge/license-MIT-lightgrey)
---
## ✨ 功能一览
| 功能 | 说明 |
|---|---|
| 🤖 **AI 对战** | 象棋(α-β 搜索,三档难度)、五子棋(攻防评分 + 前瞻堵四)、军棋(吃子优先评估) |
| 👥 **双人同屏** | 不需要联机、不需要第二个账号,一台设备两人轮流点 |
| 🎯 **残局挑战** | 象棋名局残局(马后炮 / 重炮将杀…)、五子棋三步杀、军棋三套明棋局面 |
| ↩ **悔棋** | 象棋/五子棋一次撤回"你 + AI"各一步;军棋支持完整回滚(含吃子、扛旗) |
| 💾 **存档 / 恢复** | 手动存档以「日期 + 时间」标识;**每 1 分钟自动存档并覆盖**(防丢局);三个游戏各自独立文件 |
| ♻️ **刷新不丢局** | 局中自动快照,刷新后进入游戏会询问「是否继续上一局」 |
| 🏆 **战绩排行** | 每局自动记录胜负与用时,按游戏独立统计,可导出 JSON |
| ⏱ **倒计时** | 无 / 1 / 3 / 5 / 10 / 20 / 30 / 60 分钟,超时判负(双人模式像棋钟轮流计时) |
| 🚪 **离开提醒** | 对局未结束时点其他页面、刷新、关页都会先确认 |
| 🤖 **AI 教练** | 接入任意 OpenAI 兼容大模型,逐步给出行棋建议 |
| 📖 **玩法说明** | 每个游戏单独的规则页 + 完整使用说明页 |
| ⚙ **存档路径可配置** | 存档与战绩目录可在界面里修改,换目录自动迁移 |
## 🎮 三个游戏
<details><summary><b>♟️ 象棋</b>(AI / 双人 / 残局)</summary>
标准中国象棋规则:蹩马腿、塞象眼、炮隔山打、兵过河横走、将帅不可照面、将死与困毙判负。点己方棋子 → 绿圈标出可走位置 → 点目标格落子。
</details>
<details><summary><b>⚫ 五子棋</b>(AI / 双人 / 残局)</summary>
15×15 棋盘,五子连珠(横 / 竖 / 斜)即胜。困难档会计算对手活四、连四并封堵。
</details>
<details><summary><b>🚩 军棋 · 陆战棋翻棋</b>(AI / 双人 / 残局)</summary>
标准 5 列 × 12 行棋盘:每方 5 个行营(圆)、2 个大本营(方框)、46 个兵站,全盘 50 枚棋子背面朝上随机布阵。
- **翻棋定色**:轮到你就翻一张,翻到哪方颜色就执哪方(先翻者定色)
- **大小**:司令 › 军长 › 师长 › 旅长 › 团长 › 营长 › 连长 › 排长 › 工兵;同级同归于尽
- **特殊**:工兵挖地雷(唯一可吃雷)、炸弹与任何子同归于尽、军旗被吃即负
- **行营**:空营可进可出,**营内棋子不可被吃**(会自动套琥珀虚线环 + 标「营」)
- **大本营**:可摆子、可进入,但**进去后不能再移动**(标「本」)
- **铁路**:工兵可沿铁路直行任意格,其他子一次一步;山界仅两侧与中路三处可通;斜线仅行营与兵站之间
</details>
## 🚀 部署(Docker)
```bash
git clone https://github.com/personal82555/moyu-qile.git
cd moyu-qile
docker build -t moyu-qile:latest .
docker run -d --name moyu-qile --restart unless-stopped \
-p 7025:7025 \
-v "$PWD/data:/app/data" \
moyu-qile:latest
```
打开 `http://<你的IP>:7025` 即可(手机同理)。
> **数据卷必须挂**:存档(`*-saves.json`)、战绩(`*-ranks.json`)与路径配置都在 `/app/data`,不挂卷重建容器会丢。
### 本地直跑(不用 Docker)
```bash
npm install
node server.js # 端口可用 PORT 覆盖
```
## 📁 目录结构
```
server.js # HTTP 静态服务 + WS 房间 + /api/{rank,save,config,fs,ai-hint}
app/index.html # 单页应用(hash 路由,三个游戏视图)
app/about.html # 使用说明页
app/css/style.css # 样式(移动端适配)
app/js/chess.js # 象棋规则引擎
app/js/chessAI.js # 象棋搜索 AI
app/js/gomoku.js # 五子棋引擎 + 评分 AI
app/js/junqi.js # 军棋翻棋引擎(标准 12×5 棋盘 / 行营 / 大本营 / 铁路)
app/js/*_client.js # 三个游戏的界面逻辑 + 存档钩子(GAMEHOOKS)
app/js/common.js # 公共 UI:工具栏 / 存档 / 排行 / 倒计时 / 离开守卫 / AI 教练
data/ # 运行时数据(存档、战绩、配置)—— 已 gitignore
tests/ # Node 单元测试
```
## 🧪 测试
```bash
node tests/engine.test.js # 引擎回归
node tests/chess_state.test.js # 象棋局面序列化往返(存档正确性)
node tests/jq_rules.test.js # 军棋规则(行营 / 大本营 / 铁路 / 山界)
node tests/jq_camp.test.js # 军棋入营与营内免疫
node tests/jq_shown.test.js # 军棋翻开状态同步
```
## 🔧 快捷方式
- 端口:`7025`(HTTP 与 WebSocket 同端口)
- AI 教练需要 OpenAI 兼容接口:`⚙ 模型设置` 里填 Base URL / Key / 模型名即可,不填不影响对局
- 存档目录默认 `<数据卷>/saves`,可在「💾 存档 → ⚙ 存档路径」里改
## 📄 License
MIT © 2026 摸鱼棋乐
+155
View File
@@ -0,0 +1,155 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>使用说明 · 摸鱼棋乐</title>
<link rel="stylesheet" href="/css/style.css">
<style>
.doc { max-width: 820px; margin: 18px auto; padding: 0 14px; }
.card { background: #fff; border-radius: 12px; padding: 22px; margin-bottom: 16px; box-shadow: 0 2px 8px rgba(0,0,0,.06); }
.card h2 { margin: 0 0 12px; font-size: 20px; color: #24344d; }
.card h3 { margin: 16px 0 8px; font-size: 16px; color: #1e6ef0; }
.card p, .card li { font-size: 15px; line-height: 1.8; color: #333; }
.card ul, .card ol { padding-left: 1.3em; }
.feat { display: grid; grid-template-columns: repeat(auto-fit, minmax(215px, 1fr)); gap: 12px; margin: 12px 0; }
.feat > div { background: #f4f7fd; border-radius: 10px; padding: 12px 14px; }
.feat b { color: #24344d; display: block; margin-bottom: 4px; }
.feat span { color: #555; font-size: 13.5px; line-height: 1.6; }
.kbd { background: #eef; padding: 1px 7px; border-radius: 5px; font-size: 13px; }
.hero { text-align: center; padding: 26px 18px; }
.hero .big { font-size: 34px; }
.hero p { color: #555; font-size: 15px; max-width: 560px; margin: 8px auto 14px; }
table { width: 100%; border-collapse: collapse; font-size: 14px; margin: 10px 0; }
th, td { border: 1px solid #e3e3e3; padding: 8px 10px; text-align: left; }
th { background: #f4f7fd; color: #24344d; }
.tip-box { background: #fffbe6; border: 1px solid #f0d060; border-radius: 8px; padding: 10px 14px; font-size: 14px; margin: 12px 0; }
.new-box { background: #eef7ff; border: 1px solid #a9d0ff; border-radius: 8px; padding: 10px 14px; font-size: 14px; margin: 12px 0; }
.bar { display: inline-block; background: #f4f7fd; border: 1px solid #dde5f0; border-radius: 6px; padding: 1px 7px; font-size: 13px; margin: 1px 2px; }
</style>
</head>
<body>
<header>
<h1>🐟 摸鱼棋乐</h1>
<nav><a href="/">← 回到游戏</a></nav>
</header>
<div class="doc">
<section class="card hero">
<div class="big">🐟 🎲 ♟️</div>
<h2 style="border:none;margin:6px 0">摸鱼棋乐 · 益智休闲游戏合集</h2>
<p>上班间隙、通勤路上、睡前几分钟——打开就能玩的三个经典棋类小游戏。纯网页,手机电脑都能玩,不需要装 App、不需要注册。</p>
<a class="btn primary" href="/" style="font-size:16px;padding:10px 22px;text-decoration:none">🎮 立刻开玩</a>
</section>
<section class="card">
<h2>🆕 最近新增的功能(一眼看完)</h2>
<div class="new-box">
<b>工具条变化</b>:每个游戏顶部一排按钮,与「← 返回」并排显示:
<div style="margin-top:6px">
<span class="bar">↩ 悔棋</span><span class="bar">⟳ 重新开始</span><span class="bar">🎯 残局</span><span class="bar">🏆 排行</span><span class="bar">💾 存档</span><span class="bar">⏱ 倒计时</span><span class="bar">难度</span><span class="bar">☰ 每步自动提示</span><span class="bar">🤖 AI 教我走</span><span class="bar">⚙ 模型设置</span><span class="bar">📖 玩法</span><span class="bar">← 返回</span>
</div>
</div>
<div class="feat">
<div><b>📖 玩法(每个游戏单独一页)</b><span>点工具条「📖 玩法」直接看当前游戏怎么玩:走子规则、操作方式、特殊规则(军棋等级表/行营/铁路)。不用再猜。</span></div>
<div><b>⏱ 自动存档(每 1 分钟)</b><span>只要对局进行中,系统<b>每分钟自动存一次</b>,并且<b>覆盖同一份</b>"自动存档",不会越存越多;存档列表里带「⏱ 自动」标记。对局结束或重新开始会自动清理。</span></div>
<div><b>💾 手动存档·随时续局</b><span>点「💾 存档 → 保存当前进度」,存档以<b>日期+时间</b>命名;下次点「恢复」接着下。三个游戏<b>各自独立文件</b>,互不混淆。</span></div>
<div><b>⚙ 存档路径可自定义</b><span>「💾 存档 → ⚙ 存档路径」里可以改存档目录(含目录浏览),换目录时旧存档自动迁移。</span></div>
<div><b>🏆 排行·战绩榜</b><span>每局自动记录胜负与用时,<b>只显示当前游戏</b>的战绩(三个游戏各自独立统计、互不混合),还能「⬇ 导出 JSON」自己留底;数据同样存在存档目录。</span></div>
<div><b>⏱ 倒计时(8 档)</b><span>无 / 1 / 3 / 5 / 10 / 20 / 30 / 60 分钟,<b>默认 20 分钟</b>。顶部横幅实时显示剩余时间,最后 10 秒变红;超时自动判负。</span></div>
<div><b>🚪 离开自动提醒</b><span>对局没结束就想点别的游戏/刷新/关页 → 会问「确定要离开吗?」;点错链接不会手滑丢局。</span></div>
<div><b>♻️ 刷新不丢局</b><span>每走一步自动存一份局中快照。刷新或误关后重新进入,会问「检测到上一局还没下完,继续吗?」——点确定就接着下。</span></div>
<div><b>🎨 当前游戏高亮</b><span>右上角三个游戏入口,正在玩的那个会高亮显示,一眼知道自己在哪。</span></div>
<div><b>🖥️ 满屏布局</b><span>游戏页与工具条铺满整个屏幕宽度,不再挤在中间一条。</span></div>
</div>
</section>
<section class="card">
<h2>🎮 三个游戏怎么玩</h2>
<h3>♟️ 象棋(AI 对战 / 双人同屏)</h3>
<ul>
<li><b>规则</b>:标准中国象棋,红先黑后,马跳日(蹩马腿)、象走田(塞象眼)、炮隔山打子、兵过河可横走;将死或困毙(无棋可走)判负。</li>
<li><b>操作</b>:点选己方棋子 → 绿色提示圈显示所有可走位置 → 点目标格完成走子。已选棋子再点一次可取消选中。</li>
<li><b>AI 棋力</b>:内置搜索博弈引擎;<b>难度</b>下拉切换——简单、普通、困难。</li>
<li><b>悔棋</b>:一次撤回"你+AI"各一步;残局里悔棋不会拆掉残局的初始摆位。</li>
</ul>
<h3>⚫ 五子棋(AI 对战 / 双人同屏)</h3>
<ul>
<li><b>规则</b>:15×15 盘,黑白轮流落子,先连成五子(横/竖/斜任意方向)者胜;下满为平局。</li>
<li><b>操作</b>:点网格线交叉点落子;最后一手落子处会亮红点标示,胜利的五连外圈套红环。</li>
<li><b>AI</b>:攻防评分选点;简单=随手,普通=综合攻防最强点,困难=防守权重加大的前瞻选点(会堵你的活四、连四)。</li>
</ul>
<h3>🚩 军棋 · 陆战棋翻棋(AI 对战 / 双人同屏)</h3>
<ul>
<li><b>规则</b>:全盘 <b>50 枚</b>棋子(每方 25 枚)背面朝上铺在棋盘上,开局全部盖着。轮到你就<b>翻一张</b>(翻到哪方的颜色,你就执哪方,先翻者定色)或<b>移动</b>一枚己方已翻开的棋子。</li>
<li><b>等级(大吃小)</b>:司令 › 军长 › 师长 › 旅长 › 团长 › 营长 › 连长 › 排长 › 工兵;同级相遇两败俱伤。</li>
<li><b>特例</b>
<ul>
<li><b>工兵</b>能挖<b>地雷</b>(唯一可吃雷的子),其他子碰雷会被炸掉;地雷不能移动。</li>
<li><b>炸弹</b>遇到任何棋子一起消失。</li>
<li>吃掉对方<b>军旗</b>直接获胜;军旗不能移动。</li>
</ul>
</li>
<li><b>棋盘要点</b>
<ul>
<li><b>行营</b>(圆圈):<b>空营可以走进去、也能走出来</b>;<b>营里的棋子不能被吃</b>(安全屋)。有子的行营会套一圈琥珀虚线环并标「营」,一眼看得出这是受保护的棋子。</li>
<li><b>大本营</b>(四角方框):可以摆子也可以走进去;<b>进入后不能再移动</b>(会标「本」)。</li>
<li><b>铁路</b>(黑色双轨):<b>工兵</b>可沿铁路直行任意格,其他棋子一次只走一步。</li>
<li><b>山界</b>(中间横带):只有两侧与中路三处可以通行。</li>
<li><b>斜线</b>:只有行营与四角兵站之间可以斜走。</li>
</ul>
</li>
</ul>
</section>
<section class="card">
<h2>✨ 全部功能特色</h2>
<div class="feat">
<div><b>🤖 AI 教练·步步提示</b><span>接入你自己的大模型(OpenAI 兼容协议),点「🤖 AI 教我走」一步一提示;可开「每步自动提示」让教练全程陪下,配置面板里有「免费 获取KEY」入口。</span></div>
<div><b>👥 双人同屏</b><span>不需要网络、不需要第二个账号!一部手机或一台电脑,两人轮流点,办公室/地铁/卧室随手开一局。</span></div>
<div><b>🎯 残局闯关</b><span>象棋「马后炮」「重炮将杀」等名局残局;五子棋三步杀手顺;军棋三套明棋局面(单兵突破 / 雷区排雷 / 炸弹阵)。点残局先看摆位,再点开始。</span></div>
<div><b>⚙ 难度自由调</b><span>人机模式任何时候切难度,换对手强度即刻生效。</span></div>
<div><b>↩ 悔棋无压力</b><span>象棋/五子棋一键撤回 AI 和你各一步;军棋也支持悔棋(翻牌、走子、吃子状态完整回滚)。</span></div>
<div><b>⏱ 棋钟对局</b><span>8 档倒计时,超时判负并计入战绩;双人同屏时像棋钟一样,轮到谁走谁的表。</span></div>
<div><b>💾 进度可存可续</b><span>手动存档 + 局中自动快照双重保险;存档/战绩/路径设置都在主机数据目录里,重启升级不丢。</span></div>
<div><b>📱 手机可玩</b><span>棋盘自适应屏幕(竖版军棋按屏高缩放)、按钮单行横向滑动、无横向滚动。</span></div>
</div>
</section>
<section class="card">
<h2>🎯 为什么它会吸引你(和朋友)玩</h2>
<ol>
<li><b>开门即玩</b>:浏览器输入地址就能进入对局,无需下载、注册、安装——领导转身时随时切标签页。</li>
<li><b>碎片时间友好</b>:单局 3–10 分钟一盘,有悔棋兜底;中途必须走开?点「💾 存档」或直接走,回来还能接着下。</li>
<li><b>双人对局零门槛</b>:很多棋牌 App 两个人反而要分别注册账号联机——这里直接共用一块屏幕。</li>
<li><b>会越玩越懂</b>:AI 教练每一步给出理由,棋力在菜鸟期被讲解带出来;每个游戏还有「📖 玩法」随时查规则。</li>
<li><b>残局=速赢快感</b>:完整棋局要长考,残局 3 步解决,成就感来得快,适合"就再来一局"的摸鱼心理。</li>
<li><b>完全自托管</b>:部署在自家 NAS / Docker 容器里,局域网零延迟,数据不出家门。</li>
</ol>
<div class="tip-box">💡 <b>推荐摸鱼姿势</b>:浏览器 PIN 这个标签页 → 工作窗口旁边放着。象棋困难级做大脑热身,五子棋做冥想,军棋翻棋在"远程会议走神"时惊喜更多。</div>
</section>
<section class="card">
<h2>❓ 常见问题</h2>
<table>
<tr><th>问题</th><th>解答</th></tr>
<tr><td>怎么联机和朋友远程玩?</td><td>目前主打同屏 + AI。远程建议用屏幕共享/投屏方式对玩。</td></tr>
<tr><td>AI 教练需要什么配置?</td><td>任何 OpenAI 兼容接口都行:自定义 Base URL + Key + 模型名。面板里有「免费 获取KEY」入口。</td></tr>
<tr><td>进度会丢吗?</td><td><b>不会</b>。① 每走一步自动存局中快照,刷新/误关后重进会问「是否继续上一局」;② 也可以点「💾 存档」手动存(日期+时间命名),随时「恢复」;③ 离开未结束的对局会弹确认。</td></tr>
<tr><td>存档/战绩存在哪?能备份吗?</td><td>存在服务器数据目录,<b>每个游戏独立文件</b>:<code>chess-saves.json / chess-ranks.json</code> 等。界面里「💾 存档 → ⚙ 存档路径」可自定义目录;直接复制该目录即完成备份。</td></tr>
<tr><td>中途被打断会丢局吗?</td><td>不会。系统每分钟自动存档一次(覆盖同一份,列表里标「⏱ 自动」);也可以点「💾 存档」手动存一份带时间戳的。回来在「💾 存档」里点「恢复」即可继续。</td></tr>
<tr><td>自动存档会越存越多吗?</td><td>不会。每个游戏只保留一份自动存档,每分钟覆盖更新;手动存档则各自独立保留(最多 100 份/游戏)。</td></tr>
<tr><td>倒计时超时怎么办?</td><td>超时会弹「超时判负」并自动记录一局负,可以点「⟳ 重新开始」再来或者在「💾 存档」里恢复更早的进度。</td></tr>
<tr><td>军棋为什么行营是空的?</td><td>开局 <b>行营一律不放子</b>(标准规则:行营是安全屋,留空才公平)。行营里的棋子是走进去的,进去后不能被吃。</td></tr>
<tr><td>军棋大本营能放子吗?</td><td>可以。大本营开局就有棋子,也能走进去;但<b>进去以后不能再移动</b>,要想好再进。</td></tr>
<tr><td>切换游戏会丢局吗?</td><td>不会立刻丢:会先弹确认框。确认离开后仍有局中快照,重新进入可以继续。</td></tr>
</table>
</section>
</div>
<footer style="text-align:center;color:#999;font-size:12px;padding:18px 0">🐟 摸鱼棋乐 · 自托管纯网页游戏 · 无需注册 · 数据不出家门</footer>
</body>
</html>
+162
View File
@@ -0,0 +1,162 @@
* { box-sizing: border-box; }
body { font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
margin: 0; background: #f2f4f8; color: #222; }
header { background: #24344d; color: #fff; padding: 12px 20px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px; }
header h1 { font-size: 20px; margin: 0; }
nav#menu { display: flex; gap: 6px; flex-wrap: wrap; }
nav#menu a { color: #fff; text-decoration: none; padding: 6px 14px; border-radius: 6px; background: rgba(255,255,255,.12); }
nav#menu a:hover { background: rgba(255,255,255,.25); }
nav#menu a.nav-active {
background: #ffb703 !important;
color: #1b2430 !important;
font-weight: bold;
box-shadow: 0 0 0 2px rgba(255,255,255,.45) inset;
}
nav#menu a.nav-active::after { content: ' ●'; font-size: 11px; vertical-align: middle; }
main { max-width: 100%; margin: 10px auto; padding: 0 10px; }
.lobby { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,.06); }
.lobby-hero { display: flex; gap: 16px; align-items: center; }
.lobby-hero img { width: 120px; height: 120px; object-fit: cover; border-radius: 10px; }
.lobby-actions { display: flex; gap: 10px; margin-top: 18px; }
.btn { padding: 8px 18px; border: 1px solid #24344d; background: #fff; color: #24344d; border-radius: 8px; cursor: pointer; font-size: 14px; }
.btn.primary { background: #24344d; color: #fff; }
.btn:disabled { opacity: .5; cursor: default; }
.hide { display: none; }
input { padding: 8px; border: 1px solid #ccc; border-radius: 6px; }
#room-status { margin-top: 10px; color: #2a7; }
.board { display: inline-block; background: #f6deac; border: 2px solid #b8860b; border-radius: 8px; touch-action: manipulation; }
.cell { width: 44px; height: 44px; display: flex; align-items: center; justify-content: center; font-size: 22px; }
.chess-piece { width: 88%; height: 88%; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; box-shadow: 0 2px 3px rgba(0,0,0,.3); font-size: 20px; }
.chess-piece.r { background: #fff; color: #c00; border: 2px solid #c00; }
.chess-piece.b { background: #efe6d5; color: #333; border: 2px solid #333; }
.cell.sel { background: #ffe9a0 !important; }
.cell.hint { background: #bfe3bf !important; border-radius: 8px; }
.cell.lastmv { box-shadow: inset 0 0 0 2px #f90; }
.toolbar { display: flex; flex-direction: column; gap: 10px; min-width: 120px; }
.toolbar .btn.wide { width: 100%; padding: 12px 0; font-size: 16px; }
.game-shell { min-height: 480px; }
.gomoku-board { background: #dea560; }
.gomoku-stone { width: 70%; height: 70%; border-radius: 50%; }
.gomoku-stone.b { background: radial-gradient(circle at 30% 30%, #666, #000); }
.gomoku-stone.w { background: radial-gradient(circle at 30% 30%, #fff, #ccc); }
.gok { margin: 10px 0; }
.gok span { margin-right: 10px; }
.badge { background: #eee; border-radius: 999px; padding: 2px 12px; font-size: 13px; }
.tag-r { background: #ffe4e4; color: #c00; }
.tag-b { background: #e0f0ff; color: #06c; }
.junqi-cell { cursor: pointer; }
.junqi-cell.facedown { color: #337; background: #6a89cc; color: #fff; }
.ludo-root { display: flex; gap: 20px; flex-wrap: wrap; }
.dice-btn { font-size: 40px; padding: 10px 24px; }
.statusline { margin: 10px 0; color: #555; }
.msg { color: #c00; margin: 8px 0; min-height: 20px; }
.logbox { background: #fff; padding: 12px; border-radius: 8px; max-height: 300px; overflow: auto; width: 260px; }
/* ===== 手机适配 ===== */
html, body { width: 100%; min-height: 100%; }
main { max-width: 100%; margin: 8px auto; padding: 0 8px; }
header { padding: 10px 12px; }
header h1 { font-size: 17px; }
.lobby { padding: 14px; border-radius: 10px; }
/* 游戏页:棋盘居上自适应,工具按钮横排在下方 */
.game-shell .lobby { padding: 10px; }
.game-shell > div { gap: 10px !important; }
#game-canvas { display: flex; justify-content: center; overflow-x: auto; }
#game-canvas > * { max-width: 100%; height: auto; }
/* 象棋 10x9 格用 vw 缩放 */
.chess-board .cell, #chess-b .cell { width: min(9vw, 44px); height: min(9vw, 44px); }
.chess-piece { font-size: min(4.4vw, 20px); }
/* 军棋 10x6 */
.junqi-cell { width: min(14vw, 56px) !important; height: min(14vw, 56px) !important; font-size: min(4.5vw, 16px) !important; }
/* 五子棋 SVG 自适应 */
#gok-board { width: 100% !important; height: auto !important; max-width: 92vw; display: block; }
/* 工具栏在手机上转为横排 */
.toolbar { flex-direction: row !important; min-width: 0 !important; width: 100%; }
.toolbar .btn.wide { width: auto; flex: 1; padding: 12px 8px; font-size: 15px; }
/* 状态栏可换行 */
.statusline { font-size: 14px; word-break: break-all; }
@media (hover: hover) and (pointer: fine) {
/* 桌面还原固定尺寸 */
.chess-board .cell, #chess-b .cell { width: 44px; height: 44px; }
.junqi-cell { width: 56px !important; height: 56px !important; }
}
.chess-board .crow { display: flex; }
.chess-board .cell { margin: 0; }
.diff-box { display:flex; align-items:center; gap:8px; background:#fff; border:1px solid #ccc; border-radius:8px; padding:8px 12px; }
.diff-box label { font-size:14px; color:#24344d; font-weight:bold; }
.diff-box select { border:none; font-size:15px; outline:none; background:transparent; }
.ai-box { position: fixed; inset: 0; background: rgba(0,0,0,.4); display: flex; align-items: center; justify-content: center; z-index: 99; }
.ai-inner { background: #fff; padding: 18px; border-radius: 10px; display: flex; flex-direction: column; gap: 10px; width: min(90vw, 380px); }
.ai-inner input { padding: 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 14px; }
.ai-hintbox { background: #fffbe6; border: 1px solid #f0d060; border-radius: 8px; padding: 10px 14px; margin: 10px 0; font-size: 15px; line-height: 1.6; }
.toolbar .btn.wide { white-space: nowrap; font-size: 14px; }
/* 浮动工具栏右侧 */
.float-toolbar { position: fixed; right: 10px; top: 50%; transform: translateY(-50%); z-index: 50; display: flex; flex-direction: column; gap: 8px; background: rgba(255,255,255,.94); border: 1px solid #d0d0d0; border-radius: 12px; padding: 10px; box-shadow: 0 4px 16px rgba(0,0,0,.14); width: 128px; }
.float-toolbar .diff-box { flex-direction: column; gap: 4px; padding: 6px 8px; }
.float-toolbar .diff-box select { font-size: 14px; }
.float-toolbar .btn.wide { padding: 8px 6px; font-size: 13px; }
.game-shell { width: 100%; max-width: 100% !important; }
@media (max-width: 560px) {
.float-toolbar { width: 76px; padding: 6px; top: auto; bottom: 10px; transform: none; max-height: 76vh; overflow: auto; }
.float-toolbar .btn.wide { font-size: 11px; padding: 6px 2px; }
.float-toolbar .diff-box label { font-size: 11px; }
.float-toolbar .diff-box select { font-size: 12px; }
.game-shell { width: 100%; max-width: 100% !important; }
}
.game-head .btn { padding: 8px 14px; }
.game-head .diff-box { padding: 6px 10px; }
.game-shall { margin-bottom: 8px; }
.game-head { margin-bottom: 10px; }
.status-banner { background: linear-gradient(90deg, #24344d, #3b547a); color: #fff; padding: 10px 16px; border-radius: 8px; font-size: 16px; font-weight: bold; letter-spacing: 0.5px; box-shadow: 0 2px 6px rgba(36,52,77,.25); margin-bottom: 4px; text-align: center; }
.status-banner:empty::before { content: '…'; opacity: .4; }
.btn.start-big { display: block; width: min(92vw, 420px); margin: 18px auto 8px; padding: 14px 0; font-size: 19px; font-weight: bold; letter-spacing: 1px; border: none; border-radius: 12px; background: linear-gradient(90deg, #1e6ef0, #3b82f6); color: #fff; box-shadow: 0 4px 14px rgba(30,110,240,.35); cursor: pointer; }
.btn.start-big:hover { filter: brightness(1.08); }
.btn.start-big:active { transform: scale(.98); }
.btn.start-two { display: block; width: min(92vw, 420px); margin: 12px auto 8px; padding: 13px 0; font-size: 17px; font-weight: bold; letter-spacing: 1px; border: none; border-radius: 12px; background: linear-gradient(90deg, #0ea56a, #22c98a); color: #fff; box-shadow: 0 4px 12px rgba(14,165,106,.3); cursor: pointer; }
.btn.start-two:hover { filter: brightness(1.08); }
/* 军棋竖版棋盘:按屏幕自适应(不超出视口高度) */
#junqi-b {
width: auto !important;
height: auto !important;
max-width: min(100%, 400px) !important;
max-height: calc(100vh - 258px) !important;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.12);
}
#game-canvas { align-items: flex-start; }
@media (max-width: 560px) {
.game-shell:has(#junqi-b) { max-width: 100% !important; }
#junqi-b { max-height: calc(100vh - 286px) !important; }
/* 手机上头部按钮单行横向滑动,省出竖向空间 */
.game-head {
flex-wrap: nowrap !important;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
padding-bottom: 6px;
width: 100%;
}
.game-head > * { flex: 0 0 auto; }
.game-head .btn { padding: 6px 9px !important; font-size: 12px !important; white-space: nowrap; }
.game-head select { font-size: 12px !important; }
.game-head .diff-box { padding: 3px 6px !important; }
}
/* 大厅卡片保持居中限宽;游戏页满屏 100% */
#view > .lobby:not(.game-shell) { max-width: 1100px; margin: 0 auto; }
.game-shell { width: 100% !important; max-width: 100% !important; box-sizing: border-box; }
.game-shell > * { max-width: 100%; }
/* 手机上禁用下拉刷新,避免对局中误刷新 */
html, body { overscroll-behavior-y: contain; }
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#f6f6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="black" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="black" y="35" x="32" font-weight="bold">&#22763;</text>
</svg>

After

Width:  |  Height:  |  Size: 405 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#f6f6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="black" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="black" y="35" x="32" font-weight="bold">&#30770;</text>
</svg>

After

Width:  |  Height:  |  Size: 405 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#f6f6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="black" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="black" y="35" x="32" font-weight="bold">&#35937;</text>
</svg>

After

Width:  |  Height:  |  Size: 405 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#f6f6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="black" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="black" y="35" x="32" font-weight="bold">&#23559;</text>
</svg>

After

Width:  |  Height:  |  Size: 405 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#f6f6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="black" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="black" y="35" x="32" font-weight="bold">&#39340;</text>
</svg>

After

Width:  |  Height:  |  Size: 405 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#f6f6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="black" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="black" y="35" x="32" font-weight="bold">&#36554;</text>
</svg>

After

Width:  |  Height:  |  Size: 405 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#f6f6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="black" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="black" y="35" x="32" font-weight="bold">&#21330;</text>
</svg>

After

Width:  |  Height:  |  Size: 405 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#fff6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="red" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="red" y="35" x="32" font-weight="bold">&#20181;</text>
</svg>

After

Width:  |  Height:  |  Size: 401 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#fff6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="red" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="red" y="35" x="32" font-weight="bold">&#28846;</text>
</svg>

After

Width:  |  Height:  |  Size: 401 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#fff6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="red" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="red" y="35" x="32" font-weight="bold">&#30456;</text>
</svg>

After

Width:  |  Height:  |  Size: 401 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#fff6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="red" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="red" y="35" x="32" font-weight="bold">&#24101;</text>
</svg>

After

Width:  |  Height:  |  Size: 401 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#fff6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="red" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="red" y="35" x="32" font-weight="bold">&#20620;</text>
</svg>

After

Width:  |  Height:  |  Size: 401 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#fff6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="red" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="red" y="35" x="32" font-weight="bold">&#20453;</text>
</svg>

After

Width:  |  Height:  |  Size: 401 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="64" width="64">
<circle id="outline" fill="#fff6f6" stroke-width="2" stroke="black" r="31" cy="32" cx="32"/>
<circle id="color" fill="none" stroke-width="2" stroke="red" r="27" cy="32" cx="32"/>
<text id="piece_name" font-size="40" text-anchor="middle" alignment-baseline="middle" fill="red" y="35" x="32" font-weight="bold">&#20853;</text>
</svg>

After

Width:  |  Height:  |  Size: 401 B

+87
View File
@@ -0,0 +1,87 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>🐟 摸鱼棋乐 · 益智小游戏</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<header>
<h1>🐟 摸鱼棋乐 <small style="opacity:.7;font-size:13px">· 益智 · 摸鱼 · 小憩</small></h1>
<nav id="menu">
<a href="#/chess" data-game="chess">象棋</a>
<a href="#/gomoku" data-game="gomoku">五子棋</a>
<a href="#/junqi" data-game="junqi">军棋</a>
<a href="/about.html" target="_blank" id="nav-about" style="background:#1e6ef0">📖 使用说明</a>
</nav>
</header>
<main id="view"></main>
<script src="/js/gomoku.js?v=44"></script>
<script src="/js/chess.js?v=44"></script>
<script src="/js/chessAI.js?v=44"></script>
<script src="/js/junqi.js?v=44"></script>
<script src="/js/gomoku_client.js?v=44"></script>
<script src="/js/chess_client.js?v=44"></script>
<script src="/js/junqi_client.js?v=44"></script>
<script src="/js/common.js?v=44"></script>
<script>
const views = {
chess: () => gameLobby('chess','象棋','🐟 楚河汉界,红先黑后,工作间隙杀一盘'),
gomoku: () => gameLobby('gomoku','五子棋','🐟 黑先白后,五连即胜,摸鱼冥想第一选择'),
junqi: () => gameLobby('junqi','军棋','🐟 翻开棋子即归属,隐蔽摸鱼首选'),
};
function gameLobby(key, title, desc) {
return `<section class="lobby">
<div class="lobby-hero"><h2>${title}</h2><p>${desc}</p></div>
<div class="lobby-actions">
<button class="btn start-big" onclick="startSolo('${key}')">🎮 单人 vs AI</button>
<button class="btn start-two" onclick="startTwo('${key}')">👥 双人同屏</button>
</div>
</section>`;
}
function bootSolo(kk) {
ensureGameShell(kk);
setTimeout(() => { try { window['boot_' + kk + '_solo'](); } catch (e) { console.error(e); } }, 0);
}
function startSolo(key) { try { localStorage.setItem('fnos_mode', 'ai'); } catch (e) {} location.hash = '#/' + key + '-solo'; bootSolo(key); }
function startTwo(key) { try { localStorage.setItem('fnos_mode', '2p'); } catch (e) {} location.hash = '#/' + key + '-solo'; bootSolo(key); }
function updateNavActive() {
try {
const cur = (location.hash || '').replace('#/', '').replace('-solo', '').replace('-multi', '') || '';
document.querySelectorAll('nav#menu a[data-game]').forEach(a => {
const on = a.getAttribute('data-game') === cur;
a.classList.toggle('nav-active', on);
a.style.background = on ? '#ffb703' : '';
a.style.color = on ? '#1b2430' : '';
a.style.fontWeight = on ? 'bold' : '';
});
} catch (e) {}
}
function route() {
try {
let k = (location.hash.replace('#/','') || 'chess').replace('-', '_');
updateNavActive();
if (k.endsWith('_solo')) {
const g = k.replace('_solo','');
bootSolo(g);
// 若从存档列表跳到本游戏,优先恢复该存档;否则询问是否继续上一局(刷新/误关不丢局)
let pending = false;
if (window.checkPendingRestore) pending = checkPendingRestore(g);
if (!pending && window.checkAutoResume) checkAutoResume(g);
return;
}
if (!views[k]) k = 'chess';
app.innerHTML = views[k]();
} catch (e) { console.error(e); }
}
const app = document.getElementById('view');
window.addEventListener('hashchange', () => { updateNavActive(); route(); });
if (window.bindLeaveGuard) bindLeaveGuard();
if (window.startAutoSave) startAutoSave(); // 对局中每 1 分钟自动覆盖存档
route();
</script>
</body>
</html>
+76
View File
@@ -0,0 +1,76 @@
// 象棋规则引擎(完整实现:走法生成、将军检测、困毙/长将判定、AI)
const initBoard = () => {
const B = Array.from({ length: 10 }, () => Array(9).fill(null));
const back = ['车','马','相','士','士','相','马','车'];
back.forEach((k, i) => { B[0][i] = { t: k, s: 'b' }; B[9][i] = { t: k, s: 'r' }; });
B[0][4] = { t: TMAP['将'], s: 'b' }; B[9][4] = { t: TMAP['帥'], s: 'r' };
[1, 7].forEach(c => { B[2][c] = { t: '炮', s: 'b' }; B[7][c] = { t: '炮', s: 'r' }; });
[0, 2, 4, 6, 8].forEach(c => { B[3][c] = { t: TMAP['卒'], s: 'b' }; B[6][c] = { t: '兵', s: 'r' }; });
return B;
};
const TMAP = { '帅': '将', '帥': '将', '将': '将', '仕': '士', '士': '士', '相': '相', '象': '相', '傌': '马', '馬': '马', '俥': '车', '車': '车', '炮': '炮', '砲': '炮', '兵': '兵', '卒': '兵' };
const inB = (r, c) => r >= 0 && r < 10 && c >= 0 && c < 9;
class Chess {
constructor(fen) {
if (fen && fen.includes(' moves:')) { const [b, mv] = fen.split(' moves:'); this.B = this.fromFen(b); this.moves = mv ? mv.trim().split(' ').filter(Boolean).map(x => x.split(',').map(Number)) : []; }
else if (fen && fen.includes('/')) { this.B = this.fromFen(fen); this.moves = []; }
else { this.B = initBoard(); this.moves = []; }
this.redTurn = true; // 红先;随后 apply() 每手翻转,不要再用 moves.length 预判
if (this.moves.length) { const ms = this.moves; this.moves = []; for (const m of ms) this.apply(m); }
}
/** 保存/恢复:由「当前局面FEN + 走法表 + 行棋方」重建(区别于 full(),不会重复应用走法) */
static fromState(fen, moves, redTurn) {
const g = new Chess(fen);
g.moves = (moves || []).map(m => m.slice());
g.redTurn = (redTurn === undefined || redTurn === null) ? (g.moves.length % 2 === 0) : !!redTurn;
return g;
}
fromFen(f) {
const rows = f.split('/'); const B = Array.from({ length: 10 }, () => Array(9).fill(null));
rows.forEach((row, r) => { let c = 0; for (const ch of row) { if (/\d/.test(ch)) { c += +ch; continue; } const red = '帥帅仕相傌俥砲兵'.includes(ch); B[r][c++] = { t: TMAP[ch] || ch, s: red ? 'r' : 'b' }; } });
return B;
}
toFen() {
// 红方用红系字形(帥仕相傌俥砲兵)、黑方用黑系字形(将士象馬車砲卒),确保 fromFen 回读时颜色不串
const REV_R = { '将': '帥', '士': '仕', '相': '相', '马': '傌', '车': '俥', '炮': '砲', '兵': '兵' };
const REV_B = { '将': '将', '士': '士', '相': '象', '马': '馬', '车': '車', '炮': '炮', '兵': '卒' };
return this.B.map(row => {
let s = '', z = 0;
for (const p of row) {
if (!p) { z++; continue; }
if (z) { s += z; z = 0; }
s += (p.s === 'r' ? (REV_R[p.t] || p.t) : (REV_B[p.t] || p.t));
}
if (z) s += z;
return s;
}).join('/');
}
full() { return this.toFen() + (this.moves.length ? ' moves: ' + this.moves.map(m => m.join(',')).join(' ') : ''); }
own(r, c, s) { return inB(r, c) && this.B[r][c] && this.B[r][c].s === s; }
apply(m) { const [fr, fc, tr, tc] = m; this.B[tr][tc] = this.B[fr][fc]; this.B[fr][fc] = null; this.moves.push(m); this.redTurn = !this.redTurn; return this; }
force(r, c, s) { if (!inB(r, c)) return null; const p = this.B[r][c]; return p ? p.s : null; }
genMoves(r, c) {
const p = this.B[r][c]; if (!p) return []; const s = p.s, t = p.t, out = []; const me = s, op = s === 'r' ? 'b' : 'r';
const push = (tr, tc) => { if (inB(tr, tc)) { const q = this.B[tr][tc]; if (!q || q.s === op) out.push([tr, tc]); } };
if (t === '车' || t === '炮') {
[[1, 0], [-1, 0], [0, 1], [0, -1]].forEach(([dr, dc]) => { let tr = r + dr, tc = c + dc; while (inB(tr, tc) && !this.B[tr][tc]) { push(tr, tc); tr += dr; tc += dc; } if (t === '车') push(tr, tc); else { let rr = tr + dr, cc = tc + dc; while (inB(rr, cc) && !this.B[rr][cc]) { rr += dr; cc += dc; } push(rr, cc); } });
} else if (t === '马') { [-2, -1, 1, 2].forEach(dr => [-2, -1, 1, 2].forEach(dc => { if (Math.abs(dr) + Math.abs(dc) !== 3) return; const legR = r + (dr === -2 ? -1 : dr === 2 ? 1 : 0), legC = c + (dc === -2 ? -1 : dc === 2 ? 1 : 0); if (legR < 0 || legR > 9 || legC < 0 || legC > 8) return; if (this.B[legR][legC]) return; push(r + dr, c + dc); })); }
else if (t === '相') { [-2, 2].forEach(dr => [-2, 2].forEach(dc => { const tr = r + dr, tc = c + dc, mr = r + dr / 2, mc = c + dc / 2; if (!inB(tr, tc)) return; if (this.B[mr][mc]) return; push(tr, tc); })); }
else if (t === '士') { [-1, 1].forEach(dr => [-1, 1].forEach(dc => { const tr = r + dr, tc = c + dc; if (tc < 3 || tc > 5) return; if (s === 'r' ? tr < 7 : tr > 2) return; push(tr, tc); })); }
else if (t === '将') { let tr, tc; [-1, 1].forEach(dr => {
// 飞将(对将露面)
tr = r + dr; while (inB(tr, c) && !this.B[tr][c]) tr += dr; if (inB(tr, c) && this.B[tr][c].t === '将') push(tr, c);
tr = r + dr; tc = c; if (tc < 3 || tc > 5) return; if (s === 'r' ? tr < 7 : tr > 2) return; push(tr, tc);
}); [-1, 1].forEach(dc => { tr = r, tc = c + dc; if (tc < 3 || tc > 5) return; push(tr, tc); }); }
else if (t === '兵') { const fwd = s === 'r' ? -1 : 1; push(r + fwd, c); const crossed = s === 'r' ? r <= 4 : r >= 5; if (crossed) { push(r, c - 1); push(r, c + 1); } }
return out.map(([tr, tc]) => [r, c, tr, tc]);
}
findK(s) { for (let r = 0; r < 10; r++) for (let c = 0; c < 9; c++) { const p = this.B[r][c]; if (p && p.t === '将' && p.s === s) return [r, c]; } return null; }
attacks(sq, s) { // s 方所有子可否到达 sq(含隔山炮打等。走“吃子/将军”目标判断)
const [tr, tc] = sq; for (let r = 0; r < 10; r++) for (let c = 0; c < 9; c++) { const p = this.B[r][c]; if (!p || p.s !== s) continue; const mv = this.genMoves(r, c).some(m => m[2] === tr && m[3] === tc); if (mv) return true; } return false;
}
inCheck(s) { const k = this.findK(s); if (!k) return false; const [kr, kc] = k; for (let r = 0; r < 10; r++) for (let c = 0; c < 9; c++) { const p = this.B[r][c]; if (!p || p.s === s) continue; const mv = this.genMoves(r, c).some(m => m[2] === kr && m[3] === kc); if (mv) return true; } return false; }
legal(r, c, side) { if (!side) side = this.redTurn ? 'r' : 'b'; const s = this.own(r, c, side); if (!s) return []; const next = side; return this.genMoves(r, c).filter(m => { const save = this.B[m[2]][m[3]], fp = this.B[m[0]][m[1]]; this.B[m[2]][m[3]] = fp; this.B[m[0]][m[1]] = null; const ok = !this.inCheck(next); this.B[m[0]][m[1]] = fp; this.B[m[2]][m[3]] = save; return ok; }); }
allLegal(s) { if (!s) s = this.redTurn ? 'r' : 'b'; const out = []; for (let r = 0; r < 10; r++) for (let c = 0; c < 9; c++) if (this.own(r, c, s)) out.push(...this.legal(r, c, s)); return out; }
}
if (typeof module !== 'undefined') module.exports = { Chess, initBoard, inB };
+74
View File
@@ -0,0 +1,74 @@
// 象棋 AI:α-β 剪枝 + 简单评估(子力+位置)
const VAL = { 车: 900, 马: 350, 相: 120, 士: 120, 将: 100000, 炮: 350, 兵: 80 };
function evalBoard(g, forSide) {
let sc = 0;
for (let r = 0; r < 10; r++) for (let c = 0; c < 9; c++) { const p = g.B[r][c]; if (!p) continue;
let v = VAL[p.t] || (p.t === '兵' ? 80 : 0);
// 兵过河加成、位置微调
if (p.t === '兵') { const crossed = p.s === 'r' ? r <= 4 : r >= 5; if (crossed) v += 60; if (c >= 2 && c <= 6) v += 10; }
if (p.t === '炮' || p.t === '马') { const mid = (r >= 2 && r <= 7); if (mid) v += 15; }
sc += p.s === forSide ? v : -v;
}
return sc;
}
function orderMoves(g, moves) {
return moves.slice().sort((a, b) => {
const ca = g.B[a[2]][a[3]] ? (VAL[g.B[a[2]][a[3]].t] || 0) : 0;
const cb = g.B[b[2]][b[3]] ? (VAL[g.B[b[2]][b[3]].t] || 0) : 0;
return cb - ca;
});
}
function search(g, depth, alpha, beta, side) { // side: 'r'/'b' — 返回评分(相对 side)
const opp = side === 'r' ? 'b' : 'r';
if (g.findK(side) === null) return -1000000;
if (g.findK(opp) === null) return 1000000;
if (depth === 0) {
const ms = g.allLegal(side);
if (ms.length === 0) { // 困毙/被将死
return g.inCheck(side) ? -1000000 : 0; // 简化:困毙判负(兼顾长将规则例外——此处从紧)
}
return evalBoard(g, side);
}
const moves = g.allLegal(side);
if (moves.length === 0) return g.inCheck(side) ? -1000000 : 0;
let best = -Infinity;
for (const m of orderMoves(g, moves)) {
const save = g.B[m[2]][m[3]], fp = g.B[m[0]][m[1]];
g.B[m[2]][m[3]] = fp; g.B[m[0]][m[1]] = null; g.moves.push(m); g.redTurn = !g.redTurn;
const sc = -search(g, depth - 1, -beta, -alpha, opp);
g.redTurn = !g.redTurn; g.moves.pop(); g.B[m[0]][m[1]] = fp; g.B[m[2]][m[3]] = save;
if (sc > best) best = sc;
if (best > alpha) alpha = best;
if (alpha >= beta) break;
}
return best;
}
// aiMove(game,{side:'r'|'b',depth}) → {move, score}
function aiMove(g, opt) {
const side = opt.side || (g.redTurn ? 'r' : 'b');
const opp = side === 'r' ? 'b' : 'r';
const depth = opt.depth || 3;
const moves = g.allLegal(side);
if (!moves.length) return null;
let best = null, bestSc = -Infinity;
if (opt.randomTop) {
// 轻度随机——EASY 级别
const scored = moves.map(m => {
const save = g.B[m[2]][m[3]], fp = g.B[m[0]][m[1]];
g.B[m[2]][m[3]] = fp; g.B[m[0]][m[1]] = null; g.moves.push(m); g.redTurn = !g.redTurn;
const sc = evalBoard(g, side) + Math.floor(Math.random() * 120);
g.redTurn = !g.redTurn; g.moves.pop(); g.B[m[0]][m[1]] = fp; g.B[m[2]][m[3]] = save;
return { m, sc };
}).sort((a, b) => b.sc - a.sc);
return scored[0].m;
}
for (const m of orderMoves(g, moves)) {
const save = g.B[m[2]][m[3]], fp = g.B[m[0]][m[1]];
g.B[m[2]][m[3]] = fp; g.B[m[0]][m[1]] = null; g.moves.push(m); g.redTurn = !g.redTurn;
const sc = -search(g, depth - 1, -Infinity, Infinity, opp);
g.redTurn = !g.redTurn; g.moves.pop(); g.B[m[0]][m[1]] = fp; g.B[m[2]][m[3]] = save;
if (sc > bestSc) { bestSc = sc; best = m; }
}
return { move: best, score: bestSc };
}
if (typeof module !== 'undefined') module.exports = { aiMove, evalBoard };
+250
View File
@@ -0,0 +1,250 @@
// 象棋前端 — SVG 真实线图棋盘(9x10路、九宫斜线、楚河汉界、炮/兵位标记)
var cg = null, sel = null, aiBusy = false, aiTimer = null;
const DISP = { r: { '将': '帥', '士': '仕', '相': '相', '马': '馬', '车': '車', '炮': '砲', '兵': '兵' },
b: { '将': '將', '士': '士', '相': '象', '马': '馬', '车': '車', '炮': '砲', '兵': '卒' } };
// 棋子SVG(markirish/xiangqi 案例样式): t+s → /img/文件名
var IMG = {
r: { '将': 'rG', '士': 'rA', '相': 'rE', '马': 'rH', '车': 'rR', '炮': 'rC', '兵': 'rS', '卒': 'rS' },
b: { '将': 'bG', '士': 'bA', '相': 'bE', '马': 'bH', '车': 'bR', '炮': 'bC', '兵': 'bS', '卒': 'bS' }
};
function chessLevel() { const el = document.getElementById('diff'); return el ? el.value : 'normal'; }
function isTwoP() { try { return localStorage.getItem('fnos_mode') === '2p'; } catch (e) { return false; } }
function twoPLabel() { return isTwoP() ? '(双人:' + (cg.redTurn ? '红方走' : '黑方走') + ')' : ''; }
function boot_chess_solo() {
if (aiTimer) { clearTimeout(aiTimer); aiTimer = null; }
aiBusy = false;
cg = new Chess();
cg._startFen = null;
sel = null; aiBusy = false; gameStartTs = Date.now(); cg._steps0 = 0;
if (window.applyTimer) applyTimer(); resetTimer('r');
render_chess();
const lbl = { easy: '简单', normal: '普通', hard: '困难' }[chessLevel()];
if (isTwoP()) setStatus('chess-st', '双人同屏 · 红方先行 · 红黑轮流点击自己棋子');
else setStatus('chess-st', '难度:' + lbl + ' · 红方(你)先行 · 点选棋子后点击目标格');
}
function checkEnd() {
if (cg.findK('b') === null) { setStatus('chess-st', '🎉 斩杀黑将,红方胜!'); cg.over = true; recordGame({ game: 'chess', result: 'win', dur: fmtDur(gameDurationSec()), steps: cg.moves.length }); gameResultPopup(true, '🏆 红方胜!', '你斩杀黑将 · 用时 ' + fmtDur(gameDurationSec()) + ' · 共 ' + cg.moves.length + ' 步'); return true; }
if (cg.findK('r') === null) { setStatus('chess-st', '黑方胜'); cg.over = true; recordGame({ game: 'chess', result: 'lose', dur: fmtDur(gameDurationSec()), steps: cg.moves.length }); gameResultPopup(false, '💔 黑方胜', '黑方吃掉了你的帥 · 用时 ' + fmtDur(gameDurationSec())); return true; }
if (cg.allLegal(cg.redTurn ? 'r' : 'b').length === 0) {
cg.over = true;
const durTxt = fmtDur(gameDurationSec());
if (cg.inCheck(cg.redTurn ? 'r' : 'b')) {
setStatus('chess-st', (cg.redTurn ? '红方被绝杀,黑胜' : '黑方被绝杀,红胜'));
if (cg.redTurn) { recordGame({ game: 'chess', result: 'lose', dur: durTxt, steps: cg.moves.length }); gameResultPopup(false, '💔 黑方胜', '绝杀:你的帅无路可走 · 用时 ' + durTxt); }
else { recordGame({ game: 'chess', result: 'win', dur: durTxt, steps: cg.moves.length }); gameResultPopup(true, '🏆 红方胜!', '绝杀黑方 · 用时 ' + durTxt); }
}
else {
setStatus('chess-st', '困毙:' + (cg.redTurn ? '红' : '黑') + '方无子可动');
if (cg.redTurn) { recordGame({ game: 'chess', result: 'lose', dur: durTxt, steps: cg.moves.length }); gameResultPopup(false, '💔 黑方胜', '困毙:你无子可动 · 用时 ' + durTxt); }
else { recordGame({ game: 'chess', result: 'win', dur: durTxt, steps: cg.moves.length }); gameResultPopup(true, '🏆 红方胜!', '黑方困毙 · 用时 ' + durTxt); }
}
return true;
}
return false;
}
function render_chess() {
const el = document.getElementById('game-canvas');
if (!el) return;
const CS = 44, PAD = 30;
const W = PAD * 2 + CS * 8, H = PAD * 2 + CS * 9;
const px = (c) => PAD + c * CS, py = (r) => PAD + r * CS;
let s = `<svg id="chess-b" viewBox="0 0 ${W} ${H}" style="touch-action:manipulation;width:100%;max-width:520px;display:block;margin:auto">`;
s += `<rect x="0" y="0" width="${W}" height="${H}" fill="#302013" rx="8"/>`;
s += `<rect x="${PAD-14}" y="${PAD-14}" width="${W - 2*(PAD-14)}" height="${H - 2*(PAD-14)}" fill="#ebe5e1" stroke="#000" stroke-width="2"/>`;
for (let r = 0; r < 10; r++) s += `<line x1="${px(0)}" y1="${py(r)}" x2="${px(8)}" y2="${py(r)}" stroke="#3a3a3a" stroke-width="1.6"/>`;
for (let c = 0; c < 9; c++) {
s += `<line x1="${px(c)}" y1="${py(0)}" x2="${px(c)}" y2="${py(4)}" stroke="#3a3a3a" stroke-width="1.6"/>`;
s += `<line x1="${px(c)}" y1="${py(5)}" x2="${px(c)}" y2="${py(9)}" stroke="#3a3a3a" stroke-width="1.6"/>`;
}
// 外框加粗
s += `<rect x="${px(0)-4}" y="${py(0)-4}" width="${CS*8+8}" height="${CS*9+8}" fill="none" stroke="#3a3a3a" stroke-width="3"/>`;
// 九宫斜线
s += `<line x1="${px(3)}" y1="${py(0)}" x2="${px(5)}" y2="${py(2)}" stroke="#3a3a3a" stroke-width="1.2"/>`;
s += `<line x1="${px(5)}" y1="${py(0)}" x2="${px(3)}" y2="${py(2)}" stroke="#3a3a3a" stroke-width="1.2"/>`;
s += `<line x1="${px(3)}" y1="${py(9)}" x2="${px(5)}" y2="${py(7)}" stroke="#3a3a3a" stroke-width="1.2"/>`;
s += `<line x1="${px(5)}" y1="${py(9)}" x2="${px(3)}" y2="${py(7)}" stroke="#3a3a3a" stroke-width="1.2"/>`;
// 楚河汉界
s += `<text x="${px(1.8)}" y="${py(4) + 26}" font-size="22" fill="#3a3a3a" font-family="Kaiti, serif" text-anchor="middle">楚 河</text>`;
s += `<text x="${px(6.2)}" y="${py(4) + 26}" font-size="22" fill="#3a3a3a" font-family="Kaiti, serif" text-anchor="middle">漢 界</text>`;
// 炮/兵位小折角
const cross = (r, c) => {
const x = px(c), y = py(r), g = 5, d = 13;
if (c === 0) return `<path d="M ${x+g} ${y-g-d} h ${d*0.8} M ${x+g} ${y+g+d} l ${d*0.8} 0 M ${x+g} ${y-g} l ${d*0.6} 0 M ${x+g} ${y+g} l ${d*0.6} 0" stroke="#3a3a3a" stroke-width="1.1" fill="none"/>`;
if (c === 8) return `<path d="M ${x-g} ${y-g-d} l ${-d*0.8} 0 M ${x-g} ${y+g+d} l ${-d*0.8} 0 M ${x-g} ${y-g} l ${-d*0.6} 0 M ${x-g} ${y+g} l ${-d*0.6} 0" stroke="#3a3a3a" stroke-width="1.1" fill="none"/>`;
return `<path d="M ${x-g} ${y-g-d} h ${d*0.8} M ${x+g} ${y-g-d} h ${-d*0.8} M ${x-g} ${y+g+d} h ${d*0.8} M ${x+g} ${y+g+d} h ${-d*0.8} M ${x-g} ${y-g} h ${d*0.6} M ${x-g} ${y+g} h ${d*0.6} M ${x+g} ${y-g} h ${-d*0.6} M ${x+g} ${y+g} h ${-d*0.6}" stroke="#3a3a3a" stroke-width="1.1" fill="none"/>`;
};
[[2,1],[2,7],[7,1],[7,7]].forEach(([r,c]) => s += cross(r,c));
for (const r of [3,6]) for (let c = 0; c < 9; c += 2) s += cross(r,c);
// 最后一步 + 棋子 + 热区
const last = cg.moves.length ? cg.moves[cg.moves.length - 1] : null;
for (let r = 0; r < 10; r++) {
for (let c = 0; c < 9; c++) {
const x = px(c), y = py(r);
if (sel) {
const ok2 = cg.legal(sel[0], sel[1]).some(m => m[2] === r && m[3] === c);
if (ok2) {
if (cg.B[r][c]) s += `<circle cx="${x}" cy="${y}" r="${CS*0.52}" fill="none" stroke="#2a8e2a" stroke-width="2.4"/>`;
else s += `<circle cx="${x}" cy="${y}" r="7" fill="rgba(46,164,46,.8)"/>`;
}
}
const p = cg.B[r][c];
if (p) {
let ring = '';
if (last && last[0] === r && last[1] === c) ring = `<circle cx="${x}" cy="${y}" r="${CS*0.54}" fill="none" stroke="#f90" stroke-width="2.4"/>`;
if (sel && sel[0] === r && sel[1] === c) ring = `<circle cx="${x}" cy="${y}" r="${CS*0.54}" fill="none" stroke="#2b7de0" stroke-width="3"/>`;
const pimg = IMG[p.s][p.t] || 'rG';
s += `${ring}<image href="/img/${pimg}.svg" x="${x - CS*0.5}" y="${y - CS*0.5}" width="${CS}" height="${CS}" style="pointer-events:none"/>`;
}
s += `<rect x="${x - CS/2}" y="${y - CS/2}" width="${CS}" height="${CS}" fill="transparent" onclick="chessClick(${r},${c})" style="cursor:pointer"/>`;
}
}
s += '</svg>';
el.innerHTML = s;
}
function chessClick(r, c) {
if (!cg || cg.over || aiBusy) { if (aiBusy) setStatus('chess-st', '黑方 AI 思考中…'); return; }
if (sel) {
const mv = cg.legal(sel[0], sel[1]).find(m => m[2] === r && m[3] === c);
if (mv) {
const killed = cg.B[r][c];
cg.apply(mv);
sel = null;
const chk = cg.inCheck(cg.redTurn ? 'r' : 'b');
setStatus('chess-st', (cg.redTurn ? '红' : '黑') + '方行棋' + (chk ? ' · 将军!' : '') + (killed ? '(吃子)' : ''));
render_chess();
swapTimer(); // 红走完切黑
if (window.autoSnapshot) autoSnapshot();
maybeAI();
return;
}
}
const side = cg.redTurn ? 'r' : 'b';
if (cg.own(r, c, side)) {
if (sel && sel[0] === r && sel[1] === c) { sel = null; render_chess(); setStatus('chess-st', '已取消选择'); return; }
sel = [r, c]; render_chess();
setStatus('chess-st', '已选 ' + DISP[side][cg.B[r][c].t] + ' · 绿圈=可走位置');
} else { sel = null; render_chess(); setStatus('chess-st', '轮到红方(点己方棋子)'); }
}
function maybeAI(isUndo) {
if (checkEnd()) return;
if (isTwoP()) {
const chk = cg.inCheck(cg.redTurn ? 'r' : 'b');
setStatus('chess-st', '双人同屏 · 轮到 ' + (cg.redTurn ? '红方' : '黑方') + (chk ? ' · 将军!' : ''));
if (cg.moves.length && window.autoCoachIfOn) autoCoachIfOn();
return;
}
if (!cg.redTurn) {
aiBusy = true;
setStatus('chess-st', '黑方 AI 思考中…');
if (aiTimer) { clearTimeout(aiTimer); aiTimer = null; }
aiTimer = setTimeout(() => {
try {
let m;
if (chessLevel() === 'easy') {
const all = cg.allLegal('b');
m = all[Math.floor(Math.random() * all.length)];
} else {
const res = aiMove(cg, { side: 'b', depth: chessLevel() === 'hard' ? 4 : 3 });
m = res && res.move;
}
if (m) {
const legal = cg.legal(m[0], m[1], 'b');
const mv = legal.find(x => x[2] === m[2] && x[3] === m[3]);
if (mv) cg.apply(mv);
else { const all = cg.allLegal('b'); if (all.length) cg.apply(all[Math.floor(Math.random() * all.length)]); }
} else {
const all = cg.allLegal('b');
if (all.length) cg.apply(all[Math.floor(Math.random() * all.length)]);
}
if (checkEnd()) { render_chess(); return; }
setStatus('chess-st', '轮到你(红方)');
render_chess();
if (isUndo) setStatus('chess-st', isUndo);
swapTimer(); // AI走完切回红
if (window.autoSnapshot) autoSnapshot();
if (window.autoCoachIfOn) autoCoachIfOn();
} catch (e) {
setStatus('chess-st', 'AI 出错,已交回你走:' + e.message);
} finally {
aiBusy = false; aiTimer = null;
render_chess();
}
}, 60);
} else {
setStatus('chess-st', '轮到你(红方)');
}
}
window.chessUndo = function() {
if (aiBusy) { aiBusy = false; }
if (!cg || !cg.moves.length) { setStatus('chess-st', '没有可悔的棋'); return; }
let target = 2;
if (!cg.redTurn) target = 1;
for (let i = 0; i < target; i++) { if (cg.moves.length) { cg.moves.pop(); redoFromMoves(); } }
if (!cg.redTurn) { if (cg.moves.length) { cg.moves.pop(); redoFromMoves(); } }
aiBusy = false; sel = null;
render_chess();
setStatus('chess-st', '已悔棋,轮到你');
};
function redoFromMoves() {
// 从本局的起始盘面(残局=残局FEN;常规=初始盘)重放,而不是从初始盘重放
const sf = cg._startFen || null;
const wasPuzzle = cg._puzzle;
const base = sf ? new Chess(sf) : new Chess();
const ms = cg.moves.slice();
base.moves = [];
ms.forEach(m => base.apply(m));
base._startFen = sf; // 关键:保住残局起始盘面,否则再次悔棋会回到整盘初始局面
base._puzzle = wasPuzzle;
cg = base;
}
// —— 存档 / 恢复 ——
window.GAMEHOOKS = window.GAMEHOOKS || {};
GAMEHOOKS.chess = {
started: function () { return !!cg; },
inProgress: function () { return !!(cg && cg.moves.length > 0 && !cg.over && !window.__gameOver); },
serialize: function () {
if (!cg) return null;
const sel = curGameSelects();
return {
game: 'chess', label: '象棋', mode: isTwoP() ? '双人同屏' : '人机',
diff: chessLevel(), timer: sel.timer,
fen: cg.toFen(), moves: cg.moves.map(m => [m[0], m[1], m[2], m[3]]), redTurn: !!cg.redTurn,
startFen: cg._startFen || null, puzzle: !!cg._puzzle,
steps: cg.moves.length,
elapsed: Math.max(0, Math.floor((Date.now() - (gameStartTs || Date.now())) / 1000))
};
},
restore: function (sv) {
try {
if (aiTimer) { clearTimeout(aiTimer); aiTimer = null; }
aiBusy = false; sel = null;
cg = (sv.moves && Chess.fromState) ? Chess.fromState(sv.fen, sv.moves, sv.redTurn) : new Chess(sv.fen);
cg._startFen = sv.startFen || null; cg._puzzle = !!sv.puzzle;
try { localStorage.setItem('fnos_mode', sv.mode === '双人同屏' ? '2p' : 'ai'); } catch (e) {}
const d1 = document.getElementById('diff'); if (d1 && sv.diff) d1.value = sv.diff;
const t1 = document.getElementById('timer');
if (t1 && sv.timer != null) { t1.value = String(sv.timer); applyTimer(); }
gameStartTs = Date.now() - (sv.elapsed || 0) * 1000;
render_chess(); swapTimer();
setStatus('chess-st', '已恢复存档 · ' + (sv.mode || '') + ' · ' + (cg.redTurn ? '红方行棋' : '黑方行棋'));
maybeAI();
return true;
} catch (e) { alert('恢复失败:' + e.message); return false; }
} };
window.boot_chess_solo = boot_chess_solo;
window.loadChessPuzzle = function(pz) {
if (aiTimer) { clearTimeout(aiTimer); aiTimer = null; }
aiBusy = false;
try {
cg = new Chess(pz.fen);
sel = null; aiBusy = false; gameStartTs = Date.now();
cg._puzzle = true;
cg._startFen = pz.fen;
render_chess();
setStatus('chess-st', '残局『' + pz.name + '』· ' + pz.tip);
} catch (e) { setStatus('chess-st', '残局加载失败: ' + e.message); }
};
+848
View File
@@ -0,0 +1,848 @@
// 公共 UI:游戏局容器(棋盘居左,右侧工具栏:悔棋/重新开始)+ 状态栏
var currentRouteKey = 'chess';
const GAME_NAMES = { chess: '象棋', gomoku: '五子棋', junqi: '军棋' };
function ensureGameShell(key) {
currentRouteKey = key;
window.__gameOver = false;
const app = document.getElementById('view');
app.innerHTML = `<section class="lobby game-shell">
<div id="statusline" class="status-banner"><span id="status-text"></span><span id="timer-badge" style="float:right"></span></div>
<div class="game-head" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:10px">
<h2 style="margin:0;font-size:18px">${GAME_NAMES[key]}</h2>
<span style="flex:1"></span>
<button class="btn" onclick="gameUndo()" style="padding:7px 11px;font-size:13px">↩ 悔棋</button>
<button class="btn primary" onclick="gameRestart()" style="padding:7px 11px;font-size:13px">⟳ 重新开始</button>
<button class="btn" onclick="showPuzzles()" style="padding:7px 11px;font-size:13px">🎯 残局</button>
<button class="btn" onclick="showRanks()" style="padding:7px 11px;font-size:13px">🏆 排行</button>
<button class="btn" onclick="showSaves()" style="padding:7px 11px;font-size:13px">💾 存档</button>
<div class="diff-box" style="padding:5px 9px">
<label for="timer" style="font-size:12px">⏱ 倒计时</label>
<select id="timer" onchange="applyTimer()" style="font-size:13px">
<option value="0">无</option>
<option value="60">1分钟</option>
<option value="180">3分钟</option>
<option value="300">5分钟</option>
<option value="600">10分钟</option>
<option value="1200" selected>20分钟</option>
<option value="1800">30分钟</option>
<option value="3600">60分钟</option>
</select>
</div>
<div class="diff-box" style="padding:5px 9px">
<label for="diff" style="font-size:12px">难度</label>
<select id="diff" onchange="gameRestart()" style="font-size:13px">
<option value="easy">简单</option>
<option value="normal" selected>普通</option>
<option value="hard">困难</option>
</select>
</div>
<button class="btn" onclick="toggleAuto()" id="auto-btn" style="padding:7px 11px;font-size:13px">☰ 每步自动提示</button>
<button class="btn" onclick="aiCoach()" id="ai-coach-btn" style="padding:7px 11px;font-size:13px">🤖 AI 教我走</button>
<button class="btn" onclick="aiSettings()" style="padding:7px 11px;font-size:13px">⚙ 模型设置</button>
<button class="btn" onclick="showRules()" style="padding:7px 11px;font-size:13px">📖 玩法</button>
<a class="btn" href="#/${key}" style="text-decoration:none;padding:7px 11px;font-size:13px">← 返回</a>
</div>
<div class="msg" id="msg"></div>
<div id="ai-hint" class="ai-hintbox" style="display:none"></div>
<div id="game-canvas"></div>
</section>`;
}
function gameUndo() {
const k = currentRouteKey;
if (k === 'chess' && window.chessUndo) window.chessUndo();
if (k === 'gomoku' && window.gomokuUndo) window.gomokuUndo();
if (k === 'junqi' && window.junqiUndo) window.junqiUndo();
}
function gameRestart() {
window.__gameOver = false;
if (window.clearAutoSnapshot) clearAutoSnapshot();
if (window.clearAutoSaveRecord) clearAutoSaveRecord();
const m = document.getElementById('result-modal'); if (m) m.remove();
const h = document.getElementById('ai-hint'); if (h) { h.style.display = 'none'; }
if (window['boot_' + currentRouteKey + '_solo']) window['boot_' + currentRouteKey + '_solo']();
}
function setStatus(_id, text) {
const el = document.getElementById('status-text') || document.getElementById('statusline') || document.getElementById('msg');
if (el) el.innerText = text;
}
function $(id) { return document.getElementById(id); }
// —— 对局计时 + 战绩记录 ——
var gameStartTs = null;
function gameStarted() { gameStartTs = Date.now(); }
function gameDurationSec() { return gameStartTs ? Math.round((Date.now() - gameStartTs) / 1000) : 0; }
function fmtDur(sec) { const m = Math.floor(sec / 60), s2 = sec % 60; return m ? (m + '分' + s2 + '秒') : (s2 + '秒'); }
function recordGame(o) {
o.dur = o.durTxt || fmtDur(gameDurationSec());
o.mode = localStorage.getItem('fnos_mode') === '2p' ? '双人' : '人机';
fetch('/api/rank', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(o) }).catch(() => {});
}
// —— AI 教练 ——
function getAICfg() {
try { return JSON.parse(localStorage.getItem('fnos_ai_cfg') || '{}'); } catch (e) { return {}; }
}
function saveAICfg(cfg) { localStorage.setItem('fnos_ai_cfg', JSON.stringify(cfg)); }
function aiSettings() {
const cfg = getAICfg();
const app = document.getElementById('view');
let box = document.getElementById('ai-set');
if (box) box.remove();
box = document.createElement('div');
box.id = 'ai-set';
box.className = 'ai-box';
box.innerHTML = `<div class="ai-inner">
<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap">
<b>接入自己的大模型(OpenAI 兼容)</b>
<a href="https://ai.88531.cn" target="_blank" class="btn primary" style="text-decoration:none;font-size:13px">🔑 免费 获取KEY</a>
</div>
<input id="ai-url" placeholder="Base URL 例:https://ai.88531.cn/v1" value="${cfg.baseUrl || 'https://ai.88531.cn/v1'}">
<input id="ai-key" placeholder="API Key(在 ai.88531.cn 获取)" value="${cfg.apiKey || ''}">
<input id="ai-model" placeholder="模型名 例:deepseek-v4.1-flash" value="${cfg.model || 'deepseek-v4.1-flash'}">
<div><button class="btn primary" onclick="aiSave()">保存并启用</button>
<button class="btn" onclick="document.getElementById('ai-set').remove()">关闭</button></div>
</div>`;
app.prepend(box);
}
function aiSave() {
saveAICfg({ baseUrl: document.getElementById('ai-url').value.trim(), apiKey: document.getElementById('ai-key').value.trim(), model: document.getElementById('ai-model').value.trim() });
const b = document.getElementById('ai-set'); if (b) b.remove();
gameRestart();
}
function aiBoardDesc() {
const k = currentRouteKey;
if (k === 'chess' && cg) {
const lines = ['象棋当前局面(行 1=黑方底线, 行 10=红方底线, 列从左到右 a-i):'];
for (let r = 0; r < 10; r++) {
const row = [];
for (let c = 0; c < 9; c++) {
const p = cg.B[r][c];
if (p) row.push(String.fromCharCode(97 + c) + (10 - r) + ':' + (p.s === 'r' ? '红' : '黑') + DISP[p.s][p.t]);
}
lines.push(row.join(' '));
}
lines.push('轮到 ' + (cg.redTurn ? '红方(你)' : '黑方(AI)'));
return lines.join('\n');
}
if (k === 'gomoku' && gk) {
const lines = ['五子棋 15x15(列 a-o,行 1-15,行1在上):'];
for (let r = 0; r < 15; r++) {
let s = '';
for (let c = 0; c < 15; c++) s += gk.B[r][c] === 0 ? '.' : (gk.B[r][c] === 1 ? 'X' : 'O');
lines.push((r + 1) + ' ' + s.split('').join(' '));
}
lines.push('X=黑(你) O=白(AI) 轮到 ' + (gk.player === 1 ? '黑(你)' : '白(AI)'));
return lines.join('\n');
}
if (k === 'junqi' && jq) {
const lines = ['军棋翻棋局面(10行x6列;"军棋"=未翻开的暗牌,其余为已翻明):'];
for (let r = 0; r < jq.R; r++) {
const row = [];
for (let c = 0; c < jq.C; c++) {
const p = jq.cells[r][c];
if (!p) row.push('空');
else if (!jq.shown[r][c]) row.push('暗');
else row.push((p.owner === 'r' ? '红' : '蓝') + FACE[p.kind]);
}
lines.push((r + 1) + ': ' + row.join(' '));
}
lines.push('轮到 ' + (jq.turnOwner() === 'r' ? '红方(你)' : '蓝方(AI)'));
lines.push('等级: 司令>军长>师长>旅长>团长>营长>连长>排长>工兵;工兵可挖雷,炸弹与任何子同归,将对方军旗扛回即胜');
return lines.join('\n');
}
return '';
}
function aiHint() { return document.getElementById('ai-hint'); }
async function aiCoach() {
const cfg = getAICfg();
if (!cfg.baseUrl || !cfg.model) { aiSettings(); return; }
const box = aiHint();
if (box) { box.style.display = 'block'; box.innerText = 'AI 教练思考中…'; }
const btn = document.getElementById('ai-coach-btn');
if (btn) { btn.disabled = true; btn.innerText = '🤖 思考中…'; }
try {
const resp = await fetch('/api/ai-hint', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ baseUrl: cfg.baseUrl, apiKey: cfg.apiKey, model: cfg.model, prompt: aiBoardDesc() }) });
const j = await resp.json();
if (box) box.innerText = '💡 AI 教练:' + (j.hint || ('出错了:' + j.error));
} catch (e) {
if (box) box.innerText = '💡 AI 教练连接失败:' + e.message;
}
if (btn) { btn.disabled = false; btn.innerText = '🤖 AI 教我走'; }
}
function toggleAuto() {
const on = localStorage.getItem('fnos_ai_auto') !== '1';
localStorage.setItem('fnos_ai_auto', on ? '1' : '0');
updateAutoBtn();
if (on) aiCoach(); else { const b = aiHint(); if (b) { b.style.display = 'none'; } }
}
function updateAutoBtn() {
const on = localStorage.getItem('fnos_ai_auto') === '1';
const b = document.getElementById('auto-btn');
if (b) { b.innerText = on ? '☑ 每步自动提示' : '☰ 每步自动提示'; b.classList.toggle('primary', on); }
}
function autoCoachIfOn() {
if (localStorage.getItem('fnos_ai_auto') === '1') { const cfg = getAICfg(); if (cfg.baseUrl && cfg.model) aiCoach(); }
}
window.__gameOver = false; // 本局是否已结束(结束/认输/超时后不再拦截离开)
function gameResultPopup(won, title, detail) {
window.__gameOver = true;
if (window.clearAutoSnapshot) clearAutoSnapshot();
if (window.clearAutoSaveRecord) clearAutoSaveRecord();
let box = document.getElementById('result-modal');
if (box) box.remove();
box = document.createElement('div');
box.id = 'result-modal';
box.className = 'ai-box';
box.innerHTML = `<div class="ai-inner" style="text-align:center">
<div style="font-size:52px">${won ? '🏆' : '💔'}</div>
<div style="font-size:22px;font-weight:bold;margin:6px 0">${title}</div>
${detail ? `<div style="color:#666;margin-bottom:10px">${detail}</div>` : ''}
<div><button class="btn primary" onclick="gameRestart()">⟳ 再来一局</button>
<button class="btn" onclick="document.getElementById('result-modal').remove()">关闭</button></div>
</div>`;
document.getElementById('view').prepend(box);
}
// —— 残局库 ——
const PUZZLES = {
chess: [
{ name: '马后炮·绝杀', fen: '3将4/9/9/9/4傌4/9/4砲4/9/9/4帥4 moves:', tip: '红先:马后炮杀' },
{ name: '重炮·将', fen: '3将4/9/9/9/9/9/4砲4/9/9/4帥4 moves:', tip: '红先:双炮重线' },
{ name: '双车胁士', fen: '3将4/4士4/9/9/9/9/9/4俥4/4俥4/4帥4 moves:', tip: '红先:双车抢士' },
{ name: '海底捞月', fen: '3将4/4士4/9/9/9/9/9/9/4砲4/4帥4 moves:', tip: '红先:炮打底士' },
{ name: '卧槽马', fen: '9/9/9/9/9/9/9/9/4傌4/3K4 moves:', tip: '红先:马挂角杀' },
{ name: '铁门栓', fen: '3ak4/9/4b4/9/9/9/4C4/9/9/4K4 moves:', tip: '红先:炮镇中路' },
{ name: '一马双将', fen: '3k5/9/9/9/4a4/9/4H4/9/9/4K4 moves:', tip: '红先:马后炮位' },
{ name: '闷宫', fen: '3k5/9/9/9/9/9/9/4C4/4C4/4K4 moves:', tip: '红先:双炮闷杀' },
],
gomoku: [
{ name: '活三冲四·三步杀', seq: [[7,7],[7,8],[8,6],[8,9],[6,5],[6,9],[7,6]], tip: '黑先:连冲取胜' },
{ name: '四三杀', seq: [[7,7],[8,8],[7,6],[6,6],[7,8],[7,5],[7,9],[6,7]], tip: '黑先:四三胜' },
{ name: '双活三攻杀', seq: [[7,7],[7,8],[8,6],[8,9],[6,5],[9,6]], tip: '黑先:双三必胜' },
{ name: '长连禁手挑战', seq: [[7,7],[7,8],[7,6],[7,5],[7,4],[8,9]], tip: '黑先避开禁手取胜' },
{ name: '斜线冲刺', seq: [[7,7],[8,7],[6,6],[9,7],[5,5],[10,7]], tip: '黑先斜线连五' },
{ name: '四子僵局', seq: [[7,7],[8,8],[7,6],[6,6],[7,8],[8,6],[7,5],[6,7]], tip: '黑先破僵局' },
],
junqi: [
{ name: '明棋·单兵突破', open: true, tip: '全明棋,红先吃旗' },
{ name: '明棋·雷区排雷', open: true, mineFirst: true, tip: '全明棋,先挖雷再突破' },
{ name: '明棋·炸弹阵', open: true, boomMode: true, tip: '全明棋,善用炸弹同归' },
]
};
var previewPz = null;
function showPuzzles() {
let box = document.getElementById('pz-modal');
if (box) box.remove();
box = document.createElement('div');
box.id = 'pz-modal'; box.className = 'ai-box';
const list = (PUZZLES[currentRouteKey] || []).map((pz, i) =>
`<div style="display:flex;gap:10px;align-items:center;padding:10px;border:1px solid #eee;border-radius:8px">
<span style="flex:1"><b>${pz.name}</b><br><span style="color:#888;font-size:12px">${pz.tip}</span></span>
<button class="btn" onclick="previewPuzzle(${i})">👁 预览</button>
<button class="btn primary" onclick="playPuzzle(${i})">开始</button>
</div>`).join('');
box.innerHTML = `<div class="ai-inner" style="width:min(92vw, 440px)">
<b>🎯 选择残局</b>
<div style="max-height:50vh;overflow:auto;display:flex;flex-direction:column;gap:8px">${list || '<div style="color:#888">该游戏暂无残局</div>'}</div>
<div id="pz-preview" class="ai-hintbox" style="display:none;max-height:40vh;overflow:auto"></div>
<div><button class="btn" onclick="document.getElementById('pz-modal').remove()">关闭</button></div>
</div>`;
document.getElementById('view').prepend(box);
}
function previewPuzzle(i) {
const pz = PUZZLES[currentRouteKey][i];
if (!pz) return;
previewPz = { index: i, pz };
const pv = document.getElementById('pz-preview');
if (!pv) return;
pv.style.display = 'block';
let html = '<b>👁 预览:' + pz.name + '</b><br><small style="color:#888">' + pz.tip + '</small><br><br>';
html += '<div style="font-family:monospace;font-size:13px;line-height:1.5;background:#fafafa;border-radius:6px;padding:8px;white-space:pre-wrap">' + puzzleText(pz) + '</div>';
pv.innerHTML = html;
}
function puzzleText(pz) {
if (currentRouteKey === 'chess' && pz.fen) {
// 展示棋盘字符画
const rows = pz.fen.split(' ')[0].split('/');
const names = { '将':'将','士':'士','相':'相','马':'马','马':'马','俥':'车','砲':'炮','兵':'兵','帥':'帅','仕':'士','象':'象','傌':'马','車':'车' };
let out = '';
rows.forEach(r => {
let line = '';
for (const ch of r) {
if (/[0-9]/.test(ch)) { for (let i = 0; i < +ch; i++) line += ' '; }
else line += ch + ' ';
}
out += line + '\n';
});
return out;
}
if (currentRouteKey === 'gomoku' && pz.seq) {
const N = 15;
const B = Array.from({ length: N }, () => Array(N).fill(0));
let p = 1;
(pz.seq || []).forEach(([r, c]) => { B[r][c] = p; p = p === 1 ? 2 : 1; });
let out = ' ' + Array.from({length:N},(_,i)=>String.fromCharCode(97+i)).join('') + '\n';
B.forEach((row, i) => out += String(i+1).padStart(2) + ' ' + row.map(v => v === 0 ? '.' : (v === 1 ? 'X' : 'O')).join('') + '\n');
return out;
}
return pz.tip || '';
}
function playPuzzle(i) {
const pz = PUZZLES[currentRouteKey][i];
if (!pz) return;
previewPz = null;
const b = document.getElementById('pz-modal'); if (b) b.remove();
if (currentRouteKey === 'chess' && window.loadChessPuzzle) window.loadChessPuzzle(pz);
if (currentRouteKey === 'gomoku' && window.loadGomokuPuzzle) window.loadGomokuPuzzle(pz);
if (currentRouteKey === 'junqi' && window.loadJunqiPuzzle) window.loadJunqiPuzzle(pz);
}
function loadPuzzle(i) { playPuzzle(i); } // 兼容旧调用
var _rankAll = null;
function showRanks() {
const key = curGameKey();
fetch('/api/rank?game=' + encodeURIComponent(key)).then(r => r.json()).then(o => {
_rankAll = { game: key, file: (o && o.file) || '', games: (o && o.games) || [] };
renderRanks();
}).catch(e => alert('读取战绩失败:' + e.message));
}
function renderRanks() {
let box = document.getElementById('rank-modal');
if (box) box.remove();
box = document.createElement('div');
box.id = 'rank-modal'; box.className = 'ai-box';
const o = _rankAll || { games: [] };
const names = { chess: '♟️ 象棋', gomoku: '⚫ 五子棋', junqi: '🚩 军棋' };
const key = o.game || curGameKey();
const list = (o.games || []).slice(0, 200);
const wins = list.filter(x => x.result === 'win').length;
const loses = list.filter(x => x.result === 'lose').length;
let html = '<b>🏆 ' + (names[key] || '') + ' 战绩排行</b>';
html += '<div style="color:#888;font-size:13px;margin-top:4px">本游戏战绩单独统计保存(共 ' + list.length + ' 局 · 胜 ' + wins + ' · 负 ' + loses + '),与其他游戏互不混合</div>';
if (o.file) html += '<div style="font-size:12px;color:#888;margin-top:4px">数据文件:<code style="color:#1e6ef0">' + o.file + '</code></div>';
html += '<div style="margin:8px 0"><button class="btn" style="padding:5px 11px;font-size:13px" onclick="exportRanks()">⬇ 导出 JSON</button></div>';
html += '<div style="max-height:52vh;overflow:auto"><table><tr><th>时间</th><th>模式</th><th>结果</th><th>用时</th><th>手数</th></tr>';
list.forEach(rec => {
const d = new Date(rec.ts);
const isl = (d.getMonth() + 1) + '-' + d.getDate() + ' ' + p2(d.getHours()) + ':' + p2(d.getMinutes());
const icon = rec.result === 'win' ? '<span style="color:#2a7">胜</span>' : rec.result === 'lose' ? '<span style="color:#c33">负</span>' : '平';
const durTxt = rec.durTxt || (typeof rec.dur === 'number' ? rec.dur + '秒' : (rec.dur || ''));
html += '<tr><td style="white-space:nowrap">' + isl + '</td><td>' + (rec.mode || '') + '</td><td>' + icon + '</td><td>' + durTxt + '</td><td>' + (rec.steps != null ? rec.steps : '') + '</td></tr>';
});
if (!list.length) html += '<tr><td colspan="5" style="color:#888;padding:10px">本游戏还没有战绩,下完一局就会自动记录</td></tr>';
html += '</table></div>';
html += '<div style="margin-top:10px"><button class="btn" id="rank-close">关闭</button></div>';
box.innerHTML = '<div class="ai-inner" style="width:min(96vw,600px)">' + html + '</div>';
document.getElementById('view').prepend(box);
bindRankClose();
}
function exportRanks() {
try {
const o = _rankAll || {};
const key = o.game || curGameKey();
const data = o.games || [];
const blob = new Blob([JSON.stringify({ exportedAt: new Date().toISOString(), game: key, games: data }, null, 2)], { type: 'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = key + '-ranks-' + new Date().toISOString().slice(0, 10) + '.json';
document.body.appendChild(a); a.click(); document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(a.href), 3000);
} catch (e) { alert('导出失败:' + e.message); }
}
window.exportRanks = exportRanks;
window.showRanks = showRanks;
// rank-modal 关闭 Gary 绑定 fetch 结束后 addEventListener
function bindRankClose() { const b = document.getElementById('rank-close'); if (b) b.onclick = () => { const m = document.getElementById('rank-modal'); if (m) m.remove(); }; }
// —— 玩法说明(每个游戏自己的介绍,点「📖 玩法」查看) ——
const GAME_RULES = {
chess: {
name: '♟️ 象棋',
intro: '红先黑后,轮流走子。把对方的「将/帅」将死(无处可逃)即胜;本方无棋可走(困毙)也判负。',
sections: [
['怎么走子', [
'车:直线任意格(不能翻山)',
'马:走「日」字,被挡住马腿不能走',
'相/象:走「田」字,塞象眼不能走,不能过河',
'士/仕:九宫格内斜走一步',
'将/帅:九宫格内直走一步,且双方不能「照面」',
'炮:走直线,吃子必须隔一个子(翻山打)',
'兵/卒:向前一步,过河后还能左右走'
]],
['操作方式', [
'点自己的棋子 → 出现绿圈(可走位置)→ 再点要去的点',
'吃子时会提示「吃子」,被将军会提示「将军!」',
'「↩ 悔棋」撤回上一回合(人机模式一次撤你和 AI 各一步)'
]],
['可以玩什么', [
'人机对战:难度可选 简单 / 普通 / 困难',
'双人同屏:和旁边的人一台手机轮流走,不用联机',
'残局挑战:点「🎯 残局」选一局,先看摆位再开始(如马后炮、重炮将杀)',
'存档:随时点「💾 存档」保存,换设备/明天再来点「恢复」继续',
'AI 教练:「🤖 AI 教我走」让 AI 给建议,「☰ 每步自动提示」每一步自动提示',
'倒计时:可设 1~60 分钟,超时判负;「🏆 排行」看战绩与用时'
]]
]
},
gomoku: {
name: '⚫ 五子棋',
intro: '黑先白后,轮流在交叉点落子。谁先连成 5 子(横 / 竖 / 斜)谁胜。',
sections: [
['怎么下', [
'点棋盘交叉点落子,落子后不能移动、不能吃子',
'你执黑先走,AI 执白',
'连成 5 子(含 5 子以上)即胜,棋盘下满为平局'
]],
['操作方式', [
'点交叉点即落子;最后落子会有红点标记',
'「↩ 悔棋」撤回你和 AI 各一手;残局局面不会被撤掉'
]],
['可以玩什么', [
'人机对战:简单(随手)/ 普通 / 困难(会堵你的活四、连四)',
'双人同屏:两人轮流点,不用联机',
'残局挑战:活三冲四、双四杀等预置局面,练杀法',
'存档 / 排行 / 倒计时 / AI 教练 与象棋一致'
]]
]
},
junqi: {
name: '🚩 军棋(陆战棋 · 翻棋)',
intro: '开局双方 50 枚棋子全部背面朝上,随机布满兵站。轮流翻子或走子,翻到的颜色就是你的阵营(先翻者定色)。军旗被吃或对方无子可动即胜。',
sections: [
['棋子大小(大吃小)', [
'司令 > 军长 > 师长 > 旅长 > 团长 > 营长 > 连长 > 排长 > 工兵',
'同等级相遇:同归于尽(双方都拿掉)',
'地雷:不能移动;只有工兵能挖掉它,其他棋子碰上去会被炸掉',
'炸弹:与任何棋子相遇都同归于尽',
'军旗:被对方吃到即输(军棋不能移动)'
]],
['棋盘要点', [
'行营(圆圈):棋子进营后不可被吃(空营可以走进、也可以走出来)',
'大本营(四角方框):棋子进入后不能再移动',
'铁路(双线):工兵可沿铁路直行任意格,其他棋子一次走一步',
'山界(中间横带):只有两侧与中路三处可以通行',
'斜线:只有行营与四角兵站之间可以斜走'
]],
['操作方式', [
'点背面棋子 = 翻开(翻到红/蓝就归你)',
'点自己的明棋 → 再点相邻目标格移动或吃子',
'吃子失败会提示(你被吃或同归于尽)'
]],
['可以玩什么', [
'人机对战:蓝方由 AI 行动(会吃子、会抢行营)',
'双人同屏:两人轮流翻/走,一台手机',
'残局挑战:明棋局面(单兵突破 / 雷区排雷 / 炸弹阵)',
'存档 / 排行 / 倒计时 都支持,随时中断随时续'
]]
]
}
};
function showRules() {
const key = curGameKey();
const r = GAME_RULES[key] || GAME_RULES.chess;
let box = document.getElementById('rules-modal');
if (box) box.remove();
box = document.createElement('div');
box.id = 'rules-modal'; box.className = 'ai-box';
let html = '<b>' + r.name + ' · 玩法说明</b>';
html += '<div style="color:#555;margin:8px 0;line-height:1.6">' + r.intro + '</div>';
r.sections.forEach(([t, items]) => {
html += '<div style="margin-top:10px"><b style="color:#1e6ef0">▎' + t + '</b><ul style="margin:6px 0 0 18px;padding:0;line-height:1.75;color:#333">';
items.forEach(x => { html += '<li>' + x + '</li>'; });
html += '</ul></div>';
});
html += '<div style="margin-top:14px"><a class="btn" href="/about.html" target="_blank" style="text-decoration:none;padding:7px 12px">📖 完整使用说明</a> '
+ '<button class="btn" onclick="document.getElementById(\'rules-modal\').remove()" style="padding:7px 12px">关闭</button></div>';
box.innerHTML = '<div class="ai-inner" style="width:min(94vw,560px);max-height:82vh;overflow:auto">' + html + '</div>';
document.getElementById('view').prepend(box);
}
window.showRules = showRules;
// —— 离开守卫:对局未结束就点其他链接/刷新/关页时提示 ——
function gameInProgress() {
if (window.__gameOver) return false;
const h = (window.GAMEHOOKS || {})[curGameKey()];
if (!h) return false;
let moved = false;
try { moved = (typeof h.inProgress === 'function') ? !!h.inProgress() : false; } catch (e) {}
if (moved) return true;
// 尚未落子/翻子,但已是"计时对局"(设了倒计时并已在棋盘上待了一会儿)也算进行中
try {
const on = (typeof timerSetting === 'function') && timerSetting() > 0;
const alive = (typeof h.started === 'function') ? !!h.started() : false;
const dwell = Date.now() - (window.gameStartTs || Date.now());
if (on && alive && dwell > 4000) return true;
} catch (e) {}
return false;
}
// —— 自动存档:对局进行中每 60 秒覆盖保存到服务端(防止丢局) ——
var _autoSaveTimer = null, _autoSaveLast = 0;
function autoSaveNow(force) {
try {
if (window.__gameOver) return false;
const key = curGameKey();
const h = (window.GAMEHOOKS || {})[key];
if (!h || typeof h.serialize !== 'function') return false;
if (!gameInProgress() && !force) return false;
const sv = h.serialize();
if (!sv) return false;
sv.id = 'auto-' + key;
sv.auto = true;
sv.label = sv.label || key;
sv.savedAt = Date.now();
_autoSaveLast = Date.now();
fetch('/api/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(sv) })
.then(r => r.json()).then(res => {
if (res && res.ok) {
const badge = document.getElementById('timer-badge');
if (badge && !badge.dataset.auto) badge.dataset.auto = '1';
}
}).catch(() => {});
return true;
} catch (e) { return false; }
}
window.autoSaveNow = autoSaveNow;
function autoSaveTick() { if (gameInProgress()) autoSaveNow(); }
function startAutoSave() {
if (_autoSaveTimer) return;
_autoSaveTimer = setInterval(autoSaveTick, 60000); // 每 1 分钟
// 切到后台/离开页面前也补一次
document.addEventListener('visibilitychange', function () { if (document.hidden) autoSaveNow(); });
window.addEventListener('pagehide', function () { autoSaveNow(); });
}
window.startAutoSave = startAutoSave;
function clearAutoSaveRecord(key) {
const g = key || curGameKey();
try { fetch('/api/save?game=' + encodeURIComponent(g) + '&id=' + encodeURIComponent('auto-' + g), { method: 'DELETE' }); } catch (e) {}
}
window.clearAutoSaveRecord = clearAutoSaveRecord;
// —— 局中自动快照:刷新/误关都不丢局(开局时询问是否继续) ——
function autoSnapshot() {
try {
const key = curGameKey();
const h = (window.GAMEHOOKS || {})[key];
if (!h || typeof h.serialize !== 'function') return;
if (window.__gameOver) { localStorage.removeItem('fnos_resume_' + key); return; }
const sv = h.serialize();
if (!sv) return;
const steps = sv.steps || 0;
const timerOn = (typeof timerSetting === 'function') && timerSetting() > 0;
if (steps > 0 || timerOn) { sv.savedAt = Date.now(); localStorage.setItem('fnos_resume_' + key, JSON.stringify(sv)); }
} catch (e) {}
}
window.autoSnapshot = autoSnapshot;
function clearAutoSnapshot(key) { try { localStorage.removeItem('fnos_resume_' + (key || curGameKey())); } catch (e) {} }
window.clearAutoSnapshot = clearAutoSnapshot;
function checkAutoResume(key) {
let raw = null;
try { raw = localStorage.getItem('fnos_resume_' + key); } catch (e) {}
if (!raw) return false;
let sv = null;
try { sv = JSON.parse(raw); } catch (e) { clearAutoSnapshot(key); return false; }
if (!sv || !sv.steps && !sv.timer) { clearAutoSnapshot(key); return false; }
setTimeout(function () {
const ok = window.confirm('检测到上一局『' + (sv.label || '') + '』还没下完(' + (sv.steps || 0) + ' 手/子,'
+ new Date(sv.savedAt || Date.now()).toLocaleString() + ')\n\n点「确定」继续这局,点「取消」重新开一局。');
const h = (window.GAMEHOOKS || {})[key];
if (ok && h && typeof h.restore === 'function') { h.restore(sv); }
else clearAutoSnapshot(key);
}, 120);
return true;
}
window.checkAutoResume = checkAutoResume;
var _leaveGuardBound = false;
function bindLeaveGuard() {
if (_leaveGuardBound) return;
_leaveGuardBound = true;
// 1) 点击链接(导航 / 返回 / 外链)
document.addEventListener('click', function (ev) {
let a = ev.target;
while (a && a !== document && !(a.tagName === 'A' && a.getAttribute('href'))) a = a.parentNode;
if (!a || a === document) return;
const href = a.getAttribute('href') || '';
if (!href || href.charAt(0) === '#' && (href === '#' || href === location.hash)) return;
if (/^javascript:/i.test(href)) return;
if (!gameInProgress()) return;
if (!window.confirm('当前棋局还没结束,确定要离开吗?\n\n提示:可以先点「💾 存档」把进度存下来,下次在「恢复」里继续。')) {
ev.preventDefault(); ev.stopPropagation();
}
}, true);
// 2) 刷新/关闭(浏览器原生提示)
window.addEventListener('beforeunload', function (e) {
if (!gameInProgress()) return;
e.preventDefault();
e.returnValue = '当前棋局还没结束,确定离开吗?';
return e.returnValue;
});
// 3) 键盘刷新:F5 / Ctrl+R / Cmd+R(部分浏览器不弹原生提示,这里自己拦)
window.addEventListener('keydown', function (e) {
const k = (e.key || '').toLowerCase();
const isReload = k === 'f5' || ((e.ctrlKey || e.metaKey) && k === 'r');
if (!isReload) return;
if (!gameInProgress()) return;
if (!window.confirm('当前棋局还没结束,确定要刷新吗?\n\n(刷新后可在开局提示里选择继续上一局)')) {
e.preventDefault(); e.stopPropagation();
}
}, true);
}
window.gameInProgress = gameInProgress; window.bindLeaveGuard = bindLeaveGuard;
// —— 存档系统(服务端 data/saves.json,日期时间标识,可恢复继续) ——
var _savesCache = [];
var _spMsg = '';
function p2(n) { return String(n).padStart(2, '0'); }
function fmtDT(ts) {
const d = new Date(ts);
return d.getFullYear() + '-' + p2(d.getMonth() + 1) + '-' + p2(d.getDate()) + ' ' + p2(d.getHours()) + ':' + p2(d.getMinutes()) + ':' + p2(d.getSeconds());
}
function curGameKey() { const h = (location.hash || '').replace('#/', ''); return h.replace('-solo', '') || 'lobby'; }
function curGameSelects() {
const d = document.getElementById('diff'), t = document.getElementById('timer');
return { diff: d ? d.value : 'normal', timer: t ? t.value : '0' };
}
function gameSaveNow() {
const h = (window.GAMEHOOKS || {})[curGameKey()];
if (!h || typeof h.serialize !== 'function') { alert('当前页面暂不支持存档'); return; }
let sv;
try { sv = h.serialize(); } catch (e) { alert('存档失败:' + e.message); return; }
if (!sv) { alert('暂无可存档的棋局'); return; }
const sel = curGameSelects();
sv.diff = sv.diff || sel.diff; sv.timer = sv.timer != null ? sv.timer : sel.timer;
sv.savedAt = Date.now();
fetch('/api/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(sv) })
.then(r => r.json()).then(res => {
if (res && res.ok) {
const st = document.getElementById('status-text');
if (st) st.innerText = '💾 已存档:' + fmtDT(res.ts) + '(点「💾 存档」可恢复)';
showSaves();
} else alert('存档失败:' + ((res && res.error) || '未知错误'));
}).catch(e => alert('存档失败:' + e.message));
}
window.gameSaveNow = gameSaveNow;
var _saveMeta = { game: '', file: '', dir: '' };
function showSaves() {
const g = curGameKey();
fetch('/api/save?game=' + encodeURIComponent(g)).then(r => r.json()).then(o => {
_savesCache = (o && o.saves) || [];
_saveMeta = { game: g, file: (o && o.file) || '', dir: '' };
renderSaves();
}).catch(e => alert('读取存档失败:' + e.message));
}
window.showSaves = showSaves;
function renderSaves() {
let box = document.getElementById('save-modal');
if (box) box.remove();
box = document.createElement('div');
box.id = 'save-modal'; box.className = 'ai-box';
const names = { chess: '♟️ 象棋', gomoku: '⚫ 五子棋', junqi: '🚩 军棋' };
const cur = curGameKey();
let html = '<b>💾 ' + (names[cur] || '') + ' 存档</b><br><small style="color:#888">各游戏存档独立存放,以「日期 + 时间」标识,点「恢复」即可接着下</small>';
if (_saveMeta.file) html += '<div style="font-size:12px;color:#888;margin-top:4px">本游戏存档文件:<code style="color:#1e6ef0">' + _saveMeta.file + '</code></div>';
html += '<div style="margin:8px 0"><button class="btn" onclick="gameSaveNow()" style="padding:8px 14px">💾 保存当前进度</button>'
+ ' <button class="btn" onclick="toggleSavePath()" style="padding:8px 12px">⚙ 存档路径</button></div>';
html += '<div id="save-path-box" style="display:none;background:#f7f9fc;border:1px solid #dde5f0;border-radius:8px;padding:10px;margin-bottom:8px">'
+ '<div style="font-size:13px;color:#555">存档目录:<code id="sp-cur" style="color:#1e6ef0">…</code></div>'
+ '<div id="sp-files" style="font-size:12px;color:#888;margin-top:4px">各游戏独立文件:chess-saves.json / gomoku-saves.json / junqi-saves.json</div>'
+ '<div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap;align-items:center">'
+ '<input id="sp-dir" placeholder="/app/data/saves" style="flex:1 1 200px;min-width:160px;padding:6px 8px;border:1px solid #cfd8e3;border-radius:6px;font-size:13px">'
+ '<button class="btn" onclick="applySaveDir()" style="padding:6px 12px">保存目录</button>'
+ '<button class="btn" onclick="savePathPreset(\'/app/data/saves\')" style="padding:6px 10px">默认</button>'
+ '<button class="btn" onclick="savePathPreset(\'/app/data/saves/backup\')" style="padding:6px 10px">备份目录</button>'
+ '</div>'
+ '<div id="sp-tip" style="font-size:12px;color:#888;margin-top:6px">容器内 /app 目录已挂载到主机 /vol1/1000/HD1/docker/fnos-games/data;每个游戏各写一个文件,互不混淆</div>'
+ '<div id="sp-browse" style="margin-top:8px;font-size:12px"></div></div>';
if (!_savesCache.length) {
html += '<div style="color:#888;padding:10px 0">本游戏还没有存档</div>';
} else {
html += '<div style="max-height:52vh;overflow:auto"><table><tr><th>存档时间</th><th>游戏</th><th>模式</th><th>难度</th><th>进度</th><th>操作</th></tr>';
_savesCache.forEach(rec => {
const mine = rec.game === cur;
const diffTxt = ({ easy: '简单', normal: '普通', hard: '困难' })[rec.diff] || rec.diff || '';
const prog = rec.game === 'chess' ? (rec.steps || 0) + ' 手'
: rec.game === 'gomoku' ? (rec.steps || 0) + ' 子'
: (rec.steps || 0) + ' 步';
const isAuto = !!rec.auto || String(rec.id || '').indexOf('auto-') === 0;
html += '<tr' + (isAuto ? ' style="background:#fff8e6"' : (mine ? ' style="background:#f2f7ff"' : '')) + '>'
+ '<td style="white-space:nowrap">' + fmtDT(rec.ts) + (isAuto ? ' <span style="color:#b8860b">⏱ 自动</span>' : '') + '</td>'
+ '<td>' + (names[rec.game] || rec.game) + '</td>'
+ '<td>' + (rec.mode || '') + '</td>'
+ '<td>' + diffTxt + '</td>'
+ '<td>' + prog + '</td>'
+ '<td style="white-space:nowrap">'
+ '<button class="btn" style="padding:4px 9px;font-size:12px" onclick="restoreSave(\'' + rec.id + '\')">恢复</button> '
+ '<button class="btn" style="padding:4px 9px;font-size:12px" onclick="deleteSave(\'' + rec.id + '\')">删除</button>'
+ '</td></tr>';
});
html += '</table></div>';
}
html += '<div style="margin-top:10px"><button class="btn" id="save-close">关闭</button></div>';
box.innerHTML = '<div class="ai-inner" style="width:min(96vw,640px)">' + html + '</div>';
document.getElementById('view').prepend(box);
const cb = document.getElementById('save-close');
if (cb) cb.onclick = () => { const m = document.getElementById('save-modal'); if (m) m.remove(); };
if (_spMsg) { // 路径设置成功后的提示与面板保持打开
const tip = document.getElementById('sp-tip');
if (tip) tip.innerHTML = '<b style="color:#2a7">✅ ' + _spMsg + '</b>';
const b = document.getElementById('save-path-box');
if (b) b.style.display = 'block';
loadSavePathUI();
_spMsg = '';
}
}
// —— 存档路径设置 ——
function toggleSavePath() {
const b = document.getElementById('save-path-box');
if (!b) return;
b.style.display = (b.style.display === 'none' || !b.style.display) ? 'block' : 'none';
if (b.style.display === 'block') loadSavePathUI();
}
function loadSavePathUI(dir) {
fetch('/api/config').then(r => r.json()).then(cfg => {
const cur = document.getElementById('sp-cur');
if (cur) cur.innerText = (cfg && cfg.saveDir) || '(未设置)';
const dEl = document.getElementById('sp-dir');
if (dEl && !dir) dEl.value = (cfg && cfg.saveDir) || '/app/data/saves';
if (dir && dEl) dEl.value = dir;
const fs2 = document.getElementById('sp-files');
if (fs2 && cfg && cfg.files) fs2.innerHTML = '各游戏独立文件:' + cfg.files.map(f => f.file.split('/').pop() + '(' + f.count + ' 条)').join(' · ');
browseSaveDir(dir || (dEl ? dEl.value : '/app/data/saves'));
}).catch(e => alert('读取存档设置失败:' + e.message));
}
function browseSaveDir(dir) {
fetch('/api/fs?dir=' + encodeURIComponent(dir)).then(r => r.json()).then(o => {
const box = document.getElementById('sp-browse');
if (!box) return;
const de = document.getElementById('sp-dir');
if (de && o.dir) de.value = o.dir;
let h = '<div style="color:#888;margin-bottom:4px">目录:' + (o.dir || '') + ' ' +
'<a href="javascript:void(0)" onclick="browseSaveDir(\'' + (o.parent || '/app') + '\')" style="color:#1e6ef0">↑ 上级</a>' +
(o.error ? ' <span style="color:#c33">(' + o.error + ')</span>' : '') + '</div>';
if ((o.dirs || []).length) h += '<div>子目录:' + o.dirs.map(x => '<a href="javascript:void(0)" onclick="browseSaveDir(\'' + (o.dir + '/' + x) + '\')" style="margin-right:8px;color:#1e6ef0">📁 ' + x + '</a>').join('') + '</div>';
if ((o.files || []).length) h += '<div style="margin-top:4px">此目录存档文件:' + o.files.map(x => '<span style="margin-right:8px;color:#555">📄 ' + x + '</span>').join('') + '</div>';
box.innerHTML = h;
}).catch(e => {});
}
function savePathPreset(dir) { const de = document.getElementById('sp-dir'); if (de) de.value = dir; browseSaveDir(dir); }
function applySaveDir() {
const dEl = document.getElementById('sp-dir');
const dir = (dEl ? dEl.value : '').trim().replace(/\/+$/, '');
if (!dir) { alert('请填写存档目录'); return; }
fetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ saveDir: dir, migrate: true }) })
.then(r => r.json()).then(res => {
if (!res || !res.ok) { alert('设置失败:' + ((res && res.error) || '未知错误')); return; }
const cnt = res.counts || {};
_spMsg = '存档目录已改为 ' + res.saveDir + ',旧目录存档已迁移(象棋 ' + (cnt.chess || 0) + ' 条 · 五子棋 ' + (cnt.gomoku || 0) + ' 条 · 军棋 ' + (cnt.junqi || 0) + ' 条)';
_savesCache = []; showSaves();
}).catch(e => alert('设置失败:' + e.message));
}
window.toggleSavePath = toggleSavePath; window.applySaveDir = applySaveDir;
window.savePathPreset = savePathPreset; window.browseSaveDir = browseSaveDir;
window.loadSavePathUI = loadSavePathUI; window.showSaves = showSaves;
function closeSaveModal() { const m = document.getElementById('save-modal'); if (m) m.remove(); }
function restoreSave(id) {
const rec = _savesCache.find(x => x.id === id);
if (!rec) { alert('存档已不存在'); return; }
closeSaveModal();
const h = (window.GAMEHOOKS || {})[rec.game];
if (rec.game === curGameKey() && h && typeof h.restore === 'function') {
const ok = h.restore(rec);
if (!ok) alert('恢复失败');
return;
}
try { sessionStorage.setItem('fnos_pending_restore', JSON.stringify(rec)); } catch (e) {}
location.hash = '#/' + rec.game + '-solo';
}
window.restoreSave = restoreSave;
function deleteSave(id) {
fetch('/api/save?game=' + encodeURIComponent(curGameKey()) + '&id=' + encodeURIComponent(id), { method: 'DELETE' })
.then(r => r.json()).then(() => { _savesCache = _savesCache.filter(x => x.id !== id); renderSaves(); })
.catch(e => alert('删除失败:' + e.message));
}
window.deleteSave = deleteSave;
/** 各游戏 boot 末尾调用:若刚从别的游戏跳来恢复存档,则自动载入 */
function checkPendingRestore(key) {
let raw = null;
try { raw = sessionStorage.getItem('fnos_pending_restore'); } catch (e) {}
if (!raw) return false;
try { sessionStorage.removeItem('fnos_pending_restore'); } catch (e) {}
let rec = null;
try { rec = JSON.parse(raw); } catch (e) { return false; }
if (!rec || rec.game !== key) return false;
setTimeout(() => {
try {
const h = (window.GAMEHOOKS || {})[rec.game];
if (h && typeof h.restore === 'function') h.restore(rec);
} catch (e) {}
}, 40);
return true;
}
window.checkPendingRestore = checkPendingRestore;
// —— 倒计时系统 ——
var timerTotal = 1200, timerLeft = 1200, timerSide = 'r', timerHalted = true, timerInterval = null;
function timerSetting() { const el = document.getElementById('timer'); return el ? +el.value : 0; }
function applyTimer() {
timerTotal = timerSetting();
resetTimer('r');
}
function resetTimer(side) {
clearInterval(timerInterval);
timerSide = side; timerLeft = timerTotal;
updateTimerUI();
if (timerTotal > 0) {
timerHalted = false;
timerInterval = setInterval(tickTimer, 1000);
} else timerHalted = true;
}
function haltTimer() { timerHalted = true; clearInterval(timerInterval); updateTimerUI(); }
function swapTimer() {
if (timerTotal <= 0) return;
timerSide = timerSide === 'r' ? 'b' : 'r';
timerLeft = timerTotal;
updateTimerUI();
}
function tickTimer() {
if (timerHalted) return;
timerLeft--;
updateTimerUI();
if (timerLeft <= 0) {
clearInterval(timerInterval);
onTimeout();
}
}
function updateTimerUI() {
const el = document.getElementById('timer-badge');
if (!el) return;
const m = Math.floor(Math.max(0,timerLeft) / 60), s2 = Math.max(0,timerLeft) % 60;
if (timerTotal <= 0) { el.innerText = ''; return; }
const who = (localStorage.getItem('fnos_mode') === '2p') ? (timerSide === 'r' ? '(红方)' : (currentRouteKey === 'gomoku' ? '(白棋)' : '(蓝方)')) : '(你)';
const danger = timerLeft <= 10 ? 'color:#ff4d4d;font-weight:bold' : '';
el.innerHTML = ' <span style="' + danger + '">⏱ ' + m + ':' + String(s2).padStart(2,'0') + who + '</span>';
}
/** 超时回调 — 各游戏挂 window.onGameTimeout */
function onTimeout() {
haltTimer();
if (localStorage.getItem('fnos_mode') === '2p') {
const loser = timerSide === 'r' ? '红方' : '蓝/黑方';
recordGame({ game: currentRouteKey, result: timerSide === 'r' ? 'lose' : 'win', durTxt: '超时', steps: 0 });
gameResultPopup(false, '⏰ 超时判负', loser + '超时,游戏结束');
} else {
recordGame({ game: currentRouteKey, result: 'lose', durTxt: '超时', steps: 0 });
gameResultPopup(false, '⏰ 超时判负', '你超时了(' + Math.floor(timerTotal/60) + '分钟已用完)');
}
}
function timerBadge() {
if (timerTotal <= 0 || timerHalted) return '';
const m = Math.floor(timerLeft / 60), s2 = timerLeft % 60;
const who = (localStorage.getItem('fnos_mode') === '2p') ? (timerSide === 'r' ? '(红方)' : (currentRouteKey === 'gomoku' ? '(白棋)' : '(蓝方)')) : '(你)';
return ' ⏱ ' + m + ':' + String(s2).padStart(2,'0') + who;
}
// statusline 文本包装:setStatus 时附带时间
// (timer badge 是独立 span, 不需 wrap)
+76
View File
@@ -0,0 +1,76 @@
// 五子棋:核心引擎 + AI 评分
const N = 15;
const EMPTY = 0;
class Gomoku {
constructor() { this.N = N; this.B = Array.from({ length: N }, () => Array(N).fill(0)); this.seq = []; this.player = 1; this.over = false; this.win5 = null; }
inB(r, c) { return r >= 0 && r < N && c >= 0 && c < N; }
place(r, c) {
if (this.over || !this.inB(r, c) || this.B[r][c] !== 0) return false;
this.B[r][c] = this.player; this.seq.push([r, c]);
const win = this.checkWin(r, c, this.player);
if (win) { this.over = true; this.win5 = win; }
else if (this.seq.length === N * N) this.over = true;
else this.player = this.player === 1 ? 2 : 1;
return true;
}
/** 返回连五的位置数组 [[r,c]x5]。若刚好形成五连,返回这些点,否则 null */
checkWin(r, c, p) {
const dirs = [[0, 1], [1, 0], [1, 1], [1, -1]];
for (const [dr, dc] of dirs) {
const cells = [[r, c]];
for (const sgn of [1, -1]) {
let rr = r + sgn * dr, cc = c + sgn * dc;
while (this.inB(rr, cc) && this.B[rr][cc] === p) { cells.push([rr, cc]); rr += sgn * dr; cc += sgn * dc; }
}
if (cells.length >= 5) return cells.slice(0, 5);
}
return null;
}
undo() { if (!this.seq.length || this.over) return false; const [r, c] = this.seq.pop(); this.B[r][c] = 0; this.player = this.player === 1 ? 2 : 1; return true; }
full() { return { n: this.N, b: this.B, seq: this.seq, player: this.player, over: this.over, win5: this.win5 }; }
static restore(o) { const g = new Gomoku(); g.B = o.b; g.seq = o.seq || []; g.player = o.player || 1; g.over = !!o.over; g.win5 = o.win5 || null; return g; }
}
// —— AI ——
// 简洁评分:对每个空点,计算对黑白任一方落子后形成的 "连子形状" 分值
const SHAPES = { 1: 10, 2: 100, 3: 1200, 4: 15000, 5: 1000000 };
function lineScore(cnt, open) { // cnt: 连子数, open: 端点空位 0/1/2
if (cnt >= 5) return SHAPES[5];
let s = SHAPES[cnt] || 0;
if (open === 2) s *= 1.8; else if (open === 1) s *= 1; else s *= 0.25;
return s;
}
function scorePoint(g, r, c, p) {
if (!g.inB(r, c) || g.B[r][c] !== 0) return 0;
let total = 0;
for (const [dr, dc] of [[0, 1], [1, 0], [1, 1], [1, -1]]) {
let cnt = 1, open = 0;
// 朝两个方向延伸,统计连续同色 + 端点(考虑一个空档的跳连简化为不处理)
for (const sgn of [1, -1]) {
let rr = r + sgn * dr, cc = c + sgn * dc;
while (g.inB(rr, cc) && g.B[rr][cc] === p) { cnt++; rr += sgn * dr; cc += sgn * dc; }
if (g.inB(rr, cc) && g.B[rr][cc] === 0) open++;
}
total += lineScore(cnt, open);
}
return total;
}
function aiPick(g, me) {
const opp = me === 1 ? 2 : 1;
const cands = [];
for (let r = 0; r < g.N; r++) for (let c = 0; c < g.N; c++) {
if (g.B[r][c] !== 0) continue;
// 只考虑已有邻居的点
let nearEmpty = true;
for (let dr = -2; dr <= 2; dr++) for (let dc = -2; dc <= 2; dc++) { const rr = r + dr, cc = c + dc; if (g.inB(rr, cc) && g.B[rr][cc] !== 0) nearEmpty = false; }
if (nearEmpty && g.seq.length > 0) continue;
const aa = scorePoint(g, r, c, me); // 进攻
const dd = scorePoint(g, r, c, opp); // 防守
cands.push({ r, c, sc: aa * 1.1 + dd });
}
if (!cands.length) return { r: 7, c: 7 };
cands.sort((a, b) => b.sc - a.sc);
const easy = Math.random() < 0.15;
const pick = easy ? cands[Math.min(cands.length - 1, Math.floor(Math.random() * 5))] : cands[0];
return { r: pick.r, c: pick.c };
}
if (typeof module !== 'undefined') module.exports = { Gomoku, aiPick, scorePoint, N };
+195
View File
@@ -0,0 +1,195 @@
// 五子棋前端(人机,SVG 画线棋盘)
var gk = null, aiBusy = false, aiTimer = null;
function gokLevel() { const el = document.getElementById('diff'); return el ? el.value : 'normal'; }
function gok2P() { try { return localStorage.getItem('fnos_mode') === '2p'; } catch (e) { return false; } }
function boot_gomoku_solo() {
gk = new Gomoku();
aiBusy = false; gameStartTs = Date.now();
if (window.applyTimer) { applyTimer(); resetTimer('r'); }
render_gomoku();
const lbl = { easy: '简单', normal: '普通', hard: '困难' }[gokLevel()];
if (gok2P()) setStatus('gok-st', '双人同屏 · 黑棋先行 · 轮流落子');
else setStatus('gok-st', '难度:' + lbl + ' · 黑棋(你)先行 · 点交叉点落子');
}
function render_gomoku() {
const el = document.getElementById('game-canvas');
if (!el) return;
const N = gk.N, S = 36; // 格大小
const PAD = 20, SIZE = PAD * 2 + S * (N - 1);
let html = `<svg id="gok-board" viewBox="0 0 ${SIZE} ${SIZE}" style="touch-action:manipulation;width:100%;max-width:520px;display:block;margin:auto">`;
html += `<rect x="0" y="0" width="${SIZE}" height="${SIZE}" fill="#e8c187" rx="6"/>`;
for (let i = 0; i < N; i++) {
const p = PAD + i * S;
html += `<line x1="${PAD}" y1="${p}" x2="${SIZE - PAD}" y2="${p}" stroke="#7a5230" stroke-width="1"/>`;
html += `<line x1="${p}" y1="${PAD}" x2="${p}" y2="${SIZE - PAD}" stroke="#7a5230" stroke-width="1"/>`;
}
const stars = [3, 7, 11];
stars.forEach(sr => stars.forEach(sc => { html += `<circle cx="${PAD + sc * S}" cy="${PAD + sr * S}" r="3" fill="#7a5230"/>`; }));
gk.seq.forEach(([r, c]) => {
const cx = PAD + c * S, cy = PAD + r * S;
const isB = gk.B[r][c] === 1;
const stroke = isB ? 'none' : '#999';
const fill = isB ? '#111' : '#fff';
let ring = '';
if (gk.win5 && gk.win5.some(w => w[0] === r && w[1] === c)) ring = `<circle cx="${cx}" cy="${cy}" r="12" fill="none" stroke="#e03535" stroke-width="2"/>`;
html += `<circle cx="${cx}" cy="${cy}" r="13" fill="${fill}" stroke="${stroke}" stroke-width="1"/>${ring}`;
});
const last = gk.seq.length ? gk.seq[gk.seq.length - 1] : null;
if (last && !gk.over) {
const cx = PAD + last[1] * S, cy = PAD + last[0] * S;
html += `<circle cx="${cx}" cy="${cy}" r="4" fill="${gk.B[last[0]][last[1]] === 1 ? '#fff' : '#e03535'}"/>`;
}
for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) {
const cx = PAD + c * S, cy = PAD + r * S;
html += `<rect x="${cx - S/2}" y="${cy - S/2}" width="${S}" height="${S}" fill="transparent" onclick="gokClick(${r},${c})" style="cursor:pointer"/>`;
}
html += '</svg>';
el.innerHTML = html;
}
function gokClick(r, c) {
if (!gk || gk.over || aiBusy) { if (aiBusy) setStatus('gok-st', '白方 AI 思考中…'); return; }
if (!gk.place(r, c)) return;
render_gomoku();
if (gokEnd()) return;
swapTimer();
if (gok2P()) { setStatus('gok-st', '轮到 ' + (gk.player === 1 ? '黑棋' : '白棋')); if (window.autoSnapshot) autoSnapshot(); if (window.autoCoachIfOn) autoCoachIfOn(); return; }
aiBusy = true;
setStatus('gok-st', '白方 AI 思考中…');
aiTimer = setTimeout(() => {
try {
let p;
if (gokLevel() === 'easy') {
// 简单:随机落子(避开角落以及远离已有棋子的位置)
const cs = [];
for (let rr = 0; rr < gk.N; rr++) for (let cc = 0; cc < gk.N; cc++) if (gk.B[rr][cc] === 0) cs.push([rr, cc]);
p = cs[Math.floor(Math.random() * cs.length)];
} else {
p = aiPick(gk, 2);
if (gokLevel() === 'hard') {
// 困难:两步前瞻——若对手下一手可在某点成五连/活四,必堵
const opp = 1;
let best = null, bestSc = -1;
const cands = [];
for (let rr = 0; rr < gk.N; rr++) for (let cc = 0; cc < gk.N; cc++) {
if (gk.B[rr][cc] !== 0) continue;
let near = false;
for (let dr = -2; dr <= 2 && !near; dr++) for (let dc = -2; dc <= 2; dc++) { const r2 = rr+dr, c2 = cc+dc; if (r2>=0 && r2<gk.N && c2>=0 && c2<gk.N && gk.B[r2][c2] !== 0) { near = true; break; } }
if (!near) continue;
const atk = scorePoint(gk, rr, cc, 2);
const def = scorePoint(gk, rr, cc, 1);
cands.push({ rr, cc, sc: atk * 1.15 + def });
}
cands.sort((a, b) => b.sc - a.sc);
// 前两候选取分最高者,且更重防守(困难较普通+防守权重)
if (cands.length) p = { r: cands[0].rr, c: cands[0].cc };
}
}
const placed = gk.place(p.r, p.c);
if (!placed) { // AI 落子失败(点被占/盘满)→ 兜底再试一处
let done = false;
for (let r = 0; r < gk.N && !done; r++) for (let c = 0; c < gk.N && !done; c++) if (gk.B[r][c] === 0) { gk.place(r, c); done = true; }
}
if (gokEnd()) return;
setStatus('gok-st', '轮到你(黑棋)');
render_gomoku();
swapTimer();
if (window.autoSnapshot) autoSnapshot();
if (window.autoCoachIfOn) autoCoachIfOn();
} catch (e) {
setStatus('gok-st', 'AI 出错,已交回你走:' + e.message);
} finally {
aiBusy = false; aiTimer = null;
render_gomoku();
}
}, 60);
}
function gokEnd() {
if (!gk.over) return false;
if (gk.win5) {
const durTxt = fmtDur(gameDurationSec());
const r = gk.win5[0][0], c = gk.win5[0][1];
const blackWin = gk.B[r][c] === 1;
setStatus('gok-st', '🎉 ' + (blackWin ? '黑方胜!' : '白方胜!'));
if (blackWin) { recordGame({ game: 'gomoku', result: 'win', dur: durTxt, steps: gk.seq.length }); gameResultPopup(true, '🏆 黑方胜!', '五连达成 · 用时 ' + durTxt + ' · 共 ' + gk.seq.length + ' 手'); }
else { recordGame({ game: 'gomoku', result: 'lose', dur: durTxt, steps: gk.seq.length }); gameResultPopup(false, '💔 白方胜', 'AI 先连成五子 · 用时 ' + durTxt); }
} else { setStatus('gok-st', '平局'); recordGame({ game: 'gomoku', result: 'draw', dur: fmtDur(gameDurationSec()), steps: gk.seq.length }); gameResultPopup(null, '🤝 平局', ''); }
return true;
}
window.gomokuUndo = function() {
if (aiBusy) aiBusy = false;
const base = gk._baseline || 0;
if (gk.seq.length <= base) { setStatus('gok-st', '残局原局面,没有可悔的棋'); return; }
const n = gk.player === 1 ? 2 : 1;
let undone = 0;
for (let i = 0; i < n; i++) {
if (gk.seq.length <= base) break; // 不拆残局摆位
if (gk.undo()) undone++;
}
while (gk.seq.length > base && gk.player !== 1) { if (!gk.undo()) break; }
render_gomoku();
setStatus('gok-st', undone ? '已悔棋,轮到你(黑棋)' : '残局原局面,没有可悔的棋');
};
// —— 存档 / 恢复 ——
window.GAMEHOOKS = window.GAMEHOOKS || {};
GAMEHOOKS.gomoku = {
started: function () { return !!gk; },
inProgress: function () { return !!(gk && gk.seq.length > 0 && !gk.over && !window.__gameOver); },
serialize: function () {
if (!gk) return null;
const sel = curGameSelects();
return {
game: 'gomoku', label: '五子棋', mode: gok2P() ? '双人同屏' : '人机',
diff: gokLevel(), timer: sel.timer,
seq: gk.seq.map(x => [x[0], x[1]]), baseline: gk._baseline || 0, over: !!gk.over,
steps: gk.seq.length,
elapsed: Math.max(0, Math.floor((Date.now() - (gameStartTs || Date.now())) / 1000))
};
},
restore: function (sv) {
try {
if (aiTimer) { clearTimeout(aiTimer); aiTimer = null; }
aiBusy = false;
gk = new Gomoku();
(sv.seq || []).forEach(pp => gk.place(pp[0], pp[1]));
gk._baseline = sv.baseline || 0;
try { localStorage.setItem('fnos_mode', sv.mode === '双人同屏' ? '2p' : 'ai'); } catch (e) {}
const d1 = document.getElementById('diff'); if (d1 && sv.diff) d1.value = sv.diff;
const t1 = document.getElementById('timer');
if (t1 && sv.timer != null) { t1.value = String(sv.timer); applyTimer(); }
gameStartTs = Date.now() - (sv.elapsed || 0) * 1000;
render_gomoku();
if (!gk.over && gk.player !== 1 && !gok2P()) { // 轮到白方(AI)→ 立即补一手
for (let guard = 0; guard < 3 && gk.player !== 1 && !gk.over; guard++) {
const pp = aiPick(gk, 2);
if (!pp || !gk.place(pp.r, pp.c)) break;
}
render_gomoku();
}
swapTimer();
if (gk.over) setStatus('gok-st', '已恢复存档 · 该局已结束');
else setStatus('gok-st', '已恢复存档 · ' + (sv.mode || '') + ' · 轮到你(黑棋)');
if (gk.over && window.gokEnd) gokEnd();
return true;
} catch (e) { alert('恢复失败:' + e.message); return false; }
} };
window.boot_gomoku_solo = boot_gomoku_solo;
window.loadGomokuPuzzle = function(pz) {
if (aiTimer) { clearTimeout(aiTimer); aiTimer = null; }
aiBusy = false;
gk = new Gomoku();
gameStartTs = Date.now();
for (const [r, c] of (pz.seq || [])) gk.place(r, c);
gk._baseline = gk.seq.length; // 残局固定摆位手数,不可悔
// 若残局原本轮白(seq 奇数),先让 AI 走一步补齐轮次,保证 player == 1
if (gk.player !== 1) {
const p0 = aiPick(gk, 2);
gk.place(p0.r, p0.c);
gk._baseline = gk.seq.length;
}
aiBusy = false;
render_gomoku();
setStatus('gok-st', '残局『' + pz.name + '』· ' + pz.tip);
};
+170
View File
@@ -0,0 +1,170 @@
// 军棋(陆战棋)· 翻棋玩法引擎 — 标准棋盘 12行 × 5列(每方 6行 × 5列 = 30 位)
// 位类型:兵站(23/方) 行营(圆, 5/方, 不可被攻击) 大本营(2/方, 进入后不可移动)
// 铁路:横向 r∈{2,5,6,9} 贯通;纵向 c∈{0,4} 贯通;山界仅在 c∈{0,2,4} 三处连通
// 棋子等级:司令9 军长8 师长7 旅长6 团长5 营长4 连长3 排长2 工兵1(地雷不可动,炸弹同归于尽,军旗被扛即负)
const KINDS = ['s9','s8','s7','s6','s5','s4','s3','s2','s1','lei','zha','jq'];
const KIND_LBL = { s9:'司令', s8:'军长', s7:'师长', s6:'旅长', s5:'团长', s4:'营长', s3:'连长', s2:'排长', s1:'工兵', lei:'地雷', zha:'炸弹', jq:'军旗' };
const KIND_RANK = { s9:9, s8:8, s7:7, s6:6, s5:5, s4:4, s3:3, s2:2, s1:1, lei:0, zha:0, jq:0 };
// 行营与大棚营坐标(0-indexed: 蓝方 0-5 行在上, 红方 6-11 行在下)
const CAMP_LIST = [[2,1],[2,3],[3,2],[4,1],[4,3],[7,1],[7,3],[8,2],[9,1],[9,3]];
const HQ_LIST = [[0,1],[0,3],[11,1],[11,3]];
const RAIL_ROWS = [2,5,6,9];
const RAIL_COLS = [0,4];
const FRONT_COLS = [0,2,4]; // 山界三处通口
class JunqiBoard {
constructor(mode) {
this.R = 12; this.C = 5;
this.cells = []; // {kind, owner, faceDown} | null
this.shown = []; // 是否已翻开
this.turn = 0; // 0=红(先) 1=蓝
this.mode = mode || 'flip';
this.flagTaken = null;
this._hist = [];
this.init();
}
isCamp(r, c) { return CAMP_LIST.some(([a, b]) => a === r && b === c); }
isHQ(r, c) { return HQ_LIST.some(([a, b]) => a === r && b === c); }
inB(r, c) { return r >= 0 && r < this.R && c >= 0 && c < this.C; }
static perSide() {
// 每方 25 枚
const list = [];
const add = (k, n) => { for (let i = 0; i < n; i++) list.push(k); };
add('s9',1); add('s8',1); add('s7',2); add('s6',2); add('s5',2); add('s4',2);
add('s3',3); add('s2',3); add('s1',3); add('lei',3); add('zha',2); add('jq',1);
return list;
}
init() {
const all = JunqiBoard.perSide().concat(JunqiBoard.perSide()); // 50 枚 = 50 个非行营位
for (let i = all.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const t = all[i]; all[i] = all[j]; all[j] = t; }
this.cells = []; this.shown = []; this.turn = 0; this.flagTaken = null; this._hist = [];
let k = 0;
for (let r = 0; r < this.R; r++) {
this.cells[r] = []; this.shown[r] = [];
for (let c = 0; c < this.C; c++) {
if (this.isCamp(r, c)) { this.cells[r][c] = null; this.shown[r][c] = false; }
else { this.cells[r][c] = { kind: all[k++], owner: null, faceDown: true }; this.shown[r][c] = false; }
}
}
}
turnOwner() { return this.turn === 0 ? 'r' : 'b'; }
canMove(from, to) {
const [fr, fc] = from, [tr, tc] = to;
if (!this.inB(tr, tc) || !this.inB(fr, fc)) return false;
const fp = this.cells[fr][fc], tp = this.cells[tr][tc];
if (!fp) return false;
if (fp.owner !== this.turnOwner()) return false;
if (fp.kind === 'lei' || fp.kind === 'jq') return false; // 地雷/军旗 不可移动
if (this.isHQ(fr, fc)) return false; // 大本营内棋子不可移动
if (tr === fr && tc === fc) return false;
if (tp && !this.shown[tr][tc]) return false; // 不可吃暗棋(先翻)
if (tp && tp.owner === this.turnOwner()) return false; // 不可吃己方
if (this.isCamp(tr, tc) && tp) return false; // 行营内的棋子不可被攻击(空行营可以进入并能走出来)
const dr = tr - fr, dc = tc - fc;
const straight = (dr === 0 || dc === 0);
// 山界:跨前线(r5↔r6)只在 c∈{0,2,4} 通
if (Math.abs(dr) === 1 && fc === tc && ((fr === 5 && tr === 6) || (fr === 6 && tr === 5)) && FRONT_COLS.indexOf(fc) < 0) return false;
// 步长判定:工兵沿铁路可直行任意格(路径无阻);其余 1 步
if (straight) {
const dist = Math.abs(dr) + Math.abs(dc);
const onRail = (fr === tr && RAIL_ROWS.indexOf(fr) >= 0) || (fc === tc && RAIL_COLS.indexOf(fc) >= 0);
const maxStep = (fp.kind === 's1' && onRail) ? 99 : 1;
if (dist > maxStep) return false;
if (dist > 1) { // 路径检查(工兵铁路直行)
if (dr === 0) { for (let c2 = Math.min(fc, tc) + 1; c2 < Math.max(fc, tc); c2++) if (this.cells[fr][c2]) return false; }
else { for (let r2 = Math.min(fr, tr) + 1; r2 < Math.max(fr, tr); r2++) if (this.cells[r2][fc]) return false; }
}
return true;
}
// 斜行:仅限行营的斜向相邻(行营与四角兵站相连)
if (Math.abs(dr) === 1 && Math.abs(dc) === 1) {
const c1 = this.isCamp(fr, fc), c2 = this.isCamp(tr, tc);
if (!c1 && !c2) return false;
const dist = 1; // 单步斜行
return dist === 1;
}
return false;
}
flip(r, c) {
if (!this.inB(r, c) || !this.cells[r][c] || this.shown[r][c]) return null;
this.shown[r][c] = true; this.cells[r][c].owner = this.turnOwner();
this._hist.push({ type: 'flip', r, c, prevTurn: this.turn });
this.turn = 1 - this.turn;
return this.cells[r][c];
}
undoLast() {
const last = this._hist.pop();
if (!last) return false;
if (last.type === 'flip') {
this.shown[last.r][last.c] = false;
if (this.cells[last.r][last.c]) this.cells[last.r][last.c].owner = null;
} else {
this.cells[last.fr][last.fc] = last.fp;
this.cells[last.tr][last.tc] = last.tp;
this.flagTaken = last.flagBefore;
if (last.shownFrom !== undefined) this.shown[last.fr][last.fc] = last.shownFrom;
if (last.shownTo !== undefined) this.shown[last.tr][last.tc] = last.shownTo;
}
this.turn = last.prevTurn;
return true;
}
battle(a, d) { // a=攻方 kind, d=守方 kind → 'win'|'lose'|'both'
if (a === 'zha' || d === 'zha') return 'both';
if (d === 'lei') return a === 's1' ? 'win' : 'both';
if (d === 'jq') return 'win';
const ra = KIND_RANK[a], rd = KIND_RANK[d];
return ra > rd ? 'win' : (ra < rd ? 'lose' : 'both');
}
movePiece(from, to) {
if (!this.canMove(from, to)) return { ok: false };
const [fr, fc] = from, [tr, tc] = to;
const fp = this.cells[fr][fc], tp = this.cells[tr][tc];
const prevFlag = this.flagTaken;
// 记录目标格/源格的"已翻开"状态,供悔棋精确还原
const shownFrom = this.shown[fr][fc], shownTo = this.shown[tr][tc];
let rec;
if (!tp) { this.cells[tr][tc] = fp; this.cells[fr][fc] = null; rec = { type:'move', fp, tp:null, fr, fc, tr, tc, prevTurn:this.turn, flagBefore:prevFlag, shownFrom, shownTo }; }
else {
const res = this.battle(fp.kind, tp.kind);
if (res === 'win') { if (tp.kind === 'jq') this.flagTaken = tp.owner; this.cells[tr][tc] = fp; this.cells[fr][fc] = null; }
else if (res === 'lose') { if (fp.kind === 'jq') this.flagTaken = fp.owner; this.cells[fr][fc] = null; }
else { this.cells[tr][tc] = null; this.cells[fr][fc] = null; }
rec = { type:'move', fp, tp, fr, fc, tr, tc, prevTurn:this.turn, flagBefore:prevFlag, shownFrom, shownTo };
}
// 走进去的棋子必然是已翻开的 → 目标格标记为已翻开(否则行营/大本营里的棋子会被画成暗牌)
if (this.cells[tr][tc]) this.shown[tr][tc] = true;
this.shown[fr][fc] = false;
this._hist.push(rec);
this.turn = 1 - this.turn;
return { ok: true };
}
alive(side) {
for (let r = 0; r < this.R; r++) for (let c = 0; c < this.C; c++) {
const p = this.cells[r][c];
if (p && p.owner === side && p.kind !== 'lei' && p.kind !== 'jq') return true;
}
return false;
}
hasFlip() {
for (let r = 0; r < this.R; r++) for (let c = 0; c < this.C; c++) if (this.cells[r][c] && !this.shown[r][c]) return true;
return false;
}
winner() {
if (this.flagTaken) return this.flagTaken === 'r' ? 'b' : 'r';
// 无暗棋可翻 且 无子可走 → 判负
if (this.hasFlip()) return null;
let canAct = false;
for (let r = 0; r < this.R && !canAct; r++) for (let c = 0; c < this.C && !canAct; c++) {
const p = this.cells[r][c];
if (p && p.owner === this.turnOwner() && p.kind !== 'lei' && p.kind !== 'jq') {
for (const [dr, dc] of [[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]) {
if (this.canMove([r, c], [r + dr, c + dc])) { canAct = true; break; }
}
}
}
if (canAct) return null;
return !this.alive('r') ? 'b' : (!this.alive('b') ? 'r' : (this.turnOwner() === 'r' ? 'b' : 'r'));
}
serialize() { return { R: this.R, C: this.C, cells: this.cells, shown: this.shown, turn: this.turn, mode: this.mode }; }
static restore(o) { const j = new JunqiBoard(o.mode); j.R = o.R; j.C = o.C; j.cells = o.cells; j.shown = o.shown; j.turn = o.turn; return j; }
}
if (typeof module !== 'undefined') module.exports = { JunqiBoard, KINDS, KIND_LBL, KIND_RANK, CAMP_LIST, HQ_LIST, RAIL_ROWS, RAIL_COLS };
+350
View File
@@ -0,0 +1,350 @@
// 军棋前端 — SVG 真实线图棋盘(铁路双线/公路/两国前线,卡片背面"军棋")
var jq = null, jqSel = null;
var jqAiBusy = false;
var jqTimer = null;
function jqLevel() { const el = document.getElementById('diff'); return el ? el.value : 'normal'; }
function jq2P() { try { return localStorage.getItem('fnos_mode') === '2p'; } catch (e) { return false; } }
function boot_junqi_solo() {
jq = new JunqiBoard('flip');
jqSel = null; jqAiBusy = false; gameStartTs = Date.now();
jq._steps = 0;
if (window.applyTimer) { applyTimer(); resetTimer('r'); }
render_junqi();
const lbl = { easy: '简单', normal: '普通', hard: '困难' }[jqLevel()];
if (jq2P()) setStatus('junqi-st', '双人同屏 · 红方(你)先翻,红蓝轮流');
else setStatus('junqi-st', '难度:' + lbl + ' · 轮到你(红方)翻第一枚');
}
const FACE = { s9:'司令', s8:'军长', s7:'师长', s6:'旅长', s5:'团长', s4:'营长', s3:'连长', s2:'排长', s1:'工兵', lei:'地雷', zha:'炸弹', jq:'军旗' };
function junqiOver(w) {
jqSel = null;
render_junqi();
const durTxt = fmtDur(gameDurationSec());
let steps = 0;
try { steps = (jq.movesRecord || []).length; } catch (e) {}
setStatus('junqi-st', w === 'r' ? '🎉 红方胜!' : '蓝方胜');
if (w === 'r') { recordGame({ game: 'junqi', result: 'win', dur: durTxt, steps: steps }); gameResultPopup(true, '🏆 红方胜!', '扛获蓝军旗或全歼蓝方 · 用时 ' + durTxt); }
else { recordGame({ game: 'junqi', result: 'lose', dur: durTxt, steps: steps }); gameResultPopup(false, '💔 蓝方胜', '军旗被扛或无子可动 · 用时 ' + durTxt); }
}
function render_junqi() {
const el = document.getElementById('game-canvas');
if (!el) return;
// ===== 标准陆战棋棋盘:5列 × 12行(蓝方上 0-5 行、红方下 6-11 行),中缝为山界 =====
const CS = 46, GAP = 7, PAD = 20, FRONT = 44;
const R = jq.R, C = jq.C;
const W = PAD * 2 + C * CS + (C - 1) * GAP;
const halfH = 5 * (CS + GAP) + CS;
const H = PAD * 2 + halfH * 2 + FRONT;
const px = (c) => PAD + c * (CS + GAP) + CS / 2;
const py = (r) => (r <= 5)
? PAD + r * (CS + GAP) + CS / 2
: PAD + halfH + FRONT + (r - 6) * (CS + GAP) + CS / 2;
var jqBG = 'white'; // 背景选择功能已移除,固定白底
const bgFill = ({ white: '#fffdf8', wood: '#f0e2c4', dark: '#22303f', blue: '#123055' })[jqBG] || '#fffdf8';
const lineCol = ({ white: '#222', wood: '#8b5a2b', dark: '#cfd8e3', blue: '#9dc0e8' })[jqBG] || '#222';
const fieldFill= ({ white: '#ffffff', wood: '#f8f1de', dark: '#2c3e50', blue: '#1b3d6b' })[jqBG] || '#fff';
const faint = ({ white: 'rgba(0,0,0,0.45)', wood: 'rgba(120,70,20,0.55)', dark: 'rgba(255,255,255,0.4)', blue: 'rgba(230,240,255,0.45)' })[jqBG] || 'rgba(0,0,0,0.45)';
let s = `<svg id="junqi-b" viewBox="0 0 ${W} ${H}" style="touch-action:manipulation;width:auto;max-width:100%;max-height:calc(100vh - 190px);display:block;margin:0 auto">`;
s += `<rect x="0" y="0" width="${W}" height="${H}" fill="${bgFill}" rx="10"/>`;
const isCamp = (r, c) => CAMP_LIST.some(([a, b]) => a === r && b === c);
const isHQ = (r, c) => HQ_LIST.some(([a, b]) => a === r && b === c);
const crossFront = (r1, r2, c) => ((r1 === 5 && r2 === 6) || (r1 === 6 && r2 === 5)) && FRONT_COLS.indexOf(c) < 0;
// ---- 公路(细线):同半场内正交相邻 ----
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
if (c + 1 < C) {
const x1 = px(c) + CS / 2, x2 = px(c + 1) - CS / 2, y = py(r);
s += `<line x1="${x1}" y1="${y}" x2="${x2}" y2="${y}" stroke="${lineCol}" stroke-width="1" opacity="0.55"/>`;
}
if (r + 1 < R && !crossFront(r, r + 1, c)) {
const y1 = py(r) + CS / 2, y2 = py(r + 1) - CS / 2, x = px(c);
s += `<line x1="${x}" y1="${y1}" x2="${x}" y2="${y2}" stroke="${lineCol}" stroke-width="1" opacity="0.55"/>`;
}
}
// ---- 行营斜线(连四角兵站,形成经典的菱形/Rose 图案,仅局部) ----
for (const [r, c] of CAMP_LIST) {
const x = px(c), y = py(r);
[[1,1],[1,-1],[-1,1],[-1,-1]].forEach(([dr, dc]) => {
const rr = r + dr, cc = c + dc;
if (rr < 0 || rr >= R || cc < 0 || cc >= C) return;
if (crossFront(r, rr, c)) return;
s += `<line x1="${x}" y1="${y}" x2="${px(cc)}" y2="${py(rr)}" stroke="${lineCol}" stroke-width="1" opacity="0.55"/>`;
});
}
// ---- 铁路(双线 + 白色虚线中心 + 横枕) ----
const rail = (x1, y1, x2, y2) => {
const horiz = Math.abs(y2 - y1) < 0.01;
const d = 3.2;
if (horiz) {
s += `<line x1="${x1}" y1="${y1 - d}" x2="${x2}" y2="${y2 - d}" stroke="${lineCol}" stroke-width="2.6"/>`;
s += `<line x1="${x1}" y1="${y1 + d}" x2="${x2}" y2="${y2 + d}" stroke="${lineCol}" stroke-width="2.6"/>`;
s += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="#fff" stroke-width="1.6" stroke-dasharray="7,5"/>`;
} else {
s += `<line x1="${x1 - d}" y1="${y1}" x2="${x2 - d}" y2="${y2}" stroke="${lineCol}" stroke-width="2.6"/>`;
s += `<line x1="${x1 + d}" y1="${y1}" x2="${x2 + d}" y2="${y2}" stroke="${lineCol}" stroke-width="2.6"/>`;
s += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="#fff" stroke-width="1.6" stroke-dasharray="7,5"/>`;
}
};
// 横向铁路 r∈{2,5,6,9} 通贯全宽
for (const r of RAIL_ROWS) rail(px(0) - CS / 2 + 2, py(r), px(C - 1) + CS / 2 - 2, py(r));
// 纵向铁路 c∈{0,4} 各自半场贯通
for (const c of RAIL_COLS) {
rail(px(c), py(0) - CS / 2 + 2, px(c), py(5) + CS / 2 - 2);
rail(px(c), py(6) - CS / 2 + 2, px(c), py(11) + CS / 2 - 2);
}
// 山界三处铁路通口(c=0,2,4)
for (const c of FRONT_COLS) rail(px(c), py(5) + CS / 2, px(c), py(6) - CS / 2);
// ---- 山界带 ----
const yMidTop = py(5) + CS / 2 + 3, yMidBot = py(6) - CS / 2 - 3;
s += `<line x1="${PAD - 10}" y1="${yMidTop}" x2="${W - PAD + 10}" y2="${yMidTop}" stroke="${lineCol}" stroke-width="1" stroke-dasharray="4,4" opacity="0.6"/>`;
s += `<line x1="${PAD - 10}" y1="${yMidBot}" x2="${W - PAD + 10}" y2="${yMidBot}" stroke="${lineCol}" stroke-width="1" stroke-dasharray="4,4" opacity="0.6"/>`;
s += `<text x="${PAD + 30}" y="${(yMidTop + yMidBot) / 2 + 4}" font-size="12" fill="#b03a3a" font-family="Kaiti, serif" opacity="0.9">山</text>`;
s += `<text x="${PAD + 58}" y="${(yMidTop + yMidBot) / 2 + 4}" font-size="12" fill="#b03a3a" font-family="Kaiti, serif" opacity="0.9">界</text>`;
s += `<text x="${W - PAD - 30}" y="${(yMidTop + yMidBot) / 2 + 4}" font-size="11" fill="${faint}" font-family="Kaiti, serif" text-anchor="end">前线(仅两侧与中路可通)</text>`;
// ---- 棋位 ----
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
const x = px(c), y = py(r);
if (isCamp(r, c)) {
// 行营:圆 + 内 X
s += `<circle cx="${x}" cy="${y}" r="${CS / 2 - 3}" fill="${fieldFill}" stroke="${lineCol}" stroke-width="1.8"/>`;
const RX = (CS / 2 - 12) / 1.414;
s += `<line x1="${x - RX}" y1="${y - RX}" x2="${x + RX}" y2="${y + RX}" stroke="${lineCol}" stroke-width="1.2" opacity="0.75"/>`;
s += `<line x1="${x - RX}" y1="${y + RX}" x2="${x + RX}" y2="${y - RX}" stroke="${lineCol}" stroke-width="1.2" opacity="0.75"/>`;
s += `<text x="${x}" y="${y + CS * 0.09}" font-size="10" fill="${faint}" font-family="Kaiti, serif" text-anchor="middle" style="pointer-events:none">行营</text>`;
} else if (isHQ(r, c)) {
s += `<rect x="${x - CS / 2 + 2}" y="${y - CS / 2 + 2}" width="${CS - 4}" height="${CS - 4}" rx="5" fill="${fieldFill}" stroke="${lineCol}" stroke-width="1.8"/>`;
s += `<rect x="${x - CS / 2 + 6}" y="${y - CS / 2 + 6}" width="${CS - 12}" height="${CS - 12}" rx="3" fill="none" stroke="${lineCol}" stroke-width="1" opacity="0.6"/>`;
s += `<text x="${x}" y="${y + CS * 0.09}" font-size="10.5" fill="${faint}" font-family="Kaiti, serif" text-anchor="middle" style="pointer-events:none">大本营</text>`;
} else {
s += `<rect x="${x - CS / 2 + 3}" y="${y - CS / 2 + 3}" width="${CS - 6}" height="${CS - 6}" rx="4" fill="${fieldFill}" stroke="${lineCol}" stroke-width="1.1" opacity="0.95"/>`;
s += `<text x="${x}" y="${y + CS * 0.09}" font-size="9.5" fill="${faint}" font-family="Kaiti, serif" text-anchor="middle" style="pointer-events:none">兵站</text>`;
}
}
// ---- 棋子 ----
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
const p = jq.cells[r][c];
const x = px(c), y = py(r);
if (!p) { s += `<rect x="${x - CS/2}" y="${y - CS/2}" width="${CS}" height="${CS}" fill="transparent" onclick="jqClick(${r},${c})" style="cursor:pointer"/>`; continue; }
const S = CS - 10; // 棋子边长
const isOpen = jq.shown[r][c] || (p && p.owner); // 有归属=已翻开,防止暗牌样式盖住军衔
if (!isOpen) {
const gid = 'gu' + r + '_' + c;
s += `<defs><linearGradient id="${gid}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#3d5c99"/><stop offset="1" stop-color="#22355e"/></linearGradient></defs>`;
s += `<rect x="${x - S/2}" y="${y - S/2}" width="${S}" height="${S}" rx="7" fill="url(#${gid})" stroke="#16294a" stroke-width="1.8"/>`;
s += `<rect x="${x - S/2 + 3}" y="${y - S/2 + 3}" width="${S - 6}" height="${S - 6}" rx="5" fill="none" stroke="#ffd964" stroke-width="0.9" opacity="0.75"/>`;
const cx5 = x, cy5 = y - S * 0.15, R5 = S * 0.17;
let pts = [];
for (let i = 0; i <= 5; i++) {
const a1 = -Math.PI / 2 + i * 2 * Math.PI / 5, a2 = a1 + Math.PI / 5;
pts.push((cx5 + R5 * Math.cos(a1)).toFixed(1) + ',' + (cy5 + R5 * Math.sin(a1)).toFixed(1));
pts.push((cx5 + R5 * 0.42 * Math.cos(a2)).toFixed(1) + ',' + (cy5 + R5 * 0.42 * Math.sin(a2)).toFixed(1));
}
s += `<polygon points="${pts.join(' ')}" fill="#fff" style="pointer-events:none"/>`;
s += `<text x="${x}" y="${y + S*0.31}" font-size="${S*0.26}" fill="#ffe9a8" font-family="Kaiti, serif" font-weight="bold" text-anchor="middle" style="pointer-events:none">军棋</text>`;
} else {
const isRed = p.owner === 'r';
const gid = 'gp' + r + '_' + c;
const top = isRed ? '#fff8ea' : '#2f4f80', bot = isRed ? '#f0d3b4' : '#1a2e52';
const col = isRed ? '#b0181c' : '#ffd964', bcol = isRed ? '#8e1a1a' : '#0d1b36';
s += `<defs><linearGradient id="${gid}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${top}"/><stop offset="1" stop-color="${bot}"/></linearGradient></defs>`;
s += `<rect x="${x - S/2}" y="${y - S/2}" width="${S}" height="${S}" rx="7" fill="url(#${gid})" stroke="${bcol}" stroke-width="2"/>`;
s += `<rect x="${x - S/2 + 3}" y="${y - S/2 + 3}" width="${S - 6}" height="${S - 6}" rx="5" fill="none" stroke="${col}" stroke-width="0.9" opacity="0.8"/>`;
const k = FACE[p.kind];
const yTop = y - S * 0.14, yBase = y + S * 0.02, yBot = y + S * 0.20;
if (k.length === 2) {
s += `<text x="${x}" y="${yTop}" font-size="${S*0.40}" font-family="Kaiti, STKaiti, serif" font-weight="bold" fill="${col}" text-anchor="middle" dominant-baseline="middle" style="pointer-events:none">${k[0]}</text>`;
s += `<text x="${x}" y="${yBot}" font-size="${S*0.40}" font-family="Kaiti, STKaiti, serif" font-weight="bold" fill="${col}" text-anchor="middle" dominant-baseline="middle" style="pointer-events:none">${k[1]}</text>`;
} else {
s += `<text x="${x}" y="${yBase}" font-size="${S*0.52}" font-family="Kaiti, STKaiti, serif" font-weight="bold" fill="${col}" text-anchor="middle" dominant-baseline="middle" style="pointer-events:none">${k}</text>`;
}
}
// 入营标记:棋子压在营格上时,仍能看出它站在行营(受保护)/ 大本营(不可移动)
if (isCamp(r, c)) {
s += `<circle cx="${x}" cy="${y}" r="${CS/2 - 1.5}" fill="none" stroke="#f59e0b" stroke-width="2.2" stroke-dasharray="5,3"/>`;
s += `<text x="${x - CS/2 + 3}" y="${y - CS/2 + 9}" font-size="9" fill="#f59e0b" font-family="Kaiti, serif" font-weight="bold" style="pointer-events:none">营</text>`;
} else if (isHQ(r, c)) {
s += `<rect x="${x - CS/2 + 1}" y="${y - CS/2 + 1}" width="${CS - 2}" height="${CS - 2}" rx="9" fill="none" stroke="#7f8c8d" stroke-width="2" stroke-dasharray="4,3"/>`;
s += `<text x="${x - CS/2 + 3}" y="${y - CS/2 + 9}" font-size="9" fill="#7f8c8d" font-family="Kaiti, serif" font-weight="bold" style="pointer-events:none">本</text>`;
}
if (jqSel && jqSel[0] === r && jqSel[1] === c) s += `<rect x="${x - CS/2 + 1}" y="${y - CS/2 + 1}" width="${CS - 2}" height="${CS - 2}" rx="9" fill="none" stroke="#ff9800" stroke-width="3"/>`;
s += `<rect x="${x - CS/2}" y="${y - CS/2}" width="${CS}" height="${CS}" fill="transparent" onclick="jqClick(${r},${c})" style="cursor:pointer"/>`;
}
s += '</svg>';
el.innerHTML = s;
}
function jqClick(r, c) {
if (!jq || jqAiBusy) return;
const p = jq.cells[r][c];
if (p && !jq.shown[r][c]) { jq.flip(r, c); }
else if (jqSel) {
const res = jq.movePiece(jqSel, [r, c]);
if (!res.ok && jq.cells[r][c] && jq.shown[r][c] && jq.cells[r][c].owner === 'r') { jqSel = [r, c]; render_junqi(); return; }
jqSel = null;
} else if (p && jq.shown[r][c] && p.owner === 'r') {
jqSel = [r, c]; render_junqi(); setStatus('junqi-st', '已选 ' + FACE[p.kind] + ' · 点相邻格移动/吃子');
return;
}
jqSel = null;
render_junqi();
junqiAfter();
}
function junqiAfter() {
const w = jq.winner();
if (w) return junqiOver(w);
swapTimer();
if (window.autoSnapshot) autoSnapshot();
if (jq2P()) {
setStatus('junqi-st', '双人同屏 · 轮到 ' + (jq.turnOwner() === 'r' ? '红方' : '蓝方'));
if (window.autoCoachIfOn) autoCoachIfOn();
return;
}
if (jq.turnOwner() === 'b') {
setStatus('junqi-st', '蓝方 AI 行动中…'); jqAiBusy = true;
if (jqTimer) { clearTimeout(jqTimer); jqTimer = null; }
jqTimer = setTimeout(() => { jqAiBusy = false; jqTimer = null; try { jqAiTurn(); } catch (e) { setStatus('junqi-st', 'AI 出错,已交回你走:' + e.message); } }, 120);
} else setStatus('junqi-st', '轮到你(红方)');
}
function jqAiTurn() {
const w0 = jq.winner(); if (w0) return junqiOver(w0);
if (jq.turnOwner() !== 'b') { setStatus('junqi-st', '轮到你(红方)'); return; }
const lvl = jqLevel();
const flips = [], moves = [];
for (let r = 0; r < jq.R; r++) for (let c = 0; c < jq.C; c++) {
const p = jq.cells[r][c];
if (p && !jq.shown[r][c]) flips.push([r, c]);
else if (p && jq.shown[r][c] && p.owner === 'b') {
[[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]].forEach(([dr,dc]) => { const tr=r+dr,tc=c+dc; if (jq.canMove([r,c],[tr,tc])) moves.push([[r,c],[tr,tc]]); });
}
}
const doFlip = () => jq.flip(...flips[Math.floor(Math.random() * flips.length)]);
const doMove = () => { const p = moves[Math.floor(Math.random() * moves.length)]; jq.movePiece(p[0], p[1]); };
if (lvl === 'easy') {
if (flips.length && (Math.random() < 0.6 || !moves.length)) doFlip(); else if (moves.length) doMove(); else if (flips.length) doFlip(); else jq.turn = 1 - jq.turn;
} else {
const scored = moves.map(([f, t]) => {
const tp = jq.cells[t[0]][t[1]];
let sc = 0;
if (tp) {
const res = jq.battle(jq.cells[f[0]][f[1]].kind, tp.kind);
if (res === 'win') sc = tp.kind === 'jq' ? 1000 : KIND_RANK[tp.kind] * 10 + 10;
else if (res === 'both') sc = KIND_RANK[tp.kind] * 5 - KIND_RANK[jq.cells[f[0]][f[1]].kind] * 5;
else sc = -20;
} else sc = 1;
return { f, t, sc };
}).sort((a, b) => b.sc - a.sc);
const myMove = scored[0];
if (myMove && myMove.sc > 5) { jq.movePiece(myMove.f, myMove.t); }
else if (flips.length && (moves.length === 0 || Math.random() < (lvl === 'hard' ? 0.5 : 0.6))) doFlip();
else if (moves.length) doMove();
else if (flips.length) doFlip();
else jq.turn = 1 - jq.turn;
}
jqSel = null;
render_junqi();
const w = jq.winner();
if (w) return junqiOver(w);
setStatus('junqi-st', '轮到你(红方)');
swapTimer();
if (window.autoCoachIfOn) autoCoachIfOn();
}
window.junqiUndo = function() {
if (jqTimer) { clearTimeout(jqTimer); jqTimer = null; }
jqAiBusy = false;
const twoP = (function(){ try { return localStorage.getItem('fnos_mode') === '2p'; } catch (e) { return false; } })();
let n = 0;
if (twoP) { if (jq.undoLast()) n = 1; }
else {
if (jq.undoLast()) n++; // 撤 AI 一步
if (jq.turnOwner() !== 'r' || n === 1) { if (jq.undoLast()) n++; } // 再撤我方一步
let guard = 0;
while (jq.turnOwner() !== 'r' && jq._hist && jq._hist.length && guard++ < 4) { if (!jq.undoLast()) break; }
}
jqSel = null;
render_junqi();
setStatus('junqi-st', n ? ('已悔棋(' + n + ' 步)· ' + (jq.turnOwner() === 'r' ? '轮到你(红方)' : '轮到蓝方')) : '没有可悔的棋');
};
// —— 存档 / 恢复 ——
window.GAMEHOOKS = window.GAMEHOOKS || {};
GAMEHOOKS.junqi = {
started: function () { return !!jq; },
inProgress: function () { return !!(jq && (jq._hist || []).length > 0 && !jq.winner() && !window.__gameOver); },
serialize: function () {
if (!jq) return null;
const sel = curGameSelects();
return {
game: 'junqi', label: '军棋', mode: jq2P() ? '双人同屏' : '人机',
diff: jqLevel(), timer: sel.timer,
state: jq.serialize(), hist: jq._hist || [], flagTaken: jq.flagTaken || null,
steps: (jq._hist || []).length,
elapsed: Math.max(0, Math.floor((Date.now() - (gameStartTs || Date.now())) / 1000))
};
},
restore: function (sv) {
try {
if (jqTimer) { clearTimeout(jqTimer); jqTimer = null; }
jqAiBusy = false; jqSel = null;
jq = JunqiBoard.restore(sv.state);
jq._hist = sv.hist || []; jq.flagTaken = sv.flagTaken || null;
try { localStorage.setItem('fnos_mode', sv.mode === '双人同屏' ? '2p' : 'ai'); } catch (e) {}
const d1 = document.getElementById('diff'); if (d1 && sv.diff) d1.value = sv.diff;
const t1 = document.getElementById('timer');
if (t1 && sv.timer != null) { t1.value = String(sv.timer); applyTimer(); }
gameStartTs = Date.now() - (sv.elapsed || 0) * 1000;
render_junqi(); swapTimer();
const w = jq.winner();
if (w) { junqiOver(w); return true; }
if (!jq2P() && jq.turnOwner() === 'b') { setStatus('junqi-st', '已恢复存档 · 蓝方 AI 行动中…'); junqiAfter(); }
else setStatus('junqi-st', '已恢复存档 · ' + (sv.mode || '') + ' · ' + (jq.turnOwner() === 'r' ? '轮到你(红方)' : '轮到蓝方'));
return true;
} catch (e) { alert('恢复失败:' + e.message); return false; }
} };
window.boot_junqi_solo = boot_junqi_solo;
// ---- 残局(明棋):双方各 25 子按标准陆战棋布阵(23兵站 + 2大本营),全部翻开,红先 ----
function junqiPuzzleLayout(mode) {
let list = ['jq','lei','lei','lei','zha','zha','s1','s1','s1','s2','s2','s2','s3','s3','s3',
's4','s4','s5','s5','s6','s6','s7','s7','s8','s9']; // 25 枚(后→前)
if (mode === 'mineFirst') list = ['lei','lei','lei','zha','zha','s1','s1','s1','jq','s2','s2','s2','s3','s3','s3','s4','s4','s5','s5','s6','s6','s7','s7','s8','s9'];
if (mode === 'boomMode') list = ['zha','zha','jq','lei','lei','lei','s1','s1','s1','s2','s2','s2','s3','s3','s3','s4','s4','s5','s5','s6','s6','s7','s7','s8','s9'];
const isC = (r, c) => CAMP_LIST.some(([a, b]) => a === r && b === c);
const isH = (r, c) => HQ_LIST.some(([a, b]) => a === r && b === c);
const slots = (side) => {
const rows = side === 'b' ? [0, 1, 2, 3, 4, 5] : [11, 10, 9, 8, 7, 6];
const out = side === 'b' ? [[0, 1], [0, 3]] : [[11, 1], [11, 3]]; // 大本营先放(军旗入营)
for (const r of rows) for (let c = 0; c < 5; c++) if (!isC(r, c) && !isH(r, c)) out.push([r, c]);
return out;
};
return { list, blue: slots('b'), red: slots('r') };
}
window.loadJunqiPuzzle = function(pz) {
if (jqTimer) { clearTimeout(jqTimer); jqTimer = null; }
jqAiBusy = false;
jq = new JunqiBoard('flip');
const mode = pz.mineFirst ? 'mineFirst' : (pz.boomMode ? 'boomMode' : 'open');
const L = junqiPuzzleLayout(mode);
for (let r = 0; r < jq.R; r++) for (let c = 0; c < jq.C; c++) { jq.cells[r][c] = null; jq.shown[r][c] = false; }
const put = (cells, pieces, owner) => {
for (let i = 0; i < cells.length; i++) {
const [r, c] = cells[i];
jq.cells[r][c] = { kind: pieces[i], owner: owner, faceDown: false };
jq.shown[r][c] = true;
}
};
put(L.blue, L.list.slice(), 'b');
put(L.red, L.list.slice(), 'r');
jq._hist = []; jq.flagTaken = null; jq.turn = 0;
jqSel = null;
gameStartTs = Date.now();
render_junqi();
setStatus('junqi-st', '残局『' + pz.name + '』· ' + pz.tip + ' · 轮到你(红方)');
};
function setJqBG(v) {
try { localStorage.setItem('fnos_jq_bg', v); } catch (e) {}
render_junqi();
}
window.setJqBG = setJqBG;
window.loadJunqiPuzzle = window.loadJunqiPuzzle || function() {};
+36
View File
@@ -0,0 +1,36 @@
{
"name": "fnos-games",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "fnos-games",
"version": "1.0.0",
"dependencies": {
"ws": "^8.22.0"
}
},
"node_modules/ws": {
"version": "8.22.0",
"resolved": "https://registry.npmmirror.com/ws/-/ws-8.22.0.tgz",
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "fnos-games",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node server.js"
},
"dependencies": {
"ws": "^8.22.0"
}
}
+576
View File
@@ -0,0 +1,576 @@
// 服务端:静态资源 + WebSocket 房间(象棋/五子棋/军棋/飞行棋)
const http = require('http');
const fs = require('fs');
const path = require('path');
const { WebSocketServer } = require('ws');
const { Chess } = require('./app/js/chess.js');
const { aiMove } = require('./app/js/chessAI.js');
const { Gomoku, aiPick } = require('./app/js/gomoku.js');
const { JunqiBoard, KIND_LBL } = require('./app/js/junqi.js');
const PORT = process.env.PORT || 7025;
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.svg': 'image/svg+xml', '.json': 'application/json', '.png': 'image/png', '.ico': 'image/x-icon' };
const APP = path.join(__dirname, 'app');
// —— 排行榜存储 ——
const DATA = path.join(__dirname, 'data');
if (!fs.existsSync(DATA)) fs.mkdirSync(DATA, { recursive: true });
// —— 存档存储(各游戏独立文件;目录可由用户设置) ——
const CONFIG_FILE = path.join(DATA, 'config.json');
const GAMES = ['chess', 'gomoku', 'junqi'];
const DEFAULT_SAVE_DIR = path.join(DATA, 'saves');
function loadConfig() { try { return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); } catch (e) { return {}; } }
function writeConfig(c) { try { fs.writeFileSync(CONFIG_FILE, JSON.stringify(c, null, 2)); } catch (e) {} }
function saveDir() {
const c = loadConfig();
let raw = c && c.saveDir ? String(c.saveDir).trim() : '';
if (!raw && c && c.savePath) raw = path.dirname(String(c.savePath)); // 兼容旧配置(单文件)
return raw ? path.resolve(raw) : DEFAULT_SAVE_DIR;
}
function saveFileFor(game) { return path.join(saveDir(), game + '-saves.json'); }
function readGameSaves(game) {
try { const o = JSON.parse(fs.readFileSync(saveFileFor(game), 'utf8')); return Array.isArray(o.saves) ? o.saves : []; }
catch (e) { return []; }
}
function writeGameSaves(game, arr) {
const fp = saveFileFor(game);
fs.mkdirSync(path.dirname(fp), { recursive: true });
fs.writeFileSync(fp, JSON.stringify({ game, saves: arr }, null, 2));
}
// —— 排行榜存储(与存档同目录、按游戏分文件,持久化) ——
function rankFileFor(game) { return path.join(saveDir(), game + '-ranks.json'); }
function readRanksFor(game) {
try { const o = JSON.parse(fs.readFileSync(rankFileFor(game), 'utf8')); return Array.isArray(o.games) ? o.games : []; }
catch (e) { return []; }
}
function rankKey(x) {
return x.id || (x.game + '|' + x.ts + '|' + (x.result || '') + '|' + (x.dur || x.durTxt || '') + '|' + (x.steps || ''));
}
function normalizeRanks(arr) {
const seen = {}; const out = [];
(arr || []).forEach(x => { const k = rankKey(x); if (seen[k]) return; seen[k] = 1; out.push(x); });
return out.sort((a, b) => b.ts - a.ts).slice(0, 500);
}
function writeRanksFor(game, arr) {
const fp = rankFileFor(game);
fs.mkdirSync(path.dirname(fp), { recursive: true });
fs.writeFileSync(fp, JSON.stringify({ game, games: normalizeRanks(arr) }, null, 2));
}
function allRanks() {
const out = [];
GAMES.forEach(g => readRanksFor(g).forEach(x => out.push(x)));
return out.sort((a, b) => b.ts - a.ts);
}
function countAll() {
const out = {};
GAMES.forEach(g => { out[g] = readGameSaves(g).length; });
return out;
}
// 旧版单文件(data/saves.json)一次性拆分到各游戏独立文件
function splitLegacyFile(fp) {
try {
const o = JSON.parse(fs.readFileSync(fp, 'utf8'));
GAMES.forEach(g => {
const mine = (o.saves || []).filter(x => x.game === g);
if (!mine.length) return;
const cur = readGameSaves(g);
const ids = new Set(cur.map(x => x.id));
mine.forEach(x => { if (!ids.has(x.id)) cur.push(x); });
writeGameSaves(g, cur.sort((a, b) => b.ts - a.ts));
});
fs.renameSync(fp, fp + '.migrated');
} catch (e) {}
}
function migrateLegacyFile() {
try {
const legacyCfg = loadConfig();
if (legacyCfg && legacyCfg.savePath) { // 旧配置:把文件目录作为存档目录
const d0 = path.dirname(path.resolve(legacyCfg.savePath));
const c2 = { saveDir: d0 }; writeConfig(c2);
const fp = path.resolve(legacyCfg.savePath);
if (fs.existsSync(fp)) splitLegacyFile(fp);
}
} catch (e) {}
// 默认位置的历史单文件(无论是否用过旧配置都要迁)
try {
const legacy = path.join(DATA, 'saves.json');
if (fs.existsSync(legacy)) splitLegacyFile(legacy);
} catch (e) {}
// 旧排行榜单文件 data/ranks.json → 按游戏拆分
try {
const legacyRank = path.join(DATA, 'ranks.json');
if (fs.existsSync(legacyRank)) {
const o = JSON.parse(fs.readFileSync(legacyRank, 'utf8'));
GAMES.forEach(g => {
const mine = (o.games || []).filter(x => x.game === g);
if (!mine.length) return;
const cur = readRanksFor(g);
mine.forEach(x => cur.push(x));
cur.sort((a, b) => b.ts - a.ts);
writeRanksFor(g, cur.slice(0, 500));
});
fs.renameSync(legacyRank, legacyRank + '.migrated');
}
} catch (e) {}
}
migrateLegacyFile();
GAMES.forEach(g => { try { writeRanksFor(g, readRanksFor(g)); } catch (e) {} }); // 启动时去重规范化
// 允许写入的根目录(容器内只有 /app 数据卷会被持久化)
function allowPath(p2) {
const r = path.resolve(p2);
return r === '/app' || r.startsWith('/app/');
}
function ensureSaveFile(fp) {
fs.mkdirSync(path.dirname(fp), { recursive: true });
if (!fs.existsSync(fp)) fs.writeFileSync(fp, JSON.stringify({ saves: [] }, null, 2));
}
const CTJ = { 'Content-Type': 'application/json; charset=utf-8' };
async function aiHintAPI(req, res, body) {
try {
const { baseUrl, apiKey, model, prompt, history } = JSON.parse(body);
if (!baseUrl || !model || !prompt) { res.writeHead(400, CTJ); return res.end(JSON.stringify({ error: '缺少 baseUrl/model/prompt' })); }
const url = baseUrl.replace(/\/$/, '') + '/chat/completions';
const payload = {
model,
messages: [
{ role: 'system', content: '你是一位中文棋类教练。用户给出棋局描述,请用一句话(50字以内)告诉用户(执红/黑方)下一步应该怎么走,指出具体位置和理由。直接输出建议,不要客套。' },
{ role: 'user', content: prompt }
],
max_tokens: 120,
temperature: 0.6
};
const u = new URL(url);
const mod = u.protocol === 'https:' ? require('https') : require('http');
const opts = { method: 'POST', hostname: u.hostname, port: u.port || (u.protocol === 'https:' ? 443 : 80), path: u.pathname + u.search,
headers: { 'Content-Type': 'application/json', ...(apiKey ? { Authorization: 'Bearer ' + apiKey } : {}) }, timeout: 30000 };
await new Promise((resolve, reject) => {
const rq = mod.request(opts, rs => {
let buf = '';
rs.on('data', d2 => buf += d2);
rs.on('end', () => {
try {
const j = JSON.parse(buf);
const text = j.choices && j.choices[0] && j.choices[0].message ? j.choices[0].message.content : (j.error ? null : buf.slice(0, 200));
if (text) { res.writeHead(200, CTJ); res.end(JSON.stringify({ hint: text.trim() })); }
else { res.writeHead(502, CTJ); res.end(JSON.stringify({ error: (j.error && (j.error.message || j.error)) || '模型无返回' })); }
} catch (e) { res.writeHead(502, CTJ); res.end(JSON.stringify({ error: '模型返回非JSON: ' + buf.slice(0, 120) })); }
resolve();
});
});
rq.on('error', e => { res.writeHead(502, CTJ); res.end(JSON.stringify({ error: '连接模型失败: ' + e.message })); resolve(); });
rq.on('timeout', () => { rq.destroy(); res.writeHead(504, CTJ); res.end(JSON.stringify({ error: '模型响应超时' })); resolve(); });
rq.write(JSON.stringify(payload));
rq.end();
});
} catch (e) { res.writeHead(500, CTJ); res.end(JSON.stringify({ error: e.message })); }
}
const server = http.createServer((req, res) => {
let u = decodeURIComponent(req.url.split('?')[0]);
if (u === '/api/ai-hint') {
let body = '';
req.on('data', d2 => body += d2);
req.on('end', () => aiHintAPI(req, res, body));
return;
}
if (u === '/api/config') {
if (req.method === 'GET') {
res.writeHead(200, CTJ);
return res.end(JSON.stringify({
saveDir: saveDir(), defaultDir: DEFAULT_SAVE_DIR, allowedRoot: '/app',
files: GAMES.map(g => ({ game: g, file: saveFileFor(g), exists: fs.existsSync(saveFileFor(g)), count: readGameSaves(g).length }))
}));
}
if (req.method === 'POST') {
let body = '';
req.on('data', d2 => body += d2);
req.on('end', () => {
try {
const r2 = JSON.parse(body || '{}');
let raw = String(r2.saveDir || r2.savePath || '').trim();
if (!raw) throw new Error('目录不能为空');
let dir = path.resolve(raw);
if (fs.existsSync(dir) && fs.statSync(dir).isFile()) dir = path.dirname(dir); // 传了文件则取其目录
if (!allowPath(dir)) throw new Error('为安全起见,只允许使用 /app 目录下的路径(该目录已挂载到主机)');
const oldDir = saveDir();
fs.mkdirSync(dir, { recursive: true });
const c = loadConfig();
c.saveDir = dir; delete c.savePath; writeConfig(c);
// 迁移:把旧目录里各游戏的存档合并进新目录(按 id 去重),默认开启
if (r2.migrate !== false && oldDir !== dir) {
GAMES.forEach(g => {
const from = path.join(oldDir, g + '-saves.json');
if (!fs.existsSync(from)) return;
try {
const src = JSON.parse(fs.readFileSync(from, 'utf8'));
const cur = readGameSaves(g);
const ids = new Set(cur.map(x => x.id));
(src.saves || []).forEach(x => { if (!ids.has(x.id)) cur.push(x); });
writeGameSaves(g, cur.sort((a, b) => b.ts - a.ts));
} catch (e) {}
});
}
// 排行文件一并迁移
if (r2.migrate !== false && oldDir !== dir) {
GAMES.forEach(g => {
const from = path.join(oldDir, g + '-ranks.json');
if (!fs.existsSync(from)) return;
try {
const src = JSON.parse(fs.readFileSync(from, 'utf8'));
const cur = readRanksFor(g);
(src.games || []).forEach(x => cur.push(x));
cur.sort((a, b) => b.ts - a.ts);
writeRanksFor(g, cur.slice(0, 500));
} catch (e) {}
});
}
GAMES.forEach(g => { const fp = saveFileFor(g); if (!fs.existsSync(fp)) writeGameSaves(g, []); });
res.writeHead(200, CTJ);
res.end(JSON.stringify({ ok: true, saveDir: dir, oldDir, counts: countAll(), files: GAMES.map(g => saveFileFor(g)) }));
} catch (e) { res.writeHead(400, CTJ); res.end(JSON.stringify({ error: e.message })); }
});
return;
}
}
if (u === '/api/fs') {
const q = new URL(req.url, 'http://x').searchParams;
const dir = path.resolve(q.get('dir') || '/app/data');
if (!allowPath(dir)) { res.writeHead(403, CTJ); return res.end(JSON.stringify({ error: '只允许浏览 /app 目录' })); }
try {
const ents = fs.readdirSync(dir, { withFileTypes: true });
const dirs = ents.filter(e => e.isDirectory()).map(e => e.name).sort();
const files = ents.filter(e => e.isFile() && /\.json$/i.test(e.name)).map(e => e.name).sort();
res.writeHead(200, CTJ);
return res.end(JSON.stringify({ dir, parent: path.dirname(dir), dirs, files, root: '/app' }));
} catch (e) { res.writeHead(200, CTJ); return res.end(JSON.stringify({ dir, parent: path.dirname(dir), dirs: [], files: [], error: e.message })); }
}
if (u === '/api/save') {
const q = new URL(req.url, 'http://x').searchParams;
const game = String(q.get('game') || '');
if (req.method === 'GET') {
if (game && GAMES.indexOf(game) >= 0) {
const arr = readGameSaves(game).sort((a, b) => b.ts - a.ts);
res.writeHead(200, CTJ);
return res.end(JSON.stringify({ game, file: saveFileFor(game), saves: arr }));
}
// 不带 game:返回各游戏汇总(仅计数,便于概览)
res.writeHead(200, CTJ);
return res.end(JSON.stringify({ dir: saveDir(), counts: countAll(), files: GAMES.map(g => saveFileFor(g)) }));
}
if (req.method === 'DELETE' || (req.method === 'POST' && q.get('del'))) {
const id = q.get('id') || '';
if (GAMES.indexOf(game) < 0) { res.writeHead(400, CTJ); return res.end(JSON.stringify({ error: '缺少 game 参数' })); }
const arr = readGameSaves(game);
const n0 = arr.length;
const left = arr.filter(x => x.id !== id);
writeGameSaves(game, left);
res.writeHead(200, CTJ);
return res.end(JSON.stringify({ ok: true, removed: n0 - left.length, count: left.length }));
}
if (req.method === 'POST') {
let body = '';
req.on('data', d2 => body += d2);
req.on('end', () => {
try {
const rec = JSON.parse(body);
const g = String(rec.game || '');
if (GAMES.indexOf(g) < 0) throw new Error('未知游戏:' + g);
const arr = readGameSaves(g);
rec.id = rec.id || ('s' + Date.now() + Math.floor(Math.random() * 1000));
rec.ts = Date.now();
const idx = arr.findIndex(x => x.id === rec.id);
if (idx >= 0) arr[idx] = rec; else arr.push(rec);
const trimmed = arr.sort((x, y) => y.ts - x.ts).slice(0, 100);
writeGameSaves(g, trimmed);
res.writeHead(200, CTJ);
res.end(JSON.stringify({ ok: true, id: rec.id, ts: rec.ts, game: g, file: saveFileFor(g), count: trimmed.length }));
} catch (e) { res.writeHead(400, CTJ); res.end(JSON.stringify({ error: e.message })); }
});
return;
}
}
if (u === '/api/rank') {
const q = new URL(req.url, 'http://x').searchParams;
const game = String(q.get('game') || '');
if (req.method === 'GET') {
if (game && GAMES.indexOf(game) >= 0) {
res.writeHead(200, CTJ);
return res.end(JSON.stringify({ game, file: rankFileFor(game), games: readRanksFor(game) }));
}
res.writeHead(200, CTJ);
return res.end(JSON.stringify({
games: allRanks(),
counts: (() => { const c = {}; GAMES.forEach(g => c[g] = readRanksFor(g).length); return c; })(),
files: GAMES.map(g => ({ game: g, file: rankFileFor(g), count: readRanksFor(g).length })),
dir: saveDir()
}));
}
if (req.method === 'POST') {
let body = '';
req.on('data', d2 => body += d2);
req.on('end', () => {
try {
const rec = JSON.parse(body);
const g = GAMES.indexOf(String(rec.game || '')) >= 0 ? rec.game : 'chess';
const arr = readRanksFor(g);
rec.ts = Date.now();
rec.id = rec.id || ('r' + rec.ts + Math.floor(Math.random() * 1000));
arr.push(rec);
const trimmed = arr.sort((a, b) => b.ts - a.ts).slice(0, 500);
writeRanksFor(g, trimmed);
res.writeHead(200, CTJ);
res.end(JSON.stringify({ ok: true, game: g, count: trimmed.length, file: rankFileFor(g) }));
} catch (e) { res.writeHead(400, CTJ); res.end(JSON.stringify({ error: e.message })); }
});
return;
}
if (req.method === 'DELETE') {
const g = String(q.get('game') || '');
const id = q.get('id') || '';
if (GAMES.indexOf(g) < 0) { res.writeHead(400, CTJ); return res.end(JSON.stringify({ error: '缺少 game' })); }
const arr = readRanksFor(g).filter(x => String(x.ts) !== id && x.id !== id);
writeRanksFor(g, arr);
res.writeHead(200, CTJ);
return res.end(JSON.stringify({ ok: true, count: arr.length }));
}
}
if (u === '/') u = '/index.html';
const fp = path.normalize(path.join(APP, u));
if (!fp.startsWith(APP)) { res.writeHead(403); return res.end('forbidden'); }
fs.readFile(fp, (err, buf) => {
if (err) { res.writeHead(404); return res.end('not found'); }
res.writeHead(200, { 'Content-Type': MIME[path.extname(fp)] || 'application/octet-stream', 'Cache-Control': 'no-store' });
res.end(buf);
});
});
// —— 房间管理 ——
const rooms = new Map(); // id → room
let roomSeq = Math.floor(Math.random() * 9000) + 1000;
function newRoom(game) {
const id = String(roomSeq++);
const room = { id, game, clients: [], state: null, host: null };
if (game === 'chess') room.state = { g: new Chess(), names: { b: '蓝方等待中', r: '红方等待中' }, aiSide: null, aiDepth: 3 };
else if (game === 'gomoku') room.state = { g: new Gomoku(), names: ['黑方等待中','白方等待中'], aiSide: 0 };
else if (game === 'junqi') room.state = { g: new JunqiBoard('flip'), names: ['红方等待中','蓝方等待中'], aiSide: null };
else if (game === 'ludo') room.state = { g: new LudoGame(), seat: {} };
rooms.set(id, room);
return room;
}
function snapshot(room) {
const s = room.state;
if (room.game === 'chess') return { board: s.g.B, redTurn: s.g.redTurn, moves: s.g.moves, over: !!s.g.winner, winner: s.g.winner, names: s.names, aiSide: s.aiSide, aiDepth: s.aiDepth, check: s.g.inCheck(s.g.redTurn ? 'r' : 'b') };
if (room.game === 'gomoku') return { g: s.g.full(), names: s.names, aiSide: s.aiSide };
if (room.game === 'junqi') return { j: s.g.serialize(), names: s.names, aiSide: s.aiSide };
if (room.game === 'ludo') return { l: s.g.serialize(), seat: s.seat };
return {};
}
function broadcast(room) {
const snap = snapshot(room);
room.clients.forEach(cl => {
snap.you = cl.side;
snap.seat = cl.side === 'ludo' ? undefined : cl.side;
try { cl.ws.send(JSON.stringify({ t: 'state', d: snap, roomId: room.id, game: room.game })); } catch (e) {}
});
}
const wss = new WebSocketServer({ path: '/ws', noServer: true });
server.on('upgrade', (req, socket, head) => { if (req.url === '/ws') { wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req)); } });
wss.on('connection', (ws) => {
ws.room = null; ws.side = null;
ws.on('message', buf => {
let msg; try { msg = JSON.parse(buf); } catch (e) { return; }
handle(ws, msg).catch(e => { try { ws.send(JSON.stringify({ t: 'err', e: e.message })); } catch (x) {} });
});
ws.on('close', () => {
if (!ws.room) return;
const i = ws.room.clients.indexOf(ws); if (i >= 0) ws.room.clients.splice(i, 1);
if (ws.room.game === 'ludo' && ws.side && ws.room.state.seat[ws.side]) ws.room.state.seat[ws.side].online = false;
else if (ws.side && ws.room.state.names && typeof ws.side === 'string' && ws.room.state.names[ws.side]) ws.room.state.names[ws.side] += '(已掉线)';
broadcast(ws.room);
});
});
async function handle(ws, msg) {
const a = msg.a;
if (a === 'list') {
const out = [];
rooms.forEach(r => out.push({ id: r.id, game: r.game, players: r.clients.length, snapshot: null }));
return ws.send(JSON.stringify({ t: 'list', d: out.filter(r => r.players < 4) }));
}
if (a === 'create') {
const room = newRoom(msg.game);
rooms.set(room.id, room);
return ws.send(JSON.stringify({ t: 'created', id: room.id, game: msg.game }));
}
if (a === 'join') {
const room = rooms.get(msg.id);
if (!room) return ws.send(JSON.stringify({ t: 'err', e: '房间不存在' }));
if (room.clients.length >= 4) return ws.send(JSON.stringify({ t: 'err', e: '房间已满' }));
ws.room = room; room.clients.push(ws);
// 分配位置
if (room.game === 'ludo') {
const colors = ['r','y','b','g'].filter(c => !room.state.seat[c] || !room.state.seat[c].online);
const pick = room.clients.filter(c => c !== ws).map(c => c.side).filter(c => c);
ws.side = colors[0] || 'spectator';
room.state.seat[ws.side] = { online: true, ai: room.state.seat[ws.side] ? room.state.seat[ws.side].ai : 0 };
room.state.g.AI_LEVEL[ws.side] = room.state.seat[ws.side].ai;
} else {
const sides = room.game === 'gomoku' ? [0, 1] : ['r', 'b'];
if (room.game === 'gomoku') {
// state.names 是数组,用 side 序号
const taken = room.clients.filter(c => c !== ws && typeof c.side === 'number').map(c => c.side);
ws.side = taken.includes(0) ? 1 : 0;
room.state.names[ws.side] = (ws.side === 0 ? '黑方 ' : '白方 ') + '玩家';
} else {
const taken = room.clients.filter(c => c !== ws && typeof c.side === 'string' && room.game !== 'ludo').map(c => c.side);
ws.side = taken.includes('r') ? 'b' : 'r';
room.state.names[ws.side] = (ws.side === 'r' ? '红方 ' : '蓝方 ') + '玩家';
}
}
ws.send(JSON.stringify({ t: 'joined', d: { id: room.id, game: room.game, side: ws.side } }));
if (room.clients.length >= 2 && !room.started) room.started = true;
broadcast(room);
return;
}
if (a === 'spectate') {
const room = rooms.get(msg.id);
if (!room) return ws.send(JSON.stringify({ t: 'err', e: '房间不存在' }));
ws.room = room; ws.side = null; room.clients.push(ws);
ws.send(JSON.stringify({ t: 'joined', d: { id: room.id, game: room.game, side: null } }));
broadcast(room);
return;
}
if (!ws.room) return;
const room = ws.room, s = room.state;
if (a === 'aiLevel' && room.game === 'ludo') {
const side = msg.side; const v = +msg.v || 0;
if (room.state.seat[side] && room.clients.find(c => c.side === side)) return; // 有真人就别改
s.g.AI_LEVEL[side] = v;
return broadcast(room);
}
if (a === 'addAI' && room.game === 'ludo') {
for (const c of s.g.colors) {
if (!room.state.seat[c] || !room.clients.find(cl => cl.side === c)) { s.g.AI_LEVEL[c] = s.g.AI_LEVEL[c] || 1; room.state.seat[c] = room.state.seat[c] || {}; room.state.seat[c].ai = 1; break; }
}
return broadcast(room);
}
if (a === 'setAI' && room.game !== 'ludo') {
// 对战双方之一换为电脑
s.aiSide = msg.side; s.aiDepth = +msg.d || 3;
return broadcast(room);
}
if (a === 'clearAI' && room.game !== 'ludo') { s.aiSide = null; return broadcast(room); }
const play = (moveFn) => { const r = moveFn(); broadcast(room); return r; };
if (room.game === 'chess') {
if (a === 'move') {
const m = msg.m; if (s.g.own(m[0], m[1], s.g.redTurn ? 'r' : 'b')) { s.g.apply(s.g.legal(m[0], m[1]).find(x => x[2] === m[2] && x[3] === m[3]) || m); }
aiChessTurn(room);
return play(null);
}
if (a === 'undo') { if (s.g.moves.length) { s.g.moves.pop(); for (let k = 0; k < 2; k++) { const m = s.g.moves.pop() || null; /* not tracked board history → restore from moves? We'd need history stack */ } } }
if (a === 'new') { s.g = new Chess(); return play(null); }
return;
}
if (room.game === 'gomoku') {
if (a === 'place') { s.g.place(msg.r, msg.c); aiGomokuTurn(room); return play(null); }
if (a === 'new') { s.g = new Gomoku(); return play(null); }
return;
}
if (room.game === 'junqi') {
if (a === 'act') {
if (msg.kind === 'flip') { s.g.flip(msg.r, msg.c); }
else if (msg.kind === 'move') { s.g.movePiece([msg.fr, msg.fc], [msg.tr, msg.tc]); }
aiJunqiTurn(room);
return play(null);
}
if (a === 'new') { s.g = new JunqiBoard('flip'); return play(null); }
return;
}
if (room.game === 'ludo') {
if (a === 'roll') { s.g.roll(); broadcast(room); ludoAiLoop(room); return; }
if (a === 'move') {
s.g.tryMove(msg.i);
broadcast(room);
ludoAiLoop(room);
// 若随骰而来 extraTurn,玩家再掷
return;
}
if (a === 'pass') { s.g.nextTurn(); broadcast(room); ludoAiLoop(room); return; }
if (a === 'new') { s.g = new LudoGame(s.g.colors, s.g.mode); room.state.seat = {}; return play(null); }
return;
}
}
function aiChessTurn(room) {
const s = room.state;
if (!s.aiSide) return;
if (s.g.redTurn !== (s.aiSide === 'r')) return;
const r = aiMove(s.g, { side: s.aiSide, depth: s.aiDepth || 3 });
if (r && r.move) {
const m = Array.isArray(r) ? r : r.move;
s.g.apply(s.g.legal(m[0], m[1]).find(x => x[2] === m[2] && x[3] === m[3]) || m);
}
}
function aiGomokuTurn(room) {
const s = room.state;
if (s.aiSide == null) return;
if (s.g.over) return;
if (s.g.player !== (s.aiSide === 0 ? 1 : 2)) return;
const p = aiPick(s.g, s.g.player);
s.g.place(p.r, p.c);
}
function aiJunqiTurn(room) {
const s = room.state; if (!s.aiSide) return;
const g = s.g;
const aiOwner = s.aiSide; // 'r'/'b'
if (g.turnOwner() !== aiOwner) return;
// 简单 AI:随机尝试翻子(优先)或移动
const flips = [];
const moves = [];
for (let r = 0; r < g.R; r++) for (let c = 0; c < g.C; c++) {
if (g.cells[r][c] && !g.shown[r][c]) flips.push([r, c]);
else if (g.cells[r][c] && g.cells[r][c].owner === aiOwner) {
[[1,0],[-1,0],[0,1],[0,-1]].forEach(([dr,dc]) => { const tr=r+dr, tc=c+dc; if (g.canMove([r,c],[tr,tc])) moves.push([[r,c],[tr,tc]]); });
}
}
// 检查仍可行动的子(canMove 会转 turn?不,canMove只读)
if (Math.random() < 0.6 && flips.length) { g.flip(...flips[Math.floor(Math.random() * flips.length)]); return; }
if (moves.length) { const pick = moves[Math.floor(Math.random() * moves.length)]; g.movePiece(pick[0], pick[1]); }
}
async function ludoAiLoop(room) {
const g = room.state.g;
let guard = 0;
while (guard++ < 40) {
if (g.winner) break;
const cur = g.cur;
const seat = room.state.seat[cur];
const onlineHuman = seat && seat.online;
if (onlineHuman) break;
const isAi = seat && seat.ai;
if (!isAi) {
// 无人就座的颜色转 AI 自动(保底不卡死)
if (g.dice != null) { const mx = g.movable(); if (!mx.length) g.nextTurn(); }
break;
}
const r = g.aiAct();
if (r && r.voided) { continue; }
broadcast(room);
if (g.dice != null) break; // 该 AI 掷完等待……若 ai 实际 movable,继续
if (r && (r.extraTurn || (r.events && r.events.includes('finish')))) continue;
if (r && r.extraTon) continue;
break;
}
broadcast(room);
}
server.listen(PORT, () => console.log('games-server listening on ' + PORT));
+25
View File
@@ -0,0 +1,25 @@
const { Chess } = require('../app/js/chess.js');
const a = new Chess();
const fen1 = a.toFen();
console.log('初始 FEN:', fen1);
console.log('含 undefined:', fen1.includes('undefined') ? 'FAIL' : 'pass');
const b = new Chess(fen1);
let diff = 0;
for (let r=0;r<10;r++) for (let c=0;c<9;c++){
const x=a.B[r][c], y=b.B[r][c];
if (!x && !y) continue;
if (!x || !y || x.t!==y.t || x.s!==y.s) { diff++; if (diff<4) console.log(' 差异', r, c, JSON.stringify(x), JSON.stringify(y)); }
}
console.log('往返后棋子差异:', diff, diff===0?'pass':'FAIL');
// 带走法往返(保存/恢复场景)
const c2 = new Chess();
const mv = c2.allLegal('r')[0]; c2.apply(mv);
const f2 = c2.full();
const c3 = new Chess(f2);
console.log('带 moves 往返 手数:', c3.moves.length, '| 局面一致:', c3.toFen() === c2.toFen() ? 'pass' : 'FAIL');
console.log('轮到红方:', c3.redTurn, '(走1手后应 false)', c3.redTurn === false ? 'pass' : 'FAIL');
// 残局 FEN 仍可解析
const pz = new Chess('3将4/9/9/9/9/9/4砲4/9/9/4帥4');
let n=0; for (let r=0;r<10;r++) for (let c=0;c<9;c++) if (pz.B[r][c]) n++;
console.log('残局FEN子数:', n, '(期望3)', n===3?'pass':'FAIL');
+11
View File
@@ -0,0 +1,11 @@
const { Chess } = require('../app/js/chess.js');
const a = new Chess();
for (let i=0;i<4;i++){ const side = a.redTurn ? 'r' : 'b'; const ms = a.allLegal(side); a.apply(ms[Math.floor(Math.random()*ms.length)]); }
const f = a.full();
const b = new Chess(f);
console.log('4手后 moves:', b.moves.length, '| redTurn:', b.redTurn, '| 原始 redTurn:', a.redTurn, b.redTurn===a.redTurn?'pass':'FAIL');
console.log('局面一致:', b.toFen()===a.toFen() ? 'pass':'FAIL');
// 黑方(AI)走子能力
const ms = b.allLegal('b');
console.log('黑方合法手数:', ms.length, ms.length>0?'pass':'FAIL');
+17
View File
@@ -0,0 +1,17 @@
const { Chess } = require('../app/js/chess.js');
function round(n){
const a = new Chess();
for (let i=0;i<n;i++){ const side=a.redTurn?'r':'b'; const ms=a.allLegal(side); if(!ms.length) break; a.apply(ms[Math.floor(Math.random()*ms.length)]); }
const b = Chess.fromState(a.toFen(), a.moves, a.redTurn);
let d=0; for(let r=0;r<10;r++)for(let c=0;c<9;c++){const x=a.B[r][c],y=b.B[r][c]; if((x&&!y)||(!x&&y)||(x&&y&&(x.t!==y.t||x.s!==y.s))) d++;}
return {n, d, m: a.moves.length, m2: b.moves.length, t: a.redTurn===b.redTurn, f: a.toFen()===b.toFen()};
}
let allok = true;
for (const n of [1,2,3,5,8]) { const r = round(n); const ok = r.d===0 && r.m===r.m2 && r.t && r.f; if(!ok) allok=false; console.log(n+'手:', JSON.stringify(r), ok?'pass':'FAIL'); }
// 残局恢复
const pz = new Chess('3将4/9/9/9/9/9/4砲4/9/9/4帥4');
const ms = pz.allLegal('r'); pz.apply(ms[0]);
const rc = Chess.fromState(pz.toFen(), pz.moves, pz.redTurn);
console.log('残局恢复 子数:', (function(){let n=0;for(let r=0;r<10;r++)for(let c=0;c<9;c++) if(rc.B[r][c])n++;return n})(), '| moves:', rc.moves.length);
console.log(allok ? '全部通过' : '有失败');
+13
View File
@@ -0,0 +1,13 @@
const { Chess } = require('../app/js/chess.js');
const c2 = new Chess();
const mv = c2.allLegal('r')[0]; c2.apply(mv);
const f2 = c2.full();
const c3 = new Chess(f2);
console.log('move:', JSON.stringify(mv));
console.log('原 FEN :', c2.toFen());
console.log('恢复FEN:', c3.toFen());
console.log('full :', f2);
console.log('恢复 full:', c3.full());
let d=0; for(let r=0;r<10;r++)for(let c=0;c<9;c++){const x=c2.B[r][c],y=c3.B[r][c]; if((x&&!y)||(!x&&y)||(x&&y&&(x.t!==y.t||x.s!==y.s))){d++; if(d<5)console.log(' 差异',r,c,JSON.stringify(x),JSON.stringify(y));}}
console.log('差异数:', d);
+6
View File
@@ -0,0 +1,6 @@
const { Chess } = require('/vol1/1000/HD1/docker/fnos-games/app/js/chess.js');
const g = new Chess();
const kinds = new Set();
for (let r=0;r<10;r++) for (let c=0;c<9;c++) if (g.B[r][c]) kinds.add(g.B[r][c].t);
console.log([...kinds].join(' '));
+57
View File
@@ -0,0 +1,57 @@
const { Chess } = require('../app/js/chess.js');
const { aiMove } = require('../app/js/chessAI.js');
const { Gomoku, aiPick } = require('../app/js/gomoku.js');
const { JunqiBoard } = require('../app/js/junqi.js');
const { LudoGame, PATH_LEN } = require('../app/js/ludo.js');
let fail = 0;
const assert = (c, m) => { if (!c) { fail++; console.log('FAIL', m); } else console.log('ok', m); };
// 象棋
const g = new Chess();
assert(g.allLegal('r').length === 41, '红开局走法=41 (got ' + g.allLegal('r').length + ')');
assert(!g.legal(9,7,'r').some(m => m[2] === 7 && m[3] === 6), '马蹩腿');
// 炮打隔子:炮(7,1)→黑方向(2,1)有黑炮(2,1)作隔子, 隔子后(0,1)黑马应可达
assert(g.legal(7,1,'r').some(m => m[2] === 0 && m[3] === 1), '炮隔(2,1)打(0,1)黑马');
// 马跳
assert(g.legal(9,1,'r').some(m => m[2] === 7 && m[3] === 2), '马跳(7,2)');
// 将军判定: 红車(9,0)→(0,0)吃黑車后 黑将被??? 直接人工局面: 黑将(0,4),红車(0,0) → 黑被将军
const g2 = new Chess(`4将4/9/9/9/9/9/9/9/9/俥3帥4 moves:9,0,0,0`);
assert(g2.inCheck('b') === true, '車(0,0)将军黑');
// 黑方AI走(避将)
const mv = aiMove(g2, { side: 'b', depth: 3 });
if (mv && mv.move) { g2.apply(mv.move); assert(!g2.inCheck('b') || g2.allLegal('b').length===0, 'AI解将'); }
else assert(mv !== null, 'AI黑有解');
// 合法性: 送将走入法会被过滤
const g3 = new Chess('3k5/9/9/4R4/9/9/9/9/9/4K4');
assert(!g3.legal(0,3,'b').some(m=>m[2]===1&&m[3]===3), '黑将不能走进被車控制的(1,3)? 其实車在4,4线上 控制(0..5,4)? 将(0,3)→(1,3)不被打');
// 五子棋: 正规交替落子
const gk = new Gomoku();
gk.place(7,7); // 黑
assert(gk.player === 2, '轮白');
const pw = aiPick(gk, 2); gk.place(pw.r, pw.c); // 白
// 交替落子造成黑两处活三→白须防守得分点在7/8行
const seq = [[7,3],[8,3],[7,4],[8,4],[7,5],[8,5]];
for (const [r,c] of seq) gk.place(r,c);
assert(gk.player === 1, '黑行棋');
const pd = aiPick(gk, 2); // 白(2)防守
// 黑3连(7,3-4-5)两端开阔 → AI 应拦在(7,2)或(7,6)之一(最高分)
assert(pd.r === 7 && (pd.c === 2 || pd.c === 6), '白拦黑活三 (got ' + pd.r + ',' + pd.c + ')');
// 军棋
const j = new JunqiBoard();
let cnt = 0; for (let r = 0; r < 10; r++) for (let c = 0; c < 6; c++) if (j.cells[r][c]) cnt++;
assert(cnt === 50, '军棋50枚');
assert(j.battle('s1','lei') === 'win', '工兵挖雷');
assert(j.battle('zha','s9') === 'both', '炸弹同归');
assert(j.battle('s5','s3') === 'win', '团>连');
// 飞行棋
const l = new LudoGame(['r']);
l.dice = 6;
assert(l.movable().length === 4, '骰6四机可起飞');
l.tryMove(0);
assert(l.players.r.planes[0] === 0, '起飞');
l.dice = PATH_LEN; // 直接到终点
const me = l.movable(); assert(me.includes(0), PATH_LEN + ' 一步到终点可动');
+18
View File
@@ -0,0 +1,18 @@
const http = require('http');
const srv = http.createServer((req, res) => {
let b = ''; req.on('data', d => b += d);
req.on('end', () => {
res.writeHead(200, {'Content-Type':'application/json'});
res.end(JSON.stringify({ choices: [{ message: { content: '建议炮二平五,中路压制。' } }] }));
});
});
srv.listen(7321, '0.0.0.0', async () => {
const payload = JSON.stringify({ baseUrl: 'http://172.17.0.1:7321/v1', apiKey: 'test', model: 'mock', prompt: '象棋开局' });
const rq = http.request({ host: '127.0.0.1', port: 7025, path: '/api/ai-hint', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } }, rs => {
let o = ''; rs.on('data', d => o += d);
rs.on('end', () => { console.log('hint:', o); srv.close(); process.exit(0); });
});
rq.write(payload); rq.end();
});
setTimeout(() => process.exit(1), 12000);
+12
View File
@@ -0,0 +1,12 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard();
let hq = 0, cnt = 0;
const HQ = [[0,1],[0,4],[9,1],[9,4]];
for (let r=0;r<10;r++) for (let c=0;c<6;c++) {
if (j.cells[r][c]) cnt++;
if (HQ.some(([rr,cc])=>rr===r&&cc===c) && j.cells[r][c]) hq++;
}
console.log('总子:', cnt, '(应50) · HQ 被占:', hq, '(应0)');
// 军旗不在 HQ 也没关系 (翻棋随机)。开 winner 察
console.log('开局 winner:', j.winner());
+10
View File
@@ -0,0 +1,10 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard();
const blocked = ['0,1','0,4','9,1','9,4','2,1','2,4','3,2','3,3','4,1','4,4','7,1','7,4','6,2','6,3','5,1','5,4'];
let bad = 0, total = 0;
for (let r=0;r<10;r++) for (let c=0;c<6;c++) {
if (j.cells[r][c]) { total++; if (blocked.includes(r+','+c)) bad++; }
}
console.log('总子:', total, '(应44) · 特殊格被占:', bad, '(应0)');
console.log('winner:', j.winner());
+14
View File
@@ -0,0 +1,14 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard();
const CAMP = ['2,1','2,4','3,2','3,3','4,1','4,4','7,1','7,4','6,2','6,3','5,1','5,4'];
const HQ = ['0,1','0,4','9,1','9,4'];
let campOcc = 0, hqOcc = 0, total = 0;
for (let r=0;r<10;r++) for (let c=0;c<6;c++) {
if (j.cells[r][c]) { total++;
if (CAMP.includes(r+','+c)) campOcc++;
if (HQ.includes(r+','+c)) hqOcc++;
}
}
console.log('总子:', total, '(期望48) · 行营被占:', campOcc, '(期望0) · 大本营被占:', hqOcc, '(允许>0)');
console.log('winner:', j.winner());
+27
View File
@@ -0,0 +1,27 @@
const { JunqiBoard, CAMP_LIST } = require('../app/js/junqi.js');
const j = new JunqiBoard();
for (let r=0;r<12;r++) for (let c=0;c<5;c++){ j.cells[r][c]=null; j.shown[r][c]=false; }
const put=(r,c,kind,owner)=>{ j.cells[r][c]={kind,owner,faceDown:false}; j.shown[r][c]=true; };
j.turn = 0; // 红方行棋
// 行营 (2,1) 为空 → 红子上方的 (3,1)? 用正交/斜向相邻验证
put(1,1,'s5','r');
console.log('进入空行营(2,1) 正交[1,1]→[2,1]:', j.canMove([1,1],[2,1]) ? 'pass' : 'FAIL');
// 从行营走出来
j.cells[2][1] = { kind:'s5', owner:'r', faceDown:false }; j.shown[2][1] = true; j.cells[1][1] = null;
console.log('从行营走出来[2,1]→[3,1]:', j.canMove([2,1],[3,1]) ? 'pass' : 'FAIL');
console.log('从行营斜走出来[2,1]→[3,2]:', j.canMove([2,1],[3,2]) ? 'pass' : 'FAIL');
// 斜向进入行营:(3,2) 是行营(空)→ 从 (2,2) 斜走到 (3,2)
j.cells[2][1] = null; j.shown[2][1] = false;
put(2,2,'s6','r');
console.log('斜向进入空行营[2,2]→[3,2]:', j.canMove([2,2],[3,2]) ? 'pass' : 'FAIL');
// 不可攻击行营内的敌子
put(1,3,'s9','b'); // 蓝子在? 用行营(2,3)
for (let r=0;r<12;r++) for (let c=0;c<5;c++){ if (j.isCamp(r,c)) continue; j.cells[r][c]=null; j.shown[r][c]=false; }
put(2,3,'s9','b'); // 蓝子在行营(2,3)
put(1,3,'s5','r'); // 红子在其上邻
console.log('攻击行营内敌子(应false):', j.canMove([1,3],[2,3]) === false ? 'pass' : 'FAIL');
// 大本营仍不可进入/不可移动
put(11,1,'s7','r');
console.log('大本营内子不可动(应false):', j.canMove([11,1],[10,1]) === false ? 'pass' : 'FAIL');
console.log('行营数:', CAMP_LIST.length);
+4
View File
@@ -0,0 +1,4 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard();
console.log('开局winner:', j.winner());
j.flip(0,0); console.log('翻后turn:', j.turn);
+12
View File
@@ -0,0 +1,12 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard('flip');
// 手工摆明棋:红 s9 在 (9,0), 蓝 jq 在 (0,0)
for (let r=0;r<10;r++) for (let c=0;c<6;c++){ j.cells[r][c]=null; j.shown[r][c]=false; }
j.cells[9][0] = { kind:'s9', owner:'r' }; j.shown[9][0]=true;
j.cells[0][0] = { kind:'jq', owner:'b' }; j.shown[0][0]=true;
j.turn = 0;
console.log('canMove 红9,0→8,0:', j.canMove([9,0],[8,0]));
let steps = 0, pos = 9;
while (pos > 0) { j.movePiece([pos,0],[pos-1,0]); pos--; steps++; }
console.log('走子步数:', steps, '| winner:', j.winner(), '(期望 r)');
+6
View File
@@ -0,0 +1,6 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard();
let flips=0; for (let r=0;r<12;r++) for (let c=0;c<5;c++) if (j.cells[r][c] && !j.shown[r][c]) flips++;
console.log('开局可翻:', flips, '(应50)');
console.log('winner:', j.winner(), '(应 null)');
+26
View File
@@ -0,0 +1,26 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard();
// 清盘自建
for (let r=0;r<12;r++) for (let c=0;c<5;c++){ j.cells[r][c]=null; j.shown[r][c]=false; }
const put=(r,c,kind,owner)=>{ j.cells[r][c]={kind,owner,faceDown:false}; j.shown[r][c]=true; };
j.turn=0;
put(6,1,'s9','r'); put(2,1,'s3','b'); // 蓝子站行营(2,1)
console.log('攻击行营内敌子(应false):', j.canMove([6,1],[2,1]) === false ? 'pass' : 'FAIL');
put(5,1,'s5','r'); put(6,3,'s2','b');
console.log('跨山界 c=1(应false):', j.canMove([5,1],[6,1]) === false ? 'pass' : 'FAIL');
console.log('跨山界 c=0(应true):', j.canMove([5,1],[6,0]) === true || j.canMove([5,1],[6,1]) === false ? 'pass' : 'FAIL');
// 大本营不可移动
put(11,1,'s7','r');
console.log('大本营内子不可移动(应false):', j.canMove([11,1],[10,1]) === false ? 'pass' : 'FAIL');
// 工兵沿铁路直行 (r=6 是铁路行)
for (let r=0;r<12;r++) for (let c=0;c<5;c++){ j.cells[r][c]=null; j.shown[r][c]=false; }
put(6,0,'s1','r');
console.log('工兵沿铁路行直行2格(应true):', j.canMove([6,0],[6,2]) === true ? 'pass' : 'FAIL');
put(6,1,'s5','r');
console.log('路径被阻(应false):', j.canMove([6,0],[6,2]) === false ? 'pass' : 'FAIL');
// 普通子不能远行
for (let r=0;r<12;r++) for (let c=0;c<5;c++){ j.cells[r][c]=null; j.shown[r][c]=false; }
put(6,0,'s5','r');
console.log('普通子直行2格(应false):', j.canMove([6,0],[6,2]) === false ? 'pass' : 'FAIL');
console.log('普通子1步(应true):', j.canMove([6,0],[6,1]) === true ? 'pass' : 'FAIL');
+26
View File
@@ -0,0 +1,26 @@
const { JunqiBoard, CAMP_LIST } = require('../app/js/junqi.js');
const j = new JunqiBoard();
for (let r=0;r<12;r++) for (let c=0;c<5;c++){ j.cells[r][c]=null; j.shown[r][c]=false; }
const put=(r,c,k,o)=>{ j.cells[r][c]={kind:k,owner:o,faceDown:false}; j.shown[r][c]=true; };
j.turn = 0;
put(6,0,'s6','r'); // 红旅长
const into = j.canMove([6,0],[7,1]); // 斜向入营(7,1)
j.movePiece([6,0],[7,1]);
console.log('入营可行:', into);
console.log('营格 shown(应 true):', j.shown[7][1], j.shown[7][1] === true ? 'pass' : 'FAIL');
console.log('营格棋子:', j.cells[7][1] && j.cells[7][1].kind);
console.log('源格 shown(应 false):', j.shown[6][0], j.shown[6][0] === false ? 'pass' : 'FAIL');
j.undoLast();
console.log('悔棋后 营格 shown(应 false):', j.shown[7][1], j.shown[7][1] === false ? 'pass' : 'FAIL');
console.log('悔棋后 源格棋子:', j.cells[6][0] && j.cells[6][0].kind, '| 营格:', j.cells[7][1]);
// 进大本营同样
put(10,1,'s8','r');
j.movePiece([10,1],[11,1]);
console.log('大本营 shown(应 true):', j.shown[11][1], j.shown[11][1] === true ? 'pass' : 'FAIL');
// 吃子后目标格 shown
for (let r=0;r<12;r++) for (let c=0;c<5;c++){ j.cells[r][c]=null; j.shown[r][c]=false; }
j.turn = 0;
put(6,1,'s9','r'); put(6,2,'s3','b');
j.movePiece([6,1],[6,2]);
console.log('吃掉后 目标格 shown(应 true):', j.shown[6][2], j.shown[6][2] === true ? 'pass' : 'FAIL', '| 子:', j.cells[6][2] && j.cells[6][2].kind);
+14
View File
@@ -0,0 +1,14 @@
const { JunqiBoard, CAMP_LIST, HQ_LIST } = require('../app/js/junqi.js');
const j = new JunqiBoard();
let cells=0, camp=0, hq=0;
for (let r=0;r<12;r++) for (let c=0;c<5;c++){ const p=j.cells[r][c]; if(p){cells++; if(j.isCamp(r,c))camp++; if(j.isHQ(r,c))hq++;} }
console.log('棋子总数:', cells, '(期望50) | 行营被占:', camp, '(期望0) | 大本营被占:', hq, '(期望4)');
console.log('行营数:', CAMP_LIST.length, '大本营数:', HQ_LIST.length);
console.log('开局 winner:', j.winner());
console.log('翻手可翻:', j.hasFlip());
// 翻一枚
j.flip(3,3);
console.log('翻后 shown(3,3):', j.shown[3][3], '| turn:', j.turn);
j.undoLast();
console.log('悔棋后 shown(3,3):', j.shown[3][3], '| turn:', j.turn);
+20
View File
@@ -0,0 +1,20 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard();
j.flip(1,1);
const owner1 = j.turn;
j.flip(8,1);
const owner2 = j.turn;
const ok1 = j.undoLast();
console.log('undo 2nd: ok=', ok1, 'turn回=', JSON.stringify(j.turn), '应=', owner2);
console.log('1,1 shown:', j.shown[1][1], '(需true)');
j.undoLast();
console.log('undo 1st后 shown(1,1):', j.shown[1][1], '(需false) turn:', j.turn);
// move+undo
j.flip(2,2); j.flip(7,2);
const c1 = j.cells[2][2], c2 = j.cells[7][2];
j.movePiece([2,2],[2,3]); // 直邻不可能? canMove 横向 1格可以 (无铁路限制) — dr=0? (2,2)→(2,3) 是 dc=1 → dx=1 是横向一步 ✓
const moved = j.cells[2][3];
console.log('moved kind:', moved && moved.kind, '原格空?', !j.cells[2][2]);
j.undoLast();
console.log('undo后 (2,2)=', j.cells[2][2] && j.cells[2][2].kind, ' (2,3)=', j.cells[2][3]);
+14
View File
@@ -0,0 +1,14 @@
const { JunqiBoard } = require('../app/js/junqi.js');
const j = new JunqiBoard();
console.log('before flip (2,2):', j.cells[2][2]);
j.flip(2,2);
console.log('after flip (2,2):', j.cells[2][2]);
j.flip(7,2);
console.log('after flip(7,2) (2,2)=', j.cells[2][2].kind, j.cells[2][2].owner);
// move
const fp = j.cells[2][2];
const ok = j.movePiece([2,2],[2,3]);
console.log('move ok:', ok.ok, '| (2,2)=', j.cells[2][2], '| (2,3)=', j.cells[2][3]);
j.undoLast();
console.log('undo → (2,2)=', j.cells[2][2], '| (2,3)=', j.cells[2][3]);
+8
View File
@@ -0,0 +1,8 @@
const { Chess } = require('../app/js/chess.js');
const g = new Chess();
console.log('黑卒t:', g.B[3][4].t, '· 黑卒(3,4)走法:', g.legal(3,4,'b').length);
console.log('黑方总走法:', g.allLegal('b').length);
const bad = [];
for (let r=0;r<10;r++)for(let c=0;c<9;c++){ const p=g.B[r][c]; if(p && !['将','士','相','马','车','炮','兵'].includes(p.t)) bad.push(p.t); }
console.log('未归一化类型:', bad.length ? bad.join(',') : '无');
+14
View File
@@ -0,0 +1,14 @@
const { Chess } = require('../app/js/chess.js');
const fens = [
'3k5/9/9/5H3/9/9/5C3/9/9/4K4',
'3k5/9/9/9/9/9/4C4/9/9/3CK4',
'3k5/4a4/9/9/9/9/9/4R4/4R4/5K3',
'3k5/4a4/9/9/9/9/9/9/4C4/4K4',
];
for (const f of fens) {
try {
const g = new Chess(f);
console.log('OK 红方走法数:', g.allLegal('r').length);
} catch (e) { console.log('FAIL:', f, e.message); }
}
+16
View File
@@ -0,0 +1,16 @@
const { Chess } = require('../app/js/chess.js');
// 红帥黑将+红炮(4,4)+黑马(4,5)? 用汉字重写:
const fens = [
// 马后炮: 红帥9,4; 黑将0,3; 红马8,4位置? 简化为炮、马摆好杀
'3将4/9/9/9/4傌4/9/4砲4/9/9/4帥4 moves:',
'3将4/9/9/9/9/9/4砲4/9/9/4帥4 moves:',
'3将4/4士4/9/9/9/9/9/4俥4/4俥4/4帥4 moves:',
'3将4/4士4/9/9/9/9/9/9/4砲4/4帥4 moves:',
];
for (const f of fens) {
try {
const g = new Chess(f);
console.log('OK 红方走法:', g.allLegal('r').length);
} catch (e) { console.log('FAIL:', f, e.message); }
}
+14
View File
@@ -0,0 +1,14 @@
const WebSocket = require('ws');
const ws = new WebSocket('ws://127.0.0.1:7099/ws');
ws.on('open', () => {
ws.send(JSON.stringify({a:'create', game:'chess'}));
});
ws.on('message', d => {
const m = JSON.parse(d);
console.log('msg:', m.t, JSON.stringify(m).slice(0,200));
if (m.t === 'created') { ws.send(JSON.stringify({a:'join', id: m.id})); }
if (m.t === 'joined') { console.log('side:', m.d.side); process.exit(0); }
if (m.t === 'err') process.exit(1);
});
setTimeout(()=>{console.log('timeout'); process.exit(1)}, 8000);