# Connect Four - Pico 2W

A Connect Four game with AI for the Raspberry Pi Pico 2W, using a PicoResTouch-LCD-2.8 touchscreen display (2.8" TFT with resistive touch).

## Hardware

### Requirements

- **Raspberry Pi Pico 2W** (RP2350, with headers soldered)
- **Waveshare Pico-ResTouch-LCD-2.8** (320x240 ST7789 TFT + XPT2046 resistive touch)

The Pico 2W plugs directly into the display board's header socket. No additional wiring needed.

### Pin Mapping (PicoResTouch-LCD-2.8)

| Component         | GPIO   | Function          |
| :---------------- | :----- | :---------------- |
| **LCD SCLK**      | `GP10` | SPI1 Clock        |
| **LCD MOSI**      | `GP11` | SPI1 TX           |
| **LCD MISO**      | `GP12` | SPI1 RX           |
| **LCD CS**        | `GP9`  | Display select    |
| **LCD DC**        | `GP8`  | Data/Command      |
| **LCD RST**       | `GP15` | Display reset     |
| **LCD BL**        | `GP13` | Backlight (PWM)   |
| **Touch CS**      | `GP16` | Touch select      |
| **Touch IRQ**     | `GP17` | Touch interrupt   |

All display and touch peripherals share SPI1.

## Game Modes

Touch a menu item to start:

1. **Play as Yellow** - Player plays yellow (first move), AI plays red.
2. **Play as Red** - AI plays yellow (first move), player plays red.
3. **Two Players** - Two humans alternate turns. Yellow goes first.
4. **Settings** - Adjust AI difficulty, blunder mode, view game log, recalibrate touch.

### Controls

- **Menu:** Touch a game mode or Settings to select.
- **During play:** Touch a column to drop a disc.
- **After game ends:** Touch anywhere to return to menu.
- **Demo mode:** Touch anywhere to return to menu.

### Demo Mode

When idle (no input for 60 seconds), the board enters demo mode where two AI players play against each other. The two demo players use asymmetric ply depths (randomized each game) so games frequently end in a win rather than a draw. Touch the screen to exit.

### Animations

- **Disc drop:** Discs fall from the top with accelerating speed.
- **Win:** The winning four discs flash while the rest of the board dims.
- **Draw:** All discs blink on and off.

## Settings Menu

Accessible from the main menu. All settings are saved to flash (EEPROM) and persist across reboots.

| Setting              | Range    | Description                                        |
| :------------------- | :------- | :------------------------------------------------- |
| **AI Ply**           | 1-10     | Search depth for the AI. Higher = stronger.        |
| **Blunder**          | ON/OFF   | AI randomly picks a bad move at the configured %.  |
| **Blunder %**        | 5-100%   | Chance of a blunder when enabled (step 5).         |

Additional options:
- **View Game Log** - Paginated list of all played games (type, level, winner, moves). Player wins highlighted in red. Option to clear the log.
- **Recalibrate Touch** - Re-run the two-point touch calibration.

## Game Log

The last 100 games are stored in flash. Each entry records the game type (Yellow/Red/Two-player), AI level, winner, and the column sequence. The log is viewable on-device via Settings > View Game Log.

## Touch Calibration

On first boot, the display shows a two-point calibration screen (touch top-left, then bottom-right crosshairs). Calibration data is stored in EEPROM. To recalibrate:
- Hold the touchscreen during boot, **or**
- Use Settings > Recalibrate Touch.

## Build & Upload

Requires [PlatformIO](https://platformio.org/) CLI or VS Code with PlatformIO extension.

```bash
# Build
pio run

# Upload to board (hold BOOTSEL, plug in USB, release, then run)
pio run --target upload

# Or copy the UF2 file manually:
# Hold BOOTSEL, plug in USB. Copy .pio/build/rpipico2w/firmware.uf2 to the RPI-RP2 drive.

# Monitor serial output
pio device monitor
```

### Dependencies

- [Adafruit ST7735/ST7789 Library](https://github.com/adafruit/Adafruit-ST7735-Library) - Display driver
- [Adafruit GFX Library](https://github.com/adafruit/Adafruit-GFX-Library) - Graphics primitives
- EEPROM (built-in) - Persistent settings storage
- SPI (built-in) - Hardware SPI communication

### Build Flags

Configurable parameters defined as `-D` flags in `platformio.ini`:

| Flag                   | Default | Description                                       |
| :--------------------- | :------ | :------------------------------------------------ |
| `DEFAULT_LOOK_AHEAD`   | `8`     | Default AI search depth (plies)                   |
| `DEFAULT_IDLE_TIMEOUT` | `60`    | Seconds before demo mode activates                |
| `DEMO_RESET_PAUSE`     | `20000` | Milliseconds before finished game enters demo     |
| `MAX_GAME_LOG`         | `100`   | Maximum number of games stored in the game log    |
| `BLUNDER_ENABLED`      | `0`     | Default blunder mode (0 = off, 1 = on)            |
| `BLUNDER_CHANCE`       | `20`    | Default blunder chance percentage                 |

## AI

The AI uses minimax search with alpha-beta pruning and a three-phase move strategy:

1. **Instant win/block** - Check all columns for an immediate win or opponent threat.
2. **Blunder** (optional) - Randomly pick a valid column instead of searching.
3. **Deep search** - Full minimax with alpha-beta pruning at the configured ply depth.

The board evaluation scores center column control and counts two/three-in-a-row patterns in all four directions. Column search order is center-first (`3, 2, 4, 1, 5, 0, 6`) for better alpha-beta pruning.

## Project Structure

```
src/
  config.h          Pin definitions, layout constants, colors, game defaults
  game.h / .cpp     State enum, shared globals, board helpers, AI (minimax), game logic
  touch.h / .cpp    XPT2046 raw SPI reads, touch events, calibration
  storage.h / .cpp  EEPROM persistence (calibration, settings, game log)
  display.h / .cpp  All TFT drawing (board, menu, settings UI, game log UI)
  main.cpp          setup(), loop(), state dispatch

platformio.ini                Build configuration and tunable parameters
connect_four.js / .html       Browser edition (standalone, identical AI)
Background information.md     How the AI works (suitable for all ages)
Achtergrondinformatie.md      AI explanation (Dutch)
CLAUDE.md                     AI assistant project context
```

## Browser Edition

The `connect_four.js` / `connect_four.html` files contain a standalone browser version with identical AI logic. Open `connect_four.html` in any modern browser to play. Supports mouse, keyboard, and touch input.
