Sitemap
Play With Python

Learn Python and programming through fun and games.

Member-only story

Connect Four

7 min readJan 9, 2026

--

Connect Four when the AI loses

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)…

--

--

Simon Quellen Field
Simon Quellen Field

Written by Simon Quellen Field⁠

Simon Quellen Field is a science writer and novelist currently experimenting with shorter works. Find his books at scitoys.com/books or his website scitoys.com.

Play With Python
Play With Python

Published in Play With Python

Learn Python and programming through fun and games.