- The simplest way to achieve this is to count the relative strength of the pieces on the board using the following table:With the evaluation function, we’re able to create an algorithm that chooses the move that gives the highest evaluation:The only tangible improvement is that our algorithm will now capture a piece if it can.Black plays with the aid of the simple evaluation function.
- This is done by using the Minimax algorithm.In this algorithm, the recursive tree of all possible moves is explored to a given depth, and the position is evaluated at the ending “leaves” of the tree.After that, we return either the smallest or the largest value of the child to the parent node, depending on whether it’s a white or black to move.
- The best move for white is b2-c3, because we can guarantee that we can get to a position where the evaluation is -50With minimax in place, our algorithm is starting to understand some basic tactics of chess:Minimax with depth level 2.
- This helps us evaluate the minimax search tree much deeper, while using the same resources.The alpha-beta pruning is based on the situation where we can stop evaluating a part of the search tree if we find a move that leads to a worse situation than a previously discovered move.The alpha-beta pruning does not influence the outcome of the minimax algorithm — it only makes it faster.The alpha-beta algorithm also is more efficient if we happen to visit first those paths that lead to good moves.The positions we do not need to explore if alpha-beta pruning isused and the tree is visited in the described order.With alpha-beta, we get a significant boost to the minimax algorithm, as is shown in the following example:The number of positions that are required to evaluate if we want to perform a search with depth of 4 and the “root” position is the one that is shown.Follow this link to try the alpha-beta improved version of the chess AI.Step 5: Improved evaluation functionThe initial evaluation function is quite naive as we only count the material that is found on the board.
- We can decrease or increase the evaluation, depending on the location of the piece.With the following improvement, we start to get an algorithm that plays some “decent” chess, at least from the viewpoint of a casual player:Improved evaluation and alpha-beta pruning with search depth of 3.

At each step, we’ll improve our algorithm with one of these time-tested chess-programming techniques. I’ll demonstrate how each affects the algorithm’s playing style. We’ll use the chess.js library…

Continue reading “A step-by-step guide to building a simple chess AI – freeCodeCamp”