2026-11-29
Can you write a Jai program to win Bandido 99% of the time, at interactive speed? Seems like yes. Read on or see the code (or download a copy hosted here).
"The Score" by C. Thi Nguyen was inspiring. (Ignore the misleading subtitle, which I assume an editor slapped on there. It's not a self-help book.) Like a great puzzle, it made me think, deliciously. It validates my love of games, under a broader definition including running and climbing. It makes a strong case for the profundity of these trivial activities: to paraphrase a quote referenced by the book, what would you do if you finally reached heaven or Utopia? You'd get bored and invent games. In some sense it makes me feel that I already spent much of my life in Utopia, which is quite the privilege. It also shows why "real life", for example the economy or education, is not a game. Games work because you get to choose which games you play and when. You can change the rules if it's not fun.
I like the aspects of programming and problem-solving that feel like a game. If you are good at asking questions, there is power in knowing that progress is always possible because all questions have some kind of answer (even if it's that the question is ill-posed, or required information is unavailable.)
Let's play a metagame of writing a program to play a game.
Bandido is a cooperative card game, fun for both adults and children. Buy it here. The fun is in figuring out as a group how to win. Consider playing now before I provide any spoilers.
The game is played with 1x2 aspect ratio cards, like dominos. Each has some of the six possible exits open, 2 on each long edge and one on each short edge.
The game starts with a single starting card with 5 or 6 open exits. The deck is shuffled and players maintain hands of three cards, alternately placing cards to cover two squares of an implicit grid - you must join at least one open exit of the card played with an open exit on the board. Open exits must be matched with open exits wherever cards are adjacent to one another.
In this way you build a growing system of tunnels. The players win if they close all exits. They lose if they run out of cards in the deck before doing so.
The rules specify that if no play is possible, a player returns their cards to the bottom of the deck and draws three new ones. It's not specified what happens if players enter an infinite loop of doing this; I'll assume this is a loss.
The rules specify, somewhat ambiguously, that communication between the players is allowed, but not directly revealing your hand.
The 69 cards in the deck include 2 or 3 copies of all possible cards with 1 to 4 open exits.
In my experience, players quickly recognize an obvious proxy for progress towards victory: the number of open exits remaining. This starts at 5 or 6 and must reach 0 to win. Thus, the most straightforward strategy is to try to reduce this number as rapidly as possible, avoiding playing "bad" cards with many exits when doing so will increase the number of open exits on the board.
However, the supply of "good" cards with 1 or 2 exits is low enough that playing purely to reduce the exit count usually leaves you with a small number of isolated open exits, and then being forced into playing a "bad" 3- or 4-exit card there, increasing the number of exits rapidly again.
Players then often figure out that it's worth it to try and get these "bad" cards to cancel each other out, maintaining opportunities to close off 2 exits at once with a "bad" card, thus keeping the number of open exits the same or reducing it, while concentrating "good" 1- and 2-exit cards in hand. When the time is right players can "go for the kill" together, using the "good" cards up to close off a small number of remaining open exits.
It's a nicely balanced game, in that initial play often has one wondering if it's possible to win without a lot of luck, and later play has one wondering if it's possible to always win, and how. How essential is coordination? Could you always win even if playing silently? Could you always win with a strategy which ignores what you believe other players to hold in hand?
Braid and The Witness are two of my favorite video games. They certainly qualify as art. Beautiful puzzles. Narrative elements which leave you confused enough to eventually understand they weren't the deepest point. Nonlinear, so when you get stuck you can come back.
As with Bandido, maybe don't spoiler yourself and go play!
After about a decade, the studio has released a new game, Order of the Sinking Star. I haven't played yet but have tried one of the free web games it licenses and extends, Mirror Isles (fun!).
The new game is written in a new programming language. It's officially unnamed but the compiler and file extension are "jai".
I learned about the language from this series of YouTube videos, and applied for the beta. This was a few years ago, planning to extend this project, though that hasn't happened yet.
The language seemed itself like a game I wanted to play. A compiler is something like a game - it has to run portably and performantly, and to a certain extent make it fun for the user (at least for a new language).
Like many languages, it builds on what's great about C. I adore C - I loved working with it for many years with PETSc. Its simplicity is powerful. You work with arrays of memory. If you mess that up, there is blessed Valgrind. The error messages are understandable. You can step through the code with gdb.
My love is of course related to some kinds of programming I find fun/interesting enough to care about the details:
In these, you are more or less trying to do numerical computations in parallel quickly and predictably. Compute a timestep of a simulation, fill an audio buffer, render a frame. You want it to work predictably on more than one system, but you're doing your tinkering locally in a tight loop. You probably aren't working with that many other people.
The most interesting feature of the language is its perspective on memory management. This is motivated by the observation that when making games, you can't avoid having to reason about the fact that you're working with linear arrays of bytes in memory, doled out by the operating system and accessed through elaborate cache hierarchies to mitigate the relative slowness of memory access compared to mathematical operations. Thus, you'd like to avoid the work of having to undo the conveniences put in place by approaches, very useful in other situations, which allow you to forget these details.
The implication here is that for performance, you want control over how memory is allocated and freed, and it should be made easier to do it in efficient patterns. It thus doesn't promote some common approaches like RAII, making many heap allocations, or using garbage collection.
Rather, it promotes the pattern of using custom allocators to allocate memory in large blocks and then quickly advance pointers into these blocks to dole out bits of memory, before later freeing the whole block. The applications mentioned above often give you a logical time to do that freeing.
The other feature I really appreciate is that the language goes out of its way to allow you to work in a single language. If you have the compiler, you can build the program, without having to know about Make or CMake or the C Preprocessor or C++ Templates or linker command line arguments. There are no incremental builds so at least for this sort of small project it's nice to be able to just pass a file to the compiler.
Metaprogramming is done in the language itself, which is cool. The compiler runs things in the normal language (slower, I believe, relying on byte code) during compilation, which means you can do all kinds of fun things modifying the AST. I honestly find a lot of metaprogramming to be inherently confusing and think that even here it should be used with a lot of care, but the way the language folds in on itself, I believe, is what makes it much easier to have portable memory checking and (probably) profiling, and what makes it quite easy to have the build process be specified as part of the program, not as some extra thing.
This is, then, no small feature. With the power of much more direct responsibility for memory management comes the need to examine what's happening, and it seems like these metaprogramming features could really shine there.
More comments after actually trying it are below!
So, what's our metagame?
We want to have some fun learning this new language, while trying to understand something about Bandido. Concretely,
In doing this, I hope to gain some insight into questions about the game. Are the heuristics players come up with good ones? Can you always win? How useful is communication between the players (the extremes being greedy strategy with no communication, or open hands and one player making all decisions)?
It seemed more fun to do this without asking AI to do too much for me.
Here is the resulting
code. It's based around a Game
struct.
The game state is which cells in a 2D infinite grid are occupied, and which of the edges of each occupied cell are open, plus the deck and the players' hands.
A given state only has a few places you can play cards, next to the "active" exits, so these are stored in a hash table for speed.
Once played, a card occupies two cells.
A very simple UI (just printing with bash color codes) draws the board (without retaining information about which cards were played), and lets you cycle through a list of possible moves for the active player.
A good-enough method for multithreading was to assign each possible move to a separate thread.
Similarly, a good-enough memory management approach was to allocate a single pool for the evaluation of each top-level move in each thread, and free it once finished with evaluating that move. My initial implementation used many hash tables, but these wasted memory in hot spots in the game evaluation and in the end the only ones that seem convenient are those to keep track of the occupied cells, and the set of cells with active exits. The former might well be more efficient as a fixed-size 2D array, as the board cannot become that large.
For more, in particular information on how I arrived at the autoplay, see the README.
When playing the two-player game by myself, I can usually win with a strategy informed by my personal heuristics. The UI is obviously crude, but as an analysis tool it worked great, especially as the code lets me reload games that the autoplay lost, to see why. This already gave me confidence that despite what new players often suspect, this game should usually be winnable!
I called things "done" after fiddling with parameters, fixing bugs, and optimizing until I felt I had a 99% effective (with 99% confidence) solver for the 2-player game with the 6-exit start card with some communication between players.
The good-enough autoplay solver computes a score for each game state
obtained after a possible move. It prioritizes depth, only checking the top
2 scoring moves for a given game but recursing four levels. This is of
course useful to avoid hidden traps. As discussed more in the
README, a key decision is how to avoid cheating by letting the solver
know which cards are about to be drawn. This is done by randomizing the
deck. RANDOMIZE_SOME_CARDS mode in the table below seems the
most realistic - this is intended to simulate telling your partners how
many 1- or 2-exit cards you hold, but no other details.
INVARIANT_OPPONENTS_HAND makes things easier by playing
open-handed. RANDOMIZE_OPPONENTS_HAND is meant to simulate
playing with no communication and makes things harder. Information is
hidden in these scenarios by randomizing the deck and (depending on the
mode) opponents' hands. Scores computed this way are averaged over
Realizations randomizations. With too few of these, the solver
can be misled, especially when it doesn't get a good view of nearby losing
positions.
The following table summarizes a few experiments, to show the effect of varying these parameters, and the number of players.
| Players | Realizations | Rerealization Mode | Win % | 99% Wilson CI | Avg Moves/Win | Avg Time/Game |
|---|---|---|---|---|---|---|
| 2 | 400 | RANDOMIZE_SOME_CARDS |
99.9% (999/1000) | [99.2%, 100.0%] | 19.9 | 4.21s |
| 2 | 200 | RANDOMIZE_SOME_CARDS |
99.6% (996/1000) | [98.7%, 99.9%] | 20.6 | 2.10s |
| 2 | 50 | RANDOMIZE_SOME_CARDS |
99.1% (991/1000) | [97.9%, 99.6%] | 21.2 | 0.57s |
| 2 | 400 | RANDOMIZE_OPPONENTS_HAND |
99.0% (990/1000) | [97.8%, 99.5%] | 25.8 | 5.05s |
| 2 | 400 | INVARIANT_OPPONENTS_HAND |
99.9% (4997/5000) | [99.8%, 100.0%] | 18.4 | 3.93s |
| 1 | 400 | RANDOMIZE_SOME_CARDS |
98.2% (982/1000) | [96.8%, 99.0%] | 26.9 | 5.31s |
| 3 | 400 | RANDOMIZE_SOME_CARDS |
100.0% (1000/1000) | [99.3%, 100.0%] | 16.4 | 3.29s |
Some observations from the table:
I examined the single loss in the base case in the first row. I took care in the code to make things fairly reproducible from a random seed, so the game can be replayed "live". In these cases I was most interested to see if the autoplay was doing something obviously stupid to a reasonable human player like me. Often, it was, almost always of the flavor of creating a difficult or impossible to fill internal void. The solver short circuits on the case (even flagged in the rules) that you can't win with a 1x1 void with tunnels open into it, but there are other cases with 1x2 or bigger voids that are impossible for any card, or at least any remaining card. The loss here was one of these - it chose to leave a 1x2 void with open tunnels, which is very risky. The "avoid U-shaped holes" heuristic is supposed to guard against this. An option, which might violate the spirit of not doing anything which requires rote memorization of the remaining deck, or be very slow, is to add more heuristics or even explicit checks that all remaining openings can actually be satisfied by any card left, short-circuiting the search. The bitter lesson would suggest that really what you should do is just optimize/parallelize and search deeper, though.
Is this as great a game as I thought? Yes! It starts out seeming impossible, but it now seems very winnable with the right strategy. That strategy is something humans can have fun learning and isn't totally trivial, at least as judged by requiring both some insight and some brute force for me to make a reasonable autoplay.
Is it fun to do this kind of programming in this language? Yes!
It seems to make enough smart choices re syntax and other niceties that I have nothing to say: it felt like a nice, modern language.
I started thinking in perhaps too much of an Object Oriented way, having a
Game and a DrawableGame. Better to just draw
games, modulo some pretty unimportant things like caching the bounding box.
As long as you don't get too crazy with metaprogramming it delivers on its goals of simplicity, with comprehensible error messages.
The compile time execution and metaprogramming seemed genuinely useful for
analysis purposes. My gut feeling is that metaprogramming risks being
confusing for things which aren't themselves "meta". It's great for seeing
how the "real" program works without cluttering things with instrumentation
code as much, but things can get "spooky action at a distance" very quickly
when the code that gets compiled is so different from the code you're
reading. (My only syntax gripe: why do macros look like
normal_methods() and not #like_this()?)
The built-in memory debugger was very helpful to me. Just passing the output to an LLM was enough to find any memory errors lightning fast.
Demos include some quite elaborate memory profiling. I didn't succeed in getting the IProf module to work, but achieved my modest profiling goals by using my coding agent to add some temporary, brittle, metaprogramming to profile a few functions enough to find obvious bottlenecks.
The memory management approach initially seemed like it would be error prone, but with the memory debugger and the flexibility with allocators, I have to say it's living up to the promise of being no more complex than the task at hand.
Not sure how I feel about "temporary storage". It gives me a bit of a headache to think about. The idea is that by blessing this particular storage as shared, it can be used by libraries that need small amounts of memory, and you can pick a convenient time to free the temporary storage. It makes me uncomfortable that just about anything can allocate memory without me knowing about it. In practice it's supposed to be a small amount, though, so I see the benefit of being able to use an efficient memory management system without having to think about every little twiddly byte.
It plays quite nicely with coding agents. They had no problem getting usable information from the included documentation, examples, and libraries. I thought it was especially fun to have the AI quickly parse memory reports or whip up some disposable testing or evaluation setup in a subdirectory. Without prompting, it could do things using compile-time modification of the code, e.g. for some quick regression tests. Those are brittle but I left them in the repo for interest.
Would I recommend this kind of meta-game? Yes!
As with most such ideas it took longer than I would have guessed. But I am happy to have lived for a while in this little contained world of puzzles. Just like other games, you need to decide how much cheating is fun. Sometimes you do want to look up a hint to a puzzle. Sometimes you do want to set up a fast-forward button on your emulator. Sometimes it's fun to type "porntipsguzzardo". Sometimes you do want the AI to find your bug for you. Sometimes you do want your AI to come up with some theories for you to think about. Sometimes you want to do your own writing, because, like a game, it's a way to live in a little world, to learn about it as you work.
Maybe I will return for another round of this game sometime, to examine some of my open ideas. I may even see what a frontier AI model comes up with if I ask it to do more of the thinking for me, but only when I understand better why that would be a fun game to play.