Files
Connect-four-Esp32/Background information.md
T

3.2 KiB
Raw Blame History

🕹️ Connect 4 AI: How the Brain Works

To create a competitive Connect 4 experience on a small microcontroller, the game uses a mix of mathematical strategy and "shortcuts" to play like a human master.


1. The Virtual Board

The computer sees the board as a grid of numbers. It uses a 7-column by 6-row map where:

  • 0 = Empty space
  • 1 = Yellow (Human Player)
  • 2 = Red (Computer AI)

Every time a disc is dropped, a "Scan" function checks every possible direction (horizontal, vertical, and diagonal) to see if anyone has reached four in a row.


2. Thinking Ahead (The "What If?" Engine)

The AI doesn't just look at the current board; it plays out thousands of "What if?" scenarios in its head.

The Minimax Strategy

The AI uses a strategy called Minimax. It assumes that you will play your absolute best move, and it tries to find the move that leaves you with the worst possible outcome. It "maximizes" its own advantage while "minimizing" yours.

Alpha-Beta Pruning (The Shortcut)

Calculating every possible move in Connect 4 would take hours. To make the AI fast, it uses Pruning. If the AI starts calculating a move and realizes its definitely worse than a move it already found, it "prunes" (deletes) that entire branch of thought and moves on. This allows it to ignore up to 90% of useless moves.


3. Scoring System (The AIs Instincts)

Since the computer can't always see to the very end of the game, it uses a scoring system to guess which positions are strongest:

  • Speed Matters: The AI is rewarded more for a win that happens soon than a win that takes a long time. This gives it a "killer instinct" to end the game as quickly as possible.
  • The Center is King: The AI is programmed to prefer the middle column. Mathematically, the center column is involved in the most possible winning combinations, so the AI fights to control it early in the game.

4. Being Responsive (Interrupt Handling)

Your game runs on an ESP32-C3, which is a single-tasking processor. Normally, if the AI spends 2 seconds thinking, the buttons would feel "broken" or "frozen" until it finishes.

We solve this with two clever tricks:

  1. Mid-Thought Checks: Every few milliseconds of calculation, the AI "pauses" for a microsecond to see if you have pressed the button.
  2. Instant Exit: If it detects you pressed the button while it was thinking, it abandons all calculations immediately and jumps back to the main menu.

5. Summary of an AI Move

When it is the computer's turn, it follows these steps in a split second:

  1. Check for Lethal: Can I win right now? If yes, take it.
  2. Check for Danger: Can the human win on their next move? If yes, block it.
  3. Search: Look at the middle columns first, then the edges.
  4. Prune: Throw away bad moves immediately to save time.
  5. Act: Choose the move that leads to the quickest victory.

📚 References & Further Reading