Tag Archives: Minimax

Playing 4-Bot with the Raspberry Pi

Sometime or the other we have all played Connect-4 or Four-in-a-row against either a human or a computer opponent. It is a simple game where you and your opponent each try to get four same-color pieces in a row, while trying to prevent the other from doing so. The first one to line up four adjacent pieces of the same color wins the game.

Conventionally, the game board has 42 squares made of six rows and seven columns. Players start with several discs of two colors each, and to be successful, each player has to constantly plan and revise their strategy. Therefore, an SBC or single board computer such as the Raspberry Pi, or RBPi is a suitable candidate for playing Connect-4. Besides enjoying the game, you hone your skills as a DIY enthusiast by building the game. Of course, this project will require some skill in mechanical assembly, and in coding as well.

You can have a horizontal board and an X, Y arm mechanism to let the RBPi deliver its pieces to the required square. However, a vertical board makes the mechanism simpler, as the arm then has to travel only in one axis, gravity taking care of the other. The vertical board is actually made of two faces, with a gap in between and separators to mark the columns to allow the discs to be dropped in one of the columnar spaces between the two faces. Both faces have 42 matching circular cutouts, so it is easy to see where each disc is positioned. A claw on the arm mechanism picks up a disc from a stack, positions itself above the required column, and releases the disc, allowing it to fall in the column between the board faces.

The software requires the use of Python Imaging Library for processing the image of the game board. To enhance readability, the image can be down-sampled to 16 colors, and then divided into a grid. It is only required to identify each of the 42 spaces on the board as red, yellow, or empty. This is easily done by reading the RGB value of each space in the grid, and saving this data in the form of an array. This forms the board state after every move and this is passed on to the AI or Artificial Intelligence on the RBPi for calculating the next move.

The AI used is a well-known algorithm known as Minimax – applicable to games of this nature, and there is a Python library for Minimax. Using tree-searching methods, the algorithm looks several steps ahead to calculate the next best move. Getting the RBPi to play effectively can be quite a challenge, as even a small Connect-4 board of 6×7 squares can have 4,531,985,219,092 possible game positions. Therefore, the program tries to trade-off between absolute perfect play and reasonable time for each move. If you can strike a balance between the two, the RBPi can play quite intelligently, but still complete each move in about 25 seconds – this is acceptable for a flowing game.