Skip to content
All writing

One rules engine, two places to run it

How Tujuh keeps pass and play and online games from ever disagreeing.

Tujuh is a card game you can play two ways: on one phone passed around the table, or online with a room code. The first runs on the phone. The second runs on a server. That is two places the rules could live, and two places for them to drift apart.

So the rules live in neither. They live in a small TypeScript package with no dependencies, and both the phone and the server run the same copy.

Everything is one function

Every move in the game goes through a single reducer:

reduce(state, action) → newState

It is pure. No network, no clocks, and no randomness except a seeded generator stored in the state itself. Give it the same state and the same action and you always get the same result. That one property is what makes it safe to run anywhere, and easy to test.

Three ideas do the work inside it. A pending field says whose decision it is right now, and anything that does not match is rejected ("Not your turn"). An effects queue holds what still has to happen, so drawing a Flip Three simply pushes three flips to the front of the queue. And an events list records what just happened, like "Chen busted on a second 10", which the app turns into animation, sound and the narrator line.

The server is the referee

Online, each room is a Cloudflare Durable Object that holds the real game and runs the same reducer. Phones never get the deck order or the random seed; they only see a public view of the table. The seed comes from the server’s cryptographic random source, so nobody can predict the next card.

A move arrives over the room’s WebSocket, and the player it belongs to comes from the socket, never from the message. You can only ever move for yourself. After each accepted move the room saves itself and sends everyone the new public state.

How I know it works

Because the rules are just a function, the tests can play the game. Alongside a test for every card and rule, a simulation plays 300 random Classic games and 300 random Vengeance games, and after every single move it checks that no card was lost or duplicated and that the scores still add up. Bots play whole games in every mode to prove nobody ever gets stuck.

The app ends up being a renderer. It sends intents and draws whatever comes back, which leaves all of its effort for the part people feel: the card coming up big, turning over and landing in your line.