BlogRico Zuñiga

AI & Engineering · Rico Zuñiga

From 2003 Rule-Based Bots to Reinforcement Learning: How Tongits.io’s AI Evolved

Back in November 2003, I released a free desktop Tong-its game written in C++ with a simple set of hand-coded rules running the computer opponents. More than twenty years later, the Barangay AI Bots on Tongits.io are neural agents trained over millions of self-play hands using the same hidden-card rules you play. This is the story of how those bots went from a six-step checklist to opponents that actually learn the game.

A 2003 screenshot of the original C++ Tong-its game on a blue-green table: two opponents’ face-down cards and exposed melds at the top, the discard and draw piles in the centre, the player’s hand and revealed sets at the bottom, and Dump, Show, Chow, Call and Menu buttons on the right.
The original 2003 release (github.com/ricoz/tongits): C++, SDL, and a rule-based AI that ran on desktops and later community ports for Amiga, AROS and Haiku.

2003: A Six-Step Checklist

In 2003, building a playable Tong-its opponent meant hand-writing a small expert system: a fixed list of rules deciding every move. In the original ricoz/tongits codebase, every computer turn ran through the exact same sequence:

if (pDeck.CanChow(mIdx))
    this->Chow(pDeck);
else if (pDeck.mAggressiveRobot && this->CanCall() && !pDeck.Nasapawan[mIdx])
    this->Call(pDeck);
else
    this->GetNewCard(pDeck);

while (pDeck.FindValidSet(mIdx)) Show(pDeck, -1);
while (AutoSapaw(pDeck)) {}
pDeck.FindHighestRank(mIdx);
Dump(pDeck);

In plain English: always Chow if you can, call Fight whenever the aggression flag is on, otherwise draw from the deck, immediately expose every valid meld, lay off every possible Sapaw, and dump the highest card left in hand.

For a free desktop game in 2003, it was fun enough to sit down and play a few hands. Community members even ported it to Amiga, AROS and Haiku.

Still, anyone who plays real Tong-its spots the limits within ten minutes. A scripted bot never holds back a Secret meld to hide how close it is to going out. It never passes on a Chow that would lock it into an awkward hand or tip off the table. It dumps a King even when a Queen and Jack of the same suit sit right next to it, and it has no feel for when a Fight is a bluff or a trap.

Why Rules Alone Hit a Wall

Tong-its is a three-player game with hidden information. You only see your own hand, the exposed melds, and the discard trail, never what the other two seats are holding. The right move shifts constantly depending on how many cards remain in the deck, who has already dropped a meld, who is at risk of getting burned (Sunog), and what your previous discard just gave away.

You can try patching a rule-based bot with more if statements: hold Secret melds early, avoid discarding near an opponent’s Chow, estimate deadwood before calling Fight. Pretty quickly those rules start fighting each other, and the bot still plays the same predictable line every hand.

Switching to Reinforcement Learning

When I started building Tongits.io, I wanted the bots to learn Tong-its the way good human players do: by playing millions of hands and seeing what actually wins Zilis and avoids a burn.

Instead of writing tactics by hand, we train neural policy networks with Proximal Policy Optimization (PPO) through self-play directly against the game’s real rules engine. An agent starts knowing only which moves are legal, then plays millions of hands against past and current versions of itself. Our reigning champion, Pepper X, came out of a 3-million-hand self-play run.

A live Boss table on Tongits.io with two AI opponents seated at the top corners, melds laid out in the centre panel, and the player’s hand fanned along the bottom dock.
A live Boss table on Tongits.io: every RL bot plays from the same hidden-card view a human seat gets.

No peeking

Every bot sees only its own hand, exposed melds, discard history, and opponent card counts.

No rigged decks

The server shuffles once per hand, and bots run on the exact same deal and rules engine as human players.

Learned, not scripted

Self-play teaches when to hide a meld, pass on a tempting Chow, race for a Fight, or shed deadwood early.

Under the Hood: Five Engineering Choices

Getting RL agents to play well in a live web game took a few deliberate architecture decisions:

  1. Training on the real TypeScript rules engine. Self-play workers run directly against the same TypeScript game engine that powers production tables. Python handles neural network training, while the engine enforces every rule, so there is never any drift between simulation and live play.
  2. Optimizing for Zilis, not raw win rate. Win rate can be deceptive in Tong-its: a player can win often and still bleed chips to Sunog penalties or mistimed Fights. Our models optimize for long-term expected table payouts and Match Pool carries.
  3. Action masking over penalties. Illegal moves are masked out before the model selects an action using exact engine state guards, so training spends zero time on invalid moves and converges much faster.
  4. Sub-millisecond in-process serving. Trained models export to ONNX and run directly inside the game server via onnxruntime-node. A forward pass takes under a millisecond, with natural ~1.5-second turn pacing added on top so tables feel human.
  5. Seed-paired promotion gates. No candidate ships on training loss alone. Every challenger has to clear a seed-paired duplicate benchmark of 5,000 hands against the reigning champion at 2-sigma statistical superiority before reaching live tables. That is how Pepper X earned its crown, and we publish the trained champion and persona ONNX models openly on Hugging Face.

What the AI Learned on Its Own

None of the tactics below were programmed in. They surfaced on their own during self-play once the agents started playing for real expected payouts:

Meld concealment (Anti-Sapaw)

Instead of laying down sets right away, the agent keeps completed melds hidden so opponents cannot dump deadwood onto them via Sapaw, revealing just in time to avoid a burn.

Skipping self-Sapaw to keep Fight open

Laying off a card onto your own exposed meld locks you out of calling Fight on your next turn. Without any rule telling it to, the agent learned to skip legal self-Sapaw plays when it wants to call Fight next.

Sunog starvation & early Fights

When an opponent has no exposed melds past mid-game, the agent hoards flexible middle connectors (6s, 7s, 8s) and calls early Fights to collect the burn bonus before they can drop a meld.

Bluff Fights & bait discards

The policy tracks the 52-card discard trail to estimate live outs, holds high-potential runs instead of blindly dumping Kings, and occasionally calls Fight with borderline deadwood to push cautious seats into folding.

2003 vs. Tongits.io at a Glance

2003 Rule-Based AITongits.io RL Agents
Taking a ChowAlways Chows whenever the top discard forms a meld.Weighs deadwood reduction against exposing information and giving up a blind draw.
Exposing meldsReveals every valid meld immediately.Decides whether to expose early to avoid a burn or hold a Secret meld for leverage.
DiscardingDumps the single highest-rank card left in hand.Balances deadwood points, near-meld potential, and what opponents are likely chasing.
Calling FightSingle boolean flag (aggressive on or off).Times Fight calls and folds from deck depth, opponent card counts, and hand strength.
Table personalityOne uniform computer opponent.Rookie, Regular and Boss tiers with distinct playstyles, finite Zili purses, and live records.

From One Policy to a Living Barangay

In the Philippines, a barangay is a local neighborhood or village community, the kind of place where regulars gather around a card table and quickly learn each other’s habits. A single optimal bot would feel robotic if every seat played the same way, so we built the Barangay AI Bots to feel like a real neighborhood of players.

Each bot pairs a trained RL policy with its own persona archetype, temperature setting, and skill tier, from forgiving Rookies to high-purse Bosses running our strongest champion models (including Boss Jev, powered by TypeSafe’s System One judgment model alongside Pepper X). To keep the economy fair, Easy difficulty is restricted to free Friendly tables, while staked tables scale up to full-strength Expert and Boss opponents.

Every bot also plays with a finite Zili wallet of its own. Drain a bot to zero and it does not quietly refill with infinite chips. It falls into the AI Graveyard, permanently recording who landed the final blow.

The Barangay AI Bots directory on Tongits.io showing Bosses Magayon and Bacobaco with their Pepper X Trained Champion tags, RL Brain Policy disclosures, Zili purses, and win records.
The modern Barangay AI Bots roster: live purses, win rates, champion models, and inspectable RL brain policies.

Try Them at the Table

Building the 2003 version showed me how hard it is to capture the feel of a real Tong-its table with hand-written rules. Training agents with reinforcement learning finally got us there: opponents that read the table, adjust to the hand, and play fair without ever seeing your cards.

Browse the live roster on Barangay AI Bots, check out our head-to-head TypeSafe Jev vs. Pepper X benchmark, or deal a free hand and see how you hold up.

v1.14.0-228b0ae