Latest pachinko-pybind: 0.10.0
Bot Development
Build bots that compete in live multiplayer games. Bots run on your own machineand connect to the Pachinko servers over WebSocket using a per-bot token. Write a deterministic Python script, or load a reinforcement-learning checkpoint — the runtime is the same.
Overview
Each bot is a Python process you start yourself with a token issued by this site. The SDK opens a long-lived connection to the matchmaker, waits for an assignment, and drives one game at a time. When a game ends the SDK keeps the session open and waits for the next match, so a single process can play indefinitely.
Deterministic (.py)
Subclass Bot, implement on_tick(state), return a list of actions. Full control, no training required. Good for rule-based strategies.
RL agent (.py)
Train any model using pachinko_gym (Gymnasium wrapper). Load your weights inside on_game_start and run inference in on_tick— full freedom over architecture and framework.
Quick start
1. Go to My Botsand create a bot. Copy the token shown to you — it is only displayed once. Then top the bot up from your wallet: it needs at least 2,000₿ to connect and each match costs a 1,000₿ buy-in (see Matchmaking & chips).
2. Install the SDK and write a script that connects with your token:
from pachinko_sdk import Bot, run_online, AttackMove, ToggleSpawn
class MyBot(Bot):
def on_tick(self, state) -> list:
actions = []
for b in state.my_buildings:
if b.kind in ("squarracks", "circhery", "triables") and not b.spawn_toggle:
actions.append(ToggleSpawn(b.id, True))
if state.enemy_buildings and state.idle_units():
t = state.enemy_buildings[0]
for u in state.idle_units():
actions.append(AttackMove(u.id, t.x, t.y))
return actions
if __name__ == "__main__":
run_online(MyBot(),
orchestrator_url="https://pachinko-rts.com/orchestrator",
bot_token="bot_...paste_your_token_here...")3. Run it. The bot stays connected and plays match after match until you stop it. Watch it in action on the Spectate page.
Matchmaking & chips
How a match forms
As soon as your bot connects it joins the same queue as human players. A lobby has up to 8 seats and launches when either the lobby is full or 20 secondshave passed since the last human or SDK bot arrived (each new arrival restarts the window). Any seats still empty at launch are filled with the server's built-in AI, so you never wait for other people to show up — a typical wait from waiting for match assignment to matched into gameis about 20–30 seconds.
The server runs at most 12 matches at once. If it is at capacity you stay in the queue until a match ends (the SDK keeps polling; no action needed). Lobbies that contain humans go through a 30-second accept step first — if someone declines, the lobby is cancelled and your bot silently returns to the queue. Lobbies with no humans skip that step and start immediately, with two caveats: a few of the 12 slots are always kept for lobbies that include a human, and a bot-only lobby is held back while the built-in AI pool is running low, so humans queueing later still get full lobbies.
Limits per account: 5 active bots and 3 connected at a time (a fourth connect gets HTTP 429). Bot-only lobbies run under a 15-minute time cap instead of 60, and any match where no human or SDK bot has issued a unit command for 6 minutes ends early as abandoned (score tiebreak, exact ties refund the stakes). A bot that only bets and never moves its units will hit that.
One seat per account per match. Your hand play and your bots are one account, and a match never seats two of them: you never meet your own bot, and two of your bots never play each other. When several are waiting, the first takes the seat and the others go into the next lobby with their place in the queue kept. Offline, run_local_series refuses such a match unless you pass allow_shared_account=True (SDK 0.9.9).
A match runs until one player is left standing (everyone else eliminated or folded) or until the 60-minute time limit, when the highest score wins. With forever=True (the default) the SDK re-queues after every match; pass forever=False to run_online to play exactly one.
Three balances
Chips (₿) live in three places:
- Your wallet— your account balance (10,000₿ sign-up bonus). Also used for spectator betting.
- Bot balance— each bot has its own bankroll, which starts at 0. Move chips in (and back out) from My Bots. A bot needs at least 2,000₿ to connect; below that the orchestrator rejects the session with HTTP 402 and the SDK logs
Insufficient bot balance. - In-match stack — every match takes a 1,000₿ buy-in from the bot balance and hands the bot a 1,000-chip stack to bet with. Whatever is left in the stack at the end goes back to the bot balance.
So one match costs at most 1,000₿, and your net result is simply final stack − 1,000. A settlement of −200means you posted 200 chips in blinds and calls and won nothing back; a bot that folds out of every hand loses only its blinds. The match pot is zero-sum between the players — no rake is taken from it (the 5% house rake applies only to spectator betting pools).
How chips move during a match
Betting is poker-style with blinds of 50 / 100. There is a pre-game round (round 0, after the item mulligan — rerolling items also costs chips from your stack) and then a further round every 5 minutes of game time; the RTS pauses while a round is open. On your turn you have 30 seconds to answer via on_bet_action, otherwise you are auto-folded. Folding is permanent for the match: you forfeit your share of the pot and your units stop accepting commands.
All rounds accumulate into one pot, which is settled by finishing position when the match ends: 70 / 20 / 10%to 1st / 2nd / 3rd (renormalised when fewer positions are paid — the last-placed player never earns from it), plus a bounty of one small blind (50) per elimination you cause, taken off the top. The breakdown is delivered to on_match_settled and logged as match settled: pot ... payout ... rank ....
Installation
One package, both modules
pip install pachinko-pybindPython 3.9+ required. pachinko-pybind is a single pre-built wheel that ships two Python modules: pachinko_sdk (the live-server client used by every bot) and pachinko_gym(Gymnasium environment used for offline RL training). The game simulation runs in compiled Rust under the hood — no source build needed. requests, websocket-client, and numpy install automatically.
Optional: training extras
For RL training you'll also want a learning library. The examples below use stable-baselines3 / sb3-contrib:
pip install "pachinko-pybind[train]"Versions & upgrades
Keep pachinko-pybind up to date — latest is 0.10.0, and the matchmaker requires at least 0.10.0:
pip install -U pachinko-pybindThe matchmaker enforces the minimum version at connect time (an outdated SDK gets HTTP 426 with an upgrade hint). Releases are backwards-compatible unless the release notes say otherwise, so upgrading is always the right move.
What's new
0.10.0 — one stat list for people, bots and the houselatestrequired
Bots now get exactly the numbers a person sees on the cards at the betting table, the watch page and the profile pages: the same list, labels and definitions (docs/STATS.md), for the seat and for the account behind it, and nothing else. A breaking release: fields were removed and the BettingEnv vector changed.
Profiles (PlayerProfile, the wire, fetch_profile)
- New:
hands_won_rate(share of hands won outright: the last seat standing, by battle or by everyone else folding),pnl_per_hand,recent_pnl(the last 10 finished hands, newest first).three_bet_rateandcheck_raise_rateare now filled at the table too (they were None there). net_pnlis the ledger's P&L over finished hands: the same number as the leaderboard and the profile pages.- Removed:
wins,win_rate,firsts,first_place_rate,wins_by_battle,wins_by_foldout,podium_rate,avg_placement,recent_placements,betting_net_pnl,fold_to_big_raise,mid_raise_rate,heads_up_rate,win_rate_heads_up,win_rate_multiway, and their sample sizes. No surface shows them, so no bot gets them.hands_won_rate * matchesis the oldwins. pachinko_sdk.view.STATSis the list itself (key, attribute, label, definition, format, who on the house side reads it), shipped aspachinko_sdk/player_stats.json;PlayerProfile.stat(key)reads one stat by wire key or attribute, None where the cards show "-".shrunk()takes"shove_rate"or"open_size": the two recent rates on the list, and the two the house AI reads.wideness()is unchanged.profile_from_stats/fetch_profileread the stats payload'sseatProfile, the object the table carries. The payload'splaying,habitsandhabitsStateblocks carry the list only;habitsStateholds the Shoves and Opens for pairs, whichProfileAggregator.load_stateaccepts.- Offline,
ProfileAggregator.profile()returns the same shape: Last 10 hands from thenet_chipsyou pass toupdate, 3-bet and check-raise per betting round. The bundled live profiles (LocalBettingMatch's default seats) were refreshed on 2026-12-02.
Betting bots
BettingEnvper-seat features follow the list (PER_SEAT 40 -> 52): the board and table-betting features first (0-19), then whether the seat has an account (20), the seat's stats (21-35) and its account's (36-50) in the cards' order (PROFILE_FEATURES: Hands, Hands won, P&L, P&L per hand, Last 10 hands, VPIP, PFR, 3-bet, check-raise, Folds, AF, Wins by pressure, Shoves, Opens for, and the rated hands behind the last two), and the house's wideness read (51). Retrain policies on it.BettingEnv(features="v1"),BettingFeaturizer(features="v1")andPolicyBettor(features="v1")keep the 0.9.8-0.9.10 vector for this release, so a trained policy still runs: the win-rate slots (14, 33) read Hands won, the podium-rate (15) and average-placement (16) slots read 0. The "v1" layout goes in the next release.- The house bettors' reputation term reads Hands won (the same number as the
wins / matchesit read); the mid-game raise term (mid_x, weight 0) is gone.FormBettortilts its prior by the share of the Last 10 hands in profit instead of the recent placements.
Older SDKs keep working against the 0.10.0 server, but read 0 / None for every removed field.
0.9.10 — wins and firsts agree; the house's wideness bit for bit; LMSR takes the server's dead outcomes
Profiles
winsare outright wins (the last seat standing:winsByBattle + winsByFoldout) andfirstsare 1st places, which also counts a 1st shared in a drawn match (an exact score tie at the time limit, the last seats knocked out on the same tick). Sofirsts >= wins, equal but for draws, on the site and offline alike. Until now the site'sfirstsleft out every match recorded before placements were (2 July 2026), so an older seat'sfirststrailed itswinsby its pre-July wins and itsfirstPlaceRate/winRateread low (a house AI: 681 firsts for 768 wins). Those matches now count their winner as 1st, andpodiumRateis over the matches with a placement, asavgPlacementalready was. Offline, a 1st shared in a draw no longer counts inwins(it stays infirstsandwinRate).PlayerProfile.wideness()returns the house's number exactly. The engine reads profiles in float32; the SDK computed in float64 and differed by ~1e-8 fromProfileAggregator.wideness().shrink()andprofiles.wideness()stay float64.- Docs:
import_identitycopies one identity and its account LINK, not the account's data; copy the account identity too or the copy reads without it. And a new bot is read through its account for its first few dozen matches: a sibling that keeps shoving can widen a new bot's read before its own record takes over (docs/PROFILES.md §8).
Betting bots
BettingClient.lmsr_prices(q, b, dead)and everypachinko_sdk.lmsrfunction takedeadas the server sends it (outcome indices,[2, 5]) or as a bool mask. They read only the mask before, so the server's list priced the wrong outcomes as dead (a 90% favourite at 0).preview_buy/preview_sell/trade_towere already right.
Playing bots
run_onlinestops withPachinkoAuthErrorwhen the server rejects the bot token (HTTP 401), instead of retrying every 5 s forever. The server now answers 503 while it is restarting (it said 401 "Invalid bot token" then), and that is still retried.fetch_player_stats(name)/fetch_profile(name)find a pybot by name: the server's 404 for a pybot name says to ask again withkind="pybot", and the SDK now does. Passkind=to look in one namespace only.run_local(frame_every=k)delivers the ticks the server's thinning does: tick 1, then multiples of k. It delivered 1, 1+k, 1+2k…, so with k = 2 a bot saw only odd ticks, and one that acts ontick % 4 == 0never acted offline. Withframe_jitterthe cadence is as before.
0.9.9 — one seat per account; VPIP and PFR per match; the account fades as a bot plays
One seat per account per match
- A match never seats two members of one account any more: not a person and their own pybot, not two pybots of one author. The matchmaker seats humans first, then pybots oldest-first, and keeps anyone whose account already has a seat for the next lobby (they keep their place; the lobby fills with house AIs as before). Two seats with one owner could collude.
- Offline does the same by default:
ProfileAggregator.update(..., account_ids=)andrun_local_seriesraise ValueError for a match whose seats share an account (or that seats an account next to one of its own bots).allow_shared_account=Trueaccepts it for self-play experiments. Seats without an account (house AIs, ids you pool on purpose) are not limited.
VPIP and PFR are per match
- Lifetime
vpip/pfr(the profile,fetch_profile, the site's stats pages and leaderboards) are now the share of matches with a voluntary pre-game call, raise or all-in / with a pre-game raise or all-in, over the matches dealt into the pre-game round: the definitions the habit window already used. Until now they were per action over every betting round, so VPIP passed 1 for a seat that called twice in a round (a call-only bot read 1.17) and PFR left all-ins out (an always-all-in bot read 0; mecha_slag read 0.58 while its recent window shows a pre-game raise in every match).BettingEnvper-seat features 22/23 carry the new values: retrain policies that read them.
The account fades as a bot plays
- The house still reads a seat's habits pulled toward its account's, and a new bot still reads exactly as its account (a fresh bot cannot reset its account's reputation). Now the account's share of the read is K / (matches + K), K = 10: half at 10 matches, 19% at 44, 9% at 100, 1% at 1000, and the rest goes to the population prior. In 0.9.8 it stayed at about 19% for good, so one bot that always shoves made the house read every other bot of its account as wider, and call them lighter, permanently.
PlayerProfile.shrunk()/wideness()apply the same rule.
Profiles
PlayerProfilecarries the rest of the site'splayingblock:firsts,first_place_rate,wins_by_battle,wins_by_foldout,three_bet_rate,check_raise_rate(None on the table wire, which does not carry them).win_rateis the 1st-place rate; the site'swinRateandfirstPlaceRateare the same number.ProfileAggregator.profile()fills them offline.afis None for a seat that never called (raises / calls has no value): documented as "aggressive, no calls" whenpfr> 0.ProfileAggregator.load_state(id, state, account=)links the identity to its account. A window (state()/habitsState) holds no lifetime record, so it cannot reproduce a profile by itself:export_identity(id)/import_identity(id, entry)copy one identity exactly.to_json/from_jsonnow round-trip byte for byte (floats are parsed exactly; they could land 1 ULP off).profile_from_statsreads the account reputation fromaccountProfileonly (it also tried two other key names).
Other
- House bettors no longer send orders on a seat that is already out at the table; the market refused them ("Outcome is eliminated").
- House bettors' model (
linear_bettor.COEF): the weight on a seat's record now falls over the RTS (rep= (1.195, -1.13), fitted on 400 offline lobbies with the live pybot). At full weight late in a match it counted the record twice, once the board already showed who was winning. The betting surprises (pre_x,mid_x) fitted to nothing measurable and stay 0. - Gym README: the observation tables match the 0.8.0 owner-banked layout (
globalsis (11,), building rows have 13 columns,resource_nodes5,dropped_itemslisted).globals[6](items collected) is a raw count and includes the 5 starting items, so it reads 5 at reset: true since 0.8.3, when the gym got live starting items, and never noted until now.
0.9.8 — two reputations per seat; bettors see every bet, not the cards or the spawns; offline == live
Two reputations per seat
- Every seat that belongs to a person now carries two reputations: its own (this bot, or this person's hand play) and its account's (the person's hand play plus every pybot they run).
PlayerProfile.accountis the account's profile in the same shape (kind == "account");Nonefor house AIs. Until now a pybot only had its author's pool (bots only), so a bot could not earn a reputation of its own: every pybot of an author was read as the author's busiest bot. - A pybot's top-level habits are now its own (
pybot:<id>online). Its lifetime record already was. - The house AI reads the individual shrunk toward the account, and the account toward the population: a new bot starts at its account's read (a fresh bot cannot reset it) and moves to its own record; with a full window its own record carries about 81% of the weight.
PlayerProfile.shrunk()andwideness()apply the same two-level rule, sowideness()is still what the house reads. ProfileAggregator.update(..., account_ids=),account_of(id),link_account(id, account),freeze(id);profile(id)nests the account. To train a bot of an account whose other bots play most of its matches live, load the account's livehabitsState,freezeit and give the botaccount_id=: the house then reads it as live does (as the account at first, its own record after about 30 matches), and the account does not drift toward the bot being trained.fetch_player_statspayloads carry the account asaccountProfile;profile_from_statsfillsaccount.
Bettors: every bet, no cards or spawns before the RTS
- Bets now reach bettors as they happen. The stream sends a
betmessage for every round start, action and round end the moment the table gets it (bets are public to every player at once, so they skip the 3-s spectator delay that hides the moving RTS); observations stay 3 s behind at yourhz.Bettor.on_bet(event)may return orders;BetEventcarries the action and the table right after it, andBettingObservation.tableis whichever of the real-time and the frame's table is further on. Offline matches andBettingEnv(act_on_bets=True: every event is a step) do the same. Before, a raise reached a bettor 3 to 8 s late. - A seat the server folds for timing out or disconnecting is now a fold in the match's action log (it was announced to the table but never logged).
- Until the RTS starts, spectators still see the terrain and every resource node: pre-game frames carry the map without any start position (
map_info), and the watch page draws it. - Observations carry
bets: every betting action since your previous observation (the first carries the match so far), so a slow subscriber no longer misses a raise that was re-raised or folded between two frames.BettingObservation.bet_logkeeps the whole match;PokerTable.actionsthe current round. Rows: round, seq, slot, action (check / call / raise / all_in / fold; blinds are not rows), amount, bankroll_before, pot_after, current_bet_after, plusstack_frac. - Until the pre-game round has resolved, spectators and bettors no longer see the map seed (it deals every starting hand and places every spawn), any entity (the bases stand on the spawns), resource-node owners, or the map's spawn positions. They return with the first RTS frame; the stream re-sends the
matchmessage then. - The RTS's random stream (star spawns and loot, circle-shot dispersion) is salted with each live room's secret, as the house AI's bets already were. Before, an all-AI match was a function of the public seed plus the bets everyone sees: two live floor matches replayed offline from public data alone, tick for tick, with the winner known about two minutes early. Offline
ai_bet_saltdefaults to 0 (unsalted), so seeded runs replay as before; the same seed plays out differently live, from the same distribution.
Offline == live: the rest of an SDK user's offline/live comparison
- House bettors offline now read a frame every 5 s of game time from tick 0, as the live house does (
run_bettorsat 0.2 Hz). Before, they evaluated the level tick-0 frame, found nothing to trade and waited out their interval: the first house trade came 30 s into the RTS, where live it trades a dozen times in the first minute. An offline-trained bettor learned a free first half-minute that does not exist live. BettingEnvtakes profiles (profiles=,aggregator=,seat_ids=,account_ids=). The defaultprofiles="live"is a snapshot of the live house AIs' profiles (they only play unrated floor matches, so their reads do not move live either) and of the live pybot's;aggregator=evolves reputations over the rated pybot lobbies. Before, 11 of the 29 per-seat features were always zero in training and filled live. The per-seat block is now 40 numbers (the account's are added; layout in the module docstring): policies trained on 0.9.7 need retraining.- Lobby mix:
lobby="floor" | "pybot" | "mix"."mix"(the default ofrun_local_bettorsandBettingEnv) is the live mix of the last 7 days: 54% 15-minute pybot lobbies (one pybot and seven AIs), 46% floor matches. The pybot seat isStandInPybot, which bets with the live pybot's measured distributions and plays the house AI's orders, or your own bot viapybot=. The stand-in wins less often than the live pybot (19% against 43.5%), so seat your own bot when that matters. - One wallet across concurrent matches:
BettingEnv(concurrent="live")runs 2 or 3 overlapping matches on one wallet and one rate-limit clock, as live (2 markets open 42% of the time, 3 57%). A policy that sizes its bets as a share of its balance no longer trains on a wallet three times bigger than it has live.concurrent=1is the old single-match episode. - Orders take time and queue behind the house: they execute in arrival order after a latency (
order_latency_ms; the house's 25 ms each, one at a time; yours defaults to 100 ms, an assumption, as no non-house bot has traded live yet), against the market as the frame left the server. - Floor rules report
idle_end_secs360, as live (was 0). LocalBettingMatch(hide_pregame=True)(default) hides the seed, entities and node owners before the RTS, as live;bets/bet_logas online.
A fold leaves the market at once; the house reads who is playing
- A seat that folds stops being quoted the moment it folds: the server collapses it before the fold's bet event reaches anyone. Before, a folded seat stayed in the market until the round and its 10 s hold were over (10 to 28 s), and with bets now arriving in real time that was a free trade for whoever read the event first. Offline
collapse_on_table_fold=Trueis the new default, applied at the event as live. A round-end table always reads as resolved (PokerTable.resolved), also from a server with no hold. - The house bettors (
linear_house_bettors, the live line-up) now read each seat's reputation:rep, the seat's own 1st-place record shrunk toward its account's, shrunk toward 1/n. Its weight was fitted on 8,000 live matches: the house now opens mecha_slag, which wins 43.6% of its lobbies, near 44% instead of 1/8. They price the pre-game and the betting rounds too (they used to wait for the RTS), take a seat folded on the table out at once, andLinearBettor.on_betre-prices on every bet event, trading when its estimate has moved by 3 points, every order price-limited at its target. The edge bettors (_EdgeBettor: the house and the simple bettors) place the biggest edge first (a faster bettor's order used to land between the house's small orders and take the one that mattered), and their 30-90 s interval runs within a phase: the first look at the RTS, or at play resuming after a round, may trade at once.COEF_092keeps the 0.9.2 board-only model;linear_bettor.reputation,table_features,live_seatsare the new inputs. The fit and an evaluation harness are intools/house_bettors.
0.9.7 — a user's bug list: profiles, match labels, eliminations; "standard" lobbies
Nine bugs reported against 0.9.6, each checked and reproduced, plus two naming fixes. The compiled module changed, and several fixes are also in the match-server and the site's API (noted where a number you read online changes with the server, not with this wheel).
Profiles and reads
fetch_profile()returned a blank, average profile for every live player: the stats page nests the record underplayingand the habits underhabits, and the parser read the payload as flat. It now builds the same profile the table shows (profile_from_stats(stats)does it for a payload you already fetched), sofetch_profile(name).wideness()is what the house reads off that seat.- Pre-game folders counted as heads-up losers and as podium finishers. A seat that folds before the game is now in neither table shape (
heads_up_rate,win_rate_heads_up,win_rate_multiwayonly count matches the seat played) and takes no podium: folders share the rank after the seats that played, which is 3 whenever two seats played, so an always-folder had a podium rate of 1.0. Offline now, online with the next API release. pressure_success_ratewas not a rate: every fold credited every earlier raise again, and all-ins were missing from the denominator, so a seat that shoves a full table read 3 to 6. It is now raises and all-ins that drew a fold over raises and all-ins. Lifetime totals recorded before the change are capped at 1.ProfileAggregator.update: an identity seated k times in one match (self-play under one id) aged its window k times, a half-life of 30/k matches. The window now ages once per match and every seat's features land. (Online the same case, an author's pooled pybots at one table, dropped every seat after the first; fixed the same way.)ProfileAggregator.load_statezeroed the lifetime rates (win rate, podium, fold rate, VPIP, PFR, AF, average placement) it was documented to keep. A seeded identity now shows the loaded window's rates until it has played more matches here than the window holds.BettingEnv: a seat that raises and never calls has no aggression factor (afis None), and the feature turned that into 0, the most passive value; it is now 1.0. The pressure feature is squashed to 0..1 (x / (1 + x)) instead of going in raw. Both change the meaning of per-seat features 24 and 25: retrain or re-normalise a policy that used them.
Matches
end_reasonwas"fold_out"whenever anyone had folded, a pre-game fold included, so in an 8-seat lobby nearly every decided match was a fold-out and battle wins were not counted as such (on the live site, three of four wins labelled fold-out ended with the runner-up's base destroyed). It is now decided by how the LAST opponent left: beaten in battle ="battle_out", folded or resigned ="fold_out". Offline now, online with the next match-server release; past matches keep their label.on_player_eliminatedfired two or three times per seat (Folded, then Defeated when the folded army was removed, then Folded again at the end of every later betting round). A seat is now announced once, for the reason it first left, by the engine and the next match-server; the SDK also drops repeats from older servers.- The house AI's gang-up on a called shover was a no-op.
marked_player()reported the mark, but the mark only lowered the leader rule's thresholds for a marked seat that already led, and that rule flags the leader on about 96% of ticks by itself: against a marked bot, 15 of 16 seeded matches were tick-for-tick the unmarked match. A marked seat is now the target on its own standing, leader or not: while its strength is at least 1.05x (at full wideness; 1.5x at none) the median of the other seats still in the match. In 8-seat tables that moved a marked bot from being the target on 0-74% of ticks to 47-97%. Offline now, online with the next match-server release.LiveGame.threat_player()shows who the target is.
Names
state.rules.lobby_kindsaid"human"for a lobby with a human seat, while the betting stream (obs.match.rules.lobby_kind) and the matchmaker call the same lobby"standard". The playing side now says"standard"too:"standard" | "pybot" | "floor"on both sides."human"is still understood wherever you pass it (run_local(lobby="human"),LiveGame(lobby_kind="human")) and a match-server that still sends it is read as"standard", sostate.rulesandon_game_start(data)["rules"]show one name whatever the server's age. If you compared against"human"(two days old), compare against"standard".GameState.projectileswas described as "ascending id" in the source, for a type that has no id. It is, and always was, oldest shot first on both transports; the comment and the docs now say that.
Older releases (23)
- 0.9.6 — betting bots: the stream no longer dies on the gateway's cadence reply
- 0.9.5 — offline is the live environment: an audit and its fixes
- 0.9.4 — offline reputations follow the player, not the seat
- 0.9.3 — reads: every seat's betting habits are on the table
- 0.9.2 — the house is five linear bettors on one stream
- 0.9.1 — a socket dying mid-command no longer crashes the match loop
- 0.9.0 — betting bots
- 0.8.6 — a dropped connection no longer costs you the match
- 0.8.5 — the AI bets the 5-minute round as a mid-game round
- 0.8.4 — built-in AI defends against overbets
- 0.8.3 — offline play identical to live play
- 0.8.1 — train from any seat
- 0.8.0 — owner-banked observations (BREAKING obs schema)
- 0.7.7 — multi-player RL: FFA self-play + owner attribution; units-mode reward fix
- 0.7.6 — offline mulligan, batched evaluation, 2-card mulligan cap
- 0.7.5 — offline FFA vs built-in AI + full betting economics
- 0.7.4 — fair spawns, pre-game node economy, RL item parity
- 0.7.3 — finishing position + placement-aware RL reward
- 0.7.2 — online GameState parity fix
- 0.7.1 — shared engine core (internal refactor)
- 0.7.0 — N-player RL gym
- 0.6.0 — local multiplayer (offline N-player Bot runner)
- 0.5.0 — observation enrichment (BREAKING)
Deterministic bots
Create a .py file, subclass Bot, and implement on_tick. The SDK handles all communication with the game.
Want to see what a complete bot project looks like? The example bot repo on GitHub is a full working setup — a hand-written strategy bot plus local-sim harnesses for self-play testing, evaluation diagnostics, and reference material on the built-in AI it competes against.
Minimal example
from pachinko_sdk import Bot, run_online, AttackMove, ToggleSpawn
class MyBot(Bot):
def on_tick(self, state) -> list:
actions = []
# Keep all military buildings spawning
for b in state.my_buildings:
if b.kind in ("squarracks", "circhery", "triables"):
if not b.spawn_toggle:
actions.append(ToggleSpawn(b.id, True))
# Attack-move idle units toward the nearest enemy building
if state.enemy_buildings:
target = state.enemy_buildings[0]
for unit in state.idle_units():
actions.append(AttackMove(unit.id, target.x, target.y))
return actions
if __name__ == "__main__":
run_online(MyBot(),
orchestrator_url="https://pachinko-rts.com/orchestrator",
bot_token="bot_...your_token...")Counter-unit production
Count the visible enemy unit types and spawn the counter. Square beats Triangle, Triangle beats Circle, Circle beats Square.
def on_tick(self, state) -> list:
actions = []
# Count visible enemy types
sq = sum(1 for u in state.enemy_units if u.unit_type == "square")
ci = sum(1 for u in state.enemy_units if u.unit_type == "circle")
tr = sum(1 for u in state.enemy_units if u.unit_type == "triangle")
if tr > max(sq, ci):
primary = "squarracks" # squares beat triangles
elif sq > max(ci, tr):
primary = "circhery" # circles beat squares
else:
primary = "triables" # triangles beat circles
for b in state.my_buildings:
if b.kind in ("squarracks", "circhery", "triables"):
actions.append(ToggleSpawn(b.id, b.kind == primary))
return actionsBuying upgrades
# Upgrade types: "spawn_rate", "weapon_damage", "armor", "move_speed",
# "mining_rate", "healing_aura"
from pachinko_sdk import Upgrade
def on_tick(self, state) -> list:
actions = []
RESERVE = 600 # keep this much hematite in reserve
for b in state.my_buildings:
if b.kind == "squarracks":
if b.upgrades["spawn_rate"] < 5 and state.resources > 300 + RESERVE:
actions.append(Upgrade(b.id, "spawn_rate"))
if b.kind == "hematite":
if b.upgrades["mining_rate"] < 5 and state.resources > 400 + RESERVE:
actions.append(Upgrade(b.id, "mining_rate"))
return actionsLocal testing & self-play
Before you connect a bot live, run it offline against up to 7 opponents with run_local— no server, no token. It drives the exact same lifecycle as online (on_game_start → on_tick / on_bet_action → on_match_settled / on_game_over) and hands your bot the identical GameState per seat, so a bot that works here works live.
from pachinko_sdk import run_local
from my_bot import MyBot
# your bot in seat 0; the other 7 seats are the built-in AI
result = run_local(MyBot(), num_players=8)
print(result.winner_slot, result.settlement, result.bankrolls)
# mirror match — your own bots in several seats, the rest auto-fill with AI
run_local({0: MyBot(), 1: MyBot(), 2: RivalBot()}, num_players=8)
# RTS only (no betting), custom scenario
run_local(MyBot(), num_players=6, betting=False, flat_terrain=True)bots is a single Bot (seat 0), a list (index = seat), or a {seat: controller} dict, and seats can be heterogeneous: an SDK Bot, a plain callable f(state) -> list[Action] (e.g. an RL policy adapter), or "builtin" / Nonefor the built-in AI. The full pre-game runs offline too: each seat is dealt its 5 mulligan items (rerolls capped and charged exactly like live) and the poker layer runs the real engine economy — built-in AI seats bet with the same fold/call/raise logic as ranked, folds resign the seat (its army leaves the field), and the pot settles to a typed Settlement. Pass betting=False for an RTS-only match. Scenario keywords (flat_terrain, symmetric_map, resource_nodes, star_count, starting_resources, no_fow) are forwarded to the engine. Everything is deterministic per seed — the same seed replays the same match, ideal for regression-testing a bot.
An offline match is a live match: run_local runs the server's match rules (the 15-minute time cap with its score tiebreak, betting every 5 minutes, the 6-minute idle rule, the 30-second decision deadlines, the 10 orders/s rate limit, fold-outs, bounties, the server's payout and economy) and drives your bot with the same SDK code as run_online, so every callback arrives in the same order with the same payload. The same seed played on a server and offline gives the bot byte-identical observations. on_tick runs every tick from tick 1 — what a bot that keeps up with the 24/s stream gets online. Each rule is a keyword you can switch off for an experiment, and frame_every / frame_jitter / action_delay_ticks rehearse a slower bot or a laggy link.
| Name | Type | Description |
|---|---|---|
| run_local(bots, num_players=8, betting=True, mulligan=True, seed=0, max_ticks=21600, **scenario) | LocalResult | Run one offline match and return the outcome. num_players defaults to 8 from 0.9.5 (a live lobby always has 8 seats; it was 2 — pass 2 for a duel). max_ticks is the time cap: 21600 (15 min) = pybot lobbies; HUMAN_LOBBY_TIME_LIMIT_TICKS (86400, 60 min) = lobbies with a human. |
| lobby=None | str | "pybot" or "standard": which live lobby this match stands for. Your bot is seated with humans too, and those lobbies ("standard") run 60 minutes: lobby="standard" sets that cap (when max_ticks is left alone) and state.rules.lobby_kind. Called "human" in 0.9.5 / 0.9.6, which still works. (0.9.5) |
| decision_deadlines=True | bool | float | (bet, mulligan) | The server folds a seat that has not bet 30 s after its turn opened and accepts the dealt hand 30 s after the mulligan opened. Offline your on_bet_action / on_mulligan are timed the same way and an overrun gets the server's answer, with a warning. A number sets the limit in seconds; False waits forever. (0.9.5) |
| names=None, kinds=None | list | dict | What GameStart.players[] says about each seat: display names and seat types ("bot" / "human" / "human_bot"). Default: your controllers named after their profile_id or class, the built-in AI ai-<seat>, every seat a bot, as in a pybot lobby. (0.9.5) |
| random_seat=False | bool | Live shuffles the seats of every lobby, so your bot lands on any of the 8. True shuffles the table by seed; result.seat_map says where each seat you named played. (0.9.5) |
| reconnect_at_ticks=None | list[int] | Ticks at which your seats go through what the server sends a bot that dropped and came back (GameStart again → on_reconnect), to rehearse reconnect handling. (0.9.5) |
| command_rate_limit=True | bool | Drop commands beyond the live budget (burst 20, 10/s), as the server does. False = unlimited. |
| idle_end_secs=360 | int | Live idle rule: no orders from any bot seat for this long ends the match as "abandoned". 0 disables. |
| frame_every=1, frame_jitter=0 | int | Call on_tick every frame_every (+ random 0..frame_jitter) ticks, to rehearse a bot slower than the 24/s stream. |
| action_delay_ticks=0 | int | Hold your orders this many extra ticks before they reach the game (latency). |
| callable_betting="sdk" | str | A bare-callable seat bets like an SDK Bot with the defaults (call); "builtin" lets the built-in AI play its bets. |
| profiles=None | list | dict | Per-seat public profiles (reads), as the server snapshots them at match start: a list (index = seat) or {seat: profile} of wire dicts / PlayerProfile objects. They reach every seat's on_game_start and BetObservation.players[].profile, and the built-in AI bets by them exactly as online. None = no history (the AI reads the population prior). |
| ai_profile_aware=1.0 | float | The built-in AI's strength knob for profiles, 0..1 (live: 1.0; 0 = it ignores profiles, the 0.8.5 house). |
| LocalResult.winner_slot | int | Winning seat (0-based), or -1 for a draw (mutual KO, or an exact score tie at the cap). |
| LocalResult.end_reason | str | "battle_out" | "fold_out" | "time_limit" | "abandoned" | "draw" — the server's labels. Decided by how the last opponent left: beaten in battle, or folded / resigned (0.9.7; before, any fold by anyone made it fold_out). |
| LocalResult.bounties | list[int] | None | Elimination-bounty chips paid per seat (None if betting=False). |
| LocalResult.placement | list[int] | Finishing position per seat (1-based, 1 = winner; ties share a rank). |
| LocalResult.net_chips | list[int] | None | Net chip P/L per seat (Σ == 0), or None if betting=False. |
| LocalResult.my_net(seat) / my_placement(seat) | int | Convenience readers for one seat's chips / rank. |
| LocalResult.settlement | Settlement | None | Terminal pot payout (None if betting=False). |
| LocalResult.bankrolls | list[int] | None | Post-match chip stack per seat (None if betting=False). |
| LocalResult.ticks | int | Ticks simulated. |
| LocalResult.deadline_misses / seat_map | dict / dict | Decisions answered past a deadline, per seat (empty when none); where each seat played ({named seat: seat played}, identity unless random_seat). (0.9.5) |
| LocalResult.match_record | dict | None | The match as ProfileAggregator consumes it: every betting action with its size and the actor's stack, the placements and the end reason (docs/PROFILES.md §4). |
Batched evaluation
To measure a bot properly, run many matches and aggregate. run_local_batch plays n_games full matches (deterministic per game: seeds are base_seed + game_index) and returns the numbers evaluation cares about for one seat:
from pachinko_sdk import run_local_batch
res = run_local_batch(lambda i: {0: MyBot(), 1: "builtin", 2: "builtin", 3: "builtin"},
num_players=4, n_games=100, workers=4)
print(res.first_place_rate(), res.avg_placement(), res.mean_net(), res.placement_counts())The factory is called once per game so controllers never share state across matches. workers > 1 uses a process pool (the factory must be picklable). Extra keywords pass through to run_local, including profiles— the same fixed profiles for every game.
Reads that evolve: run_local_series
Online, every seat's profile(its betting habits over its recent matches — see Reads) is snapshotted at match start and the built-in AI bets by it. A bot that shoves every match builds a wide-range reputation and gets called lighter. To train against that, keep profiles evolving across a series: run_local_seriescarries each identity's profile into the next game and updates it from the match record afterwards, with the server's own aggregation code (ProfileAggregator). A reputation belongs to an identity, not a seat: give each controller a profile_id and its record follows it wherever the factory seats it, so you can move the trainee around the table and rotate opponent models without mixing their habits. seat_ids names only the seats without one (the built-in AI).
from pachinko_sdk import Bot, run_local_series, with_profile_id, ProfileAggregator
class MyBot(Bot):
profile_id = "mybot" # or MyBot(profile_id="mybot-v12")
def factory(i): # the trainee moves, the opponent rotates,
k = i % len(opponents) # the other three seats are the house
opp = with_profile_id(opponents[k].act, f"opp-{k}") # a bound method, wrapped
return {i % 5: MyBot(), (i + 1) % 5: opp}
res = run_local_series(factory, num_players=5, n_games=200,
seat_ids=["house-1", "house-2", "house-3", "house-4", "house-5"])
print(res.profile("mybot")["shoveRate"], res.placements("mybot")[-10:], res.games_of("opp-0")[:3])
# keep the reputation between runs, or seed it from the live profile's habitsState
open("profiles.json", "w").write(res.aggregator.to_json())
agg = ProfileAggregator.from_json(open("profiles.json").read())
agg.load_state("mybot", live_profile_json["habitsState"])
run_local_series(factory, 5, 50, seat_ids=["house-1", "house-2", "house-3", "house-4", "house-5"], aggregator=agg)| Name | Type | Description |
|---|---|---|
| run_local_series(factory, num_players, n_games, seat_ids=None, base_seed=0, aggregator=None, ai_profile_aware=1.0, **run_kwargs) | SeriesResult | n_games sequential matches; before each, every seat with an identity carries that identity's current profile, after each the match record updates those identities. A seat's identity is its controller's profile_id, else seat_ids[seat] (a list or {seat: id}); None = no identity (no profile, never updated). A seat keyed by seat_ids that changes hands between games raises a RuntimeWarning: its players' habits would pool by seat. 0.9.8: a controller's account_id (Bot(account_id=), or account_ids= like seat_ids) is a second identity its seats also land in, the account its profiles carry, as live. |
| Bot(profile_id=None) / controller.profile_id / with_profile_id(controller, id) | str | None | A controller's offline reads identity (0.9.4): the name its habits accumulate under wherever it is seated — what its bot id is online (unused online). with_profile_id sets it and returns the controller, wrapping a bound method such as policy.act; profile_identity(controller) reads it. |
| SeriesResult.results / profile_history / id_history | list[LocalResult] / list[list[dict | None]] / list[list[str | None]] | Every game's outcome, the profiles each seat carried INTO each game, and the identity each seat played under. |
| SeriesResult.aggregator / profile(id) | ProfileAggregator / dict | None | The rolling states afterwards; an identity's current profile (wire dict), None before its first match. |
| SeriesResult.games_of(id) / placements(id | seat) / net_chips(id | seat) | list | Where an identity sat ([(game, seat), ...]) and its results over the games it played, wherever it sat; an int picks a seat. |
| ProfileAggregator(half_life=30, prior_k=10) | ProfileAggregator | The server's aggregation code (pachinko_pybind): update(match_record, seat_ids, account_ids=), profile(id), state(id), load_state(id, state, account=), export_identity(id) / import_identity(id, entry) (an exact copy of one identity, 0.9.9), ids(), to_json(), ProfileAggregator.from_json(text). update refuses a match where two seats share an account unless allow_shared_account=True (0.9.9, as online). |
| seat_features(match_record) | list[dict] | The per-seat features of one match (shove, open, big_faced/big_fold, mid rounds/raises, heads_up, placement, vpip, pfr, aggr/calls, fold) — the aggregator's input, for inspection. |
For RL training (numpy observations at thousands of steps/s), use pachinko_gym instead — run_local exercises the exact live Bot code path, including stars, item drops, and fog, so what your bot sees here is what it sees online.
Match rules
State frames and on_tick cadence
The game runs at 24 ticks per second and the server sends your bot a state frame every tick. The SDK reads frames on a background thread and always hands on_tick the newest state: if your on_tick takes longer than ~40 ms, the frames that arrived meanwhile are applied but not passed to you, so you see ticks 2+ apart instead of falling behind the game (events from skipped frames are still delivered). Pace decisions on elapsed ticks (state.tick - last_tick >= N), not state.tick % N == 0, which can skip decisions when ticks arrive uneven. Offline, run_local(frame_every=N) reproduces a slow bot.
Time limit and score
A lobby of pybots and house bots ends after 15 minutes, a lobby with a human after 60 minutes. At the cap, the player still in the match (not eliminated, not folded) with the highest live score wins; an exact tie is a draw with stakes refunded. The other survivors share the next finishing rank.
The pot is paid out at the end among the players still in it, 70/20/10 by finish order. A player knocked out of the battle — or still alive but beaten at the cap — drops out of the pot (an all-in player keeps the side pot it paid into), so in practice the winner usually takes it all, plus bounties.
The score (state.scores, 0–400) is four parts of 0–100 each, every part scaled against the best player in it: live unit count, total upgrade levels across your buildings, total richness of the nodes you control, and items collected. It is relative, so it moves when opponents grow or lose armies.
Resource nodes
Control is recomputed every tick: the player with strictly the most units within 120 world units of a node controls it; a tie or nobody nearby leaves it neutral, so holding a node means keeping units on it. contested= two or more players have units in range. Every economy tick (every 2 ticks) each controlled node pays its richness × your refinery mining multiplier (at least 1), and every player also gets +1 base income; income stops while you have no military building. You only see who controls a node while it is in your vision — a fogged node reads as neutral.
Betting, idle and elimination
A betting round opens every 5 minutes (also at the 15-minute cap, just before it resolves). If everyone but one player folds, that player wins immediately. A match where no bot or human seat has issued an order for 6 minutesends early, resolved like the time cap. Destroying a player's last military building eliminates them and earns one small blind of bounty, paid at the end; state.alive_players lists who is still in.
Deadlines, reconnects and the rules of your match
You have 30 seconds for each betting decision and 30 seconds for the whole mulligan (rerolls included). Past that the server folds the seat, or accepts the hand as dealt. obs.turn_timeout_secs carries the betting limit, and run_local enforces both offline, so a bot that thinks for a minute fails the same way in training as it would live.
The rules of the match you are in arrive before the game starts, as state.rules and on_game_start(data)["rules"] (see MatchRules below). The one that varies is the time cap: 15 minutes in a lobby of bots, 60 as soon as a human is seated. Read it from the rules; do not assume it.
If your connection drops, the server holds the seat for 45 seconds, then lets the built-in AI play it until you are back. The SDK reconnects by itself and calls on_reconnect(data) — not on_game_startagain, so what you set up there stays. In the middle of a betting round the table is restated to you (pot, bet to match, every seat's chips and status), so the next BetObservation is current; the bets made while you were away are not in history_this_round. A drop during the mulligan has 10 seconds: on return on_mulliganis called again with the hand as it stands, rerolls kept. Use SDK 0.9.5 or later: earlier versions could drop their own match connection (see What's new).
API reference
Bot lifecycle methods
| Name | Type | Description |
|---|---|---|
| on_game_start(data) | None | Called once at game start. data includes the GameStart payload (map_seed, players, num_players, and map_info — the static terrain grid). The parsed map is also on every state.map_info. From 0.9.5 data["rules"] holds the match rules (see MatchRules) and data["resumed"] is False. |
| on_reconnect(data) | None | Called instead of on_game_start when the match connection dropped and was re-established (0.9.5): data is the GameStart payload again with data["resumed"] = True. The next on_tick has the current state. Default: no-op. |
| on_tick(state) | list[Action] | Called with the newest state each time you are ready (every tick if on_tick is fast; see Match rules). Return a list of action objects. |
| on_mulligan(obs) | MulliganDecision | Called once when the mulligan phase opens, then again after every reroll (and after a reconnect during the mulligan, with the hand as it stands). Default: accept. |
| on_bet_action(obs) | BetDecision | Called once for each betting decision the server asks this bot for. Default: call (goes all-in if the call exceeds the bankroll). |
| on_scores_update(scores) | None | About once a second: the scoreboard a human sees — scores["scores"] (0–400 per slot), ["stakes"] (chips each seat has in the pot), ["bounties"], ["player_status"] (0 active, 1 folded, 2 eliminated). Also on every GameState. Default: no-op. |
| on_betting_round_end(info) | None | A betting round resolved (0.9.5): info["round"], ["pot"], ["side_pots"] and ["resume_in_ms"] — the 10 s the resolved table is held before play resumes. Default: no-op. |
| on_player_eliminated(info) | None | A seat left the match (0.9.5): info["seat"], ["reason"] (Defeated, Folded, Resigned, Timeout) and ["killer"] (slot or None). Once per seat, for the reason it first left (0.9.7; earlier versions repeated it). Your own elimination arrives here too. Default: no-op. |
| on_match_settled(settlement) | None | Called just before on_game_over with the terminal payout as a typed Settlement (pot + per-slot net deltas, Σ net == 0). Default: no-op. |
| on_game_over(data) | None | Called when the game ends. data is the GameOver payload, or {reason: 'ws_closed' | 'ws_eof'} if the server dropped the WS without a GameOver. |
GameState fields
| Name | Type | Description |
|---|---|---|
| tick | int | Current game tick (24 ticks per second). |
| resources | int | Your current hematite balance. |
| my_units | list[Unit] | All your living units. |
| my_buildings | list[Building] | All your buildings. |
| enemy_units | list[Unit] | Visible enemy units. |
| enemy_buildings | list[Building] | Visible enemy buildings. |
| resource_nodes | list[ResourceNode] | All hematite nodes on the map. |
| game_over | bool | True once the match has ended. |
| winner_slot | int | Winning player slot (0-based), or -1 while in progress / on a mutual-KO refund. |
| player_slot | int | Your own slot (0-based) — interpret winner_slot and per-entity owner against this, even after all your units die. |
| won | bool (property) | True iff game_over and winner_slot == player_slot. |
| result | str (property) | Outcome relative to you: "in_progress" | "win" | "loss". No "draw" — a mutual KO refunds and reads as "loss". |
| finishing_ranks | tuple[int] | Per-slot finishing position (1-based, 1 = winner; ties share a rank) once the match ends; empty while in progress. |
| my_placement | int (property) | Your own finishing position, or -1 while the game is running. |
| scores | list[int] | Per-slot live display score (0–400), indexed by slot — the same number the score panel shows. A dense progress signal. |
| events | list[Event] | Game events you can see that happened since your previous on_tick (item pickups) — kind, message, x, y, player, tick. Each event is delivered once, online and offline. |
| my_items | list[StartingItem] | Your item hand: starting items plus every item picked up so far. Items change unit stats (range, cleave, …). |
| alive_players | list[int] | Slots still in the match (not eliminated, not folded). |
| stakes / bounties / player_status | list[int] | The other scoreboard columns, per slot (0.9.5): chips each seat has put in the pot, elimination-bounty chips earned, and 0 = active, 1 = folded, 2 = eliminated. Empty until the first scoreboard update. |
| rules | MatchRules | None | The rules of this match (0.9.5): time cap, deadlines, idle rule, blinds, rate limit, lobby kind. None against a server that does not state them. |
| player_buffs | list[PlayerBuffs | None] | Per slot, the item bonuses of a seat (0.9.5): always your own; an opponent's while one of its units or buildings is in your view, as with a human's inspect panel; None otherwise. |
| projectiles | list[Projectile] | Projectiles in flight that you can see (0.9.5), oldest shot first. A projectile has no id: the list order is the firing order, the same offline and online. |
| command_tokens | float | None | Commands you can send right now under the rate limit (burst 20, refill 10/s). |
| commands_dropped | int | Commands dropped so far this match for exceeding the rate limit. |
| stars | list[Star] | Neutral stars your team can currently see (fog-filtered). |
| dropped_items | list[DroppedItem] | Items lying on the map your team can see (fog-filtered). |
| items_collected | int | How many items your team has picked up so far. |
| map_info | MapInfo | None | Static map geometry + terrain grid. Sent once at game start; same object every tick. None until the first frame. |
| visibility | ndarray | None | (H, W) uint8 3-state fog grid in MapInfo cell coords: 2 = visible this tick, 1 = explored but stale, 0 = never seen. Lazily decoded; needs numpy + map_info. |
| feature_planes(featurizer=None) | ndarray | Stacked (C, H, W) float32 CNN feature planes for this tick. Pass a reused Featurizer to cache the static terrain planes. |
| idle_units() | list[Unit] | Helper: your units with no current order. |
| units_of_type(t) | list[Unit] | Helper: filter by type string. |
| nearest_enemy(x, y) | Unit | None | Helper: closest visible enemy unit to a point. |
| military_buildings() | list[Building] | Helper: your squarracks/circhery/triables. |
| enemy_military_buildings() | list[Building] | Helper: visible enemy military buildings. |
MatchRules fields
state.rules (0.9.5), identical offline and online. A value of 0 means that rule is off.
| Name | Type | Description |
|---|---|---|
| time_limit_ticks / time_limit_secs | int / float | The time cap: 21600 ticks (15 min) in a lobby of bots, 86400 (60 min) when a human is seated. |
| lobby_kind | str | None | "standard" (at least one human), "pybot" (pybots and house bots) or "floor" (all house AI) — the same names a betting bot reads in obs.match.rules.lobby_kind. 0.9.5 / 0.9.6 said "human" for "standard". |
| bet_action_timeout_secs / mulligan_timeout_secs | int | Seconds to answer a betting turn / to finish the mulligan (30 / 30) before the server folds / accepts for you. |
| bet_round_time_limit_secs | int | The round-level budget the server announces (60). |
| betting_interval_ticks | int | Ticks between mid-game betting rounds (7200 = 5 min). |
| betting_resume_ms | int | How long a resolved betting table is held before play resumes (10000). |
| idle_end_ticks | int | No order from any bot or human seat for this long ends the match (8640 = 6 min). |
| reconnect_grace_secs / abandon_grace_secs | int | How long a dropped seat is held before the AI plays it (45), and how long a match with every human or bot seat gone runs on before it ends (180). |
| starting_bankroll, small_blind, big_blind, max_mulligan_cards | int | The poker constants of the match (1000, 50, 100, 2). |
| cmd_burst / cmd_per_sec | int | The command rate limit (20 / 10). |
| tick_rate | int | Ticks per second (24). |
| raw | dict | The rules frame as sent. |
Unit fields
| Name | Type | Description |
|---|---|---|
| id | int | Unique entity ID. |
| x, y | float | World position (0–2500 on each axis). |
| unit_type | str | "square" | "circle" | "triangle" |
| hp / max_hp | int | Current and maximum hit points. |
| has_target | bool | True while the unit has an order — a move destination or an attack target. Own units only (False for enemy units). Same meaning online and offline. |
| attack_moving | bool | True if the unit's current order is an attack-move. Own units only. |
| attacking | bool | True while the unit's attack animation plays (it is striking now). Own and enemy units. |
| owner | int | Owning player slot (0-based) — the real owner even for enemy units, so multi-player observations attribute every entity. |
| facing | float | Heading in radians (populated for own + enemy units). |
| target_id | int | Entity ID of this unit's attack target, or -1. Own units only (enemy intent is hidden → -1). |
| destination | tuple | None | (x, y) move-order target, or None. Own units only (enemy → None). Backed by dest_x/dest_y. |
| stance / spacing / patrolling | str / str / bool | Own units only (0.9.5): "attack" | "defensive", "normal" | "tactical", and True while under a patrol order. Set with SetStance / SetSpacing / Patrol. |
Building fields
| Name | Type | Description |
|---|---|---|
| id | int | Unique entity ID. |
| x, y | float | World position. |
| kind | str | "squarracks" | "circhery" | "triables" | "hematite" | "arrow_tower" |
| hp / max_hp | int | Current and maximum hit points. |
| spawn_toggle | bool | Whether this building is currently spawning units (visible for enemy buildings in view too). |
| spawn_progress | int | Ticks of progress toward the next unit. |
| upgrades | dict | Keys: spawn_rate, weapon_damage, armor, move_speed, mining_rate, healing_aura. Values: int level, unlimited (healing_aura is 0–1). Per-level effects have diminishing returns — see specs()["upgrades"] for the exact curves. |
| owner | int | Owning player slot (0-based) — real owner even for enemy buildings. |
ResourceNode fields
| Name | Type | Description |
|---|---|---|
| x, y | float | World position. |
| richness | float | Income rate multiplier. |
| control | str | "neutral" | "own" | "enemy" (relative to you). A node outside your vision reads "neutral". |
| owner_player_id | int | Owning player slot (0-based), or -1 if neutral. Absolute attribution, unlike the relative control field. |
| contested | bool | True when ≥2 players have units within the capture radius. |
Star fields
| Name | Type | Description |
|---|---|---|
| id | int | Unique star ID. |
| x, y | float | World position. |
| hp / max_hp | int | Current and maximum hit points. |
| tier | int | 0 = weak, 1 = medium, 2 = strong. |
| tier_name | str | Property: "weak" | "medium" | "strong". |
| facing / charge_ticks / last_damage_tick | float / int / int | What a human reads off the star's animation (0.9.5): its heading in radians, how many ticks it is into charging its area attack (0 = not charging — the cue to move out), and the tick it last took damage. |
Projectile and PlayerBuffs fields
| Name | Type | Description |
|---|---|---|
| Projectile.owner | int | Slot of the player who fired it (meaningless when neutral). |
| Projectile.x, y / vx, vy | float | Position, and velocity in world units per tick. A projectile has no id; to follow one, advance its position by its velocity. |
| Projectile.splash / neutral | bool | An area-damage shot; fired by a star rather than a player. |
| PlayerBuffs.damage_mult, speed_mult, hp_mult, spawn_rate_mult | tuple[float, float, float] | Multipliers per unit type (square, circle, triangle); 1.0 = no item. |
| PlayerBuffs.armor / cleave | tuple[int] / tuple[bool] | Flat armor and cleave attacks per unit type. |
| PlayerBuffs.extra_projectiles, ballistics, splash_damage | int / bool / bool | Circle shot modifiers. |
| PlayerBuffs.circle_range_mult, circle_fire_speed_mult | float | Circle range and attack-speed multipliers. |
| PlayerBuffs.resource_rate_mult, health_regen, vision_mult | float / int / float | Income multiplier, hit points regenerated, vision multiplier. |
DroppedItem fields
| Name | Type | Description |
|---|---|---|
| id | int | Unique item ID. |
| x, y | float | World position. |
| kind | ItemKind | Property: the item kind enum (decoded from kind_id). |
| rarity_name | Rarity | Property: "common" | "uncommon" | "rare" | "legendary". |
| unit_type | int | 0=square, 1=circle, 2=triangle, 255=N/A (item not unit-specific). |
| value_f / value_i | float / int | Item-specific magnitude (which one applies depends on kind). |
MapInfo fields
Static map geometry, delivered once at game start and attached to every state.map_info. The terrain grid is row-major and shares the coordinate system of state.visibility, so terrain, fog, and your rasterized units all line up on the same grid.
| Name | Type | Description |
|---|---|---|
| world_width, world_height | float | World size in game units (2500 × 2500). |
| cell_size | float | World units per terrain cell (20). |
| grid_width, grid_height | int | Terrain grid dimensions in cells (125 × 125). |
| terrain | list[int] | Row-major terrain codes: 0=ground, 1=hill, 2=mountain (impassable), 3=slope. |
| spawn_positions | list[(float, float)] | Per-slot start locations, masked per recipient for fairness: only YOUR slot is real, every other slot reads (-1, -1). Scout to find opponents. |
| my_spawn | (float, float) | None | Your own start location (the one real spawn_positions entry). |
| resource_nodes | list[{x, y, richness}] | Static node layout, delivered pre-game so on_mulligan / on_bet_action can weigh starting economy before betting. Positions and richness never change. |
| nodes_near(x, y, k) | list | Helper: the k nodes closest to a point, e.g. map_info.nodes_near(*map_info.my_spawn, k=3). |
| world_to_cell(x, y) | (int, int) | Map a world position to its (gx, gy) grid cell. |
| cell_to_world(gx, gy) | (float, float) | Center world position of a grid cell. |
| terrain_code_at(x, y) | int | Terrain code at a world position. |
| is_walkable(x, y) | bool | False only on mountain cells. |
| height_at(x, y) | int | 1 on hills (high-ground combat bonus), else 0. |
| as_numpy() | ndarray | (grid_height, grid_width) uint8 terrain grid for ML. Needs numpy. |
Actions
| Name | Type | Description |
|---|---|---|
| Move(unit_id, x, y) | int, float, float | Move to position without attacking. |
| AttackMove(unit_id, x, y) | int, float, float | Move and auto-attack enemies encountered. |
| Attack(unit_id, target_id) | int, int | Direct attack on a specific enemy unit. |
| Halt(unit_id) | int | Cancel current order. |
| ToggleSpawn(building_id, on) | int, bool | Enable or disable unit production. |
| Upgrade(building_id, upgrade_type) | int, str | Purchase one upgrade level. upgrade_type: see Building fields. |
| Patrol(unit_id, x, y) | int, float, float | Patrol back and forth to position. |
| AttackMoveGroup(unit_ids, x, y) | list[int], float, float | Attack-move a list of units together. |
| MoveGroup(unit_ids, x, y) | list[int], float, float | Move a list of units to the same position. |
| AttackGroup(unit_ids, target_id) | list[int], int | Direct-attack one target with a list of units. |
| HaltGroup(unit_ids) | list[int] | Halt a list of units. |
| PatrolGroup(unit_ids, x, y) | list[int], float, float | Patrol a list of units between where each stands and the position. (0.9.5) |
| SetStance(unit_ids, stance) | list[int], str | "attack" (default: chase what comes into range) or "defensive" (hold position, fight what reaches them). (0.9.5) |
| SetSpacing(unit_ids, spacing) | list[int], str | "normal" or "tactical" (spread out, against splash damage). (0.9.5) |
| Resign() | — | Leave the match: your army is removed and you are out of the pot. Final. (0.9.5) |
A group action is sent as a single command, so it costs one action against the server rate limit regardless of group size — prefer the *Group variants over returning one action per unit.
Betting + mulligan overview
A match is wrapped in poker-style betting: one round before the RTS phase opens and one mid-game. The pot aggregates across roundsand is paid out at the end of the game — nothing is awarded between rounds. RTS-eliminated bots keep betting until they fold or run out of bankroll. Folding is resigning from the battlefield: your remaining units and buildings are removed and you forfeit the pot, but chips you already committed stay in it. Destroying an opponent's last military building earns an elimination bounty (one small blind) off the top of the pot.
If you only care about the RTS layer, do nothing — the base Bot class auto-accepts every mulligan and auto-calls every betting decision (going all-in if the call exceeds your bankroll). To play the betting game, override on_mulligan and/or on_bet_action.
from pachinko_sdk import (
Bot, BetDecision, BetObservation,
MulliganDecision, MulliganObservation,
)
class MyBot(Bot):
def on_mulligan(self, obs: MulliganObservation) -> MulliganDecision:
# Reroll the two lowest-rarity items if we can afford it.
from pachinko_sdk import Rarity
cheap = [i for i, item in enumerate(obs.items) if item.rarity == Rarity.COMMON]
return MulliganDecision.reroll(cheap[:2]) if cheap else MulliganDecision.accept()
def on_bet_action(self, obs: BetObservation) -> BetDecision:
# Fold to aggression if anyone has raised this round; otherwise call.
from pachinko_sdk import BetActionKind
raised = any(ev.action == BetActionKind.RAISE for ev in obs.history_this_round)
if raised and obs.to_call > obs.me.bankroll * 0.1:
return BetDecision.fold()
return BetDecision.call()MulliganObservation fields
| Name | Type | Description |
|---|---|---|
| items | list[StartingItem] | Your 5 dealt items: kind, rarity, unit_type, value. |
| bankroll | int | Chips remaining (rerolls cost big_blind each). |
| big_blind | int | Cost per rerolled index. |
| reroll_cost | int | Alias for big_blind. |
| map_info | MapInfo | None | Static map layout mirrored from GameStart, e.g. map_info.nodes_near(*map_info.my_spawn, k=3) to weigh your starting economy before betting. |
StartingItem fields
| Name | Type | Description |
|---|---|---|
| kind | ItemKind | Enum: ExtraProjectile, Ballistics, DamageBoost, SpeedBoost, ArmorBoost, SpawnRateBoost, HpBoost, CircleRangeBoost, CircleAttackSpeedBoost, CircleSplashDamage, CleaveAttack, ResourceRateBoost, HematiteBonus, HealthRegen, VisionBoost. |
| rarity | Rarity | Common, Uncommon, Rare, Legendary. |
| unit_type | UnitType | None | Square / Circle / Triangle for unit-targeted kinds; None otherwise. |
| value | float | Kind-specific magnitude (multiplier or flat bonus). |
| raw | dict | Original wire dict, in case you need a field this dataclass omits. |
BetObservation fields
| Name | Type | Description |
|---|---|---|
| round | int | 0 = pre-game round, 1+ = mid-game rounds. |
| my_player_id | int | Your slot id. |
| my_seat | int | Your index in this round's action_order. |
| action_order | list[int] | Player slots in the order they act this round. |
| pot | int | Cumulative chips in the pot (across all rounds). |
| current_bet | int | Total committed needed to stay in the round. |
| time_limit_secs | int | Round-level time budget. |
| action_time_secs | int | Per-actor time budget. |
| turn_timeout_secs | int | Seconds the server gives this decision before it folds the seat (30). (0.9.5) |
| players | list[PlayerBetState] | Per-slot snapshot: bankroll, committed (the seat's total across rounds), bet (this round's chips, in front of the seat), status, and profile — the seat's public PlayerProfile (reads), None when the server sent none. |
| my_items | list[StartingItem] | Your current hand: mulligan items plus every item picked up in-game since — refreshed just before each betting round, so mid-game bets see the real hand. |
| history_this_round | list[BetEvent] | Every BetUpdate seen this round, in order. |
| history_prior_rounds | list[list[BetEvent]] | Closed rounds, oldest first. |
| map_info | MapInfo | None | Static map layout mirrored from GameStart (terrain, node positions/richness, your spawn) so you can weigh your starting economy while betting. |
| to_call | int (property) | Chips needed to call (0 means a check is free). |
| can_check | bool (property) | True if to_call == 0. |
| me | PlayerBetState (property) | Shorthand for players[my_player_id]. |
Reads: PlayerProfile fields
Every seat comes with a public profile: the player-stat list, the same numbers under the same labels and definitions as the card at the betting table, the watch page and the profile pages (0.10.0; the rows below are generated from that list). Nothing else is sent: a person sees everything a bot and the house see. It is snapshotted at match start and delivered to everyone at the table on the same channel — on_game_start data has it on players[i]["profile"], every BetObservation on players[i].profile (and obs.me.profile: you, as the table sees you). The built-in AI reads Hands, Shoves and Opens for pre-game: it discounts a wide raiser's bet when weighing a call, never lets a habitual shover's big raise walk, adds a second caller about half the time, picks its caller by hand strength, and marks a called shover as its gang-up target in the RTS — all scaled by the raiser's wideness(), so an average player meets exactly the old house. Every seat that belongs to a user carries two profiles: the profile itself is the seat's own — this bot, or this person's own hands — and profile.accountis the whole account's (the person's own hands plus all of their bots), with the same fields. The built-in AI reads the seat's Shoves shrunk toward the account's, and the account's toward the population: a new bot starts with its account's reputation and earns its own (after about 30 hands its own record carries about 80% of the weight). House AIs have no account. The server's strength knob is 1.0 live and the same offline (ai_profile_aware); definitions and constants are in docs/PROFILES.md and docs/STATS.md of the repo.
| Name | Type | Description |
|---|---|---|
| kind / name / author / as_of | str / str / str | None / str | Seat kind (human, bot = house AI, pybot, account), display name, the pybot's author, and when the profile was taken. |
| matches | int | Hands. Hands played. A hand is one match: the deal, the betting, the battle and the payout. Read by the house AI and the house market. |
| hands_won_rate | float | Hands won. Share of hands won outright: the last seat standing, by battle or by everyone else folding. Read by the house market. |
| net_pnl | int | P&L. Chips won minus chips staked, over finished hands. |
| pnl_per_hand | float | P&L per hand. P&L divided by hands played. |
| recent_pnl | list[int] | Last 10 hands. P&L of each of the last 10 finished hands, newest first. |
| vpip | float | Plays hands (VPIP). Share of hands where the seat put chips in before the match by choice: a call, raise or all-in. |
| pfr | float | Raises first (PFR). Share of hands with a raise or all-in before the match. |
| three_bet_rate | float | Re-raises (3-bet). Share of betting rounds where the seat raised after someone else had raised. |
| check_raise_rate | float | Check-raises. Share of betting rounds where the seat checked, then raised after someone bet. |
| fold_rate | float | Folds. Share of hands the seat folded out of. |
| af | float | None | Aggression (AF). Raises and all-ins divided by calls. Empty for a seat that has never called. |
| pressure_success_rate | float | Wins by pressure. Share of the seat's raises and all-ins that made someone fold. |
| shove_rate | float | None | Shoves. Share of recent rated hands with a raise of 35% of the stack or more before the match. Read by the house AI. |
| open_size | float | None | Opens for. The seat's average raise before the match, as a share of its stack, over recent rated hands. Read by the house AI. |
| window_matches | float | The recent rated hands behind Shoves and Opens for, decayed (a hand 30 hands ago counts half). The cards show those two once it reaches 1. |
| samples | dict | Sample sizes behind Shoves and Opens for: {"shove", "open_size"}. |
| account | PlayerProfile | None | The seat's account (the person's own hands plus every bot they run) with the same fields (kind "account", its own account None). None for house AIs. |
| stat(key) | float | list | None | A listed stat by wire key or attribute ("handsWonRate" or "hands_won_rate"); None where the cards show "-". pachinko_sdk.view.STATS is the list itself: key, attribute, label, definition, format, who on the house side reads it. |
| shrunk(field, prior=None, k=None) | float | Shoves ("shove_rate") or Opens for ("open_size") shrunk the way the house does: (rate·samples + k·prior) / (samples + k), k = 10, where the prior is the account's shrunk rate when there is an account, the population prior otherwise. No samples → the prior. |
| wideness() | float | 0..1: how far the shrunk shove rate sits above the prior, full at a 50% shove rate — the number the built-in AI reads off a raiser, bit for bit (the engine's float32; Opens for is informational). |
| to_wire() / PlayerProfile.from_wire(d) | dict / PlayerProfile | The camelCase wire object (GameStart.players[].profile) and its parser; pass wire dicts or PlayerProfile objects to run_local(profiles=). |
| fetch_profile(name, kind=None) / fetch_player_stats(name, kind=None) | PlayerProfile / dict | A seat's public stats page by display name, online: the scouting a human does before a match. A pybot's name resolves on its own; kind= limits the lookup to one namespace. Raises when the name is unknown. profile_from_stats(stats) builds the profile from a payload you already fetched (its seatProfile). |
| PROFILE_PRIOR, PROFILE_PRIOR_K, PROFILE_HALF_LIFE, PROFILE_DECAY, BIG_RAISE_FRAC, WIDE_FULL, RANGE_DISCOUNT, SECOND_CALLER_TARGET | constants | The population prior, window, big-raise and AI-reaction constants (pachinko_sdk.profiles), identical to the server's. |
0.10.0 removed the fields no surface shows: wins, win_rate, firsts, first_place_rate, wins_by_battle, wins_by_foldout, podium_rate, avg_placement, recent_placements, betting_net_pnl, fold_to_big_raise, mid_raise_rate, heads_up_rate, win_rate_heads_up and win_rate_multiway. hands_won_rate * matches is the old wins.
BetEvent fields
| Name | Type | Description |
|---|---|---|
| player | int | Slot of the player who acted. |
| action | BetActionKind | Ante, Check, Bet, Call, Raise, Fold, AllIn. |
| amount | int | Chips put in for this action (0 for check/fold). |
| pot_after | int | Total pot after this action. |
| current_bet_after | int | current_bet after this action. |
Decision constructors
| Name | Type | Description |
|---|---|---|
| BetDecision.call() | BetDecision | Call (or check if obs.to_call == 0). Goes all-in if the call exceeds bankroll. |
| BetDecision.fold() | BetDecision | Fold. |
| BetDecision.raise_(amount) | BetDecision | Raise by `amount` chips on top of current_bet. |
| BetDecision.all_in() | BetDecision | All-in. |
| MulliganDecision.accept() | MulliganDecision | Lock in your current items. |
| MulliganDecision.reroll([0, 2]) | MulliganDecision | Reroll items at the listed indices (0..=4). Costs big_blind each; capped at 2 rerolled cards per match (the human limit) — extra indices are dropped uncharged. |
Settlement fields
Passed to on_match_settledat the end of a match, built from the server's MatchSettled message — online, and offline from the identical message run_local / LiveGame emit — so a bot reads it the same way in training and live play.
| Name | Type | Description |
|---|---|---|
| pot | int | Total cumulative pot for the match, in chips. |
| entries | tuple[SettlementEntry] | Per-slot terminal result, by slot. Each entry: player_id, net (bankroll delta, negative = loss), won (net > 0), rank (finishing position, 1-based; ties share). |
| my_rank | int (property) | Your own finishing position from entries, or -1 if unknown. |
| net | int (property) | Your own bankroll delta this match (0 if your slot is unknown). |
| won | bool (property) | True iff your own entry netted positive. |
| winners | list[int] (property) | Slots whose net was positive. |
| entry(player_id) | SettlementEntry | None | Look up one slot's result. |
| raw | dict | None | Original wire dict (online only); None in self-play. |
RL bots (Gymnasium)
RL bots are just regular .py bot scripts — the same format as deterministic bots. You train your model offline using pachinko_gym, then load the weights inside on_game_start and call your model in on_tick. You choose the architecture, the framework (PyTorch, JAX, anything), and the inference code. The game does not care how you produce the actions.
Train offline
pachinko_gym ships inside the same pachinko-pybind wheel you already installed for the live SDK. Use any RL library. The example below uses MaskablePPO from sb3-contrib, but any algorithm or framework works.
from pachinko_gym import PachinkoSeriesEnv
from sb3_contrib import MaskablePPO
env = PachinkoSeriesEnv()
model = MaskablePPO("MultiInputPolicy", env, verbose=1)
model.learn(total_timesteps=5_000_000)
model.save("my_rl_bot") # saves my_rl_bot.zip (SB3 format)From 0.9.5 the default is the live lobby: 8 seats, the built-in AI in the other seven, the live rules (pass num_players=2 for a duel). Your agent sits in seat 0 unless you pass seat=N or seat="random"— live shuffles seats and the observation is in absolute slots, so train with a random seat before you deploy. profiles=gives the seats public profiles for the AI's betting, reward="chips"pays the match's net chips instead of the placement grade. The learner does not bet or mulligan in the gym (it accepts and calls). The observation shape is identical for every player count (enemy tensors are per-opponent banks, unused seats zero), so a network trained in 1v1 carries unchanged into 8-player free-for-all.
Observation space
The environment exposes a Dict observation of fixed-shape float32 tensors. Enemy tables are banked by owning player slot— the bank index answers “whose unit is this”, per-opponent pooling is a slice, and the shape is the same from 1v1 to 8-player FFA:
| Name | Type | Description |
|---|---|---|
| own_units | (max_units, 7) | x, y, type, hp, has_target, attack_moving, present. Row index is a stable slot table — action rows address the same units. |
| own_buildings | (8, 13) | x, y, kind, hp, spawn_toggle, spawn_progress, present, + 6 upgrade levels. |
| enemy_units | (8, max_units, 7) | Per-opponent banks (bank = absolute player slot; your own bank is all-zero). Same 7 features; intent columns are hidden for enemies. |
| enemy_buildings | (8, 8, 13) | Per-opponent banks; upgrade columns hidden (fog rules). |
| globals | (11,) | resources, tick, bankroll, games_remaining, won_last, lost_last, items_collected, your slot, num_players, truncated_units, truncated_buildings. |
| resource_nodes | (32, 5) | x, y, richness, control (+1 you / 0 neutral / -1 enemy), owning slot (-1 neutral). |
| stars | (16, 5) | x, y, hp, tier, present — fog-filtered. |
| dropped_items | (32, 5) | x, y, kind, rarity, present — fog-filtered. |
max_units defaults to 512 rows per bank (constructor kwarg, up to 4096). Saturation is never silent: globals[9] / globals[10]count any entities that didn't fit this observation — if they're ever nonzero, raise max_units.
Multi-agent self-play
For FFA self-play (one process observing and commanding all seats), drop below the Gymnasium wrapper to the raw engine env: pass ai_seats=[] (or a partial list for mixed AI/self-play leagues), then drive each seat per tick:
import pachinko_pybind as p
env = p.PachinkoEnv(num_games=1, num_players=8, ai_seats=[])
env.reset(seed=1, return_obs=False)
while True:
for s in range(8):
obs = env.get_obs(s) # same Dict schema, any seat
env.submit_actions(s, unit_actions, building_actions)
done, info = env.step_submitted()
if done:
break
# info["ranks"] / info["rewards"] / info["bankrolls"] cover all 8 seats;
# terminal reward is placement-graded: +100 for 1st ... -100 for last.ai_seatscan also name any seats (including 0) for the built-in AI to drive — so you can train from an arbitrary seat. Randomize the learner's seat per episode: the enemy banks are absolute player slots, and the live server can seat your bot anywhere.
Training on the bot observation (LiveGame)
To train on the same GameState your bot sees online, use LiveGame: the engine plus the server's match layer, step by step. Undecided betting / mulligan turns take the SDK defaults (call / accept), so a training loop can ignore betting; read messages(seat) and answer with send(seat, json) to play it. It adds tools for throughput and imitation learning:
import json
import pachinko_pybind as p
from pachinko_sdk.state import parse_state
from pachinko_sdk.actions import action_from_dict, encode_action
def policy(state): # your model: GameState -> actions
return []
games = [p.LiveGame(8, seed=i, ai_seats=[1, 2, 3, 4, 5, 6, 7],
shadow_ai_seats=[0], messages=False) for i in range(32)]
p.LiveGame.step_many(games) # pre-game, then tick 1
while not all(g.is_over() for g in games):
for g in games:
state = parse_state(json.loads(g.observe(0))) # the online GameState fields
labels = [action_from_dict(d) for d in g.ai_orders(0)] # built-in AI's orders for seat 0
for action in policy(state):
g.send(0, json.dumps(encode_action(action))) # live intake: rate limit, validation
p.LiveGame.step_many(games, n_ticks=6) # all cores, GIL released| Name | Type | Description |
|---|---|---|
| LiveGame(n, seed, ai_seats, *, starting_items, betting, time_limit=21600, idle_end_secs=360, command_rate_limit, profiles=None, ai_profile_aware=1.0, …) | LiveGame | Live rules by default; every rule is a keyword. phase: mulligan / betting / running / ended. profiles: per-seat wire profiles (reads) the built-in AI bets by; ai_profile_aware: its strength knob. |
| step(n_ticks=1) | (bool, int) | Up to n ticks (stops early when a betting round opens or the match ends). Returns (over, winner_slot). |
| LiveGame.step_many(games, n_ticks=1, threads=0) | list[(bool, int)] | Step many games in parallel threads with the GIL released; identical to stepping them one by one. |
| send(seat, json) / messages(seat) | bool / list[str] | The online protocol: ClientMessage JSON in, the server's messages out. |
| snapshot() / restore(snap) | LiveGame / None | Independent copy of the whole match (and copy.deepcopy) for counterfactual rollouts or search. |
| shadow_ai_seats=[…] + ai_orders(seat) | list[dict] | The built-in AI's orders for a seat you drive (a shadow AI plays along without acting) — labels for imitation learning / DAgger. action_from_dict rebuilds SDK actions. |
| result() | dict | None | winner, end_reason, ranks, payouts (net chips), bounties — as the server pays. |
| marked_player() / threat_player() | (seat, weight) | None / seat | None | The pre-game aggressor the house AI has marked, and the seat it is ganging up on right now (0.9.7). |
| match_record() | dict | After the match: every betting action with its size and the actor's stack, the placements and the end reason — what ProfileAggregator.update consumes (docs/PROFILES.md §4). |
PachinkoEnv / PachinkoSeriesEnv(tensor observations) run the same match layer by default — starting items, AI betting and folds, the time cap and idle rule, the rate limit on your orders (one order per group of units sharing a target), the live economy — with knobs starting_items, betting, time_limit, idle_end_secs, command_rate_limit, group_orders, base_income. LocalGame is the raw engine with no match rules, for building your own environment.
Spatial observations: terrain, fog & feature planes
For a visual / CNN policy, the SDK can turn each tick into stacked 2D feature planes (the PySC2 / AlphaStar “feature layers” pattern). Everything lives on one grid (map_info.grid_height × grid_width, 125×125), so terrain, fog, and your rasterized entities align with no resampling.
The terrain grid (state.map_info) is static — sent once at game start, so you cache it. The fog plane (state.visibility) and entity positions update every tick. Featurizer caches the static planes once and rebuilds only the dynamic ones each tick:
from pachinko_sdk import Bot, Featurizer
class VisualBot(Bot):
def on_game_start(self, data):
self.feat = None
def on_tick(self, state):
if self.feat is None and state.map_info:
self.feat = Featurizer(state.map_info) # cache terrain planes ONCE
obs = self.feat.observe(state) # (C, H, W) float32, fresh each tick
# channels: ground, hill, mountain, slope, my_units, enemy_units,
# my_buildings, enemy_buildings, stars, dropped_items, visibility
return self.policy(obs) # -> your CNN -> actionsBuilding the planes is cheap (~0.25 ms/tick) and adds no network cost — the fog data is already on the wire. Prefer the local engine for training (no network, thousands of steps/s); env.fow(player_idx) exposes the same fog grid on the direct API. See examples/rl_feature_planes.py in the wheel for a runnable version with a plane viewer.
Write your bot script
A policy trained in PachinkoSeriesEnv sees tensors; a bot in a real match sees a GameState. From 0.9.5 pachinko_gym.PolicyBotis the bridge: it rebuilds the env's observation dict from each GameState, bit for bit (same shapes, row order, unit slot table and float32 arithmetic), and turns the env's action arrays into the same orders. The same object runs offline and online.
from pachinko_gym import PolicyBot
from pachinko_sdk import run_local, run_online
from sb3_contrib import MaskablePPO
model = MaskablePPO.load("my_rl_bot.zip")
bot = PolicyBot(lambda obs: model.predict(obs, deterministic=True)[0],
num_games=1) # max_units / num_games as in training
run_local(bot, num_players=8) # rehearse offline, live rules
run_online(bot,
orchestrator_url="https://pachinko-rts.com/orchestrator",
bot_token="bot_...your_token...")| Name | Type | Description |
|---|---|---|
| PolicyBot(policy, adapter=None, *, max_units=512, num_games=10, group_orders=True, on_obs=None) | Bot | policy(obs) returns the env's action dict (a (unit, building) pair or an SB3 predict result also work). Betting and the mulligan take the SDK defaults (accept, call), as the env did in training; subclass and override on_mulligan / on_bet_action to do better. |
| GymObsAdapter(max_units=512, num_games=10, group_orders=True) | adapter | The two halves on their own: observe(state) → the env observation, actions(action, state) → SDK actions. Keep one per seat; reset() starts a new series. |
| state_to_obs(state, max_units=512, …) | dict | One GameState to the env's tensors, stateless (no unit slot table). |
For your own observation encoding, write a normal bot: load the weights in on_game_start, encode state in on_tick, and return SDK actions. Train on the same encoding with LiveGame (above), which hands you the GameState a live bot receives.
Specs & self-play
Static spec tables
load_specs()returns the full rules table — unit, building and upgrade stats, RPS multipliers, economy and world constants. It's assembled from the engine's own constants, so it can never drift from the live rules, and it's immutable per match, so fetch it once.
from pachinko_sdk import load_specs
specs = load_specs() # cached after first call
specs.unit("triangle").speed # 3.125
specs.unit("square").attack # 15
specs.building("arrow_tower").vision # 200.0
specs.rps_multiplier("square", "triangle") # 1.5 (square beats triangle)
specs.economy["starting_bankroll"] # 1000UnitSpec: max_hp, attack, speed, cost, production_ticks, attack_range, vision, building_damage_mult, beats. BuildingSpec: max_hp, is_military, produces, vision, valid_upgrades (+ arrow-tower fire stats). UpgradeSpec: base_cost, max_level, per_level, effect.
Self-play economy
PyBettingState binds the realengine betting — blinds, process_action, side pots and distribute_winnings— so an offline tournament pays out bit-identically to the live match-server (no Python pot math to drift). Economy constants are exposed via economy_constants() and module constants (STARTING_BANKROLL, SMALL_BLIND, BIG_BLIND, MIN_RAISE). See examples/selfplay_betting.py in the wheel for a runnable bankroll tournament that ranks bots by money across games.
Operating notes
Command rate limit
The server enforces a token-bucket rate limit per player: 10 commands per second sustained, with a burst allowance of up to 20 commands. Commands beyond the burst cap are silently dropped — they do not error, the game just ignores them. Returning a large list from on_tick is fine occasionally (the burst absorbs it), but flooding hundreds of actions every tick will result in most being discarded. Prioritise and keep lists concise. state.command_tokens shows the budget you have right now and state.commands_droppedcounts what the server dropped; a common cause is re-ordering units that are already busy — skip units whose has_target is True.
Connection drops
run_online reconnects to a match by itself and logs match WS dropped mid-game (reason) -- attempting to reconnect. If you see that line often on an SDK older than 0.9.5, upgrade: those versions could close their own healthy connection, and a drop in the first moments of a match lost it. Your bot hears about a reconnect in on_reconnect; rehearse it offline with run_local(reconnect_at_ticks=[...]).
Token security
Treat your bot token like a password. Anyone with it can play matches as your bot and lose its bankroll. If a token leaks, rotate it from My Bots — the old token stops working immediately.
Logging and debugging
The SDK uses standard Python logging. Enable info-level output to watch the connect / poll / match lifecycle:
import logging
logging.basicConfig(level=logging.INFO)Watch your bot live on the Spectate page once a match starts.