Inventing card games with an 82 KB model on the M5Stack CoreS3
Card Maker invents a new card game for a standard deck, explains the rules and plays it against you, all on an M5Stack CoreS3. An 82 KB model on the ESP32-S3 writes the rules. A rules engine on the same chip tests them b
Card Maker invents a new card game for a standard deck, explains the rules and plays it against you, all on an M5Stack CoreS3. An 82 KB model on the ESP32-S3 writes the rules. A rules engine on the same chip tests them by playing 100 games against itself before you see them, and then plays you.
It uses the same kind of model as my first post. This post covers what's different about it: a model that writes structured rules rather than text, decoding that can only produce valid rule sets, training data that the engine invents and tests itself, and a computer opponent that can't see your cards.
The code and model are here:
- esp32-card-maker on GitHub
- jmclean/esp32-card-maker on Hugging Face
| Invent a game | Read the rules | Play |
|---|---|---|
![]() |
![]() |
![]() |
What it makes
Two-player games in four families, each with many variations:
- Shedding (like Crazy Eights): be first to play all your cards. Which cards may follow which, what happens when you're stuck, and which ranks have powers (wild, skip, draw two, swap hands...) all vary.
- Tricks (like Whist or Hearts): win the most tricks, the fewest, or avoid hearts, with or without trumps and following suit.
- Collecting (like Rummy): draw and discard until your hand is all sets and runs.
- Capturing (like Scopa or Casino): take cards from the table by matching rank or by adding up.
Every game gets a name, a rules screen you can open during play, and you can save up to 24 you like.
| Collecting | Capturing | Saved games |
|---|---|---|
![]() |
![]() |
![]() |
A model and an engine
The model is 82 KB: 148,576 parameters at 4 bits each. The other ESP32 text models on Hugging Face are mostly 1 to 15 MB, so this is 12 to 180 times smaller. It's a fifth the size of the Sprite Maker model, and it would fit in the ESP32-S3's 512 KB of internal RAM several times over. It can be that small because its job is narrow. It doesn't have to know what a card game is, explain the rules or play. It only picks a value for each rule. The engine does everything else:
- The model writes a rule set, one token per rule. This takes 0.2 to 0.5 seconds on the device.
- The engine tests it by playing 100 quick games against itself. If the games don't end, are too short or too long, favour the first player, or end in too many draws, the model writes another. That happens to about 1 in 20 of the model's rule sets, against nearly 1 in 4 for random rules.
- The engine writes out the rules for you to read. They come from the same rule set it plays by, so they always match the game.
- The device plays you.
The engine (engine/) is plain C++, so the same source runs on the device and on a computer. That's what made generating and testing thousands of rule sets practical.
Step 1: rules as tokens
Inside the engine a rule set looks like this:
{
"name": "Crow's Gambit",
"family": "shed",
"deck": {"jokers": 2, "remove": []},
"deal": 7,
"shed": {
"match": ["suit", "rank"],
"stuck": "draw_one",
"powers": {"8": "wild", "2": "draw_two", "J": "skip", "joker": "wild"}
},
"scoring": {"type": "cards_left", "target": 50}
}
For the model it's a sequence of tokens, one per field, each token holding both the field and its value: family=shed, deal=7, match_suit=1, power_8=wild, and so on. There are 215 of them. Each family's fields always come in the same order (training/grammar.txt):
family=shed deck jokers deal match_suit match_rank match_colour match_higher match_adjacent stuck power_2 power_3 power_4 power_5 power_6 power_7 power_8 power_9 power_10 power_J power_Q power_K power_A power_joker scoring target name_a name_b
family=tricks deck deal trump follow goal scoring target name_a name_b
family=collect deck deal meld wild scoring target name_a name_b
family=capture deck deal table capture aim sweep scoring target name_a name_b
A shedding game is the longest, at 28 tokens. The tokens map one to one onto the JSON, so the engine can turn tokens into rules and back with no guessing.
Why tokens like match_suit=1 instead of the model writing JSON? A model writing JSON character by character would need to learn the syntax, could get it wrong, and would need a much longer sequence. One token per decision keeps every step a real choice about the game.
Step 2: training data the engine makes itself
There's no collection of card game rules in a form a program can play. So the engine makes its own.
host/gen_data.cpp writes random rule sets and tests each one with test_rules() from engine/rulegen.h. First, 300 games of random play:
if (rep.unfinished > games / 100) { rep.why = "games do not end"; return rep; }
if (rep.mean_turns < 10) { rep.why = "games are too short"; return rep; }
if (rep.mean_turns > 120) { rep.why = "games are too long"; return rep; }
if (first < 0.35 || first > 0.65) { rep.why = "the first player has too big an edge"; return rep; }
if (rep.draws > games / 4) { rep.why = "too many draws"; return rep; }
A game that passes those is playable, but it might be pure luck. So there's a second test: does skill matter? Beating a random player proves little, because nobody plays at random. Instead, a Monte Carlo player that thinks hard (20 playouts a move, explained in Step 6) plays one that barely thinks (2 playouts a move), 40 games, half in each seat:
for (int g = 0; g < mc_games; g++) {
int me = g & 1;
State s = deal(r, rng, g >> 1 & 1);
while (s.winner < 0)
apply(s, s.to_move == me ? monte_carlo_move(s, rng, playouts) : monte_carlo_move(s, rng, 2), rng);
score += s.winner == me ? 1 : s.winner == 2 ? 0.5 : 0;
}
rep.mc_vs_random = score / mc_games;
if (rep.mc_vs_random < 0.6) { rep.why = "skill barely matters"; return rep; }
If thinking harder doesn't win at least 60% of the time, the game is mostly luck, and it's thrown away.
Picking the best
18,000 random rule sets were tested this way, about 45 minutes on an 8-core laptop. 10,452 passed. Each one that passes gets a score:
double score = rep.mc_vs_random + 0.5 * (1 - 2 * std::fabs(first - 0.5)) +
(rep.mean_turns >= 20 && rep.mean_turns <= 60 ? 0.25 : 0);
That's how much skill matters, plus up to 0.5 for being fair to both players, plus 0.25 for games of 20 to 60 turns.
training/prepare_rules.py then keeps the best half of each family, ranked separately. Ranked all together, shedding games, which score lower on skill, would mostly be dropped, and the model would invent almost only trick games. That leaves 5,226 rule sets. The smaller families are repeated (up to 15 times) so each family makes up a fair share of the training.
So the model learns from rule sets that were already tested and better than average. It isn't learning card games from people. It's learning which corners of the engine's rule space make good games.
Step 3: training
The model is the same kind as the others in this series: a transformer in the per-layer embedding layout from slvDev/esp32-ai, with 4-bit weights on the device. It's just much smaller: 4 layers, 64 wide, 148,576 parameters, 99,424 of them in the transformer core. The context is 32 tokens, enough for the longest rule set.
ESP32AI_DEVICE=cpu ESP32AI_DATA=data/rules ESP32AI_ALIGN_EOT=0 PYTHONPATH=src \
.venv/bin/python research/tinystories/train.py --arm ple --vocab 256 --d-model 64 --n-layers 4 \
--n-heads 4 --ple-dim 32 --target-core 100000 --batch-size 64 --seq-len 32 --steps "$STEPS" \
--eval-every 500 --tag rules
3,000 steps of 64 rule sets each, with AdamW and a learning rate of 1e-3 that warms up over 200 steps and then falls along a cosine curve. It trains on a laptop CPU, with no GPU (ESP32AI_DEVICE=cpu, one of the options in my fork of slvDev's trainer), and takes about a minute. The Sprite Maker model took 35 minutes for its first stage alone. Here the slow part isn't training at all: testing 18,000 rule sets to make the data takes 45 times longer than training on it.
Step 4: decoding that can only write valid rules
A model left to itself could write deal=7 twice, skip stuck, or put a tricks field in a shedding game. The engine would reject those, and the device would waste time asking again.
So decoding is constrained. At each step only the tokens for the next field are allowed. Step 0 allows only family=... tokens. After family=shed, the next step allows only deck=... tokens, then jokers=..., and so on down the field list. Everything else gets a probability of zero:
if (step == 0) snprintf(prefix, sizeof prefix, "family=%s", family >= 0 ? FAMILY_NAME[family] : "");
else if (step - 1 < RULE_N_FIELDS[fam]) snprintf(prefix, sizeof prefix, "%s=", RULE_FIELD[fam][step - 1]);
else break;
size_t n = strlen(prefix);
float mx = -1e30f, sum = 0.f;
for (int v = 0; v < RULE_VOCAB; v++)
if (!strncmp(RULE_TOKEN[v], prefix, n) && sc.logits[v] > mx) mx = sc.logits[v];
static float pr[RULE_VOCAB];
for (int v = 0; v < RULE_VOCAB; v++) {
pr[v] = strncmp(RULE_TOKEN[v], prefix, n) ? 0.f : expf((sc.logits[v] - mx) / temperature);
sum += pr[v];
}
The model still chooses the value. It just can't choose the field. Every rule set it writes is complete and well-formed. When you ask for a particular kind of game, step 0's prefix becomes family=tricks and the rest follows.
The temperature (which divides the model's scores before they become probabilities) is 1.3. Above 1 flattens the choices, so less likely values are picked more often. I measured what that does with 400 games at each temperature, using the same model and decoding as the device:
| Temperature | Different games | Repeats outside shedding | Device accepts | Skill matters (of accepted) |
|---|---|---|---|---|
| 0.7 | 285 | 35% | 96% | 72% |
| 1.0 | 313 | 28% | 95% | 70% |
| 1.3 | 318 | 27% | 93% | 71% |
| 1.6 | 330 | 22% | 92% | 68% |
| 2.0 | 340 | 19% | 90% | 73% |
Raising it mostly buys variety. At 0.7 about a third of the trick, collecting and capturing games are repeats; at 2.0 about a fifth are. Shedding games rarely repeat at any temperature, because of all the power combinations. The cost is a few more rule sets failing the engine's checks, 10% at 2.0 against 4% at 0.7. Whether skill matters doesn't change: about 70% of accepted games pass the skill test at every temperature.
The quick test on the device
The full test takes too long on the device, so it runs only the random-play checks, over 100 games instead of 300, and skips the skill test. That's a fair trade because the model learnt only from rule sets that passed the skill test, so most of what it writes passes it too (next section).
Step 5: naming the game
Every game gets a name like "Cold-Hearted Parley" or "Wild Scramble". The name comes from the rules, not the model. rule_name() hashes the rule set's JSON (FNV-1a), then uses the hash to pick an adjective and a noun from word lists that depend on the rules:
inline std::string rule_name(const Rules &r) {
Rules plain = r;
plain.name = "";
uint32_t h = 2166136261u;
for (char ch : to_json(plain)) { h ^= (uint8_t)ch; h *= 16777619u; }
auto pick = [&](const std::vector<std::string> &v) { std::string w = v[h % v.size()]; h /= 7; return w; };
...
if (r.family == SHED) {
noun = {"Rush", "Dash", "Scramble", "Race", "Getaway", "Shuffle", "Sprint", "Stampede",
"Bolt", "Flurry", "Dump", "Exodus"};
Shedding games are a race to empty your hand, so their nouns are words like Rush, Dash and Scramble. The adjective depends on the rules: a game with wild cards can be "Wild" or "Joker's", one with draw cards "Pile-Up" or "Stacking", one with hand swaps "Swapper's" or "Trading". The same rules always get the same name, so a saved game keeps its name.
Step 6: playing you without looking at your cards
The device plays with Monte Carlo search. For each legal move, it plays the rest of the game out to the end many times with random moves (each one a playout), and picks the move that won most often:
inline Move monte_carlo_move(const State &s, Rng &rng, int playouts_per_move) {
std::vector<Move> moves;
legal_moves(s, moves);
if (moves.size() == 1) return moves[0];
int p = s.to_move;
float best = -1;
Move pick = moves[0];
for (const Move &m : moves) {
float score = 0;
for (int i = 0; i < playouts_per_move; i++) {
State g = guess(s, p, rng);
apply(g, m, rng);
score += playout(g, p, rng);
}
if (score > best) { best = score; pick = m; }
}
return pick;
}
It doesn't need to know any strategy for the game. It only needs the rules, which the engine already has. That's why it can play a game nobody has played before.
The important line is guess(). The device knows your cards, because it's running the game. Playing out from the real state would mean playing with your hand face up. So before each playout it makes a copy of the game as it could know it: your hand and the draw pile are shuffled together and dealt back out, so your cards are guessed, not seen:
// A copy of the state as player p could know it: the other hand and the stock are
// shuffled together and dealt back out, so the opponent's cards are guessed, not seen.
inline State guess(const State &s, int p, Rng &rng) {
State g = s;
int o = 1 - p;
if (s.peeked[p]) return g;
std::vector<Card> unknown(g.hand[o]);
unknown.insert(unknown.end(), g.stock.begin(), g.stock.end());
rng.shuffle(unknown);
size_t n = g.hand[o].size();
g.hand[o].assign(unknown.begin(), unknown.begin() + n);
g.stock.assign(unknown.begin() + n, unknown.end());
return g;
}
The one exception is the "peek" power in shedding games, which lets a player see the other's hand until their next turn. Then it really does know.
On the device it uses 200 playouts a move, or 40 in collecting games, where checking for sets and runs makes each playout slower.
How many games?
Counting every rule set the model can write that the engine accepts, there are about 59 quadrillion (5.9 x 10^16) possible games. Playing one every five minutes, day and night, would take about 560 billion years, 40 times the age of the universe. That ignores the name, powers on ranks a 32-card deck removes, and a joker's power when there are no jokers.
Most of that is shedding games. Each of the 13 ranks can have one of 8 powers (including none), which alone gives 8^13, about 550 billion. Tricks, collecting and capturing come to about 29,000 between them. Because training repeats the smaller families, the model still picks the four about evenly: in 400 games from the computer version, each family came up between 21% and 30% of the time.
Many are close variants, such as the same game with a different deal size, and not all pass the engine's tests.
How good is it?
400 rule sets from the model at temperature 1.3, against 400 from the random generator. First with the full self-play test (host/eval_rules.cpp). Then the way the device works: its quick checks, then the skill test on whatever those let through (host/filter_eval.cpp):
| Model | Random rules | |
|---|---|---|
| Pass the full test | 70% | 50% |
| Device accepts | 95% | 77% |
| Of those, skill matters | 74% | 68% |
The model's main gains are fewer rejected ideas, and more games where playing well pays off. By family, of the rule sets the device accepts, skill matters in:
| Family | Model | Random rules |
|---|---|---|
| Shedding | 38% | 28% |
| Tricks | 72% | 65% |
| Collecting | 100% | 100% |
| Capturing | 90% | 68% |
Capturing games improved most. Shedding games are the hardest to get right: with so many powers, a lot of combinations turn into a game decided by who draws the wild cards.
Two limits are worth saying plainly. The model can only invent within the engine's rules, so its games are variations on familiar ones. And "good" here means the game ends, is fair and rewards skill, as measured by computer players. Whether a game is fun isn't measured.
Run it
On your computer
host/play.cpp loads the same model file and runs the same inference code, sampling and rules engine as the device, and plays you in the terminal:
c++ -std=c++17 -O2 -Iengine host/play.cpp -o play
./play
It invents a game, prints the rules, then lists your legal moves each turn: type a move's number, r for the rules or q to quit. ./play -f tricks asks for a kind of game (shed, tricks, collect or capture), -s 7 sets the seed, and --watch has the computer play both sides.
On an M5Stack CoreS3
From firmware/, with PlatformIO:
pio run -e m5stack-cores3 -t upload_model
pio run -e m5stack-cores3 -t upload
The model goes into flash at 0x890000, inside the model partition shared with the other apps' models. Over serial at 115200 you can play by typing invent, play 3 (card 3 of your hand), draw, suit hearts, next or rules. tools/serial_play.py plays a game from a terminal.
Train it yourself
- Clone my fork of esp32-ai at the commit this model was trained with, and set up its environment:
git clone https://github.com/justinmclean/esp32-ai.git ~/esp32-ai
git -C ~/esp32-ai checkout 75bc998
- Point
ESP32AIat it (the default is~/esp32-ai) and make the training data. Nothing is downloaded. This tests 18,000 random rule sets, about 45 minutes on an 8-core laptop:
training/make_data.sh
- Train and export the model into
firmware/model, about a minute:
training/train.sh
What I'd tell someone starting out
- Give the model the narrowest job you can. It picks rule values; the engine explains, tests and plays. That's why it fits in 82 KB.
- One token per decision. Don't make a small model learn a syntax.
- Constrain the decoding. If only some tokens are valid at a step, only allow those. Every output is then usable.
- If there's no data, a simulator can make it. The engine invented 18,000 rule sets, tested them by self-play, and the model learnt from the best.
- Test for what you care about, not just what's easy. Games that end and are fair aren't enough; a skill test threw out games that were only luck.
- Rank within each category. Ranked all together, one family would have crowded out the rest.
- Monte Carlo search plays any game you can simulate, including ones invented a second ago. Guess the hidden cards, don't peek.
Links
- esp32-card-maker: code, engine, firmware, training scripts and the model
- jmclean/esp32-card-maker: the model and model card
- slvDev/esp32-ai and my fork: the model layout, trainer and inference code
- Training a tiny model for the M5Stack CoreS3: the first post, with Recipe Maker
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.




