Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Bao la Kiswahili — The Magnum Opus

The most complex mancala game in existence, implemented in Python with 60+ AI and utility modules.

Python 3.8+ License: MIT Tests: 19/19


The Kenya Board Game Series

This is the fourth and final entry in a progressive series teaching students ages 10–17 how to code AI for mancala games:

Game Difficulty Board Language Repo
Shisima ★☆☆☆☆ Triangle, 3 pieces HTML/JS shisima-game-lesson
Giuthi ★★☆☆☆ 2×8, relay sowing HTML/JS giuthi-ai-explorer
Kiothi ★★★☆☆ 2×10, nki, chain captures HTML/JS kiothi-mancala-lesson
Bao la Kiswahili ★★★★★ 4×8, two phases, nyumba, kichwa Python This repo

What is Bao la Kiswahili?

Bao la Kiswahili ("board of the Swahili people") is the most sophisticated mancala game ever devised. Played in Zanzibar and coastal Tanzania, it features:

  • 4×8 board (32 pits) with 64 seeds
  • Two phases: namua (seed placement from hand) and mtaji (sowing from board)
  • Nyumba (house): a special pit with 6+ seeds that can be "taxed" or enter safari mode
  • Kichwa (head): directional sowing rules from board edges
  • Marker pits: inner-row pits facing non-empty opponent pits
  • Complex captures: capturing requires crossing from your row to the opponent's row, with directional constraints
  • Takasia: restricted pits that cannot be sown from

Bao is considered a thinking game of the highest order — grandmasters in Zanzibar are held in the same esteem as chess grandmasters elsewhere.

Project Structure

bao-la-kiswahili/
├── bao/
│   ├── config.py          # Constants (rows, cols, player positions)
│   ├── board.py           # GameState, BaoBoard, Move, MoveResult
│   ├── engine.py          # Rule engine: moves, captures, sowing, game over
│   ├── cli.py             # Command-line interface
│   ├── ai/                # 34 AI strategy modules
│   │   ├── base.py        # BaoAI abstract base class
│   │   ├── minimax.py     # Classic alpha-beta pruning
│   │   ├── mcts.py        # Monte Carlo Tree Search
│   │   ├── neural_net.py  # Neural network evaluation
│   │   ├── ...            # (30 more strategies)
│   ├── analysis/          # 6 analysis modules
│   ├── training/          # 5 training/evaluation modules
│   ├── tournament/        # 4 tournament systems
│   ├── ui/                # 5 UI/display modules
│   └── utils/             # 8 utility modules
├── tests/
│   └── test_bao.py        # 19 engine tests (all passing)
├── AI_DEV_REFERENCE.py    # API reference for module developers
├── setup.py               # Package installation
└── requirements.txt       # Dependencies (stdlib + optional numpy)

AI Strategy Modules (34)

Search Algorithms

Module Class Strategy
minimax.py MinimaxAI Alpha-beta pruning with weighted evaluation
mtdf.py MTDfAI MTD(f) zero-window iterative search
scout.py ScoutAI Principal Variation Search (SCOUT)
negamax.py NegamaxAI Negamax formulation
negascout.py NegascoutAI NegaScout (PVS from negamax)
alpha_beta_transposition.py AlphaBetaTtAI Transposition tables
killer_moves.py KillerMoveAI Killer move + history heuristic
iterative_deepening.py IterativeDeepeningAI Time-limited deepening
aspiration_windows.py AspirationWindowAI Aspiration window narrowing
quiescence.py QuiescenceAI Quiescence search (anti-horizon)
ssstardis.py SSSStarAI SSS* best-first search
best_first.py BestFirstAI Best-first alpha-beta
expectimax.py ExpectimaxAI Stochastic opponent modeling
paranoid.py ParanoidAI Worst-case loss maximization

Monte Carlo Methods

Module Class Strategy
mcts.py MCTSAI UCT-based MCTS with random rollouts
mcts_heuristic.py MCTSHeuristicAI MCTS with heuristic rollouts
mcts_rave.py MCTSRAVEAI MCTS with RAVE/AMAF values

Reinforcement Learning

Module Class Strategy
temporal_difference.py TDAI TD(0) value function learning
q_learning.py QLearningAI Q-learning with epsilon-greedy
policy_gradient.py PolicyGradientAI REINFORCE policy gradient
actor_critic.py ActorCriticAI Actor-Critic with TD error

Evolutionary & Neural

Module Class Strategy
genetic.py GeneticAI Genetic algorithm weight evolution
neural_net.py NeuralNetAI 2-layer MLP evaluation (numpy or pure Python)

Strategy & Heuristic

Module Class Strategy
greedy_captures.py GreedyCaptureAI Maximizes immediate captures
defensive.py DefensiveAI Minimizes capture threats
positional.py PositionalAI Weighted positional evaluation
territorial.py TerritorialAI Territory zone control
mobility.py MobilityAI Maximizes move options
nyumba_aware.py NyumbaAwareAI Strategic nyumba management
kichwa_tactics.py KichwaTacticsAI Exploits kichwa direction rules
endgame_solver.py EndgameSolverAI Deep search for endgames

Meta & Hybrid

Module Class Strategy
ensemble.py EnsembleAI Combines multiple AIs via voting
hierarchical.py HierarchicalAI Phase-aware strategy switching
human_like.py HumanLikeAI Simulates human play with mistakes

Additional Modules (29)

Analysis (bao/analysis/)

  • board_analyzer.py — Threat counting, capture potential, vulnerability
  • game_replay.py — Step through game move-by-move
  • move_explainer.py — Natural-language move explanations
  • position_evaluator.py — Multi-factor position scoring
  • statistics.py — Game statistics tracking
  • threat_detector.py — Capture threat detection

Training (bao/training/)

  • trainer.py — Self-play training loop
  • curriculum.py — Progressive difficulty training
  • arena.py — Round-robin tournament framework
  • parameter_tuner.py — Hyperparameter grid/random search
  • evaluator.py — Comprehensive AI evaluation

Tournament (bao/tournament/)

  • swiss.py — Swiss-system tournament with Buchholz tiebreak
  • single_elim.py — Single-elimination bracket
  • rating_system.py — Elo rating system
  • match_runner.py — Match execution with stats

UI (bao/ui/)

  • cli.py — Interactive command-line interface
  • text_display.py — Rich text board rendering
  • html_renderer.py — HTML/SVG board with dark theme
  • game_recorder.py — Save/load games as JSON
  • notation.py — Bao move notation (English + Swahili)

Utils (bao/utils/)

  • opening_book.py — Opening sequence storage and retrieval
  • endgame_table.py — Retrograde analysis endgame solutions
  • state_serializer.py — GameState serialization (dict/JSON/compact)
  • move_generator.py — Comprehensive move generation utilities
  • perft.py — Performance test for move generation
  • benchmark.py — AI speed benchmarking
  • opening_analyzer.py — Opening classification and analysis
  • game_tree.py — Game tree building and visualization

Quick Start

# Clone
git clone https://github.com/drwjkirkpatrick-web/bao-la-kiswahili.git
cd bao-la-kiswahili

# Run tests
python tests/test_bao.py

# List all AI strategies
python -m bao.cli --list-ais

# Play against minimax AI
python -m bao.cli --ai minimax --depth 3

# Watch two AIs play
python -m bao.cli --ai minimax --depth 2 --ai2 mcts

# Run a tournament
python -m bao.cli --tournament minimax mcts greedy --rounds 2

# Performance test
python -m bao.cli --perft 2

Educational Use

See LESSON_PLAN.md for a 6-session curriculum designed for students ages 10–17. The curriculum covers:

  1. Bao rules and board mechanics
  2. Game state and move generation
  3. Evaluation functions and heuristics
  4. Minimax search and alpha-beta pruning
  5. Monte Carlo Tree Search
  6. Machine learning approaches (TD, Q-learning, neural nets)

Cultural Note

Bao la Kiswahili is a living tradition of the Swahili coast. It is played in Zanzibar's stone town, in the coffee houses of Lamu, and across coastal Tanzania. The game is taken seriously — there are formal tournaments and recognized masters. This implementation is an educational project intended to share appreciation for this remarkable game.

License

MIT — free for educational and personal use.

Releases

Packages

Contributors

Languages