从随机到搜索------游戏AI的三级跃迁
设计截图如下:

AIPlayer整体架构
typescript
export class AIPlayer {
private aiColor: number; // AI棋色
private humanColor: number; // 人类棋色
private difficulty: Difficulty; // 难度等级
getMove(board: number[][]): Move {
// 空棋盘下天元
if (isEmpty) return new Move(7, 7);
// 根据难度选择策略
switch (this.difficulty) {
case Difficulty.EASY: return this.getEasyMove(board);
case Difficulty.NORMAL: return this.getNormalMove(board);
case Difficulty.HARD: return this.getHardMove(board);
}
}
}
三档难度对比
| 维度 | 简单 | 普通 | 困难 |
|---|---|---|---|
| 策略 | 规则优先级 | 启发式评估 | Minimax搜索 |
| 搜索深度 | 0(只看当前) | 0(只看当前) | 2(向前看2步) |
| 候选数量 | 全部 | 全部 | Top 12 |
| 评估方式 | 单步判定 | 攻防加权 | 全盘评估 |
| 计算量 | O(n) | O(n) | O(n^3) |
| 棋力 | 新手级 | 业余级 | 进阶级 |
简单模式:规则优先级
typescript
private getEasyMove(board: number[][]): Move {
// 1. AI能赢就赢
// 2. 堵对手四连
// 3. 堵对手活三
// 4. 随机选择(偏中心)
}
简单模式用if-else优先级链做决策,没有评估函数,计算量最小。
普通模式:启发式评估
typescript
private getNormalMove(board: number[][]): Move {
for (const move of candidates) {
attackScore = evaluatePosition(AI落子)
defendScore = evaluatePosition(人类落子)
totalScore = attackScore * 1.1 + defendScore
}
return bestMove;
}
普通模式引入评估函数,对每个候选位置计算攻防综合分数。攻击略高于防御(×1.1),体现"进攻是最好的防守"。
困难模式:Minimax + Alpha-Beta
typescript
private getHardMove(board: number[][]): Move {
for (const move of topCandidates) {
score = minimax(board, depth=2, alpha, beta, isMaximizing=false)
}
return bestMove;
}
困难模式用Minimax算法向前搜索2步(我方→对方→评估),配合Alpha-Beta剪枝加速。
空棋盘的特殊处理
typescript
getMove(board: number[][]): Move {
let isEmpty = true;
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] !== EMPTY) {
isEmpty = false;
break;
}
}
if (!isEmpty) break;
}
if (isEmpty) {
return new Move(7, 7); // 天元
}
// ...
}
为什么空棋盘要下天元?
- 天元(7,7)是棋盘正中心,向各方向延伸的机会均等
- 简化候选生成------不需要遍历空棋盘
- 符合五子棋开局惯例
难度选择与页面集成
typescript
// AIBattlePage中创建AI
private aiPlayer: AIPlayer = new AIPlayer(WHITE, Difficulty.EASY);
private startLevel(level: number): void {
const config = this.levels[level - 1];
this.aiPlayer = new AIPlayer(WHITE, config.difficulty);
}
每个关卡对应一个难度等级:
- 第1关 → EASY
- 第2关 → NORMAL
- 第3关 → HARD
设计模式:策略模式
三档难度的实现本质上是策略模式:
typescript
switch (this.difficulty) {
case Difficulty.EASY: return this.getEasyMove(board);
case Difficulty.NORMAL: return this.getNormalMove(board);
case Difficulty.HARD: return this.getHardMove(board);
}
getMove是统一接口,内部根据难度选择不同的算法策略。如果将来要添加更多难度,只需新增一个方法。
总结
AIPlayer的三档难度展示了游戏AI的经典进化路径:
- 规则驱动(简单)→ 人类经验编码为if-else
- 评估函数(普通)→ 量化棋型价值
- 搜索算法(困难)→ 向前推演对手反应
这个路径也是真实游戏AI的发展历程------从早期国际象棋的规则引擎,到AlphaGo的深度学习。