This commit is contained in:
Ubuntu
2026-07-03 16:58:28 +08:00
commit 32b43f85bd
6240 changed files with 1987678 additions and 0 deletions
@@ -0,0 +1,45 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# Virtual environments
.venv/
.venv-*/
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
@@ -0,0 +1,314 @@
# A*算法原理及其在中国象棋中的应用
## 一、A*算法基本原理
### 1.1 算法概述
A*(A-Star)算法是一种启发式搜索算法,广泛应用于路径寻找和博弈决策。在中国象棋中,A*算法通过评估当前棋盘状态,搜索最优走法。
核心公式:
```
f(n) = g(n) + h(n)
```
其中:
- **g(n)**:从初始状态到当前状态的代价(已走步数)
- **h(n)**:启发函数,估计从当前状态到目标状态的代价
- **f(n)**:总评估值
### 1.2 中国象棋中的A*实现
本系统采用**Minimax算法 + Alpha-Beta剪枝**作为A*的核心搜索机制:
```
function minimax(棋盘, 深度, alpha, beta, 是否最大化, 当前方, 原始方):
if 深度 == 0:
return 评估棋盘(棋盘, 原始方)
所有走法 = 获取所有合法走法(棋盘, 当前方)
if 是否最大化:
最大评估值 = -∞
for 每个走法 in 所有走法:
新棋盘 = 执行走法(棋盘, 走法)
评估值 = minimax(新棋盘, 深度-1, alpha, beta, false, 对方, 原始方)
最大评估值 = max(最大评估值, 评估值)
alpha = max(alpha, 评估值)
if beta <= alpha: // Alpha-Beta剪枝
break
return 最大评估值
else:
最小评估值 = +∞
for 每个走法 in 所有走法:
新棋盘 = 执行走法(棋盘, 走法)
评估值 = minimax(新棋盘, 深度-1, alpha, beta, true, 对方, 原始方)
最小评估值 = min(最小评估值, 评估值)
beta = min(beta, 评估值)
if beta <= alpha: // Alpha-Beta剪枝
break
return 最小评估值
```
## 二、棋盘评估函数详解
### 2.1 评估函数组成
评估函数是A*算法的核心,决定了AI的棋风。本系统评估函数包含以下维度:
#### 2.1.1 棋子价值(Material Value)
| 棋子 | 价值 |
|------|------|
| 帅/将 | 10000 |
| 车 | 1000 |
| 马 | 450 |
| 炮 | 450 |
| 相/象 | 200 |
| 仕/士 | 200 |
| 兵/卒 | 100 |
计算公式:
```
棋子价值得分 = Σ(己方棋子价值) - Σ(对方棋子价值)
```
#### 2.1.2 位置价值(Position Bonus)
每个棋子在不同位置有不同的价值加成:
**车的位置价值表(示例):**
```
[50, 40, 40, 40, 50, 40, 40, 40, 50] // 第0行(黑方底线)
[40, 30, 30, 30, 40, 30, 30, 30, 40] // 第1行
...
[50, 40, 40, 40, 50, 40, 40, 40, 50] // 第9行(红方底线)
```
- 车在底线和中心线价值更高
- 马在河界附近价值更高(活动空间大)
- 兵/卒过河后价值递增
#### 2.1.3 出子奖励(Development Bonus)
鼓励大子从初始位置出动:
```typescript
function getDevelopmentBonus(棋子, 颜色):
初始位置 = {
"车": [{row: 9, col: 0}, {row: 9, col: 8}], // 红方示例
"马": [{row: 9, col: 1}, {row: 9, col: 7}],
"炮": [{row: 7, col: 1}, {row: 7, col: 7}]
}
if 棋子还在初始位置:
return -30 // 惩罚,鼓励出动
else:
前进程度 = 颜色 == "红" ? (9 - 当前行) : 当前行
return 50 + 前进程度 * 10 // 出动奖励 + 前进奖励
```
#### 2.1.4 攻击奖励(Attack Bonus)
评估棋子对敌方棋子的威胁:
```typescript
function getAttackBonus(棋盘, 己方棋子, 敌方棋子列表):
bonus = 0
for 敌方棋子 in 敌方棋子列表:
if 己方棋子可以攻击到(敌方棋子):
bonus += 敌方棋子价值 * 0.1
return bonus
```
#### 2.1.5 机动性奖励(Mobility Bonus)
```
机动性得分 = (己方合法走法数 - 对方合法走法数) * 10
```
#### 2.1.6 控制中心奖励(Center Control Bonus)
```typescript
function getCenterControlBonus(棋盘, 颜色):
bonus = 0
中心列 = [3, 4, 5]
for 大子 in ["车", "马", "炮"]:
if 大子在中心列:
bonus += 30
if 大子已过河:
bonus += 40
return bonus
```
#### 2.1.7 将军与将死评估
```
将军对方: +800分
被对方将军: -800分
将死对方: +100000分(胜利)
被对方将死: -100000分(失败)
```
### 2.2 完整评估函数
```typescript
function evaluateBoard(棋盘, 己方颜色):
score = 0
己方棋子 = 获取所有存活己方棋子(棋盘)
敌方棋子 = 获取所有存活敌方棋子(棋盘)
// 1. 棋子价值
for 棋子 in 己方棋子:
score += 棋子价值[棋子类型]
score += 位置价值[棋子类型][棋子位置]
score += 出子奖励(棋子, 己方颜色)
score += 攻击奖励(棋盘, 棋子, 敌方棋子)
for 棋子 in 敌方棋子:
score -= 棋子价值[棋子类型]
score -= 位置价值[棋子类型][棋子位置]
// 2. 机动性
score += (己方走法数 - 敌方走法数) * 10
// 3. 控制中心
score += 控制中心奖励(棋盘, 己方颜色)
// 4. 将军/将死
if 将军对方: score += 800
if 被对方将军: score -= 800
if 将死对方: score += 100000
if 被对方将死: score -= 100000
return score
```
## 三、搜索深度与难度设置
### 3.1 难度级别配置
| 难度 | 搜索深度 | 顶层走法限制 | 随机性 | 节点上限 |
|------|----------|--------------|--------|----------|
| 容易 | 2层 | 30个 | 有(±100分) | 50000 |
| 一般 | 2层 | 30个 | 无 | 50000 |
| 困难 | 3层 | 30个 | 无 | 50000 |
### 3.2 性能优化策略
1. **Alpha-Beta剪枝**:跳过不可能影响最终决策的分支
2. **走法排序**:优先评估吃子、将军等强走法
3. **节点限制**:超过50000节点停止搜索
4. **分支限制**:每层最多考虑20个走法
## 四、各种棋局情况下的下棋策略
### 4.1 开局阶段(前10步)
**策略重点**:快速出动大子,控制中心
- **车**:尽快出直车或横车,占据要道
- **马**:跳马到活跃位置(如屏风马、反宫马)
- **炮**:根据布局选择当头炮、过宫炮、士角炮
- **兵/卒**:挺兵活马,控制河界
**评估侧重**:
- 出子奖励权重增加
- 控制中心奖励权重增加
- 避免重复走同一棋子
### 4.2 中局阶段
**策略重点**:积极进攻,寻找战术机会
**情况1:己方优势**
- 积极兑换子力,简化局面
- 寻找将军、抽将机会
- 推进过河兵/卒
**情况2:己方劣势**
- 防守反击,寻找对方漏洞
- 避免大子被牵制
- 兑子减轻压力
**情况3:均势**
- 争夺中心控制权
- 寻找突破口
- 保持子力协调
**评估侧重**:
- 攻击奖励权重增加
- 机动性评估重要
- 注意防守己方弱点
### 4.3 残局阶段
**策略重点**:精准计算,把握胜机
**情况1:多子优势**
- 车类残局:控制要道,逐步压缩对方空间
- 马炮残局:利用灵活性和控制力
- 兵类残局:推进兵卒,制造威胁
**情况2:少子劣势**
- 防守求和
- 寻找长将、长捉等和棋手段
- 利用对方失误
**评估侧重**:
- 精确计算将杀
- 兵卒位置价值大幅提升
- 王/帅安全优先
### 4.4 特殊战术情况
#### 4.4.1 将军应对
```
检测到被将军时:
1. 优先寻找应将走法
2. 评估应将后的局面
3. 避免应将后陷入更差局面
```
#### 4.4.2 吃子决策
```
考虑吃子时:
1. 计算吃子后的子力平衡
2. 评估是否被反吃
3. 考虑吃子后的位置变化
4. 优先吃价值高的子
```
#### 4.4.3 兑子决策
```
考虑兑子时:
1. 评估兑子后的子力对比
2. 考虑兑子后的局面特点
3. 优势方倾向于兑子简化
4. 劣势方避免兑子保持复杂
```
## 五、算法局限性
### 5.1 已知局限
1. **计算深度限制**:3层深度无法看到复杂战术组合
2. **评估函数局限**:静态评估无法完全反映动态局面
3. **开局库缺失**:缺乏专业开局知识
4. **残局库缺失**:复杂残局可能无法找到最优解
### 5.2 改进方向
1. 增加开局库和残局库
2. 引入神经网络评估
3. 使用迭代加深搜索
4. 实现多线程并行搜索
## 六、代码实现关键文件
- `app/lib/astarAI.ts`:A*算法核心实现
- `app/lib/chessRules.ts`:象棋规则引擎
- `app/hooks/useChessGame.ts`:游戏状态管理
@@ -0,0 +1,433 @@
# Deepseek API 中国象棋接口文档
## 一、接口概述
### 1.1 API基本信息
| 项目 | 内容 |
|------|------|
| API端点 | `https://api.deepseek.com/v1/chat/completions` |
| 请求方法 | POST |
| 认证方式 | Bearer Token |
| 模型 | `deepseek-chat` |
### 1.2 认证方式
```http
Authorization: Bearer {YOUR_API_KEY}
Content-Type: application/json
```
## 二、棋局数据格式
### 2.1 棋盘表示格式(FEN-like)
采用类FEN(Forsyth-Edwards Notation)格式表示棋盘状态:
```
第0行/第1行/第2行/.../第9行
```
**棋盘坐标说明:**
- 行号:0-9,0为黑方底线,9为红方底线
- 列号:0-8,0为左侧,8为右侧
**棋子编码:**
| 棋子 | 红方(大写) | 黑方(小写) |
|------|-------------|-------------|
| 帅/将 | K | k |
| 仕/士 | A | a |
| 相/象 | B | b |
| 马 | N | n |
| 车 | R | r |
| 炮 | C | c |
| 兵/卒 | P | p |
| 空位 | . | . |
**示例棋盘状态:**
```
rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR
```
对应棋盘:
```
第0行: r n b a k a b n r (黑方底线)
第1行: . . . . . . . . .
第2行: . c . . . . . c .
第3行: p . p . p . p . p
第4行: . . . . . . . . .
第5行: . . . . . . . . .
第6行: P . P . P . P . P
第7行: . C . . . . . C .
第8行: . . . . . . . . .
第9行: R N B A K A B N R (红方底线)
```
### 2.2 完整请求数据结构
```typescript
interface DeepseekRequest {
model: string; // "deepseek-chat"
messages: Message[];
temperature: number; // 0.0-1.0,难度相关
max_tokens: number; // 最大返回token数
}
interface Message {
role: "system" | "user";
content: string;
}
```
## 三、提示语(Prompt)详细说明
### 3.1 系统提示语(System Prompt)
#### 3.1.1 基础系统提示语模板
```
你是一个中国象棋AI助手。当前你是{颜色}方。
棋盘表示规则:
- 每行用"/"分隔,共10行
- 每行9个格子,空位用"."表示
- 棋子表示:K=帅 k=将 A=仕 a=士 B=相 b=象 N=马 n=马 R=车 r=车 C=炮 c=炮 P=兵 p=卒
- 红方用大写字母,黑方用小写字母
坐标规则:
- 行号:0-9,0是黑方底线,9是红方底线
- 列号:0-8,0是左侧,8是右侧
你必须以以下JSON格式回复你的走法:
{
"from": {"row": 起始行号(0-9), "col": 起始列号(0-8)},
"to": {"row": 目标行号(0-9), "col": 目标列号(0-8)},
"reason": "简要说明你的走法思路(20字以内)"
}
注意:
1. 只能移动己方棋子
2. 必须遵守中国象棋规则
3. 考虑进攻和防守的平衡
```
#### 3.1.2 不同难度的系统提示语
**容易难度:**
```
{基础系统提示语}
你是初级水平的棋手。请遵循以下策略:
1. 优先选择简单的进攻或防守走法
2. 避免复杂的战术组合
3. 优先考虑吃子和将军机会
4. 保持棋子安全,避免被吃
5. 适当出动大子(车、马、炮)
温度参数:0.8(允许一定随机性)
```
**一般难度:**
```
{基础系统提示语}
你是中级水平的棋手。请遵循以下策略:
1. 选择合理的战术走法
2. 注意保护重要棋子(车、马、炮)
3. 寻找吃子机会,但避免冒进
4. 保持子力协调,避免孤子
5. 控制中心区域(第3-5列)
6. 考虑2-3步后的局面变化
温度参数:0.5(适度确定性)
```
**困难难度:**
```
{基础系统提示语}
你是高级水平的棋手。请遵循以下策略:
1. 选择最优的战术走法,追求局面优势
2. 进行深度计算,考虑3-4步后的变化
3. 积极进攻,同时注意防守
4. 利用战术组合(抽将、牵制、双将等)
5. 控制中心,争夺主动权
6. 优先考虑将死对方的将/帅
7. 在优势时简化局面,劣势时制造复杂
温度参数:0.2(高度确定性)
```
### 3.2 用户提示语(User Prompt)
```
当前棋盘状态({颜色}方走):
{棋盘FEN字符串}
最近走棋记录:
{历史走法列表}
当前局面分析:
- 己方棋子:{列表}
- 对方棋子:{列表}
- 将军状态:{是否被将军}
请给出你的走法。
```
**完整示例:**
```
当前棋盘状态(红方走):
rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR
最近走棋记录:
1. 炮二平五
2. 马8进7
3. 马二进三
当前局面分析:
- 己方(红方)棋子:帅、仕、相、马、车、炮、兵各若干
- 对方(黑方)棋子:将、士、象、马、车、炮、卒各若干
- 将军状态:未被将军
请给出你的走法。
```
## 四、Deepseek反馈格式
### 4.1 标准响应格式
```json
{
"from": {
"row": 7,
"col": 1
},
"to": {
"row": 7,
"col": 4
},
"reason": "当头炮威胁对方中路"
}
```
### 4.2 响应字段说明
| 字段 | 类型 | 说明 |
|------|------|------|
| from.row | number | 起始位置行号 (0-9) |
| from.col | number | 起始位置列号 (0-8) |
| to.row | number | 目标位置行号 (0-9) |
| to.col | number | 目标位置列号 (0-8) |
| reason | string | 走法思路说明 |
### 4.3 走法验证
收到Deepseek响应后,系统会验证走法的合法性:
```typescript
function validateMove(棋盘, from, to, 当前方颜色):
1. 检查from位置是否有己方棋子
2. 检查to位置是否在棋盘范围内
3. 检查是否符合该棋子的走法规则
4. 检查移动后是否会被将军
5. 返回验证结果:{valid: boolean, reason?: string}
```
**验证失败处理:**
- 如果Deepseek返回的走法不合法,系统会记录警告
- 自动回退到本地A* AI进行走棋
- 保证游戏能够继续进行
## 五、Deepseek下棋策略
### 5.1 开局策略(前10步)
**红方常见开局:**
1. **当头炮(炮二平五)**
- 意图:快速威胁对方中路
- 后续:可配合车、马进攻
2. **仙人指路(兵三进一)**
- 意图:活通马路,控制河界
- 后续:灵活多变
3. **飞相局(相三进五)**
- 意图:稳健防守,伺机反击
- 后续:巩固阵地后出动大子
**黑方应对策略:**
1. **屏风马(马8进7、马2进3)**
- 应对当头炮的经典防守
- 左右均衡,可刚可柔
2. **反宫马(马2进3、炮8平6)**
- 灵活多变,可转多种布局
- 注意保护中路
3. **顺手炮(炮8平5)**
- 对攻激烈,双方互有机会
- 需要精确计算
### 5.2 中局策略
#### 5.2.1 进攻策略
**1. 中路突破**
```
条件:中路兵卒已打开,炮或车可配合
走法:炮/车占中路,配合其他子力进攻
目标:威胁对方将/帅
```
**2. 侧翼进攻**
```
条件:一侧子力占优,对方防守薄弱
走法:车、马、炮配合,从侧翼渗透
目标:制造杀势或得子
```
**3. 牵制战术**
```
条件:对方某子位置尴尬,移动会导致损失
走法:用炮或车牵制对方大子
目标:限制对方子力活动,谋取利益
```
#### 5.2.2 防守策略
**1. 应将方法**
```
优先级:
1. 吃掉攻击子(如果可能)
2. 垫将(用其他子挡住)
3. 避将(将/帅移动)
选择标准:
- 应将后的局面最优
- 避免应将后被连续攻击
```
**2. 兑子解围**
```
场景:己方处于被动,子力被牵制
策略:寻找兑子机会,简化局面
注意:劣势时避免兑子,优势时积极兑子
```
### 5.3 残局策略
#### 5.3.1 必胜残局
**单车胜单士:**
```
策略:
1. 车占中路或肋道
2. 逼对方将/帅到边路
3. 帅/将助攻,形成杀势
```
**单马胜单士:**
```
策略:
1. 马控制要点,限制对方将/帅
2. 帅/将占据中路
3. 逐步缩小对方活动空间
```
#### 5.3.2 和棋残局
**单马对单象:**
```
判断:通常和棋
策略:象方注意象不要被马捉死
```
**单车对单士象:**
```
判断:通常和棋
策略:士象方注意防守位置,不要让车各个击破
```
### 5.4 特殊战术
#### 5.4.1 抽将
```
定义:移动一个子,同时将军并威胁对方其他子
示例:车将军,同时捉对方马
应对:优先应将,必要时弃子
```
#### 5.4.2 牵制
```
定义:用炮或车盯住对方重要子力,使其无法移动
示例:炮牵制对方车马
应对:寻找解脱方法,或用其他子力支援
```
#### 5.4.3 双将
```
定义:两个子同时将军
应对:必须用将/帅移动应将,无法垫将或吃子
```
## 六、错误处理与降级机制
### 6.1 API错误处理
| 错误类型 | 处理方式 |
|----------|----------|
| API超时 | 回退到A* AI |
| 返回格式错误 | 解析JSON失败,回退到A* AI |
| 走法不合法 | 记录日志,回退到A* AI |
| 网络错误 | 重试1次,仍失败则回退到A* AI |
### 6.2 降级机制流程
```
调用Deepseek API
↓
成功?
↓ 否
解析响应
↓
成功?
↓ 否
验证走法
↓
合法?
↓ 否
使用本地A* AI
```
## 七、代码实现关键文件
- `app/lib/deepseekAPI.ts`:Deepseek API接口实现
- `app/lib/astarAI.ts`:A* AI(降级备用)
- `app/hooks/useChessGame.ts`:游戏状态管理
## 八、配置说明
### 8.1 API密钥配置
在 `app/lib/deepseekAPI.ts` 中配置:
```typescript
const DEEPSEEK_API_KEY = "your-api-key-here";
```
### 8.2 难度配置
| 难度 | temperature | 提示语特点 |
|------|-------------|-----------|
| 容易 | 0.8 | 简单策略,允许随机性 |
| 一般 | 0.5 | 平衡策略,适度计算 |
| 困难 | 0.2 | 深度策略,精确计算 |
+36
View File
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
@@ -0,0 +1,285 @@
"use client";
import { useRef, useEffect } from "react";
import { Piece, Position } from "../types/chess";
import ChessPiece from "./ChessPiece";
interface ChessBoardProps {
pieces: Piece[];
selectedPieceId?: string;
validMoves: Position[];
lastMove?: { from: Position; to: Position };
onPieceClick: (piece: Piece) => void;
onEmptyClick: (pos: Position) => void;
}
// 棋盘配置
const GRID_SIZE = 55; // 格子大小
const PADDING = 40; // 边距
const BOARD_WIDTH = GRID_SIZE * 8 + PADDING * 2;
const BOARD_HEIGHT = GRID_SIZE * 9 + PADDING * 2;
export default function ChessBoard({
pieces,
selectedPieceId,
validMoves,
lastMove,
onPieceClick,
onEmptyClick,
}: ChessBoardProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
// 绘制棋盘网格
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制背景
ctx.fillStyle = "#fff9e6";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 设置线条样式
ctx.strokeStyle = "#666666";
ctx.lineWidth = 1.2;
// 绘制横线
for (let r = 0; r < 10; r++) {
ctx.beginPath();
ctx.moveTo(PADDING, PADDING + r * GRID_SIZE);
ctx.lineTo(PADDING + 8 * GRID_SIZE, PADDING + r * GRID_SIZE);
ctx.stroke();
}
// 绘制竖线(上半部分)
for (let c = 0; c < 9; c++) {
ctx.beginPath();
ctx.moveTo(PADDING + c * GRID_SIZE, PADDING);
ctx.lineTo(PADDING + c * GRID_SIZE, PADDING + 4 * GRID_SIZE);
ctx.stroke();
}
// 绘制竖线(下半部分)
for (let c = 0; c < 9; c++) {
ctx.beginPath();
ctx.moveTo(PADDING + c * GRID_SIZE, PADDING + 5 * GRID_SIZE);
ctx.lineTo(PADDING + c * GRID_SIZE, PADDING + 9 * GRID_SIZE);
ctx.stroke();
}
// 绘制九宫格斜线(黑方)
ctx.beginPath();
ctx.moveTo(PADDING + 3 * GRID_SIZE, PADDING);
ctx.lineTo(PADDING + 5 * GRID_SIZE, PADDING + 2 * GRID_SIZE);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(PADDING + 5 * GRID_SIZE, PADDING);
ctx.lineTo(PADDING + 3 * GRID_SIZE, PADDING + 2 * GRID_SIZE);
ctx.stroke();
// 绘制九宫格斜线(红方)
ctx.beginPath();
ctx.moveTo(PADDING + 3 * GRID_SIZE, PADDING + 7 * GRID_SIZE);
ctx.lineTo(PADDING + 5 * GRID_SIZE, PADDING + 9 * GRID_SIZE);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(PADDING + 5 * GRID_SIZE, PADDING + 7 * GRID_SIZE);
ctx.lineTo(PADDING + 3 * GRID_SIZE, PADDING + 9 * GRID_SIZE);
ctx.stroke();
// 绘制炮位和兵位标记
drawPositionMarkers(ctx);
// 绘制楚河汉界
ctx.font = "bold 28px serif";
ctx.fillStyle = "#8b7355";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("楚 河", PADDING + 2 * GRID_SIZE, PADDING + 4.5 * GRID_SIZE);
ctx.fillText("汉 界", PADDING + 6 * GRID_SIZE, PADDING + 4.5 * GRID_SIZE);
// 绘制上一步移动标记
if (lastMove) {
drawMoveMarker(ctx, lastMove.from, "#4a90d9");
drawMoveMarker(ctx, lastMove.to, "#4a90d9");
}
// 绘制可移动位置标记
for (const move of validMoves) {
drawValidMoveMarker(ctx, move);
}
}, [validMoves, lastMove]);
// 绘制位置标记(炮位和兵位)
const drawPositionMarkers = (ctx: CanvasRenderingContext2D) => {
ctx.strokeStyle = "#666666";
ctx.lineWidth = 1;
const markerSize = 6;
const positions = [
// 黑方炮位
{ row: 2, col: 1, left: true, right: true, top: false, bottom: true },
{ row: 2, col: 7, left: true, right: true, top: false, bottom: true },
// 黑方兵位
{ row: 3, col: 0, left: false, right: true, top: true, bottom: true },
{ row: 3, col: 2, left: true, right: true, top: true, bottom: true },
{ row: 3, col: 4, left: true, right: true, top: true, bottom: true },
{ row: 3, col: 6, left: true, right: true, top: true, bottom: true },
{ row: 3, col: 8, left: true, right: false, top: true, bottom: true },
// 红方兵位
{ row: 6, col: 0, left: false, right: true, top: true, bottom: true },
{ row: 6, col: 2, left: true, right: true, top: true, bottom: true },
{ row: 6, col: 4, left: true, right: true, top: true, bottom: true },
{ row: 6, col: 6, left: true, right: true, top: true, bottom: true },
{ row: 6, col: 8, left: true, right: false, top: true, bottom: true },
// 红方炮位
{ row: 7, col: 1, left: true, right: true, top: true, bottom: false },
{ row: 7, col: 7, left: true, right: true, top: true, bottom: false },
];
for (const pos of positions) {
const x = PADDING + pos.col * GRID_SIZE;
const y = PADDING + pos.row * GRID_SIZE;
ctx.beginPath();
if (pos.left) {
ctx.moveTo(x - markerSize, y - markerSize / 2);
ctx.lineTo(x - markerSize / 2, y - markerSize / 2);
ctx.lineTo(x - markerSize / 2, y - markerSize);
ctx.moveTo(x - markerSize, y + markerSize / 2);
ctx.lineTo(x - markerSize / 2, y + markerSize / 2);
ctx.lineTo(x - markerSize / 2, y + markerSize);
}
if (pos.right) {
ctx.moveTo(x + markerSize, y - markerSize / 2);
ctx.lineTo(x + markerSize / 2, y - markerSize / 2);
ctx.lineTo(x + markerSize / 2, y - markerSize);
ctx.moveTo(x + markerSize, y + markerSize / 2);
ctx.lineTo(x + markerSize / 2, y + markerSize / 2);
ctx.lineTo(x + markerSize / 2, y + markerSize);
}
ctx.stroke();
}
};
// 绘制移动标记
const drawMoveMarker = (
ctx: CanvasRenderingContext2D,
pos: Position,
color: string
) => {
const x = PADDING + pos.col * GRID_SIZE;
const y = PADDING + pos.row * GRID_SIZE;
const size = 8;
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.stroke();
};
// 绘制可移动位置标记
const drawValidMoveMarker = (ctx: CanvasRenderingContext2D, pos: Position) => {
const x = PADDING + pos.col * GRID_SIZE;
const y = PADDING + pos.row * GRID_SIZE;
ctx.fillStyle = "rgba(0, 150, 0, 0.4)";
ctx.beginPath();
ctx.arc(x, y, 6, 0, Math.PI * 2);
ctx.fill();
};
// 处理点击事件
const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
const rect = e.currentTarget.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const col = Math.round((x - PADDING) / GRID_SIZE);
const row = Math.round((y - PADDING) / GRID_SIZE);
if (col < 0 || col > 8 || row < 0 || row > 9) return;
const clickedPiece = pieces.find(
(p) => p.alive && p.position.row === row && p.position.col === col
);
if (clickedPiece) {
onPieceClick(clickedPiece);
} else {
onEmptyClick({ row, col });
}
};
return (
<div
style={{
position: "relative",
width: `${BOARD_WIDTH}px`,
height: `${BOARD_HEIGHT}px`,
backgroundColor: "#fff9e6",
borderRadius: "8px",
boxShadow: "0 4px 12px rgba(0,0,0,0.15), inset 0 1px 0 rgba(255,255,255,0.5)",
border: "2px solid #d4c4a8",
overflow: "hidden",
}}
>
{/* 棋盘画布 */}
<canvas
ref={canvasRef}
width={BOARD_WIDTH}
height={BOARD_HEIGHT}
style={{
position: "absolute",
top: 0,
left: 0,
pointerEvents: "none",
}}
/>
{/* 棋子层 */}
<div
onClick={handleClick}
style={{
position: "absolute",
top: 0,
left: 0,
width: `${BOARD_WIDTH}px`,
height: `${BOARD_HEIGHT}px`,
cursor: "pointer",
}}
>
{pieces
.filter((p) => p.alive)
.map((piece) => (
<div
key={piece.id}
style={{
position: "absolute",
left: `${PADDING + piece.position.col * GRID_SIZE - 22}px`,
top: `${PADDING + piece.position.row * GRID_SIZE - 22}px`,
}}
>
<ChessPiece
piece={piece}
isSelected={piece.id === selectedPieceId}
onClick={() => onPieceClick(piece)}
size={44}
/>
</div>
))}
</div>
</div>
);
}
export { GRID_SIZE, PADDING, BOARD_WIDTH, BOARD_HEIGHT };
@@ -0,0 +1,124 @@
"use client";
import { Piece } from "../types/chess";
interface ChessPieceProps {
piece: Piece;
isSelected?: boolean;
isValidMove?: boolean;
size?: number;
onClick?: () => void;
}
export default function ChessPiece({
piece,
isSelected = false,
isValidMove = false,
size = 44,
onClick,
}: ChessPieceProps) {
const isRed = piece.color === "red";
// 棋子颜色样式
const pieceColors = isRed
? {
text: "#d80000",
border: "#d80000",
innerShadow: "rgba(216, 0, 0, 0.15)",
}
: {
text: "#111111",
border: "#333333",
innerShadow: "rgba(0, 0, 0, 0.1)",
};
return (
<div
onClick={onClick}
style={{
width: `${size}px`,
height: `${size}px`,
borderRadius: "50%",
background: `linear-gradient(145deg, #ffffff 0%, #f0f0f0 50%, #e0e0e0 100%)`,
boxShadow: isSelected
? `0 0 0 3px #ffc800,
inset 0 2px 4px rgba(255,255,255,0.9),
inset 0 -2px 4px rgba(0,0,0,0.1),
0 4px 8px rgba(0,0,0,0.3),
0 6px 12px rgba(0,0,0,0.2)`
: `inset 0 2px 4px rgba(255,255,255,0.9),
inset 0 -2px 4px rgba(0,0,0,0.1),
0 3px 6px rgba(0,0,0,0.3),
0 4px 8px rgba(0,0,0,0.2)`,
border: `2px solid ${pieceColors.border}`,
display: "flex",
alignItems: "center",
justifyContent: "center",
cursor: onClick ? "pointer" : "default",
transition: "all 0.2s ease",
transform: isSelected ? "scale(1.1)" : "scale(1)",
position: "relative",
zIndex: isSelected ? 10 : 1,
}}
className="chess-piece"
>
{/* 内圈装饰 */}
<div
style={{
position: "absolute",
width: `${size * 0.75}px`,
height: `${size * 0.75}px`,
borderRadius: "50%",
border: `1px solid ${pieceColors.border}`,
opacity: 0.4,
}}
/>
{/* 棋子文字 */}
<span
style={{
fontSize: `${size * 0.55}px`,
fontWeight: "bold",
color: pieceColors.text,
fontFamily: '"SimSun", "STSong", "Songti SC", serif',
textShadow: "0 1px 2px rgba(255,255,255,0.8)",
userSelect: "none",
position: "relative",
zIndex: 2,
}}
>
{piece.type}
</span>
{/* 高光效果 */}
<div
style={{
position: "absolute",
top: "15%",
left: "20%",
width: "25%",
height: "15%",
borderRadius: "50%",
background: "linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(255,255,255,0) 100%)",
pointerEvents: "none",
}}
/>
{/* 可移动位置提示 */}
{isValidMove && !isSelected && (
<div
style={{
position: "absolute",
width: "12px",
height: "12px",
borderRadius: "50%",
backgroundColor: "rgba(0, 150, 0, 0.5)",
bottom: "-6px",
right: "-6px",
border: "2px solid white",
}}
/>
)}
</div>
);
}
@@ -0,0 +1,208 @@
"use client";
import { GameMode, Difficulty } from "../types/chess";
interface GameControlsProps {
mode: GameMode;
difficulty: Difficulty;
onModeChange: (mode: GameMode) => void;
onDifficultyChange: (difficulty: Difficulty) => void;
onNewGame: () => void;
onUndo: () => void;
onSurrender: () => void;
canUndo: boolean;
isPlaying: boolean;
}
export default function GameControls({
mode,
difficulty,
onModeChange,
onDifficultyChange,
onNewGame,
onUndo,
onSurrender,
canUndo,
isPlaying,
}: GameControlsProps) {
const modes: GameMode[] = ["人vsA*", "人vsDeepseek", "A*vsDeepseek"];
const difficulties: Difficulty[] = ["容易", "一般", "困难"];
return (
<div
style={{
display: "flex",
flexDirection: "column",
gap: "10px",
padding: "12px 16px",
backgroundColor: "#ffffff",
borderRadius: "8px",
boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
}}
>
{/* 模式和难度选择 - 标签和下拉框同一行 */}
<div
style={{
display: "flex",
gap: "16px",
flexWrap: "wrap",
justifyContent: "center",
alignItems: "center",
}}
>
<div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
<label
style={{
fontSize: "13px",
color: "#666",
fontWeight: 500,
whiteSpace: "nowrap",
}}
>
对弈模式
</label>
<select
value={mode}
onChange={(e) => onModeChange(e.target.value as GameMode)}
style={{
padding: "6px 10px",
borderRadius: "6px",
border: "1px solid #ddd",
backgroundColor: "#f9f9f9",
fontSize: "13px",
cursor: "pointer",
minWidth: "120px",
}}
>
{modes.map((m) => (
<option key={m} value={m}>
{m}
</option>
))}
</select>
</div>
<div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
<label
style={{
fontSize: "13px",
color: "#666",
fontWeight: 500,
whiteSpace: "nowrap",
}}
>
AI难度
</label>
<select
value={difficulty}
onChange={(e) => onDifficultyChange(e.target.value as Difficulty)}
style={{
padding: "6px 10px",
borderRadius: "6px",
border: "1px solid #ddd",
backgroundColor: "#f9f9f9",
fontSize: "13px",
cursor: "pointer",
minWidth: "80px",
}}
>
{difficulties.map((d) => (
<option key={d} value={d}>
{d}
</option>
))}
</select>
</div>
</div>
{/* 操作按钮 */}
<div
style={{
display: "flex",
gap: "8px",
justifyContent: "center",
flexWrap: "wrap",
}}
>
<button
onClick={onNewGame}
style={{
padding: "8px 16px",
borderRadius: "6px",
border: "none",
backgroundColor: "#2563eb",
color: "white",
fontSize: "13px",
fontWeight: 500,
cursor: "pointer",
transition: "background-color 0.2s",
}}
onMouseEnter={(e) =>
(e.currentTarget.style.backgroundColor = "#1d4ed8")
}
onMouseLeave={(e) =>
(e.currentTarget.style.backgroundColor = "#2563eb")
}
>
新局
</button>
<button
onClick={onUndo}
disabled={!canUndo || !isPlaying}
style={{
padding: "8px 16px",
borderRadius: "6px",
border: "none",
backgroundColor: canUndo && isPlaying ? "#6b7280" : "#d1d5db",
color: "white",
fontSize: "13px",
fontWeight: 500,
cursor: canUndo && isPlaying ? "pointer" : "not-allowed",
transition: "background-color 0.2s",
}}
onMouseEnter={(e) => {
if (canUndo && isPlaying) {
e.currentTarget.style.backgroundColor = "#4b5563";
}
}}
onMouseLeave={(e) => {
if (canUndo && isPlaying) {
e.currentTarget.style.backgroundColor = "#6b7280";
}
}}
>
悔棋
</button>
<button
onClick={onSurrender}
disabled={!isPlaying}
style={{
padding: "8px 16px",
borderRadius: "6px",
border: "none",
backgroundColor: isPlaying ? "#dc2626" : "#d1d5db",
color: "white",
fontSize: "13px",
fontWeight: 500,
cursor: isPlaying ? "pointer" : "not-allowed",
transition: "background-color 0.2s",
}}
onMouseEnter={(e) => {
if (isPlaying) {
e.currentTarget.style.backgroundColor = "#b91c1c";
}
}}
onMouseLeave={(e) => {
if (isPlaying) {
e.currentTarget.style.backgroundColor = "#dc2626";
}
}}
>
认输
</button>
</div>
</div>
);
}
@@ -0,0 +1,206 @@
"use client";
import { Color, GameStatus as GameStatusType, Move } from "../types/chess";
interface GameStatusProps {
status: GameStatusType;
turn: Color;
winner?: Color;
moveHistory: Move[];
onCloseModal?: () => void;
}
export default function GameStatus({
status,
turn,
winner,
moveHistory,
onCloseModal,
}: GameStatusProps) {
const getStatusMessage = () => {
switch (status) {
case "playing":
return `${turn === "red" ? "红方" : "黑方"}走棋`;
case "check":
return `${turn === "red" ? "红方" : "黑方"}被将军!`;
case "checkmate":
return `${winner === "red" ? "红方" : "黑方"}获胜!`;
case "stalemate":
case "draw":
return "和棋";
default:
return "";
}
};
const getStatusColor = () => {
switch (status) {
case "playing":
return "#2563eb";
case "check":
return "#dc2626";
case "checkmate":
return "#16a34a";
case "stalemate":
case "draw":
return "#6b7280";
default:
return "#2563eb";
}
};
// 只显示最近10步
const recentMoves = moveHistory.slice(-10);
return (
<>
{/* 状态显示 */}
<div
style={{
padding: "12px 24px",
backgroundColor: "#ffffff",
borderRadius: "8px",
boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
textAlign: "center",
}}
>
<div
style={{
fontSize: "18px",
fontWeight: "bold",
color: getStatusColor(),
}}
>
{getStatusMessage()}
</div>
{status === "check" && (
<div style={{ fontSize: "14px", color: "#dc2626", marginTop: "4px" }}>
请应将!
</div>
)}
</div>
{/* 走棋记录 */}
<div
style={{
padding: "12px",
backgroundColor: "#ffffff",
borderRadius: "8px",
boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
maxHeight: "150px",
overflowY: "auto",
}}
>
<div
style={{
fontSize: "14px",
fontWeight: "bold",
color: "#333",
marginBottom: "8px",
borderBottom: "1px solid #eee",
paddingBottom: "4px",
}}
>
走棋记录
</div>
{moveHistory.length === 0 ? (
<div style={{ fontSize: "12px", color: "#999", textAlign: "center" }}>
暂无走棋记录
</div>
) : (
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(2, 1fr)",
gap: "4px",
fontSize: "12px",
}}
>
{recentMoves.map((move, index) => {
const moveNumber = Math.floor((moveHistory.length - recentMoves.length + index) / 2) + 1;
const isRedMove = (moveHistory.length - recentMoves.length + index) % 2 === 0;
return (
<div
key={index}
style={{
color: isRedMove ? "#d80000" : "#111111",
fontWeight: index === recentMoves.length - 1 ? "bold" : "normal",
}}
>
{isRedMove ? `${moveNumber}. ` : ""}
{move.notation}
</div>
);
})}
</div>
)}
</div>
{/* 游戏结束弹窗 */}
{(status === "checkmate" || status === "stalemate" || status === "draw") && (
<div
style={{
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(0,0,0,0.5)",
display: "flex",
alignItems: "center",
justifyContent: "center",
zIndex: 100,
}}
onClick={onCloseModal}
>
<div
style={{
backgroundColor: "#ffffff",
padding: "32px 48px",
borderRadius: "16px",
boxShadow: "0 8px 32px rgba(0,0,0,0.3)",
textAlign: "center",
animation: "modalAppear 0.3s ease",
WebkitAnimation: "modalAppear 0.3s ease",
}}
onClick={(e) => e.stopPropagation()}
>
<div
style={{
fontSize: "32px",
fontWeight: "bold",
color: status === "checkmate" ? "#16a34a" : "#6b7280",
marginBottom: "16px",
}}
>
{status === "checkmate"
? `${winner === "red" ? "红方" : "黑方"}获胜!`
: "和棋"}
</div>
<div style={{ fontSize: "16px", color: "#666", marginBottom: "24px" }}>
{status === "checkmate"
? "恭喜取得胜利!"
: "双方势均力敌,不分胜负"}
</div>
<button
onClick={onCloseModal}
style={{
padding: "12px 32px",
borderRadius: "8px",
border: "none",
backgroundColor: "#2563eb",
color: "white",
fontSize: "16px",
fontWeight: "500",
cursor: "pointer",
}}
>
确定
</button>
</div>
</div>
)}
</>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@@ -0,0 +1,57 @@
@import "tailwindcss";
:root {
--background: #f3f4f6;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
}
body {
background: var(--background);
color: var(--foreground);
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* 自定义滚动条样式 */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 3px;
}
::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
/* 选中文字样式 */
::selection {
background-color: rgba(37, 99, 235, 0.2);
color: inherit;
}
/* 弹窗动画 */
@keyframes modalAppear {
from {
opacity: 0;
transform: scale(0.9);
}
to {
opacity: 1;
transform: scale(1);
}
}
@@ -0,0 +1,338 @@
"use client";
import { useState, useCallback, useEffect, useRef } from "react";
import {
Piece,
Position,
Color,
GameMode,
Difficulty,
GameStatus,
Move,
INITIAL_PIECES,
} from "../types/chess";
import {
getValidMoves,
isValidMove,
makeMove,
isInCheck,
isCheckmate,
isStalemate,
getPieceAt,
} from "../lib/chessRules";
import { findBestMove } from "../lib/astarAI";
import { getDeepseekMove } from "../lib/deepseekAPI";
// 生成唯一ID
let pieceIdCounter = 0;
const generatePieceId = () => `piece-${++pieceIdCounter}`;
// 初始化棋子
const initializePieces = (): Piece[] => {
return INITIAL_PIECES.map((p) => ({
...p,
id: generatePieceId(),
}));
};
export function useChessGame() {
// 游戏状态
const [pieces, setPieces] = useState<Piece[]>(initializePieces());
const [turn, setTurn] = useState<Color>("red");
const [status, setStatus] = useState<GameStatus>("playing");
const [gameStarted, setGameStarted] = useState<boolean>(false);
const [winner, setWinner] = useState<Color | undefined>(undefined);
const [selectedPieceId, setSelectedPieceId] = useState<string | undefined>(
undefined
);
const [validMoves, setValidMoves] = useState<Position[]>([]);
const [moveHistory, setMoveHistory] = useState<Move[]>([]);
const [gameMode, setGameMode] = useState<GameMode>("人vsA*");
const [difficulty, setDifficulty] = useState<Difficulty>("一般");
const [lastMove, setLastMove] = useState<{ from: Position; to: Position } | undefined>(undefined);
const [isAIThinking, setIsAIThinking] = useState(false);
// 用于保存历史状态以支持悔棋
const historyRef = useRef<
{ pieces: Piece[]; turn: Color; status: GameStatus; moveHistory: Move[] }[]
>([]);
// 获取选中的棋子
const selectedPiece = selectedPieceId
? pieces.find((p) => p.id === selectedPieceId)
: undefined;
// 更新游戏状态(将军/将死/困毙检测)
const updateGameStatus = useCallback(
(currentPieces: Piece[], currentTurn: Color) => {
const nextTurn = currentTurn === "red" ? "black" : "red";
if (isCheckmate(currentPieces, nextTurn)) {
setStatus("checkmate");
setWinner(currentTurn);
return "checkmate";
} else if (isStalemate(currentPieces, nextTurn)) {
setStatus("stalemate");
return "stalemate";
} else if (isInCheck(currentPieces, nextTurn)) {
setStatus("check");
return "check";
} else {
setStatus("playing");
return "playing";
}
},
[]
);
// 保存当前状态到历史
const saveToHistory = useCallback(() => {
historyRef.current.push({
pieces: JSON.parse(JSON.stringify(pieces)),
turn,
status,
moveHistory: [...moveHistory],
});
// 只保留最近20步历史
if (historyRef.current.length > 20) {
historyRef.current.shift();
}
}, [pieces, turn, status, moveHistory]);
// 处理棋子点击
const handlePieceClick = useCallback(
(piece: Piece) => {
if (!gameStarted) return;
if (status !== "playing" && status !== "check") return;
if (isAIThinking) return;
// 如果点击的是己方棋子,选中它
if (piece.color === turn) {
setSelectedPieceId(piece.id);
setValidMoves(getValidMoves(pieces, piece));
return;
}
// 如果点击的是对方棋子且已选中己方棋子,尝试吃子
if (selectedPiece && selectedPiece.color === turn) {
const validation = isValidMove(
pieces,
selectedPiece.position,
piece.position,
turn
);
if (validation.valid) {
saveToHistory();
const { pieces: newPieces, move } = makeMove(
pieces,
selectedPiece.position,
piece.position
);
setPieces(newPieces);
setMoveHistory((prev) => [...prev, move]);
setLastMove({ from: selectedPiece.position, to: piece.position });
setSelectedPieceId(undefined);
setValidMoves([]);
const newStatus = updateGameStatus(newPieces, turn);
if (newStatus === "playing" || newStatus === "check") {
setTurn(turn === "red" ? "black" : "red");
}
}
}
},
[pieces, turn, selectedPiece, status, isAIThinking, saveToHistory, updateGameStatus]
);
// 处理空白位置点击
const handleEmptyClick = useCallback(
(pos: Position) => {
if (!gameStarted) return;
if (status !== "playing" && status !== "check") return;
if (isAIThinking) return;
if (!selectedPiece) return;
const validation = isValidMove(
pieces,
selectedPiece.position,
pos,
turn
);
if (validation.valid) {
saveToHistory();
const { pieces: newPieces, move } = makeMove(
pieces,
selectedPiece.position,
pos
);
setPieces(newPieces);
setMoveHistory((prev) => [...prev, move]);
setLastMove({ from: selectedPiece.position, to: pos });
setSelectedPieceId(undefined);
setValidMoves([]);
const newStatus = updateGameStatus(newPieces, turn);
if (newStatus === "playing" || newStatus === "check") {
setTurn(turn === "red" ? "black" : "red");
}
}
},
[pieces, turn, selectedPiece, status, isAIThinking, saveToHistory, updateGameStatus]
);
// AI走棋
const makeAIMove = useCallback(async () => {
if (status !== "playing" && status !== "check") return;
setIsAIThinking(true);
try {
let aiMove = null;
// 根据游戏模式决定使用哪个AI
const isAStarTurn =
(gameMode === "人vsA*" && turn === "black") ||
(gameMode === "A*vsDeepseek" && turn === "red");
const isDeepseekTurn =
(gameMode === "人vsDeepseek" && turn === "black") ||
(gameMode === "A*vsDeepseek" && turn === "black");
if (isAStarTurn) {
// 使用A* AI
console.log(`A* AI思考中... 当前回合: ${turn}, 难度: ${difficulty}`);
aiMove = findBestMove(pieces, turn, difficulty);
console.log(`A* AI走法:`, aiMove);
} else if (isDeepseekTurn) {
// 使用Deepseek API
const moveHistoryStr = moveHistory.map((m) => m.notation);
aiMove = await getDeepseekMove(pieces, turn, difficulty, moveHistoryStr);
}
if (aiMove) {
saveToHistory();
const { pieces: newPieces, move } = makeMove(
pieces,
aiMove.from,
aiMove.to
);
setPieces(newPieces);
setMoveHistory((prev) => [...prev, move]);
setLastMove({ from: aiMove.from, to: aiMove.to });
const newStatus = updateGameStatus(newPieces, turn);
if (newStatus === "playing" || newStatus === "check") {
setTurn(turn === "red" ? "black" : "red");
}
}
} finally {
setIsAIThinking(false);
}
}, [pieces, turn, status, gameMode, difficulty, moveHistory, saveToHistory, updateGameStatus]);
// AI自动走棋效果
useEffect(() => {
// 游戏未开始时,AI不走棋
if (!gameStarted) return;
const isAITurn =
(gameMode === "人vsA*" && turn === "black") ||
(gameMode === "人vsDeepseek" && turn === "black") ||
gameMode === "A*vsDeepseek";
if (isAITurn && (status === "playing" || status === "check")) {
const timer = setTimeout(() => {
makeAIMove();
}, 500);
return () => clearTimeout(timer);
}
}, [turn, status, gameMode, gameStarted, makeAIMove]);
// 开始新游戏
const newGame = useCallback(() => {
setPieces(initializePieces());
setTurn("red");
setStatus("playing");
setWinner(undefined);
setSelectedPieceId(undefined);
setValidMoves([]);
setMoveHistory([]);
setLastMove(undefined);
setGameStarted(true);
historyRef.current = [];
pieceIdCounter = 0;
}, []);
// 开始棋局(从准备状态进入游戏)
const startGame = useCallback(() => {
console.log("[Chess] Starting game...");
setGameStarted(true);
}, []);
// 悔棋
const undo = useCallback(() => {
if (historyRef.current.length === 0) return;
const lastState = historyRef.current.pop();
if (lastState) {
setPieces(lastState.pieces);
setTurn(lastState.turn);
setStatus(lastState.status);
setMoveHistory(lastState.moveHistory);
setSelectedPieceId(undefined);
setValidMoves([]);
}
}, []);
// 认输
const surrender = useCallback(() => {
setStatus("checkmate");
setWinner(turn === "red" ? "black" : "red");
}, [turn]);
// 关闭弹窗
const closeModal = useCallback(() => {
// 弹窗关闭不做特殊处理,用户可以点击新局开始新游戏
}, []);
// 获取当前玩家类型
const getCurrentPlayerType = useCallback(() => {
if (gameMode === "A*vsDeepseek") {
return turn === "red" ? "A* AI" : "Deepseek AI";
}
if (turn === "red") return "玩家";
return gameMode === "人vsA*" ? "A* AI" : "Deepseek AI";
}, [turn, gameMode]);
return {
// 状态
pieces,
turn,
status,
winner,
selectedPieceId,
validMoves,
moveHistory,
gameMode,
difficulty,
lastMove,
isAIThinking,
gameStarted,
// 派生状态
selectedPiece,
canUndo: historyRef.current.length > 0,
isPlaying: status === "playing" || status === "check",
currentPlayerType: getCurrentPlayerType(),
// 操作
handlePieceClick,
handleEmptyClick,
newGame,
undo,
surrender,
closeModal,
setGameMode,
setDifficulty,
startGame,
};
}
@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "中国象棋 - 人机对弈",
description: "使用Next.js + TypeScript + Tailwind CSS开发的中国象棋人机对弈游戏",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN">
<body style={{ margin: 0, padding: 0, fontFamily: 'system-ui, -apple-system, sans-serif' }}>
{children}
</body>
</html>
);
}
@@ -0,0 +1,435 @@
import { Piece, Position, Color, Difficulty, AIMove, PIECE_VALUES } from "../types/chess";
import { getAllPossibleMoves, makeMove, isInCheck, isCheckmate, getPieceAt } from "./chessRules";
// 位置价值表(鼓励棋子占据有利位置)
const POSITION_BONUS: Record<string, number[][]> = {
// 帅/将 - 待在九宫格中心
"帅": [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 10, 20, 10, 0, 0, 0],
[0, 0, 0, 20, 30, 20, 0, 0, 0],
[0, 0, 0, 10, 20, 10, 0, 0, 0],
],
"将": [
[0, 0, 0, 10, 20, 10, 0, 0, 0],
[0, 0, 0, 20, 30, 20, 0, 0, 0],
[0, 0, 0, 10, 20, 10, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
],
// 车 - 控制中路和横线
"车": [
[50, 40, 40, 40, 50, 40, 40, 40, 50],
[40, 30, 30, 30, 40, 30, 30, 30, 40],
[40, 30, 30, 30, 40, 30, 30, 30, 40],
[40, 30, 30, 30, 40, 30, 30, 30, 40],
[40, 30, 30, 30, 40, 30, 30, 30, 40],
[40, 30, 30, 30, 40, 30, 30, 30, 40],
[40, 30, 30, 30, 40, 30, 30, 30, 40],
[40, 30, 30, 30, 40, 30, 30, 30, 40],
[40, 30, 30, 30, 40, 30, 30, 30, 40],
[50, 40, 40, 40, 50, 40, 40, 40, 50],
],
// 马 - 活跃位置
"马": [
[20, 30, 40, 30, 20, 30, 40, 30, 20],
[30, 40, 50, 40, 30, 40, 50, 40, 30],
[30, 50, 60, 50, 40, 50, 60, 50, 30],
[30, 40, 50, 40, 30, 40, 50, 40, 30],
[20, 30, 40, 30, 20, 30, 40, 30, 20],
[20, 30, 40, 30, 20, 30, 40, 30, 20],
[30, 40, 50, 40, 30, 40, 50, 40, 30],
[30, 50, 60, 50, 40, 50, 60, 50, 30],
[30, 40, 50, 40, 30, 40, 50, 40, 30],
[20, 30, 40, 30, 20, 30, 40, 30, 20],
],
// 炮 - 需要好的位置
"炮": [
[30, 30, 30, 30, 35, 30, 30, 30, 30],
[30, 40, 40, 40, 45, 40, 40, 40, 30],
[30, 40, 50, 50, 50, 50, 50, 40, 30],
[30, 40, 50, 50, 50, 50, 50, 40, 30],
[35, 45, 50, 50, 50, 50, 50, 45, 35],
[35, 45, 50, 50, 50, 50, 50, 45, 35],
[30, 40, 50, 50, 50, 50, 50, 40, 30],
[30, 40, 50, 50, 50, 50, 50, 40, 30],
[30, 40, 40, 40, 45, 40, 40, 40, 30],
[30, 30, 30, 30, 35, 30, 30, 30, 30],
],
// 相/象 - 防守位置
"相": [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 20, 0, 0, 0, 20, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[20, 0, 0, 0, 30, 0, 0, 0, 20],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 20, 0, 0, 0, 20, 0, 0],
],
"象": [
[0, 0, 20, 0, 0, 0, 20, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[20, 0, 0, 0, 30, 0, 0, 0, 20],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 20, 0, 0, 0, 20, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
],
// 仕/士 - 九宫格内
"仕": [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 20, 0, 20, 0, 0, 0],
[0, 0, 0, 0, 30, 0, 0, 0, 0],
[0, 0, 0, 20, 0, 20, 0, 0, 0],
],
"士": [
[0, 0, 0, 20, 0, 20, 0, 0, 0],
[0, 0, 0, 0, 30, 0, 0, 0, 0],
[0, 0, 0, 20, 0, 20, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
],
// 兵/卒 - 过河后价值增加
"兵": [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[40, 0, 40, 0, 40, 0, 40, 0, 40],
[50, 0, 50, 0, 50, 0, 50, 0, 50],
[60, 0, 60, 0, 60, 0, 60, 0, 60],
[70, 0, 70, 0, 70, 0, 70, 0, 70],
[80, 0, 80, 0, 80, 0, 80, 0, 80],
[90, 0, 90, 0, 90, 0, 90, 0, 90],
[100, 0, 100, 0, 100, 0, 100, 0, 100],
],
"卒": [
[100, 0, 100, 0, 100, 0, 100, 0, 100],
[90, 0, 90, 0, 90, 0, 90, 0, 90],
[80, 0, 80, 0, 80, 0, 80, 0, 80],
[70, 0, 70, 0, 70, 0, 70, 0, 70],
[60, 0, 60, 0, 60, 0, 60, 0, 60],
[50, 0, 50, 0, 50, 0, 50, 0, 50],
[40, 0, 40, 0, 40, 0, 40, 0, 40],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
],
};
// 评估棋盘局面
function evaluateBoard(pieces: Piece[], color: Color): number {
let score = 0;
const myPieces = pieces.filter((p) => p.alive && p.color === color);
const enemyPieces = pieces.filter((p) => p.alive && p.color !== color);
const enemyColor = color === "red" ? "black" : "red";
// 计算己方棋子价值
for (const piece of myPieces) {
const pieceValue = PIECE_VALUES[piece.type];
const positionBonus = POSITION_BONUS[piece.type]?.[piece.position.row]?.[piece.position.col] || 0;
score += pieceValue + positionBonus;
// 出子奖励 - 鼓励大子出动到有利位置
score += getDevelopmentBonus(piece, color);
// 攻击奖励 - 棋子能攻击到对方棋子
score += getAttackBonus(pieces, piece, enemyPieces);
}
// 减去对方棋子价值
for (const piece of enemyPieces) {
const pieceValue = PIECE_VALUES[piece.type];
const positionBonus = POSITION_BONUS[piece.type]?.[piece.position.row]?.[piece.position.col] || 0;
score -= pieceValue + positionBonus;
}
// 机动性奖励 - 己方棋子总移动数
const myMobility = getAllPossibleMoves(pieces, color).length;
const enemyMobility = getAllPossibleMoves(pieces, enemyColor).length;
score += (myMobility - enemyMobility) * 10;
// 将军奖励
if (isInCheck(pieces, enemyColor)) {
score += 800;
}
if (isInCheck(pieces, color)) {
score -= 800;
}
// 将死奖励/惩罚
if (isCheckmate(pieces, enemyColor)) {
score += 100000;
}
if (isCheckmate(pieces, color)) {
score -= 100000;
}
// 控制中心奖励
score += getCenterControlBonus(pieces, color);
return score;
}
// 出子奖励 - 鼓励大子从初始位置出动
function getDevelopmentBonus(piece: Piece, color: Color): number {
const initialPositions: Record<string, Position[]> = {
"车": color === "red"
? [{row: 9, col: 0}, {row: 9, col: 8}]
: [{row: 0, col: 0}, {row: 0, col: 8}],
"马": color === "red"
? [{row: 9, col: 1}, {row: 9, col: 7}]
: [{row: 0, col: 1}, {row: 0, col: 7}],
"炮": color === "red"
? [{row: 7, col: 1}, {row: 7, col: 7}]
: [{row: 2, col: 1}, {row: 2, col: 7}],
};
const type = piece.type as keyof typeof initialPositions;
if (!initialPositions[type]) return 0;
const isAtInitial = initialPositions[type].some(
pos => pos.row === piece.position.row && pos.col === piece.position.col
);
// 如果还在初始位置,惩罚;如果已经出动,奖励
if (isAtInitial) {
return -30; // 还在原位,减分鼓励出动
} else {
// 根据前进程度给予奖励
const progress = color === "red"
? 9 - piece.position.row // 红方:行号越小越靠前
: piece.position.row; // 黑方:行号越大越靠前
return 50 + progress * 10; // 出动奖励 + 前进奖励
}
}
// 攻击奖励 - 棋子能攻击到对方棋子
function getAttackBonus(pieces: Piece[], piece: Piece, enemyPieces: Piece[]): number {
let bonus = 0;
const enemyColor = piece.color === "red" ? "black" : "red";
// 检查这个棋子能攻击到哪些敌方棋子
for (const enemy of enemyPieces) {
// 简化检查:如果敌方棋子在这个棋子的攻击范围内
const rowDiff = Math.abs(piece.position.row - enemy.position.row);
const colDiff = Math.abs(piece.position.col - enemy.position.col);
// 根据棋子类型判断攻击可能性
switch (piece.type) {
case "车":
// 车在同一条线上就有威胁
if (piece.position.row === enemy.position.row || piece.position.col === enemy.position.col) {
bonus += PIECE_VALUES[enemy.type] * 0.1; // 潜在吃子威胁
}
break;
case "马":
// 马走日
if ((rowDiff === 2 && colDiff === 1) || (rowDiff === 1 && colDiff === 2)) {
bonus += PIECE_VALUES[enemy.type] * 0.1;
}
break;
case "炮":
// 炮在同一条线上
if (piece.position.row === enemy.position.row || piece.position.col === enemy.position.col) {
bonus += PIECE_VALUES[enemy.type] * 0.08;
}
break;
}
}
return bonus;
}
// 控制中心奖励
function getCenterControlBonus(pieces: Piece[], color: Color): number {
let bonus = 0;
const centerCols = [3, 4, 5]; // 中心列
const centerRows = color === "red" ? [5, 6, 7] : [2, 3, 4]; // 对方半场中心
const myPieces = pieces.filter(p => p.alive && p.color === color);
for (const piece of myPieces) {
// 大子(车、马、炮)在中心区域给予奖励
if (["车", "马", "炮"].includes(piece.type)) {
if (centerCols.includes(piece.position.col)) {
bonus += 30;
}
// 过河进入对方半场给予额外奖励
const crossedRiver = color === "red" ? piece.position.row <= 4 : piece.position.row >= 5;
if (crossedRiver) {
bonus += 40;
}
}
}
return bonus;
}
// 节点计数器,用于限制搜索规模
let nodeCount = 0;
const MAX_NODES = 50000; // 最大搜索节点数
// Minimax算法带Alpha-Beta剪枝
function minimax(
pieces: Piece[],
depth: number,
alpha: number,
beta: number,
isMaximizing: boolean,
color: Color,
originalColor: Color
): number {
nodeCount++;
// 超过最大节点数,直接返回评估值
if (nodeCount > MAX_NODES) {
return evaluateBoard(pieces, originalColor);
}
if (depth === 0) {
return evaluateBoard(pieces, originalColor);
}
const currentColor = isMaximizing ? originalColor : originalColor === "red" ? "black" : "red";
const moves = getAllPossibleMoves(pieces, currentColor);
if (moves.length === 0) {
if (isInCheck(pieces, currentColor)) {
return isMaximizing ? -100000 : 100000;
}
return 0; // 和棋
}
// 限制分支因子,只考虑前20个最佳走法
const limitedMoves = moves.slice(0, 20);
if (isMaximizing) {
let maxEval = -Infinity;
for (const { piece, to } of limitedMoves) {
const { pieces: newPieces } = makeMove(pieces, piece.position, to);
const eval_ = minimax(newPieces, depth - 1, alpha, beta, false, color, originalColor);
maxEval = Math.max(maxEval, eval_);
alpha = Math.max(alpha, eval_);
if (beta <= alpha) break;
}
return maxEval;
} else {
let minEval = Infinity;
for (const { piece, to } of limitedMoves) {
const { pieces: newPieces } = makeMove(pieces, piece.position, to);
const eval_ = minimax(newPieces, depth - 1, alpha, beta, true, color, originalColor);
minEval = Math.min(minEval, eval_);
beta = Math.min(beta, eval_);
if (beta <= alpha) break;
}
return minEval;
}
}
// 获取难度对应的搜索深度
function getDepthByDifficulty(difficulty: Difficulty): number {
switch (difficulty) {
case "容易":
return 2;
case "一般":
return 2;
case "困难":
return 3;
default:
return 2;
}
}
// A* AI主函数
export function findBestMove(
pieces: Piece[],
color: Color,
difficulty: Difficulty
): AIMove | null {
// 重置节点计数器
nodeCount = 0;
const depth = getDepthByDifficulty(difficulty);
const moves = getAllPossibleMoves(pieces, color);
// 如果没有可行走法,返回null
if (moves.length === 0) return null;
// 限制顶层搜索的走法数量,提高性能
const topMoves = moves.slice(0, 30);
let bestMove: AIMove | null = null;
let bestScore = -Infinity;
// 对于容易难度,添加一些随机性
const addRandomness = difficulty === "容易";
for (const { piece, to } of topMoves) {
const { pieces: newPieces } = makeMove(pieces, piece.position, to);
const score = minimax(
newPieces,
depth - 1,
-Infinity,
Infinity,
false,
color,
color
);
let finalScore = score;
if (addRandomness) {
// 容易难度:添加随机扰动
finalScore += (Math.random() - 0.5) * 200;
}
if (finalScore > bestScore) {
bestScore = finalScore;
bestMove = {
from: piece.position,
to,
score: finalScore,
};
}
}
return bestMove;
}
// 快速评估移动(用于提示)
export function evaluateMove(
pieces: Piece[],
from: Position,
to: Position,
color: Color
): number {
const { pieces: newPieces } = makeMove(pieces, from, to);
return evaluateBoard(newPieces, color);
}
@@ -0,0 +1,360 @@
import { Piece, Position, Color, PieceType, Move, PALACE, RIVER_ROWS } from "../types/chess";
// 获取棋盘上的棋子
export function getPieceAt(pieces: Piece[], pos: Position): Piece | undefined {
return pieces.find((p) => p.alive && p.position.row === pos.row && p.position.col === pos.col);
}
// 检查位置是否在棋盘内
export function isInBoard(pos: Position): boolean {
return pos.row >= 0 && pos.row <= 9 && pos.col >= 0 && pos.col <= 8;
}
// 检查位置是否在九宫格内
export function isInPalace(pos: Position, color: Color): boolean {
const palace = PALACE[color];
return (
pos.row >= palace.minRow &&
pos.row <= palace.maxRow &&
pos.col >= palace.minCol &&
pos.col <= palace.maxCol
);
}
// 检查是否过河
export function hasCrossedRiver(pos: Position, color: Color): boolean {
if (color === "red") {
return pos.row <= 4; // 红方向上过河
} else {
return pos.row >= 5; // 黑方向下过河
}
}
// 计算两个位置之间的棋子数(用于车和炮)
export function countPiecesBetween(pieces: Piece[], from: Position, to: Position): number {
if (from.row !== to.row && from.col !== to.col) return -1; // 不在同一直线
let count = 0;
if (from.row === to.row) {
// 横向
const minCol = Math.min(from.col, to.col);
const maxCol = Math.max(from.col, to.col);
for (let col = minCol + 1; col < maxCol; col++) {
if (getPieceAt(pieces, { row: from.row, col })) count++;
}
} else {
// 纵向
const minRow = Math.min(from.row, to.row);
const maxRow = Math.max(from.row, to.row);
for (let row = minRow + 1; row < maxRow; row++) {
if (getPieceAt(pieces, { row, col: from.col })) count++;
}
}
return count;
}
// 检查马腿是否被挡住
export function isHorseBlocked(pieces: Piece[], from: Position, to: Position): boolean {
const rowDiff = to.row - from.row;
const colDiff = to.col - from.col;
// 马走日:必须是一个方向2格,另一个方向1格
if (Math.abs(rowDiff) === 2 && Math.abs(colDiff) === 1) {
// 纵向移动2格,检查中间点
const blockPos: Position = { row: from.row + rowDiff / 2, col: from.col };
return !!getPieceAt(pieces, blockPos);
} else if (Math.abs(rowDiff) === 1 && Math.abs(colDiff) === 2) {
// 横向移动2格,检查中间点
const blockPos: Position = { row: from.row, col: from.col + colDiff / 2 };
return !!getPieceAt(pieces, blockPos);
}
return true; // 不是日字走法,视为被挡住
}
// 检查象眼是否被挡住
export function isElephantBlocked(pieces: Piece[], from: Position, to: Position): boolean {
const blockPos: Position = {
row: (from.row + to.row) / 2,
col: (from.col + to.col) / 2,
};
return !!getPieceAt(pieces, blockPos);
}
// 验证特定棋子的走法
export function isValidPieceMove(
pieces: Piece[],
piece: Piece,
to: Position
): boolean {
const from = piece.position;
const targetPiece = getPieceAt(pieces, to);
// 不能吃自己的棋子
if (targetPiece && targetPiece.color === piece.color) return false;
const rowDiff = to.row - from.row;
const colDiff = to.col - from.col;
const absRowDiff = Math.abs(rowDiff);
const absColDiff = Math.abs(colDiff);
switch (piece.type) {
case "帅":
case "将":
// 只能在九宫格内移动
if (!isInPalace(to, piece.color)) {
// 特殊情况:将帅对面(飞将)
if (colDiff === 0) {
const target = getPieceAt(pieces, to);
if (target && (target.type === "帅" || target.type === "将")) {
return countPiecesBetween(pieces, from, to) === 0;
}
}
return false;
}
// 只能横竖走一格
return (absRowDiff === 1 && absColDiff === 0) || (absRowDiff === 0 && absColDiff === 1);
case "仕":
case "士":
// 只能在九宫格内移动
if (!isInPalace(to, piece.color)) return false;
// 只能斜走一格
return absRowDiff === 1 && absColDiff === 1;
case "相":
case "象":
// 不能过河
if (hasCrossedRiver(to, piece.color)) return false;
// 必须斜走2格
if (absRowDiff !== 2 || absColDiff !== 2) return false;
// 不能被象眼挡住
return !isElephantBlocked(pieces, from, to);
case "马":
// 必须走日字
if (!((absRowDiff === 2 && absColDiff === 1) || (absRowDiff === 1 && absColDiff === 2))) {
return false;
}
// 不能被马腿挡住
return !isHorseBlocked(pieces, from, to);
case "车":
// 必须横竖走
if (from.row !== to.row && from.col !== to.col) return false;
// 路径上不能有其他棋子
return countPiecesBetween(pieces, from, to) === 0;
case "炮":
// 必须横竖走
if (from.row !== to.row && from.col !== to.col) return false;
const piecesBetween = countPiecesBetween(pieces, from, to);
if (targetPiece) {
// 吃子:中间必须有且仅有1个棋子
return piecesBetween === 1;
} else {
// 移动:中间不能有棋子
return piecesBetween === 0;
}
case "兵":
case "卒":
// 只能向前走一格(不能后退)
const forwardDir = piece.color === "red" ? -1 : 1;
if (!hasCrossedRiver(from, piece.color)) {
// 未过河:只能向前走
return rowDiff === forwardDir && colDiff === 0;
} else {
// 已过河:可以向前或向左右
return (
(rowDiff === forwardDir && colDiff === 0) || // 向前
(rowDiff === 0 && absColDiff === 1) // 左右
);
}
default:
return false;
}
}
// 检查移动后是否会被将军
export function isInCheckAfterMove(
pieces: Piece[],
from: Position,
to: Position,
color: Color
): boolean {
// 模拟移动
const newPieces = pieces.map((p) => {
if (p.position.row === from.row && p.position.col === from.col) {
return { ...p, position: to };
}
// 移除被吃的棋子
if (p.position.row === to.row && p.position.col === to.col) {
return { ...p, alive: false };
}
return p;
});
return isInCheck(newPieces, color);
}
// 检查某方是否被将军
export function isInCheck(pieces: Piece[], color: Color): boolean {
// 找到己方的帅/将
const king = pieces.find(
(p) => p.alive && p.color === color && (p.type === "帅" || p.type === "将")
);
if (!king) return false;
// 检查对方任何棋子是否能攻击到帅/将
const enemyColor = color === "red" ? "black" : "red";
const enemyPieces = pieces.filter((p) => p.alive && p.color === enemyColor);
for (const enemy of enemyPieces) {
if (isValidPieceMove(pieces, enemy, king.position)) {
return true;
}
}
return false;
}
// 获取某棋子的所有合法移动
export function getValidMoves(pieces: Piece[], piece: Piece): Position[] {
const validMoves: Position[] = [];
for (let row = 0; row <= 9; row++) {
for (let col = 0; col <= 8; col++) {
const to = { row, col };
if (
isValidPieceMove(pieces, piece, to) &&
!isInCheckAfterMove(pieces, piece.position, to, piece.color)
) {
validMoves.push(to);
}
}
}
return validMoves;
}
// 检查某方是否有任何合法移动
export function hasAnyValidMove(pieces: Piece[], color: Color): boolean {
const colorPieces = pieces.filter((p) => p.alive && p.color === color);
for (const piece of colorPieces) {
if (getValidMoves(pieces, piece).length > 0) {
return true;
}
}
return false;
}
// 检查是否将死
export function isCheckmate(pieces: Piece[], color: Color): boolean {
return isInCheck(pieces, color) && !hasAnyValidMove(pieces, color);
}
// 检查是否困毙(无子可动但不是将军)
export function isStalemate(pieces: Piece[], color: Color): boolean {
return !isInCheck(pieces, color) && !hasAnyValidMove(pieces, color);
}
// 验证移动是否合法
export function isValidMove(
pieces: Piece[],
from: Position,
to: Position,
turn: Color
): { valid: boolean; reason?: string } {
const piece = getPieceAt(pieces, from);
if (!piece) return { valid: false, reason: "没有棋子" };
if (piece.color !== turn) return { valid: false, reason: "不是己方棋子" };
if (!isInBoard(to)) return { valid: false, reason: "超出棋盘" };
const targetPiece = getPieceAt(pieces, to);
if (targetPiece && targetPiece.color === piece.color) {
return { valid: false, reason: "不能吃己方棋子" };
}
if (!isValidPieceMove(pieces, piece, to)) {
return { valid: false, reason: "不符合走法规则" };
}
if (isInCheckAfterMove(pieces, from, to, turn)) {
return { valid: false, reason: "移动后会被将军" };
}
return { valid: true };
}
// 执行移动
export function makeMove(
pieces: Piece[],
from: Position,
to: Position
): { pieces: Piece[]; move: Move; capturedPiece?: Piece } {
const piece = getPieceAt(pieces, from)!;
const targetPiece = getPieceAt(pieces, to);
const newPieces = pieces.map((p) => {
if (p.id === piece.id) {
return { ...p, position: to };
}
if (targetPiece && p.id === targetPiece.id) {
return { ...p, alive: false };
}
return p;
});
// 生成走棋记录
const notation = generateNotation(piece, from, to, targetPiece);
const move: Move = {
from,
to,
piece,
capturedPiece: targetPiece,
notation,
};
return { pieces: newPieces, move, capturedPiece: targetPiece };
}
// 生成走棋记录(中文记谱法)
function generateNotation(
piece: Piece,
from: Position,
to: Position,
captured?: Piece
): string {
const colNames = ["一", "二", "三", "四", "五", "六", "七", "八", "九"];
const colNamesBlack = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
const fromCol = piece.color === "red" ? colNames[8 - from.col] : colNamesBlack[from.col];
const toCol = piece.color === "red" ? colNames[8 - to.col] : colNamesBlack[to.col];
const direction = piece.color === "red"
? (from.row > to.row ? "进" : from.row < to.row ? "退" : "平")
: (from.row < to.row ? "进" : from.row > to.row ? "退" : "平");
const steps = Math.abs(to.row - from.row);
const stepStr = steps > 0 ? (piece.color === "red" ? colNames[steps - 1] : String(steps)) : "";
return `${piece.type}${fromCol}${direction}${stepStr || toCol}`;
}
// 获取所有可能的移动(用于AI)
export function getAllPossibleMoves(pieces: Piece[], color: Color): { piece: Piece; to: Position }[] {
const moves: { piece: Piece; to: Position }[] = [];
const colorPieces = pieces.filter((p) => p.alive && p.color === color);
for (const piece of colorPieces) {
const validMoves = getValidMoves(pieces, piece);
for (const to of validMoves) {
moves.push({ piece, to });
}
}
return moves;
}
@@ -0,0 +1,198 @@
import { Piece, Position, Color, Difficulty, AIMove } from "../types/chess";
import { getPieceAt, isValidMove } from "./chessRules";
import { findBestMove } from "./astarAI";
// Deepseek API配置 - 请在这里填写您的API密钥
const DEEPSEEK_API_KEY: string = "sk-b8e21ac94e624691844269f0e0605cf2"; // Deepseek API密钥
const PLACEHOLDER_KEY = "your-api-key-here";
const DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";
const DEEPSEEK_MODEL = "deepseek-chat";
// 将棋盘转换为FEN-like字符串表示
function boardToString(pieces: Piece[]): string {
const board: string[][] = Array(10)
.fill(null)
.map(() => Array(9).fill("."));
for (const piece of pieces) {
if (piece.alive) {
const char = pieceTypeToChar(piece.type, piece.color);
board[piece.position.row][piece.position.col] = char;
}
}
return board.map((row) => row.join("")).join("/");
}
// 棋子类型转换为字符
function pieceTypeToChar(type: string, color: Color): string {
const charMap: Record<string, string> = {
帅: "K",
将: "k",
仕: "A",
士: "a",
相: "B",
象: "b",
马: "N",
车: "R",
炮: "C",
兵: "P",
卒: "p",
};
return charMap[type] || "?";
}
// 获取难度对应的系统提示词
function getSystemPrompt(difficulty: Difficulty, color: Color): string {
const colorText = color === "red" ? "红方" : "黑方";
const basePrompt = `你是一个中国象棋AI助手。当前你是${colorText}。
棋盘表示:每行用/分隔,每行9个格子,空位用.表示。
棋子表示:K=帅 k=将 A=仕 a=士 B=相 b=象 N=马 R=车 C=炮 P=兵 p=卒
红方用大写字母,黑方用小写字母。
你必须以以下JSON格式回复你的走法:
{
"from": {"row": 行号(0-9), "col": 列号(0-8)},
"to": {"row": 行号(0-9), "col": 列号(0-8)},
"reason": "简要说明你的走法思路"
}
注意:
1. 只能移动己方棋子
2. 必须遵守中国象棋规则
3. 行号0是黑方底线,行号9是红方底线
4. 列号0是左侧,列号8是右侧`;
switch (difficulty) {
case "容易":
return `${basePrompt}
你是初级水平的棋手。请:
1. 优先选择简单的进攻或防守走法
2. 避免复杂的战术组合
3. 偶尔可以犯一些小错误
4. 优先考虑吃子和将军`;
case "一般":
return `${basePrompt}
你是中级水平的棋手。请:
1. 选择合理的战术走法
2. 注意保护重要棋子
3. 寻找吃子机会
4. 避免明显的错误`;
case "困难":
return `${basePrompt}
你是高级水平的棋手。请:
1. 选择最优的战术走法
2. 进行深度计算,寻找最佳着法
3. 积极进攻,同时注意防守
4. 利用战术组合获得优势
5. 优先考虑将死对方的将/帅`;
default:
return basePrompt;
}
}
// 调用Deepseek API获取走法
export async function getDeepseekMove(
pieces: Piece[],
color: Color,
difficulty: Difficulty,
moveHistory: string[]
): Promise<AIMove | null> {
// 如果API密钥未配置,回退到A* AI
if (DEEPSEEK_API_KEY === PLACEHOLDER_KEY || !DEEPSEEK_API_KEY) {
console.log("Deepseek API密钥未配置,使用A* AI代替");
return findBestMove(pieces, color, difficulty);
}
const boardStr = boardToString(pieces);
const systemPrompt = getSystemPrompt(difficulty, color);
const historyStr = moveHistory.slice(-10).join("\n"); // 最近10步
const userPrompt = `当前棋盘状态(${color === "red" ? "红方" : "黑方"}走):
${boardStr}
最近走棋记录:
${historyStr || "无"}
请给出你的走法。`;
try {
const response = await fetch(DEEPSEEK_API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${DEEPSEEK_API_KEY}`,
},
body: JSON.stringify({
model: DEEPSEEK_MODEL,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userPrompt },
],
temperature: difficulty === "容易" ? 0.8 : difficulty === "一般" ? 0.5 : 0.2,
max_tokens: 500,
}),
});
if (!response.ok) {
throw new Error(`API请求失败: ${response.status}`);
}
const data = await response.json();
const content = data.choices?.[0]?.message?.content;
if (!content) {
throw new Error("API返回内容为空");
}
// 解析JSON响应
const jsonMatch = content.match(/\{[\s\S]*\}/);
if (!jsonMatch) {
throw new Error("无法解析API响应");
}
const moveData = JSON.parse(jsonMatch[0]);
const from: Position = moveData.from;
const to: Position = moveData.to;
// 验证走法是否合法
const validation = isValidMove(pieces, from, to, color);
if (!validation.valid) {
console.warn(`Deepseek返回的走法不合法: ${validation.reason},回退到A* AI`);
return findBestMove(pieces, color, difficulty);
}
return {
from,
to,
};
} catch (error) {
console.error("Deepseek API调用失败:", error);
console.log("回退到A* AI");
return findBestMove(pieces, color, difficulty);
}
}
// 检查API密钥是否已配置
export function isDeepseekConfigured(): boolean {
return DEEPSEEK_API_KEY !== PLACEHOLDER_KEY && !!DEEPSEEK_API_KEY;
}
// 获取API配置状态信息
export function getDeepseekStatus(): { configured: boolean; message: string } {
if (isDeepseekConfigured()) {
return { configured: true, message: "Deepseek API已配置" };
} else {
return {
configured: false,
message: "Deepseek API未配置,将使用本地A* AI",
};
}
}
@@ -0,0 +1,251 @@
"use client";
import { useChessGame } from "./hooks/useChessGame";
import ChessBoard from "./components/ChessBoard";
import GameControls from "./components/GameControls";
import GameStatus from "./components/GameStatus";
import { BOARD_WIDTH } from "./components/ChessBoard";
export default function Home() {
const {
pieces,
turn,
status,
winner,
selectedPieceId,
validMoves,
moveHistory,
gameMode,
difficulty,
lastMove,
isAIThinking,
gameStarted,
canUndo,
isPlaying,
handlePieceClick,
handleEmptyClick,
newGame,
undo,
surrender,
closeModal,
setGameMode,
setDifficulty,
startGame,
} = useChessGame();
return (
<div
style={{
minHeight: "100vh",
backgroundColor: "#f3f4f6",
display: "flex",
flexDirection: "column",
alignItems: "center",
padding: "16px",
gap: "16px",
}}
>
{/* 标题 */}
<h1
style={{
fontSize: "24px",
fontWeight: "bold",
color: "#333",
marginBottom: "8px",
}}
>
中国象棋
</h1>
{/* 红方黑方身份提示 */}
<div
style={{
display: "flex",
gap: "24px",
padding: "10px 24px",
backgroundColor: "#ffffff",
borderRadius: "8px",
boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
fontSize: "14px",
}}
>
<div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<span
style={{
width: "12px",
height: "12px",
borderRadius: "50%",
backgroundColor: "#d80000",
display: "inline-block",
}}
/>
<span style={{ fontWeight: "bold", color: "#d80000" }}>
红方:{gameMode === "人vsA*" || gameMode === "人vsDeepseek" ? "玩家" : "A* AI"}
</span>
</div>
<div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<span
style={{
width: "12px",
height: "12px",
borderRadius: "50%",
backgroundColor: "#111111",
display: "inline-block",
}}
/>
<span style={{ fontWeight: "bold", color: "#111111" }}>
黑方:{gameMode === "人vsA*" ? "A* AI" : gameMode === "人vsDeepseek" ? "Deepseek AI" : "Deepseek AI"}
</span>
</div>
</div>
{/* AI思考提示 */}
{isAIThinking && (
<div
style={{
padding: "6px 16px",
backgroundColor: "#fef3c7",
borderRadius: "6px",
color: "#92400e",
fontSize: "14px",
fontWeight: 500,
}}
>
AI思考中...
</div>
)}
{/* 棋盘区域 */}
<div style={{ position: "relative" }}>
{/* 开始按钮遮罩 */}
{!gameStarted && (
<div
style={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(0,0,0,0.6)",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
borderRadius: "8px",
zIndex: 20,
gap: "16px",
}}
>
<div
style={{
fontSize: "20px",
color: "white",
fontWeight: "bold",
textAlign: "center",
}}
>
准备开始棋局
</div>
<button
onClick={() => {
console.log("[Chess] Button clicked!");
startGame();
}}
style={{
padding: "16px 48px",
borderRadius: "8px",
border: "none",
backgroundColor: "#16a34a",
color: "white",
fontSize: "20px",
fontWeight: "bold",
cursor: "pointer",
boxShadow: "0 4px 12px rgba(0,0,0,0.3)",
transition: "all 0.2s",
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = "#15803d";
e.currentTarget.style.transform = "scale(1.05)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "#16a34a";
e.currentTarget.style.transform = "scale(1)";
}}
>
开始
</button>
<div
style={{
fontSize: "14px",
color: "rgba(255,255,255,0.8)",
textAlign: "center",
}}
>
当前模式:{gameMode} | 难度:{difficulty}
</div>
</div>
)}
{/* 棋盘 */}
<div style={{ opacity: gameStarted ? 1 : 0.5 }}>
<ChessBoard
pieces={pieces}
selectedPieceId={selectedPieceId}
validMoves={validMoves}
lastMove={lastMove}
onPieceClick={handlePieceClick}
onEmptyClick={handleEmptyClick}
/>
</div>
</div>
{/* 游戏状态和走棋记录 */}
<div style={{ width: `${BOARD_WIDTH}px`, maxWidth: "100%" }}>
<GameStatus
status={status}
turn={turn}
winner={winner}
moveHistory={moveHistory}
onCloseModal={closeModal}
/>
</div>
{/* 游戏控制 */}
<div style={{ width: `${BOARD_WIDTH}px`, maxWidth: "100%" }}>
<GameControls
mode={gameMode}
difficulty={difficulty}
onModeChange={setGameMode}
onDifficultyChange={setDifficulty}
onNewGame={newGame}
onUndo={undo}
onSurrender={surrender}
canUndo={canUndo}
isPlaying={isPlaying}
/>
</div>
{/* 底部说明 */}
<div
style={{
marginTop: "8px",
padding: "10px",
backgroundColor: "#ffffff",
borderRadius: "8px",
boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
fontSize: "12px",
color: "#666",
textAlign: "center",
maxWidth: `${BOARD_WIDTH}px`,
}}
>
<p>点击己方棋子选中,再点击目标位置移动</p>
<p style={{ marginTop: "4px" }}>
支持人vsA*、人vsDeepseek、A*vsDeepseek三种模式
</p>
</div>
</div>
);
}
@@ -0,0 +1,147 @@
// 中国象棋类型定义
// 棋子类型
export type PieceType =
| "帅" | "将" // 帅/将
| "车" // 车
| "马" // 马
| "炮" // 炮
| "相" | "象" // 相/象
| "仕" | "士" // 仕/士
| "兵" | "卒"; // 兵/卒
// 颜色
export type Color = "red" | "black";
// 位置
export interface Position {
row: number; // 0-9
col: number; // 0-8
}
// 棋子
export interface Piece {
id: string;
type: PieceType;
color: Color;
position: Position;
alive: boolean;
}
// 移动
export interface Move {
from: Position;
to: Position;
piece: Piece;
capturedPiece?: Piece;
isCheck?: boolean;
isCheckmate?: boolean;
notation: string; // 走棋记录表示
}
// 游戏模式
export type GameMode = "人vsA*" | "人vsDeepseek" | "A*vsDeepseek";
// 难度级别
export type Difficulty = "容易" | "一般" | "困难";
// 游戏状态
export type GameStatus =
| "playing" // 进行中
| "check" // 将军
| "checkmate" // 将死
| "stalemate" // 困毙/和棋
| "draw"; // 和棋
// 游戏配置
export interface GameConfig {
mode: GameMode;
difficulty: Difficulty;
}
// 棋盘状态
export interface BoardState {
pieces: Piece[];
turn: Color;
moveHistory: Move[];
status: GameStatus;
winner?: Color;
selectedPieceId?: string;
}
// AI移动结果
export interface AIMove {
from: Position;
to: Position;
score?: number;
}
// Deepseek API配置
export interface DeepseekConfig {
apiKey: string;
apiUrl: string;
model: string;
}
// 棋子价值(用于AI评估)
export const PIECE_VALUES: Record<PieceType, number> = {
"帅": 10000,
"将": 10000,
"车": 1000,
"马": 450,
"炮": 450,
"相": 200,
"象": 200,
"仕": 200,
"士": 200,
"兵": 100,
"卒": 100,
};
// Palace(九宫格)范围
export const PALACE = {
red: { minRow: 7, maxRow: 9, minCol: 3, maxCol: 5 },
black: { minRow: 0, maxRow: 2, minCol: 3, maxCol: 5 },
};
// 河界行号
export const RIVER_ROWS = [4, 5];
// 初始棋子布局
export const INITIAL_PIECES: Omit<Piece, "id">[] = [
// 红方(底部)
{ type: "车", color: "red", position: { row: 9, col: 0 }, alive: true },
{ type: "马", color: "red", position: { row: 9, col: 1 }, alive: true },
{ type: "相", color: "red", position: { row: 9, col: 2 }, alive: true },
{ type: "仕", color: "red", position: { row: 9, col: 3 }, alive: true },
{ type: "帅", color: "red", position: { row: 9, col: 4 }, alive: true },
{ type: "仕", color: "red", position: { row: 9, col: 5 }, alive: true },
{ type: "相", color: "red", position: { row: 9, col: 6 }, alive: true },
{ type: "马", color: "red", position: { row: 9, col: 7 }, alive: true },
{ type: "车", color: "red", position: { row: 9, col: 8 }, alive: true },
{ type: "炮", color: "red", position: { row: 7, col: 1 }, alive: true },
{ type: "炮", color: "red", position: { row: 7, col: 7 }, alive: true },
{ type: "兵", color: "red", position: { row: 6, col: 0 }, alive: true },
{ type: "兵", color: "red", position: { row: 6, col: 2 }, alive: true },
{ type: "兵", color: "red", position: { row: 6, col: 4 }, alive: true },
{ type: "兵", color: "red", position: { row: 6, col: 6 }, alive: true },
{ type: "兵", color: "red", position: { row: 6, col: 8 }, alive: true },
// 黑方(顶部)
{ type: "车", color: "black", position: { row: 0, col: 0 }, alive: true },
{ type: "马", color: "black", position: { row: 0, col: 1 }, alive: true },
{ type: "象", color: "black", position: { row: 0, col: 2 }, alive: true },
{ type: "士", color: "black", position: { row: 0, col: 3 }, alive: true },
{ type: "将", color: "black", position: { row: 0, col: 4 }, alive: true },
{ type: "士", color: "black", position: { row: 0, col: 5 }, alive: true },
{ type: "象", color: "black", position: { row: 0, col: 6 }, alive: true },
{ type: "马", color: "black", position: { row: 0, col: 7 }, alive: true },
{ type: "车", color: "black", position: { row: 0, col: 8 }, alive: true },
{ type: "炮", color: "black", position: { row: 2, col: 1 }, alive: true },
{ type: "炮", color: "black", position: { row: 2, col: 7 }, alive: true },
{ type: "卒", color: "black", position: { row: 3, col: 0 }, alive: true },
{ type: "卒", color: "black", position: { row: 3, col: 2 }, alive: true },
{ type: "卒", color: "black", position: { row: 3, col: 4 }, alive: true },
{ type: "卒", color: "black", position: { row: 3, col: 6 }, alive: true },
{ type: "卒", color: "black", position: { row: 3, col: 8 }, alive: true },
];
@@ -0,0 +1,11 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
reactCompiler: true,
output: 'export',
distDir: 'dist',
assetPrefix: '.',
};
export default nextConfig;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
{
"name": "chinese-chess",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "16.1.6",
"react": "19.2.3",
"react-dom": "19.2.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0",
"tailwindcss": "^4",
"typescript": "^5"
}
}
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

@@ -0,0 +1,44 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
"dist/types/**/*.ts",
"dist/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
@@ -0,0 +1,154 @@
# 中国象棋人机对弈软件(Web版)需求分析文档
**文档版本**:V1.0(最终定稿)
**更新日期**:2026-03-15
**技术栈**:Next.js 15 + TypeScript + Tailwind CSS
---
## 一、本次核心修改总结(最重要)
1. **棋子不再使用图片** → 纯CSS + Tailwind代码绘制
2. **UI背景**:Web窗体整体**浅灰色**,棋盘**浅米黄色**
3. **棋子样式**:
- 圆形、代码绘制
- 自带**3D阴影、立体感、凸起效果**
- 红方:**红色加粗字体**
- 黑方:**黑色加粗字体**
4. 其他需求(技术栈、竖屏、三种模式、三种难度)全部保留
---
## 二、完整定稿需求(可直接开发)
### 1. 技术栈(不变)
- 框架:**Next.js**(App Router)
- 语言:**TypeScript**
- 样式:**Tailwind CSS**
- 渲染:纯前端Canvas / CSS绘制棋盘+棋子
### 2. 界面与视觉(重大修改)
#### 2.1 屏幕与背景
- 布局:**1080×1920 竖屏优先**,全屏展示
- 页面背景:**浅灰色(#f3f4f6)**
- 棋盘底色:**浅米黄色(#fff9e6)**
- 棋盘边框:浅棕色、圆角、柔和阴影
#### 2.2 棋子(代码绘制,无图片)
- 形状:正圆形
- 效果:**纯CSS 3D凸起阴影**(内阴影+外阴影,立体质感)
- 文字:**加粗、居中、大号字体**
- 颜色区分:
- 红方棋子:**红色字体(#d80000)**
- 黑方棋子:**黑色字体(#111111)**
- 交互:点击后放大、高亮、阴影加深
#### 2.3 棋盘(代码绘制)
- 标准9×10棋盘,楚河汉界
- 线条:深灰色细线
- 九宫格清晰标注
- 全部使用CSS/Canvas绘制,无外部资源
### 3. 对弈模式(保留不变)
1. **人 VS A*算法(本地AI)**
2. **人 VS Deepseek API(云端大模型)**
3. **A*算法 VS Deepseek API(AI自动对战)**
### 4. AI难度(保留不变)
- 容易
- 一般
- 困难
### 5. 规则(保留完整版)
严格遵守中国象棋官方规则:走法、吃子、将军、胜负和判定、禁手等。
### 6. 功能清单
- 开始新局
- 悔棋
- 重置棋局
- 认输 / 和棋
- 模式选择
- 难度选择
- 走棋记录
- 将军提示
- 胜负弹窗
### 7. 非功能需求
- 无任何外部图片、字体、资源依赖
- 加载速度 < 2秒
- 本地AI响应 < 2秒
- API响应 < 5秒
- 移动端竖屏完美运行
---
## 三、总结
✅ 主要技术栈 Next.js + TypeScript + Tailwind
✅ 竖屏布局
✅ 浅灰背景 + 浅米黄棋盘
✅ **纯代码绘制的3D立体棋子**
✅ 完整象棋规则引擎
✅ 三种对弈模式
✅ 三种难度
✅ A*算法AI 实现的中国象棋算法,也包含3个层次的难度系数。
✅ Deepseek API对接结构,Deekseek key可配置,不同困难配置下的给deepseek的提示语不一样,请合理设计提示语,达到3个层次的难度系数。