Member-only story
Connect Four
Building a smart opponent
Here we have another chance to build a game where the computer is smart enough to win.
Connect Four is a game where players drop pieces down from the top to land on the bottom or on top of pieces dropped earlier. The goal is to make pieces that have four in a row, either horizontally, vertically, or diagonally.
I would encourage you to do a web search for “connect four strategies” to find out the best ways to win.
Our home-brew AI is not going to use any of them, other than to weigh the center column heavier than the others. It will perform a brute-force MiniMax algorithm. This is good enough to win against beginners.
If you are a more seasoned player, you can boost the look-ahead from four to something higher. Seven is still playable on my computer, and usually beats me.
Let’s look at the game:
import tkinter as tk
from tkinter import messagebox
import random
import copy
# --- Configuration ---
ROWS = 6
COLS = 7
CELL_SIZE = 80
BG_COLOR = "#f0f0f0"
BOARD_COLOR = "#0055BB" # Classic Navy Blue
# Chip Colors
EMPTY = 0
PLAYER = 1 # Red
AI = 2 # Yellow
COLOR_MAP = {
EMPTY: "white", # The 'hole' in the board
PLAYER: "#D50000", # Red
AI: "#FFEA00" # Yellow
}
# AI Difficulty Depth (Higher = Smarter but slower)…








