# 技能 | 只要五步，教你撸一个缩减版国际象棋AI

• 移动生成
• 棋面评估
• Minimax算法
• alpha beta剪枝

https://github.com/lhartikk/simple-chess-ai

https://github.com/jhlywa/chess.js https://github.com/oakmac/chessboardjs/

var calculateBestMove =function(game) { //generate all the moves for a given position var newGameMoves = game.ugly_moves(); return newGameMoves[Math.floor(Math.random() * newGameMoves.length)]; };

var calculateBestMove = function (game) { var newGameMoves = game.ugly_moves(); var bestMove = null; //use any negative large number var bestValue = -9999; for (var i = 0; i < newGameMoves.length; i++) { var newGameMove = newGameMoves[i]; game.ugly_move(newGameMove); //take the negative as AI plays as black var boardValue = -evaluateBoard(game.board()) game.undo(); if (boardValue > bestValue) { bestValue = boardValue; bestMove = newGameMove } } return bestMove; };

https://jsfiddle.net/lhartikk/m5q6fgtb/1/

https://en.wikipedia.org/wiki/Minimax

var minimax = function (depth, game, isMaximisingPlayer) { if (depth === 0) { return -evaluateBoard(game.board()); } var newGameMoves = game.ugly_moves(); if (isMaximisingPlayer) { var bestMove = -9999; for (var i = 0; i < newGameMoves.length; i++) { game.ugly_move(newGameMoves[i]); bestMove = Math.max(bestMove, minimax(depth - 1, game, !isMaximisingPlayer)); game.undo(); } return bestMove; } else { var bestMove = 9999; for (var i = 0; i < newGameMoves.length; i++) { game.ugly_move(newGameMoves[i]); bestMove = Math.min(bestMove, minimax(depth - 1, game, !isMaximisingPlayer)); game.undo(); } return bestMove; } };

Apha-beta剪枝是Minimax算法的优化，允许我们减去搜索树中的一些分支。在相同的资源下，这种方法有助于我们加深Minimax搜对索树的评估。如果发现某个走法会导致更糟糕的局势，那么Alpha-beta 剪枝就会停止评估该分支。这个方法不会影响Minimax算法，相反会提升算法速度。如果一开始就能发现最佳走法，

https://chessprogramming.wikispaces.com/Simplified+evaluation+function

https://github.com/lhartikk/simple-chess-ai

• 移动顺序

https://chessprogramming.wikispaces.com/Move+Ordering

• 更快地移动生成棋局

https://chessprogramming.wikispaces.com/Move+Generation

• 残局的评估

https://chessprogramming.wikispaces.com/Endgame

2164 篇文章137 人订阅

0 条评论

## 相关文章

653130

### 【前沿】用AlphaGo Zero方法实现增强学习下棋

【导读】Google DeepMind AlphaGo团队在Nature上发表两篇论文《Mastering the game of Go without Hum...

40180

11220

30050

45920

38490

68270

20820

1.2K100

48950