Creating a Connect 4 AI with Python
Connect 4 is a game we have all learnt to play and often times its simple nature can make it seem like there is less to it then there really is. The reality of the matter is that connect 4 can get quite complex, with multiple billions of possibilities and a finite board, meaning not only can it be difficult to score on a opponent but if an opponent thinks ahead, you will be forced into a losing position. In this post I hope to use minimax algorithms to develop an AI capable of beating a human.
Define Game “Rules” and Metrics
Here we will define the user and AI, the coordinate fill or no fill and the actual coins the user and AI are using. Lastly we will define the columns, rows and frames for the board.
Create Board, Validator
Here we create the numpy board of columns and rows filled with 0’s (empty) and we define the print board function which flips the board since gravity is opposite the numpy coordinates. Secondly we create a validation class which makes sure wherever the coin is being placed can be placed.
Winning and Scorer
Create class to check if any of the positions constitutes a win. Also create a score index this will be the main motivation for the AI as it will score all the positions user have and it will dictate the best move off of it. In this specific scenario 3 in a row is 5 points, 2 in a row is 3 and 4 in a row is 100 points. Opponent having a 3 in a row is -4.
Create an agent that uses the minimax algorithm to predict the best score position based on this move and the next possible moves. In the end will iteratively go through each column and see which has the highest score potential.
Create game by calling previous columns and assigning turns, and user inputs. Also define colors and game metrics. Create while loop for game that switches turns back and forth with the AI using its minimax algorithm until game is won. When game is won print winner and close game.