Untitled

HexDroid Scripting Detected boxlabs 8 Views Size: 85.43 KB Posted on: Nov 24, 26 @ 11:04 PM
  1. ; Poker Night for HexDroid
  2. ;
  3. ; A multiplayer discord-like poker game for IRC
  4. ;   data model (lists/maps)  +  view{} table  +  age.* encrypted transport
  5. ;
  6. ; the player who opens the table deals. The dealer sees every hand (it scores the showdown),
  7. ; so play with people you trust. It publishes a hash of each deck's seed at the deal and the seed
  8. ; when the hand ends, so every player can check the cards weren't changed mid-hand.
  9. ;
  10. ; only players in the channel can sit down, and leaving it (part, quit, kick, lost
  11. ; connection) takes you off the table at once. Each device also checks in every 10 s, so a phone
  12. ; that dies behind a bouncer is noticed within about a minute. Coming back within five minutes
  13. ; restores your chips.
  14.  
  15.  
  16. on LOAD {
  17.   set %watchgen 0
  18.   set %hbgen 0
  19.   set %sb 5
  20.   set %bb 10
  21.   set %rankmap $map(A,14,K,13,Q,12,J,11,T,10,9,9,8,8,7,7,6,6,5,5,4,4,3,3,2,2)
  22.   ; default avatars: a stable emoji face per player (picked from a hash of their fingerprint) so a
  23.   ; seat is instantly recognisable instead of a bare initial. An uploaded photo still wins over it.
  24.   set %emojimap $map(0,🦊,1,🐼,2,🐵,3,🐯,4,🦁,5,🐸,6,🐙,7,🦉,8,🐺,9,🐷,a,🐨,b,🐰,c,🦝,d,🐮,e,🐳,f,🦄)
  25.   poker_reset
  26.   sidebar add poker poker_open ♠ Play Poker
  27. }
  28.  
  29. ; Full reset to a clean lobby. Used on load AND when the table is closed, so closing a game
  30. ; terminates it completely - re-opening (even on a different network) shows a fresh lobby
  31. ; instead of the previous hand.
  32. alias poker_reset {
  33.   set %practice 0
  34.   set %chan #game
  35.   set %hosted 0
  36.   set %ishost 0
  37.   set %hostlocked 0        ; host decided for this table (we minted, or adopted a host's key): freeze it
  38.   set %bots $map()
  39.   set %seats $list()
  40.   set %name $map()
  41.   set %stack $map()
  42.   set %bet $map()
  43.   set %folded $map()
  44.   set %board $list()
  45.   set %myhole $map()
  46.   set %hole $map()
  47.   set %reveal $map()       ; fp->"c1 c2" of non-folded hands, populated ONLY at showdown then
  48.   set %started 0
  49.   set %street lobby
  50.   set %pot 0
  51.   set %tocall 0
  52.   set %turn 0
  53.   set %betamount 0
  54.   set %handid 0
  55.   set %button 0
  56.   set %hostfp
  57.   set %hostfrom            ; fp we accept authoritative state + STOP from (the dealer that keyed the table)
  58.   set %gameover 0
  59.   set %champion
  60.   set %startstack 1000
  61.   set %winners $list()
  62.   set %winnertext
  63.   set %allin $map()
  64.   set %turnid 0            ; bumped every time the turn moves; a stale clock tick is ignored
  65.   set %actclockms 45000    ; per-turn shot-clock (ms); the host auto-checks/folds an AWOL player
  66.   set %pending $map()      ; fp->name of players who joined mid-hand; seated at the next deal
  67.   set %clockleft 0         ; visual per-turn countdown (seconds), ticked locally on every node
  68.   set %clockturn 0         ; last %turnid a countdown was started for (avoids restart on re-broadcast)
  69.   set %avatar $map()       ; optional fp->image-URL for player avatars; empty falls back to initials
  70.   set %evseq 0             ; host: monotonic broadcast sequence (full states AND deltas share it)
  71.   set %cliseq 0            ; client: highest broadcast sequence applied, for delta gap detection
  72.   set %resyncing 0         ; client: 1 while waiting for a full-state resync after a detected gap
  73.   set %advturn 0           ; host: poker_advance set this to 1 iff it only moved the turn (=> delta-able)
  74.   set %lastraise 0         ; size of the last full raise this round; a raise must add at least this
  75.   set %noreraise $map()    ; fp->1: acted before a short all-in, so may only call or fold this round
  76.   set %minraiseto          ; client: smallest legal raise-to for the seat to act (0 = may not raise)
  77.   set %strikes $map()      ; host: consecutive turns a seat timed out on; two removes them
  78.   set %leaving $map()      ; host: seats to remove at the next deal
  79.   set %commit              ; hash of this hand's deck seed, published at the deal
  80.   set %revealseed          ; host: the seed, published once the hand ends so players can check the deal
  81.   set %checkedhand         ; client: the commitment whose deal we already checked
  82.   set %holefresh 0         ; client: hole cards arrived since the last new commitment
  83.   set %holehand            ; client: the commitment our current hole cards were dealt under
  84.   set %hostquiet 0         ; client: watchdog ticks since the dealer was last heard
  85.   set %watching 0
  86.   set %silent $map()       ; host: presence sweeps since each player's device last checked in
  87.   set %gone $map()         ; host: fp->generation for players who left and may come back in time
  88.   set %forgotten $map()    ; host: players whose grace ran out; a rejoin is a fresh buy-in
  89.   set %gonegen 0
  90.   set %lastact $map()      ; fp->CHECK|CALL|RAISE|ALL-IN|FOLD, this street, shown on the seat
  91.   ; bumping a generation stops any timer loop left over from an earlier table
  92.   set %watchgen $calc(%watchgen + 1)
  93.   set %hbgen $calc(%hbgen + 1)
  94. }
  95.  
  96. ; ---- open / join -----------------------------------------------------------
  97. ; The sidebar entry point: just (re)draw the table. Render copes with every state
  98. ; (empty lobby, seated-and-waiting, mid-hand, showdown).
  99. alias poker_open { set %closed 0 | poker_render }
  100.  
  101. ; /poker_avatar <url>  - set your own table avatar image (empty URL clears it back to your initial).
  102. ; Local to this device; others keep whatever avatar they have set for you.
  103. alias poker_avatar {
  104.   setat %avatar $age.me $1-
  105.   poker_render
  106. }
  107.  
  108. ; The user tapped Close on the table → halt the bot loop so a pending timer tick can't
  109. ; re-render and pop the table straight back open.
  110. on SIGNAL:view_closed {
  111.   ; Closing the table properly. %closed latches FIRST so that nothing below (or any inbound state /
  112.   ; delta / timer tick that lands afterwards) can re-render and pop the table straight back open.
  113.   ; poker_endtable is an ALIAS, not a signal handler: a bare verb here only resolves against aliases,
  114.   ; so naming a signal handler would fall through to the slash pipeline and hit the server as an
  115.   ; unknown command, leaving the table running with no way to stop it.
  116.   set %closed 1
  117.   poker_endtable
  118. }
  119.  
  120. ; Dealer ends the table: drop our queued flood first (so STOP isn't stuck behind it or dropped by the
  121. ; purge), broadcast an authenticated STOP move, then tear our own key/roster down. "Anyone can re-open"
  122. ; falls out naturally: once everyone has torn down, normal election lets any player open a fresh table.
  123. ; A non-dealer just leaves quietly. Defined as an alias so it is callable as a plain verb (buttons
  124. ; raise SIGNALs, so the button is wired through the thin handler below).
  125. alias poker_endtable {
  126.   if (%practice == 1) { poker_reset | return }
  127.   if (%ishost == 1 && %hosted == 1) {
  128.     age.purge %chan          ; discard the paced-out state-broadcast backlog while we still hold K_G
  129.     age.send %chan stop       ; authenticated, members-only STOP into the now-drained queue
  130.     age.close %chan           ; drop key/roster locally. NOT a purge, so the queued STOP still goes out
  131.     poker_reset
  132.     return
  133.   }
  134.   poker_teardown              ; not actually the dealer: just leave and clean up
  135. }
  136.  
  137. ; The header "End Table" button (buttons raise SIGNAL:<name>). Ends the table and redraws the lobby;
  138. ; the redraw is a no-op when this arrived via a closed view, because poker_render honours %closed.
  139. on SIGNAL:poker_stop {
  140.   poker_endtable
  141.   poker_render
  142. }
  143.  
  144. ; We received the dealer's STOP: drop our own queued flood and tear down.
  145. alias poker_onstop {
  146.   toast The dealer ended the table
  147.   poker_teardown
  148.   poker_render                ; drop back to the lobby (no-op if we already closed the view)
  149. }
  150.  
  151. ; Local teardown shared by every close path: purge any of our queued AGE for this table, drop the
  152. ; key/roster/announce state in the bridge (age.close), then reset the game model. age.close is a no-op
  153. ; in practice. Order: purge before close so nothing for this channel is left trickling out.
  154. alias poker_teardown {
  155.   if (%practice == 0) { age.purge %chan | age.close %chan }
  156.   poker_reset
  157. }
  158.  
  159. alias poker {
  160.   ; Practice runs entirely on the local loopback (#practice is never an IRC channel).
  161.   ; A real game must actually be in the shared IRC channel so peers can exchange +AGE lines.
  162.   if (%practice == 0) { join %chan }
  163.   age.join %chan                              ; announce our +AGE identity (real: broadcast; practice: skipped)
  164.   age.send %chan join $age.me $me 1000        ; register me (local always; to peers once the host has keyed)
  165.   if (%practice == 0) { toast Joined %chan, waiting for the host to start the hand }
  166.   else { toast Joined the table - waiting for players }
  167. }
  168.  
  169. ; lobby buttons
  170. on SIGNAL:poker_join  { poker }
  171. on SIGNAL:poker_start {
  172.   if (%gameover == 1) { return }
  173.   if (%practice == 1) { poker_deal | return }
  174.   ; The player who taps Open HOSTS the table. Host is decided by action, never by fingerprint order:
  175.   ; electing the lowest fingerprint made the tapper stand down whenever it wasn't the lowest, while
  176.   ; the elected owner's device sat showing an Open button nobody tapped - so nobody minted and both
  177.   ; sides waited forever. If two players tap at the same moment both mint, and the bridge converges
  178.   ; on the lower fingerprint's key (invite authorisation); the loser adopts it via age_ready and
  179.   ; stops being host. Once a host exists (%hostlocked) it never changes for the life of the table.
  180.   if (%hostlocked == 1 && %ishost == 0) { toast Waiting for the host to start the hand | return }
  181.   if (%hosted == 0) { poker_host | return }
  182.   poker_deal
  183. }
  184.  
  185. ; Mint the shared table key and lock ourselves in as host for the life of this table.
  186. alias poker_host {
  187.   age.host %chan
  188.   set %hosted 1
  189.   set %hostlocked 1
  190.   set %ishost 1
  191.   set %hostfp %me
  192.   set %hbgen $calc(%hbgen + 1)
  193.   timer 15000 poker_hb %hbgen
  194.   poker_render
  195.   toast Table keyed. Players are joining; tap Deal when ready
  196. }
  197.  
  198. ; Dealer heartbeat, so players can tell a quiet table from a dealer who has gone.
  199. on SIGNAL:poker_hb {
  200.   if ($1 != %hbgen) { return }
  201.   if (%ishost == 0) { return }
  202.   if (%hosted == 0) { return }
  203.   age.send %chan hb
  204.   poker_sweeppresence
  205.   timer 15000 poker_hb %hbgen
  206. }
  207.  
  208. ; Player watchdog: a dealer silent for about a minute (no state, move or heartbeat) has left, and
  209. ; the table can't continue without it.
  210. alias poker_watchstart {
  211.   if (%watching == 1) { return }
  212.   set %watching 1
  213.   set %watchgen $calc(%watchgen + 1)
  214.   timer 10000 poker_watch %watchgen
  215. }
  216.  
  217. on SIGNAL:poker_watch {
  218.   if ($1 != %watchgen) { return }
  219.   if (%ishost == 1) { set %watching 0 | return }
  220.   if ($len(%hostfrom) == 0) { set %watching 0 | return }
  221.   if ($has(%name,$age.me) == true) { age.send %chan alive }
  222.   set %hostquiet $calc(%hostquiet + 1)
  223.   if (%hostquiet >= 6) {
  224.     set %watching 0
  225.     toast The dealer stopped responding, so the table has ended
  226.     poker_teardown
  227.     poker_render
  228.     return
  229.   }
  230.   timer 10000 poker_watch %watchgen
  231. }
  232.  
  233. on SIGNAL:age_peer {
  234.   ; a +AGE peer announced on $chan: refresh the lobby so a new arrival shows up. Host election is not
  235.   ; re-run here - the host is whoever opened the table, and %hostlocked freezes it.
  236.   if ($chan != %chan) { return }
  237.   poker_render
  238. }
  239.  
  240. on SIGNAL:age_ready {
  241.   ; the shared table key just arrived: we are a CLIENT, not the host (a host mints its own key and
  242.   ; never receives an invite). This also covers losing a simultaneous-open race: we minted, the peer's
  243.   ; lower-fingerprint key won, and we adopt it and stop hosting. Register at the table over the
  244.   ; now-encrypted channel so the host sees us seated.
  245.   set %hostlocked 1
  246.   set %ishost 0
  247.   set %hosted 0
  248.   if (%practice == 0) { age.send %chan join $age.me $me 1000 }
  249. }
  250.  
  251. on SIGNAL:age_msg {
  252.   ; $from = sender fp ; $1 = move type ; $2- = payload
  253.   ; Host-authoritative: the dealer runs all game logic and broadcasts state; clients render it.
  254.   set %me $age.me
  255.   if ($1 == join)      { poker_onjoin $1 $2 $3 $4 }
  256.   elseif ($1 == act)   { if (%ishost == 1) { poker_onact $1 $2 $3 } }
  257.   elseif ($1 == state) { if ($from != %me) { set %hostfrom $from | set %hostquiet 0 | poker_watchstart | poker_applystate $2- } }
  258.   ; Pass the delta's tokens through INDIVIDUALLY. `$3-` would arrive as a single joined argument
  259.   ; (that is what `poker_applystate $2-` wants for its JSON blob), so the alias would see the whole
  260.   ; rest of the line as $2 and never match "act": the delta was silently dropped and the client sat
  261.   ; on a stale turn. Tokens: ev seq act fp bet stack fold allin pot tocall turn turnid.
  262.   elseif ($1 == ev)    { if ($from != %me) { set %hostfrom $from | set %hostquiet 0 | poker_onev $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 } }
  263.   elseif ($1 == hb)    { if ($from == %hostfrom) { set %hostquiet 0 } }
  264.   elseif ($1 == alive) { if (%ishost == 1) { setat %silent $from 0 } }
  265.   elseif ($1 == sync)  { if (%ishost == 1 && $from != %me) { poker_broadcast } }   ; a client missed a delta; resend full state
  266.   elseif ($1 == stop)  {
  267.     ; the dealer ended the table. Honour STOP only from the authenticated host we've been following
  268.     ; (the signature already proves $from; this stops a non-dealer member from nuking the table), and
  269.     ; never from our own local echo (the sender tears down in poker_stop instead).
  270.     if ($from != %me && $from == %hostfrom) { poker_onstop }
  271.   }
  272. }
  273.  
  274. ; Someone left the game channel: part, quit, kick, or our own connection dropping ($from is then us).
  275. on SIGNAL:age_left {
  276.   if ($chan != %chan) { return }
  277.   poker_onleft $from
  278. }
  279.  
  280. ; $1 = the fingerprint that left. We left: tear down. The dealer left: the table ends. As dealer:
  281. ; take the player off the table now, keeping their chips for the grace period in case they return.
  282. alias poker_onleft {
  283.   set %lfp $1
  284.   if (%practice == 1) { return }
  285.   if (%lfp == $age.me) {
  286.     if (%hostlocked == 1) { toast You left the table }
  287.     poker_teardown
  288.     poker_render
  289.     return
  290.   }
  291.   if (%ishost == 0) {
  292.     if (%lfp == %hostfrom) {
  293.       toast The dealer left, so the table has ended
  294.       poker_teardown
  295.       poker_render
  296.     }
  297.     return
  298.   }
  299.   set %seatedl 0
  300.   if ($has(%seats,%lfp) == true) { set %seatedl 1 }
  301.   if ($get(%pending,%lfp) == 1) { set %seatedl 1 }
  302.   if (%seatedl == 0) { return }
  303.   setat %pending %lfp 0
  304.   setat %silent %lfp 0
  305.   ; keep their chips for five minutes; poker_forget releases them after that
  306.   set %gonegen $calc(%gonegen + 1)
  307.   setat %gone %lfp %gonegen
  308.   timer 300000 poker_forget %lfp %gonegen
  309.   setat %leaving %lfp 1
  310.   if (%started == 1) {
  311.     ; In a hand: fold them, unless they're all-in, whose chips are committed and play to showdown.
  312.     if ($has(%seats,%lfp) == true) { if ($get(%folded,%lfp) != 1) { if ($get(%allin,%lfp) != 1) {
  313.       if ($get(%seats,%turn) == %lfp) { age.local %lfp act fold }
  314.       else {
  315.         setat %folded %lfp 1
  316.         setat %acted %lfp 1
  317.         poker_checkfoldout
  318.       }
  319.     } } }
  320.   } else {
  321.     poker_removeleavers
  322.   }
  323.   toast $get(%name,%lfp) left the table
  324.   poker_broadcast
  325.   poker_render
  326. }
  327.  
  328. ; Host: a fold outside the player's turn can leave one player standing, who wins at once.
  329. alias poker_checkfoldout {
  330.   set %live 0
  331.   set %onlyfp
  332.   foreach %fp %seats { if ($get(%folded,%fp) != 1) { set %live $calc(%live + 1) | set %onlyfp %fp } }
  333.   if (%live < 2) { poker_endhand %onlyfp }
  334. }
  335.  
  336. ; A departed player's grace ran out ($1 fp, $2 generation): their chips are released, so coming
  337. ; back later is a fresh buy-in.
  338. on SIGNAL:poker_forget {
  339.   if ($get(%gone,$1) != $2) { return }
  340.   if ($has(%seats,$1) == true) { return }
  341.   setat %gone $1 0
  342.   setat %forgotten $1 1
  343. }
  344.  
  345. ; Host: take the seats marked in %leaving off the table. The button stays with the same player
  346. ; where it can; if they left, the next deal's button move lands on whoever sat after them.
  347. alias poker_removeleavers {
  348.   set %anyleaving 0
  349.   foreach %fp %seats { if ($get(%leaving,%fp) == 1) { set %anyleaving 1 } }
  350.   if (%anyleaving == 0) { set %leaving $map() | return }
  351.   set %oldbtn %button
  352.   set %btnfp $get(%seats,%button)
  353.   set %kept $list()
  354.   foreach %fp %seats { if ($get(%leaving,%fp) != 1) { push %kept %fp } }
  355.   set %seats %kept
  356.   set %leaving $map()
  357.   if ($len(%seats) == 0) { set %button 0 | return }
  358.   set %button $find(%seats,%btnfp)
  359.   if (%button < 0) { set %button $mod($calc(%oldbtn - 1 + $len(%seats)), $len(%seats)) }
  360. }
  361.  
  362. ; Host presence sweep, every heartbeat: a player's device checks in every 10 s, so one silent for
  363. ; four sweeps (about a minute) is gone even if IRC still shows them, as behind a bouncer.
  364. alias poker_sweeppresence {
  365.   set %quietfps $list()
  366.   foreach %fp %seats { poker_tickpresence %fp }
  367.   foreach %fp $keys(%pending) { if ($get(%pending,%fp) == 1) { poker_tickpresence %fp } }
  368.   foreach %qfp %quietfps { poker_onleft %qfp }
  369. }
  370.  
  371. alias poker_tickpresence {
  372.   if ($1 == $age.me) { return }
  373.   if ($has(%bots,$1) == true) { return }
  374.   set %sil $calc($get(%silent,$1) + 1)
  375.   setat %silent $1 %sil
  376.   if (%sil >= 4) { push %quietfps $1 }
  377. }
  378.  
  379. ; ---- host-authoritative state sync -----------------------------------------
  380. alias poker_sethost {
  381.   set %me $age.me
  382.   if (%practice == 1) { set %ishost 1 | set %hostfp %me | return }
  383.   ; Host is decided by ACTION (who tapped Open), not by fingerprint order. %hostlocked is set when we
  384.   ; mint (poker_host) or when we adopt a host's key (age_ready), and from then on the host is fixed
  385.   ; for the life of the table - a later joiner can never steal authority mid-hand. Before any table
  386.   ; exists nobody is host yet, and anyone may open one.
  387.   if (%hostlocked == 1) { return }
  388.   set %ishost 0
  389.   set %hostfp
  390. }
  391.  
  392. ; ---- seat helpers: find the next seat still in the hand / able to act ----------
  393. ; A busted or folded seat is skipped. These use locals (set -l) so they never clobber
  394. ; a caller's %n/%fp/%idx while it is mid-loop.
  395. alias poker_nextin {
  396.   ; $1 = start index; returns the next index (wrapping) whose seat isn't folded/busted
  397.   set -l %n $len(%seats)
  398.   set -l %k 0
  399.   while (%k < %n) {
  400.     set -l %idx $mod($calc($1 + %k), %n)
  401.     if ($get(%folded, $get(%seats, %idx)) != 1) { return %idx }
  402.     set -l %k $calc(%k + 1)
  403.   }
  404.   return $mod($1, %n)
  405. }
  406. alias poker_nextactor {
  407.   ; $1 = start index; returns the next index (wrapping) that can still act (not folded, not all-in)
  408.   set -l %n $len(%seats)
  409.   set -l %k 0
  410.   while (%k < %n) {
  411.     set -l %idx $mod($calc($1 + %k), %n)
  412.     set -l %fp $get(%seats, %idx)
  413.     if ($get(%folded, %fp) != 1) { if ($get(%allin, %fp) != 1) { return %idx } }
  414.     set -l %k $calc(%k + 1)
  415.   }
  416.   return $mod($1, %n)
  417. }
  418.  
  419. alias poker_broadcast {
  420.   if (%ishost == 0) { return }
  421.   set %evseq $calc(%evseq + 1)   ; full states and deltas share one monotonic sequence (carried as q)
  422.   ; Compact wire state (age_msg reassembles tokens with $2-, single spaces; keep names free of
  423.   ; double spaces). Per-player fields are arrays ALIGNED TO %seats (each fp once, not repeated as
  424.   ; map keys); top-level keys are single letters; default/empty fields are omitted so a mid-hand
  425.   ; update usually fits ONE AGE line. Key legend (mirrored in poker_applystate):
  426.   ;   s=seats n=names k=stacks b=bets f=folded a=allin d=board r=reveal p=pot c=tocall
  427.   ;   t=turn e=street y=started u=button g=turnid w=winner o=gameover h=champion
  428.   set %aN $list()
  429.   set %aS $list()
  430.   set %aB $list()
  431.   set %aF $list()
  432.   set %aA $list()
  433.   set %aR $list()
  434.   set %hasrev 0
  435.   foreach %fp %seats {
  436.     push %aN $get(%name,%fp)
  437.     push %aS $get(%stack,%fp)
  438.     push %aB $get(%bet,%fp)
  439.     push %aF $get(%folded,%fp)
  440.     push %aA $get(%allin,%fp)
  441.     set %rvv $get(%reveal,%fp)
  442.     push %aR %rvv
  443.     if ($len(%rvv) > 0) { set %hasrev 1 }
  444.   }
  445.   set %st $map()
  446.   setat %st s %seats
  447.   setat %st n %aN
  448.   setat %st k %aS
  449.   setat %st b %aB
  450.   setat %st f %aF
  451.   setat %st a %aA
  452.   setat %st d %board
  453.   if (%hasrev == 1) { setat %st r %aR }        ; only at showdown; mid-hand it is all mucked
  454.   setat %st p %pot
  455.   setat %st c %tocall
  456.   setat %st t %turn
  457.   setat %st e %street
  458.   setat %st y %started
  459.   setat %st u %button
  460.   setat %st q %evseq                                     ; sequence baseline so clients can gap-check deltas
  461.   setat %st g %turnid
  462.   if (%started == 1) { setat %st m $poker_minraise }       ; smallest legal raise-to for the seat to act
  463.   if ($len(%commit) > 0) { setat %st z %commit }            ; this hand's deck commitment
  464.   if (%started == 0) { if ($len(%revealseed) > 0) { setat %st x %revealseed } }   ; its seed, once over
  465.   if ($len(%winnertext) > 0) { setat %st w %winnertext }   ; only on a result
  466.   if (%gameover == 1) { setat %st o 1 }                     ; only when the table has ended
  467.   if ($len(%champion) > 0) { setat %st h %champion }
  468.   age.send %chan state $tojson(%st)
  469. }
  470.  
  471. ; Host: broadcast just the fields an in-street action changes, as ONE short line (no FRAG), instead of
  472. ; the whole table. $1 = the acting fp. A dropped delta is caught by the sequence gap check in
  473. ; poker_onev and healed with a full-state resync, so this stays lossless.
  474. alias poker_evact {
  475.   if (%ishost == 0) { return }
  476.   set %evseq $calc(%evseq + 1)
  477.   set %efd 0
  478.   if ($get(%folded,$1) == 1) { set %efd 1 }
  479.   set %eai 0
  480.   if ($get(%allin,$1) == 1) { set %eai 1 }
  481.   age.send %chan ev %evseq act $1 $get(%bet,$1) $get(%stack,$1) %efd %eai %pot %tocall %turn %turnid $poker_minraise
  482. }
  483.  
  484. ; The smallest legal raise-to for the seat to act, or 0 when it may only call or fold.
  485. alias poker_minraise {
  486.   set -l %cur $get(%seats,%turn)
  487.   if ($get(%noreraise,%cur) == 1) { return 0 }
  488.   return $calc(%tocall + %lastraise)
  489. }
  490.  
  491. ; Client: apply an inbound delta. Called as poker_onev <seq> <type> <payload...>. Enforces contiguity
  492. ; against %cliseq; a gap means we missed a delta, so ask the host once for a full resync and ignore
  493. ; further deltas until it lands (poker_applystate clears %resyncing).
  494. alias poker_onev {
  495.   if (%ishost == 1) { return }                     ; the host is authoritative; it never applies deltas
  496.   set %eseq $1
  497.   if (%eseq <= %cliseq) { return }                 ; stale / duplicate
  498.   if (%eseq > $calc(%cliseq + 1)) {
  499.     if (%resyncing == 0) { set %resyncing 1 | age.send %chan sync }
  500.     return
  501.   }
  502.   if ($2 == act) { poker_ev_act $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 }
  503.   set %cliseq %eseq
  504.   poker_startclock
  505.   poker_render
  506. }
  507.  
  508. ; Apply an act delta: $1 fp  $2 bet  $3 stack  $4 fold  $5 allin  $6 pot  $7 tocall  $8 turn  $9 turnid
  509. ; $10 min raise-to (absent from older dealers). folded/allin only latch on, matching poker_applystate.
  510. alias poker_ev_act {
  511.   set %betbefore $get(%bet,$1)
  512.   set %callbefore %tocall
  513.   setat %bet $1 $2
  514.   setat %stack $1 $3
  515.   if ($4 == 1) { setat %folded $1 1 }
  516.   if ($5 == 1) { setat %allin $1 1 }
  517.   set %pot $6
  518.   set %tocall $7
  519.   set %turn $8
  520.   set %turnid $9
  521.   set %minraiseto $10
  522.   setat %lastact $1 $poker_actlabel($1, %betbefore, %callbefore)
  523. }
  524.  
  525. ; What seat $1 just did, from its bet before ($2) and the amount to call before ($3).
  526. alias poker_actlabel {
  527.   if ($get(%folded,$1) == 1) { return FOLD }
  528.   if ($get(%allin,$1) == 1) { return ALL-IN }
  529.   set -l %nb $get(%bet,$1)
  530.   if ($len(%nb) == 0) { set -l %nb 0 }
  531.   if (%nb > $3) { return RAISE }
  532.   if (%nb > $2) { return CALL }
  533.   return CHECK
  534. }
  535.  
  536. alias poker_applystate {
  537.   set %j $1-
  538.   set %seats $list()
  539.   set %i 0
  540.   set %go 1
  541.   while (%go == 1) {
  542.     set %fp $json(%j, s.%i)
  543.     if ($len(%fp) == 0) { set %go 0 } else { push %seats %fp | set %i $calc(%i + 1) }
  544.   }
  545.   set %board $list()
  546.   set %i 0
  547.   set %go 1
  548.   while (%go == 1) {
  549.     set %cd $json(%j, d.%i)
  550.     if ($len(%cd) == 0) { set %go 0 } else { push %board %cd | set %i $calc(%i + 1) }
  551.   }
  552.   set %name $map()
  553.   set %stack $map()
  554.   set %bet $map()
  555.   set %folded $map()
  556.   set %allin $map()
  557.   set %reveal $map()
  558.   ; per-player fields arrive as arrays aligned to %seats (see poker_broadcast); zip them by index.
  559.   set %i 0
  560.   foreach %fp %seats {
  561.     setat %name %fp $json(%j, n.%i)
  562.     setat %stack %fp $json(%j, k.%i)
  563.     set %bv $json(%j, b.%i)
  564.     if ($len(%bv) > 0) { setat %bet %fp %bv }
  565.     set %fd $json(%j, f.%i)
  566.     if (%fd == 1) { setat %folded %fp 1 }
  567.     set %ai $json(%j, a.%i)
  568.     if (%ai == 1) { setat %allin %fp 1 }
  569.     set %rv $json(%j, r.%i)
  570.     if ($len(%rv) > 0) { setat %reveal %fp %rv }
  571.     set %i $calc(%i + 1)
  572.   }
  573.   set %pot $json(%j, p)
  574.   set %tocall $json(%j, c)
  575.   set %turn $json(%j, t)
  576.   set %street $json(%j, e)
  577.   set %started $json(%j, y)
  578.   set %button $json(%j, u)
  579.   set %turnid $json(%j, g)
  580.   set %minraiseto $json(%j, m)
  581.   if (%street != %laststreet) { set %lastact $map() | set %laststreet %street }
  582.   ; A new commitment starts a new hand. Our sealed cards arrive just before its first state, so
  583.   ; only cards received since the previous commitment belong to it.
  584.   set %zv $json(%j, z)
  585.   if ($len(%zv) > 0) { if (%zv != %commit) {
  586.     set %holehand
  587.     if (%holefresh == 1) { set %holehand %zv }
  588.     set %holefresh 0
  589.     set %commit %zv
  590.   } }
  591.   set %xv $json(%j, x)
  592.   if ($len(%xv) > 0) { if (%checkedhand != %commit) { poker_checkdeal %xv } }
  593.   ; A full state is an authoritative resync point: adopt its sequence baseline and clear any pending
  594.   ; gap so subsequent deltas are measured from here.
  595.   set %qv $json(%j, q)
  596.   if ($len(%qv) > 0) { set %cliseq %qv }
  597.   set %resyncing 0
  598.   ; winner/gameover/champion are omitted from the wire unless set, so a missing field restores to
  599.   ; empty / 0 ("not over", no banner) - correct for a live hand.
  600.   set %winnertext $json(%j, w)
  601.   set %gameover $json(%j, o)
  602.   if ($len(%gameover) == 0) { set %gameover 0 }
  603.   set %champion $json(%j, h)
  604.   poker_sethost
  605.   poker_startclock
  606.   poker_render
  607. }
  608.  
  609. alias poker_onjoin {
  610.   ; $2 = fp, $3 = name, $4 = stack
  611.   ; track roster as a map fp->name and an ordered list (idempotent on rejoin). A brand-new player
  612.   ; who arrives mid-hand is parked in %pending and seated at the next deal, so a join never
  613.   ; renumbers %seats or shifts the turn pointer inside a live hand.
  614.   ; Only players present in the channel may sit down. $age.members lists the +AGE peers here now;
  615.   ; an empty list (nobody announced yet, or an older app) doesn't block anyone.
  616.   if (%practice == 0) { if ($2 != $age.me) {
  617.     set %herefps $age.members(%chan)
  618.     if ($len(%herefps) > 0) { if ($has($split(%herefps),$2) == false) { return } }
  619.   } }
  620.   set %newp 0
  621.   if ($has(%name,$2) == false) { set %newp 1 }
  622.   if ($get(%forgotten,$2) == 1) { set %newp 1 | setat %forgotten $2 0 }
  623.   setat %gone $2 0
  624.   setat %silent $2 0
  625.   setat %name $2 $3
  626.   ; the buy-in stack in $4 applies to NEW players only. A join from a player we already know is a
  627.   ; REJOIN (left and came back, app restart, or a re-invite echo), and overwriting their live stack
  628.   ; with the buy-in both breaks chip conservation mid-hand and hands anyone a free refill exploit:
  629.   ; leave the table, rejoin, and your losses are erased. Returning players keep their chips.
  630.   if (%newp == 1) { setat %stack $2 $4 }
  631.   ; seat anyone not seated or waiting: new players, and players removed for being away
  632.   if ($has(%seats,$2) == false) { if ($get(%pending,$2) != 1) {
  633.     if (%started == 1) { setat %pending $2 1 }
  634.     else { push %seats $2 }
  635.   } }
  636.   setat %strikes $2 0
  637.   setat %leaving $2 0
  638.   poker_sethost
  639.   if (%ishost == 1) { poker_broadcast }
  640.   poker_render
  641. }
  642.  
  643. ; ---- practice mode: play a full hand solo against calling-station bots --------
  644. alias poker_practice {
  645.   set %practice 1
  646.   set %bots $map()
  647.   set %chan #practice
  648.   poker
  649.   age.send %chan join bot1 Botcall 1000
  650.   setat %bots bot1 1
  651.   age.send %chan join bot2 Robofish 1000
  652.   setat %bots bot2 1
  653.   poker_deal
  654. }
  655.  
  656. ; bot turn-driver - runs on a scheduled tick (NOT synchronously) so the main thread
  657. ; is never blocked by a long cascade of bot actions; each tick acts once, the UI
  658. ; repaints, then the next action is re-scheduled by poker_onact / poker_deal below.
  659. on SIGNAL:poker_botstep {
  660.   if (%practice == 1) {
  661.     if (%started == 1) {
  662.       set %cur $get(%seats,%turn)
  663.       if ($has(%bots,%cur) == true) { poker_botbrain %cur }
  664.     }
  665.   }
  666. }
  667.  
  668. ; Arm the per-turn shot clock. Bumps %turnid so a tick scheduled for an earlier turn is ignored
  669. ; once the turn moves on. In real games the host schedules itself to auto-act if the seat to move
  670. ; goes quiet (disconnected or just away), so one absent player can never freeze the whole table.
  671. ; Bots run on their own fast driver (poker_botstep), so this only ever resolves a human who left.
  672. alias poker_armclock {
  673.   ; %turnid is bumped by the turn-setters (postblinds/advance/firstact), so it already reflects the
  674.   ; turn being armed here. This only (re)arms the host timeout and the local countdown; being called
  675.   ; more than once for the same turn is harmless (same turnid, idempotent countdown).
  676.   if (%practice == 0) { if (%ishost == 1) { timer %actclockms poker_turntimeout %turnid } }
  677.   poker_startclock
  678. }
  679.  
  680. ; Local visual countdown (host and every client). It just ticks a per-turn number down once a
  681. ; second and repaints; the host's poker_turntimeout is what actually acts when it hits zero.
  682. ; Keyed on %turnid so a new turn restarts it and a stale tick from a finished turn is ignored.
  683. alias poker_startclock {
  684.   if (%practice == 1) { return }
  685.   if (%turnid == %clockturn) { return }
  686.   set %clockturn %turnid
  687.   set %clockleft $int($calc(%actclockms / 1000))
  688.   timer 1000 poker_clocktick %turnid
  689. }
  690.  
  691. on SIGNAL:poker_clocktick {
  692.   if ($1 != %turnid) { return }
  693.   if (%started == 0) { return }
  694.   set %clockleft $calc(%clockleft - 1)
  695.   if (%clockleft < 0) { set %clockleft 0 }
  696.   poker_render
  697.   if (%clockleft > 0) { timer 1000 poker_clocktick %turnid }
  698. }
  699.  
  700. on SIGNAL:poker_turntimeout {
  701.   if (%ishost == 0) { return }
  702.   if (%started == 0) { return }
  703.   if ($1 != %turnid) { return }                  ; the turn already moved on; stale tick
  704.   set %cur $get(%seats,%turn)
  705.   if ($has(%bots,%cur) == true) { return }        ; bots resolve themselves
  706.   ; auto-act for the away seat: check when it costs nothing, otherwise fold. age.local injects the
  707.   ; move locally as that seat (exactly like a bot move) and the host re-broadcasts the result.
  708.   ; A second missed turn in a row folds them and removes them at the next deal; they can rejoin.
  709.   set %strk $calc($get(%strikes,%cur) + 1)
  710.   if (%strk >= 2) {
  711.     setat %leaving %cur 1
  712.     age.local %cur act fold
  713.     toast $get(%name,%cur) is away and will leave the table after this hand
  714.   }
  715.   elseif ($calc(%tocall - $get(%bet,%cur)) <= 0) { age.local %cur act check }
  716.   else { age.local %cur act fold }
  717.   setat %strikes %cur %strk
  718. }
  719.  
  720. ; A simple but believable bot: folds trash, calls/raises by hand strength, bluffs occasionally.
  721. ; Pre-flop it scores the two hole cards; post-flop it uses the made-hand category (0..7). Pot odds
  722. ; make cheap calls more tempting, and a random roll keeps it from being predictable. Two named
  723. ; practice bots have distinct styles so solo play isn't monotonous: Botcall (bot1) is a loose-
  724. ; passive calling station (calls very wide, almost never raises or bluffs) and Robofish (bot2) is a
  725. ; loose-aggressive maniac (raises a wide range, bluffs often). Any other bot uses the middle profile.
  726. ; Approximate drawing outs to a flush or straight for $1- (hole + board), 0 if a straight is
  727. ; already made or there is no draw. Flush draw (exactly 4 of a suit) ~ 9 outs; open-ended straight
  728. ; draw (2+ ranks complete a straight) ~ 8; gutshot (exactly 1) ~ 4. Used post-flop so the bot can
  729. ; semi-bluff and call the right price on draws instead of folding every unmade hand.
  730. alias poker_outs {
  731.   set -l %h $map()
  732.   set -l %su $map()
  733.   foreach %card $1- {
  734.     set -l %rv $get(%rankmap, $left(%card, 1))
  735.     setat %h %rv 1
  736.     set -l %s $right(%card, 1)
  737.     setat %su %s $calc($get(%su, %s) + 1)
  738.   }
  739.   set -l %outs 0
  740.   foreach %s $keys(%su) { if ($get(%su, %s) == 4) { set -l %outs $calc(%outs + 9) } }
  741.   if ($poker_straighthi($join($keys(%h))) == 0) {
  742.     set -l %compl 0
  743.     set -l %r 2
  744.     while (%r < 15) {
  745.       if ($get(%h, %r) != 1) {
  746.         if ($poker_straighthi($join($keys(%h)) %r) > 0) { set -l %compl $calc(%compl + 1) }
  747.       }
  748.       set -l %r $calc(%r + 1)
  749.     }
  750.     if (%compl >= 2) { set -l %outs $calc(%outs + 8) }
  751.     elseif (%compl == 1) { set -l %outs $calc(%outs + 4) }
  752.   }
  753.   return %outs
  754. }
  755.  
  756. alias poker_botbrain {
  757.   set %bot $1
  758.   set %mybet $get(%bet,%bot)
  759.   set %need $calc(%tocall - %mybet)
  760.   if (%need < 0) { set %need 0 }
  761.   set %stk $get(%stack,%bot)
  762.   set %roll $rand(0, 99)
  763.  
  764.   ; ---- personality knobs (kept as flat conditions; grouping like (A || B) && C also works now) ----
  765.   set %callpf 19       ; pre-flop score needed to call a bet
  766.   set %raisepf 26      ; pre-flop score needed to raise
  767.   set %bluff 6         ; roll cutoff for a pure bluff (higher = bluffs more)
  768.   set %aggr 50         ; roll cutoff for value-raising a marginal made hand
  769.   set %stationcall 0   ; 1 = call down light rather than fold
  770.   set %rmult 3         ; raise size in big blinds
  771.   if (%bot == bot1) { set %callpf 12 | set %raisepf 34 | set %bluff 0 | set %aggr 15 | set %stationcall 1 }
  772.   if (%bot == bot2) { set %callpf 16 | set %raisepf 20 | set %bluff 35 | set %aggr 80 | set %rmult 4 }
  773.   set %aggr2 $calc(%aggr - 15)
  774.   if (%aggr2 < 0) { set %aggr2 0 }
  775.  
  776.   ; raise target = current call level + N big blinds, capped at all-in
  777.   set %raiseto $calc(%tocall + $calc(%bb * %rmult))
  778.   set %maxto $calc(%mybet + %stk)
  779.   if (%raiseto > %maxto) { set %raiseto %maxto }
  780.  
  781.   ; a call is "cheap" when it costs a quarter of the pot or less
  782.   set %cheapthresh $calc(%pot / 4)
  783.   set %cheap 0
  784.   if (%need <= %cheapthresh) { set %cheap 1 }
  785.   ; pot odds: the price of a call as a percentage of the pot after we put the chips in. A flush/OESD
  786.   ; (~8-9 outs) is roughly a 1-in-3 shot with two cards to come, so calling is right up to ~33%.
  787.   set %price 100
  788.   set %denom $calc(%pot + %need)
  789.   if (%denom > 0) { set %price $int($calc(%need * 100 / %denom)) }
  790.  
  791.   if ($len(%board) == 0) {
  792.     ; ---- pre-flop: score the two hole cards (high cards + pair/suited bonuses) ----
  793.     ; split on the default (space) delimiter; $split(x, " ") works too now that quoted args
  794.     ; are string literals, but the bare form stays the simplest spelling.
  795.     set %hc $split($get(%hole,%bot))
  796.     set %c1 $get(%hc, 0)
  797.     set %c2 $get(%hc, 1)
  798.     set %r1 $get(%rankmap, $left(%c1, 1))
  799.     set %r2 $get(%rankmap, $left(%c2, 1))
  800.     set %pf $calc(%r1 + %r2)
  801.     if (%r1 == %r2) { set %pf $calc(%pf + 12) }
  802.     if ($right(%c1, 1) == $right(%c2, 1)) { set %pf $calc(%pf + 4) }
  803.     if (%need == 0) {
  804.       if (%pf >= %raisepf) { age.local %bot act raise %raiseto }
  805.       elseif (%pf >= 18 && %roll < %aggr) { age.local %bot act raise %raiseto }
  806.       elseif (%roll < %bluff) { age.local %bot act raise %raiseto }
  807.       else { age.local %bot act check }
  808.     } else {
  809.       if (%pf >= %raisepf) { age.local %bot act raise %raiseto }
  810.       elseif (%pf >= %callpf) { age.local %bot act call }
  811.       elseif (%cheap == 1 && %roll < 30) { age.local %bot act call }
  812.       elseif (%stationcall == 1 && %cheap == 1) { age.local %bot act call }
  813.       else { age.local %bot act fold }
  814.     }
  815.   } else {
  816.     ; ---- post-flop: made-hand category 0=high .. 7=quads ----
  817.     set %sc $poker_handscore($get(%hole,%bot) $join(%board))
  818.     set %cat $int($calc(%sc / 759375))
  819.     ; drawing outs, but only while a card is still to come (turn/river); on the river a draw is dead
  820.     set %outs 0
  821.     if ($len(%board) < 5) { set %outs $poker_outs($get(%hole,%bot) $join(%board)) }
  822.     set %strongdraw 0
  823.     if (%outs >= 8) { set %strongdraw 1 }
  824.     if (%need == 0) {
  825.       if (%cat >= 3) { age.local %bot act raise %raiseto }
  826.       elseif (%cat == 2 && %roll < %aggr) { age.local %bot act raise %raiseto }
  827.       elseif (%cat == 1 && %roll < %aggr2) { age.local %bot act raise %raiseto }
  828.       elseif (%strongdraw == 1 && %roll < %aggr) { age.local %bot act raise %raiseto }
  829.       elseif (%roll < %bluff) { age.local %bot act raise %raiseto }
  830.       else { age.local %bot act check }
  831.     } else {
  832.       if (%cat >= 4) { age.local %bot act raise %raiseto }
  833.       elseif (%cat >= 2 && %roll < %aggr) { age.local %bot act raise %raiseto }
  834.       elseif (%cat >= 2) { age.local %bot act call }
  835.       elseif (%cat == 1 && %stationcall == 1) { age.local %bot act call }
  836.       elseif (%cat == 1 && %cheap == 1) { age.local %bot act call }
  837.       elseif (%cat == 1 && %roll < 55) { age.local %bot act call }
  838.       elseif (%cat == 1) { age.local %bot act fold }
  839.       elseif (%strongdraw == 1 && %cheap == 1 && %roll < %aggr2) { age.local %bot act raise %raiseto }
  840.       elseif (%strongdraw == 1 && %price <= 33) { age.local %bot act call }
  841.       elseif (%outs >= 4 && %price <= 12) { age.local %bot act call }
  842.       elseif (%stationcall == 1 && %cheap == 1) { age.local %bot act call }
  843.       elseif (%cheap == 1 && %roll < 55) { age.local %bot act call }
  844.       elseif (%roll < %bluff) { age.local %bot act raise %raiseto }
  845.       elseif (%roll < 10) { age.local %bot act call }
  846.       else { age.local %bot act fold }
  847.     }
  848.   }
  849. }
  850.  
  851. ; ---- start a hand (dealer button rotates each hand) ------------------------
  852. alias poker_deal {
  853.   poker_sethost
  854.   ; take off players who left or timed out twice
  855.   poker_removeleavers
  856.   ; seat anyone who joined during the previous hand (parked in %pending), now that seat order and
  857.   ; the turn pointer can safely change. Guard against double-seating on a rejoin.
  858.   foreach %fp $keys(%pending) { if ($get(%pending,%fp) == 1) { if ($has(%seats, %fp) == false) { push %seats %fp } } }
  859.   set %pending $map()
  860.   if ($calc($len(%seats) + 0) < 2) {
  861.     toast Not enough players left to deal
  862.     poker_broadcast
  863.     poker_render
  864.     return
  865.   }
  866.   set %started 1
  867.   set %winnertext
  868.   set %board $list()
  869.   set %folded $map()
  870.   set %bet $map()
  871.   set %hole $map()
  872.   set %myhole $map()
  873.   set %reveal $map()      ; last hand's shown cards clear so they don't linger into the new deal
  874.   set %lastact $map()
  875.   set %street preflop
  876.   set %pot 0
  877.   set %tocall %bb
  878.   ; players with no chips are out for the hand: mark them folded so every downstream loop
  879.   ; (turn advance, showdown, live-count) skips them with no special-casing.
  880.   foreach %fp %seats { if ($get(%stack,%fp) <= 0) { setat %folded %fp 1 } }
  881.   ; move the dealer button to the next player who still has chips (first hand keeps seat 0)
  882.   if (%handid > 0) { set %button $poker_nextin($calc(%button + 1)) }
  883.   set %handid $calc(%handid + 1)
  884.   set %dealerfp $get(%seats, %button)
  885.   ; Shuffle from a private seed and publish a hash of it now; the seed follows when the hand ends,
  886.   ; so players can check the deal (poker_checkdeal). It doesn't stop the dealer seeing the cards.
  887.   set %seed $age.rand(32)
  888.   set %commit $left($age.sha(%seed), 32)
  889.   set %revealseed
  890.   poker_builddeck
  891.   ; deal 2 hole cards per seat; only seal to players actually in the hand
  892.   set %i 0
  893.   foreach %fp %seats {
  894.     set %c1 $get(%deck,$calc(%i * 2))
  895.     set %c2 $get(%deck,$calc(%i * 2 + 1))
  896.     if ($get(%folded,%fp) != 1) { age.seal %fp %c1 %c2 }
  897.     if (%ishost == 1) { setat %hole %fp %c1 %c2 }
  898.     set %i $calc(%i + 1)
  899.   }
  900.   ; community sits after all hole cards
  901.   set %base $calc($len(%seats) * 2)
  902.   ; post blinds relative to the button and open betting
  903.   poker_postblinds
  904.   poker_render
  905.   poker_broadcast
  906.   timer 350 poker_botstep
  907.   poker_armclock
  908. }
  909.  
  910. alias poker_builddeck {
  911.   set %deck $list()
  912.   set %keyed $list()
  913.   foreach %r $list(2,3,4,5,6,7,8,9,T,J,Q,K,A) {
  914.     foreach %s $list(c,d,h,s) {
  915.       ; keyed shuffle: sort cards by a PRF of (seed, card) - a verifiable permutation
  916.       push %keyed $age.sha(%seed%r%s)~%r%s
  917.     }
  918.   }
  919.   set %keyed $sort(%keyed)
  920.   foreach %k %keyed {
  921.     set %card $get($split(%k,~),1)
  922.     push %deck %card
  923.   }
  924. }
  925.  
  926. alias poker_postblinds {
  927.   set %contrib $map()
  928.   set %acted $map()
  929.   set %allin $map()
  930.   ; how many players are actually in this hand (chips at the start)
  931.   set %inhand 0
  932.   foreach %fp %seats { if ($get(%folded,%fp) != 1) { set %inhand $calc(%inhand + 1) } }
  933.   ; blind seats relative to the button, skipping busted players
  934.   if (%inhand < 3) {
  935.     ; heads-up: the button posts the small blind and acts first pre-flop
  936.     set %sbi %button
  937.     set %bbi $poker_nextin($calc(%button + 1))
  938.   } else {
  939.     set %sbi $poker_nextin($calc(%button + 1))
  940.     set %bbi $poker_nextin($calc(%sbi + 1))
  941.   }
  942.   set %sbfp $get(%seats, %sbi)
  943.   set %bbfp $get(%seats, %bbi)
  944.   ; post blinds, clamped to stack (a short stack goes all-in on its blind)
  945.   set %sbamt %sb
  946.   if (%sbamt > $get(%stack,%sbfp)) { set %sbamt $get(%stack,%sbfp) }
  947.   set %bbamt %bb
  948.   if (%bbamt > $get(%stack,%bbfp)) { set %bbamt $get(%stack,%bbfp) }
  949.   setat %bet %sbfp %sbamt
  950.   setat %bet %bbfp %bbamt
  951.   setat %contrib %sbfp %sbamt
  952.   setat %contrib %bbfp %bbamt
  953.   setat %stack %sbfp $calc($get(%stack,%sbfp) - %sbamt)
  954.   setat %stack %bbfp $calc($get(%stack,%bbfp) - %bbamt)
  955.   if ($get(%stack,%sbfp) <= 0) { setat %allin %sbfp 1 }
  956.   if ($get(%stack,%bbfp) <= 0) { setat %allin %bbfp 1 }
  957.   set %pot $calc(%sbamt + %bbamt)
  958.   set %tocall %bb
  959.   set %lastraise %bb
  960.   set %noreraise $map()
  961.   ; first to act pre-flop = next player who can act after the big blind (heads-up: the SB/button)
  962.   if (%inhand < 3) { set %turn %sbi }
  963.   else { set %turn $poker_nextactor($calc(%bbi + 1)) }
  964.   set %turnid $calc(%turnid + 1)
  965. }
  966.  
  967. ; our sealed hole cards arrive here
  968. on SIGNAL:age_deal {
  969.   ; $data = "<c1> <c2>"
  970.   setat %myhole me $data
  971.   set %holefresh 1
  972.   poker_render
  973. }
  974.  
  975. ; ---- betting ---------------------------------------------------------------
  976. on SIGNAL:poker_fold  { age.send %chan act fold }
  977. on SIGNAL:poker_call  { age.send %chan act call }
  978. on SIGNAL:poker_raise { age.send %chan act raise %betamount }
  979. on SIGNAL:poker_min   { set %betamount 0 | poker_render }
  980. on SIGNAL:poker_q     { poker_presize 1 4 }
  981. on SIGNAL:poker_h     { poker_presize 1 2 }
  982. on SIGNAL:poker_pot   { poker_presize 1 1 }
  983. on SIGNAL:poker_t     { poker_presize 3 4 }
  984.  
  985. ; Raise to the current bet plus $1/$2 of the pot after calling (a "pot" raise is the standard one);
  986. ; poker_render then clamps it between the minimum raise and all-in.
  987. alias poker_presize {
  988.   set %pneed $calc(%tocall - $get(%bet,$age.me))
  989.   if (%pneed < 0) { set %pneed 0 }
  990.   set %betamount $int($calc(%tocall + $calc($calc(%pot + %pneed) * $1 / $2)))
  991.   poker_render
  992. }
  993. on SIGNAL:poker_allin { set %betamount 999999999 | poker_render }
  994. on SIGNAL:poker_dec   { set %betamount $calc(%betamount - %bb) | poker_render }
  995. on SIGNAL:poker_inc   { set %betamount $calc(%betamount + %bb) | poker_render }
  996.  
  997. alias poker_onact {
  998.   ; Drop stale / double-tapped / out-of-turn actions. The view only shows action buttons on
  999.   ; your turn, but taps can still race the async re-render; without this guard a second tap
  1000.   ; re-applies a move for a seat that has already acted, corrupting stacks/pot and the turn
  1001.   ; pointer (the "mash the buttons" crash). Only the seat whose turn it is may act.
  1002.   if (%started == 0) { halt }
  1003.   if ($from != $get(%seats,%turn)) { halt }
  1004.   ; $from acted: $2 = fold|check|call|raise ; $3 = raise-to amount
  1005.   set %fp $from
  1006.   setat %strikes %fp 0
  1007.   setat %silent %fp 0
  1008.   set %betbefore $get(%bet,%fp)
  1009.   set %callbefore %tocall
  1010.   if ($2 == fold) {
  1011.     setat %folded %fp 1
  1012.     setat %acted %fp 1
  1013.   }
  1014.   elseif ($2 == raise) { poker_raiseto %fp $3 }
  1015.   elseif ($2 == allin) { poker_raiseto %fp all }
  1016.   else {
  1017.     ; call or check (call short-stack = all-in for the rest)
  1018.     set %need $calc(%tocall - $get(%bet,%fp))
  1019.     if (%need < 0) { set %need 0 }
  1020.     set %put %need
  1021.     if (%put > $get(%stack,%fp)) { set %put $get(%stack,%fp) }
  1022.     setat %bet %fp $calc($get(%bet,%fp) + %put)
  1023.     setat %stack %fp $calc($get(%stack,%fp) - %put)
  1024.     setat %contrib %fp $calc($get(%contrib,%fp) + %put)
  1025.     set %pot $calc(%pot + %put)
  1026.     setat %acted %fp 1
  1027.     if ($get(%stack,%fp) == 0) { setat %allin %fp 1 }
  1028.   }
  1029.   setat %lastact %fp $poker_actlabel(%fp, %betbefore, %callbefore)
  1030.   poker_advance
  1031.   poker_render
  1032.   ; A plain in-street action only moved the turn: push a one-line delta (no FRAG) instead of the whole
  1033.   ; table. Street changes / hand ends fall through to a full state (poker_nextstreet/endhand paths).
  1034.   if (%advturn == 1) { poker_evact %fp } else { poker_broadcast }
  1035.   timer 350 poker_botstep
  1036.   poker_armclock
  1037. }
  1038.  
  1039. ; Host: $1 raises to $2, or goes all-in when $2 is "all". A raise must reach the current bet plus the
  1040. ; last full raise (at least the big blind); a smaller one is lifted to that minimum, and a player who
  1041. ; can't cover it goes all-in. Only a full raise reopens the betting: after a short all-in, players
  1042. ; who already acted may call or fold but not raise again. A raise from such a player is a call.
  1043. alias poker_raiseto {
  1044.   set %fp $1
  1045.   set %rmax $calc($get(%bet,%fp) + $get(%stack,%fp))
  1046.   if ($get(%noreraise,%fp) == 1) { set %rto %tocall }
  1047.   elseif ($2 == all) { set %rto %rmax }
  1048.   else {
  1049.     set %rto $int($2)
  1050.     set %rmin $calc(%tocall + %lastraise)
  1051.     if (%rto < %rmin) { set %rto %rmin }
  1052.   }
  1053.   if (%rto > %rmax) { set %rto %rmax }
  1054.   set %put $calc(%rto - $get(%bet,%fp))
  1055.   if (%put < 0) { set %put 0 }
  1056.   setat %bet %fp $calc($get(%bet,%fp) + %put)
  1057.   setat %stack %fp $calc($get(%stack,%fp) - %put)
  1058.   setat %contrib %fp $calc($get(%contrib,%fp) + %put)
  1059.   set %pot $calc(%pot + %put)
  1060.   set %newbet $get(%bet,%fp)
  1061.   if (%newbet > %tocall) {
  1062.     set %raiseby $calc(%newbet - %tocall)
  1063.     if (%raiseby >= %lastraise) {
  1064.       set %lastraise %raiseby
  1065.       set %acted $map()
  1066.       set %noreraise $map()
  1067.     } else {
  1068.       foreach %afp $keys(%acted) { setat %noreraise %afp 1 }
  1069.     }
  1070.     set %tocall %newbet
  1071.   }
  1072.   setat %acted %fp 1
  1073.   if ($get(%stack,%fp) == 0) { setat %allin %fp 1 }
  1074. }
  1075.  
  1076. alias poker_endhand {
  1077.   ; $1 = sole survivor fp - everyone else folded; wins the whole pot
  1078.   setat %stack $1 $calc($get(%stack,$1) + %pot)
  1079.   set %winners $list()
  1080.   push %winners $get(%name,$1)
  1081.   set %winnertext $get(%name,$1) wins %pot
  1082.   set %revealseed %seed
  1083.   set %pot 0                 ; pot is now in the survivor's stack; clear it for the lobby
  1084.   set %started 0
  1085.   set %street lobby
  1086.   poker_checkover
  1087.   signal poker_win
  1088.   poker_broadcast            ; push the final stacks, pot=0 and winner line to every client
  1089.   poker_render
  1090. }
  1091.  
  1092. ; End-of-session check: if one player (or none) has chips left, the game is over and the
  1093. ; last player standing is the champion. Call after a hand's chips have been paid out.
  1094. ;
  1095. ; Robust champion selection: the winner is the seat holding the most chips, which is by
  1096. ; definition the sole survivor once everyone else has busted to 0. Deriving it from the max
  1097. ; stack (rather than "the last seat we saw with a positive stack") means we never emit an
  1098. ; empty champion - the bug behind the reported "<empty> wins the table" banner, which happened
  1099. ; whenever the survivor-tracking loop finished with no positive-stack seat recorded (e.g. an
  1100. ; all-in showdown edge where the pot had not yet landed in a stack when this ran). We only
  1101. ; declare the game over when there IS a named survivor; a seatless/blank table is left alone.
  1102. alias poker_checkover {
  1103.   set %alive 0
  1104.   set %topfp
  1105.   set %topstk -1
  1106.   foreach %fp %seats {
  1107.     set %stk $get(%stack,%fp)
  1108.     if (%stk > 0) { set %alive $calc(%alive + 1) }
  1109.     if (%stk > %topstk) { set %topstk %stk | set %topfp %fp }
  1110.   }
  1111.   if (%alive < 2) {
  1112.     if ($len(%topfp) > 0) {
  1113.       set %champname $get(%name,%topfp)
  1114.       if ($len(%champname) > 0) {
  1115.         set %gameover 1
  1116.         set %champion %champname
  1117.       }
  1118.     }
  1119.   }
  1120. }
  1121.  
  1122. alias poker_advance {
  1123.   set %advturn 0
  1124.   ; last player standing wins immediately
  1125.   set %live 0
  1126.   set %onlyfp
  1127.   foreach %fp %seats { if ($get(%folded,%fp) != 1) { set %live $calc(%live + 1) | set %onlyfp %fp } }
  1128.   if (%live < 2) {
  1129.     poker_endhand %onlyfp
  1130.   } else {
  1131.     ; round closes when every non-folded, non-all-in player has acted AND matched %tocall
  1132.     set %open 0
  1133.     foreach %fp %seats {
  1134.       if ($get(%folded,%fp) != 1) { if ($get(%allin,%fp) != 1) {
  1135.         if ($get(%acted,%fp) != 1) { set %open 1 }
  1136.         if ($get(%bet,%fp) != %tocall) { set %open 1 }
  1137.       } }
  1138.     }
  1139.     if (%open == 0) {
  1140.       poker_nextstreet
  1141.     } else {
  1142.       ; advance to the next seat that can act (non-folded, non-all-in)
  1143.       set %n $len(%seats)
  1144.       set %steps 0
  1145.       set %done 0
  1146.       while (%steps < %n) {
  1147.         if (%done == 0) {
  1148.           set %turn $mod($calc(%turn + 1), %n)
  1149.           set %cur $get(%seats,%turn)
  1150.           if ($get(%folded,%cur) != 1) { if ($get(%allin,%cur) != 1) { set %done 1 } }
  1151.         }
  1152.         set %steps $calc(%steps + 1)
  1153.       }
  1154.       set %turnid $calc(%turnid + 1)
  1155.       set %advturn 1
  1156.     }
  1157.   }
  1158. }
  1159.  
  1160. alias poker_firstact {
  1161.   ; first to act after the flop = first player who can act to the left of the button
  1162.   set %turn $poker_nextactor($calc(%button + 1))
  1163.   set %turnid $calc(%turnid + 1)
  1164. }
  1165.  
  1166. alias poker_nextstreet {
  1167.   if (%street == river) {
  1168.     poker_showdown
  1169.   } else {
  1170.     ; dealer reveals the next board card(s) from its deck
  1171.     if (%street == preflop) { set %street flop | poker_reveal 3 }
  1172.     elseif (%street == flop) { set %street turn | poker_reveal 1 }
  1173.     elseif (%street == turn) { set %street river | poker_reveal 1 }
  1174.     set %tocall 0
  1175.     set %lastraise %bb
  1176.     set %noreraise $map()
  1177.     set %lastact $map()
  1178.     set %bet $map()
  1179.     set %acted $map()
  1180.     poker_firstact
  1181.     ; if fewer than two players can still act (rest all-in/folded), run the board out
  1182.     set %actors 0
  1183.     foreach %fp %seats { if ($get(%folded,%fp) != 1) { if ($get(%allin,%fp) != 1) { set %actors $calc(%actors + 1) } } }
  1184.     if (%actors < 2) { poker_nextstreet }
  1185.     else { timer 350 poker_botstep | poker_armclock }   ; re-arm the bot loop: a new street can open on a bot's turn
  1186.   }
  1187. }
  1188.  
  1189. ; Client: check the finished hand against the dealer's commitment. $1 = the revealed seed. Its hash
  1190. ; must match the commitment published at the deal, and the deck it builds must hold our own hole
  1191. ; cards and the board where the deal puts them.
  1192. alias poker_checkdeal {
  1193.   set %checkedhand %commit
  1194.   set %dealok 1
  1195.   if ($left($age.sha($1), 32) != %commit) { set %dealok 0 }
  1196.   else {
  1197.     set %seed $1
  1198.     poker_builddeck
  1199.     set %mi $find(%seats, $age.me)
  1200.     set %mine $get(%myhole, me)
  1201.     if (%mi >= 0) { if (%holehand == %commit) {
  1202.       set %mc $split(%mine)
  1203.       if ($get(%mc, 0) != $get(%deck, $calc(%mi * 2))) { set %dealok 0 }
  1204.       if ($get(%mc, 1) != $get(%deck, $calc(%mi * 2 + 1))) { set %dealok 0 }
  1205.     } }
  1206.     set %b0 $calc($len(%seats) * 2)
  1207.     set %bk 0
  1208.     foreach %bc %board {
  1209.       if (%bc != $get(%deck, $calc(%b0 + %bk))) { set %dealok 0 }
  1210.       set %bk $calc(%bk + 1)
  1211.     }
  1212.   }
  1213.   if (%dealok == 0) { toast Warning: this hand's cards don't match the deck the dealer committed to }
  1214. }
  1215.  
  1216. alias poker_reveal {
  1217.   ; $1 = count. dealer pulls from %deck at %base and broadcasts.
  1218.   set %n 0
  1219.   while (%n < $1) {
  1220.     set %card $get(%deck,%base)
  1221.     push %board %card
  1222.     set %base $calc(%base + 1)
  1223.     set %n $calc(%n + 1)
  1224.   }
  1225. }
  1226.  
  1227.  
  1228. ; ---- hand evaluation (value function - returns a sortable score) ----
  1229. ; Hand evaluation. Scores the BEST 5-card poker hand from the 5-7 cards in $1-.
  1230. ; Category is the leading base-15 digit, high to low: 8 straight flush (incl.
  1231. ; royal = ace-high), 7 four of a kind, 6 full house, 5 flush, 4 straight,
  1232. ; 3 trips, 2 two pair, 1 pair, 0 high card. The five base-15 digits below the
  1233. ; category are the CORRECT tiebreak ranks for that category (the flush's own
  1234. ; five cards, the straight's high card, a pair's kickers, ...), so equal
  1235. ; categories compare exactly as real poker does. Aces play high everywhere and
  1236. ; also low for the wheel (A-2-3-4-5); a straight flush beats quads; and 7-card
  1237. ; flush/straight scoring uses the actual five cards, never stray kickers.
  1238. alias poker_handscore {
  1239.   set %hist $map()
  1240.   set %suit $map()
  1241.   foreach %card $1- {
  1242.     set %rv $get(%rankmap,$left(%card,1))
  1243.     set %su $right(%card,1)
  1244.     setat %hist %rv $calc($get(%hist,%rv) + 1)
  1245.     setat %suit %su $calc($get(%suit,%su) + 1)
  1246.   }
  1247.   ; flush suit = the (at most one) suit holding 5+ cards
  1248.   set %fsuit
  1249.   foreach %su $keys(%suit) { if ($get(%suit,%su) > 4) { set %fsuit %su } }
  1250.   ; the flush cards' ranks (distinct within a suit), high to low
  1251.   set %flushranks $list()
  1252.   if ($len(%fsuit) > 0) {
  1253.     foreach %card $1- { if ($right(%card,1) == %fsuit) { push %flushranks $get(%rankmap,$left(%card,1)) } }
  1254.     set %flushranks $reverse($sort(%flushranks))
  1255.   }
  1256.   ; best straight high card (wheel-aware): among all ranks, and within the flush suit
  1257.   set %sthi $poker_straighthi($join($keys(%hist)))
  1258.   set %sfhi 0
  1259.   if ($len(%flushranks) > 0) { set %sfhi $poker_straighthi($join(%flushranks)) }
  1260.   ; count buckets: highest quad rank; trips and pairs-or-better, each high to low
  1261.   set %quad 0
  1262.   set %trips $list()
  1263.   set %pairs $list()
  1264.   foreach %k $keys(%hist) {
  1265.     set %c $get(%hist,%k)
  1266.     if (%c > 3) { if (%k > %quad) { set %quad %k } }
  1267.     if (%c == 3) { push %trips %k }
  1268.     if (%c > 1) { push %pairs %k }          ; a trip also serves as a pair (full house / two pair)
  1269.   }
  1270.   set %trips $reverse($sort(%trips))
  1271.   set %pairs $reverse($sort(%pairs))
  1272.   set %distinct $reverse($sort($keys(%hist)))   ; distinct ranks high to low, for kickers
  1273.   ; full house = a trip plus any OTHER paired rank (a second trip counts as that pair)
  1274.   set %fhtrip 0
  1275.   set %fhpair 0
  1276.   if ($len(%trips) > 0) {
  1277.     set %fhtrip $get(%trips,0)
  1278.     foreach %pk %pairs { if (%fhpair == 0) { if (%pk != %fhtrip) { set %fhpair %pk } } }
  1279.   }
  1280.   set %isfh 0
  1281.   if (%fhtrip > 0) { if (%fhpair > 0) { set %isfh 1 } }
  1282.   ; ---- category + its tiebreak ranks (%tb, most significant first) ----
  1283.   set %cat 0
  1284.   set %tb $list()
  1285.   if (%sfhi > 0) {
  1286.     set %cat 8 | push %tb %sfhi
  1287.   } elseif (%quad > 0) {
  1288.     set %cat 7 | push %tb %quad
  1289.     foreach %d %distinct { if ($len(%tb) < 2) { if (%d != %quad) { push %tb %d } } }
  1290.   } elseif (%isfh == 1) {
  1291.     set %cat 6 | push %tb %fhtrip | push %tb %fhpair
  1292.   } elseif ($len(%fsuit) > 0) {
  1293.     set %cat 5
  1294.     foreach %r %flushranks { if ($len(%tb) < 5) { push %tb %r } }
  1295.   } elseif (%sthi > 0) {
  1296.     set %cat 4 | push %tb %sthi
  1297.   } elseif ($len(%trips) > 0) {
  1298.     set %cat 3 | push %tb $get(%trips,0)
  1299.     foreach %d %distinct { if ($len(%tb) < 3) { if (%d != $get(%trips,0)) { push %tb %d } } }
  1300.   } elseif ($len(%pairs) > 1) {
  1301.     set %cat 2
  1302.     set %p1 $get(%pairs,0)
  1303.     set %p2 $get(%pairs,1)
  1304.     push %tb %p1 | push %tb %p2
  1305.     foreach %d %distinct { if ($len(%tb) < 3) { if (%d != %p1) { if (%d != %p2) { push %tb %d } } } }
  1306.   } elseif ($len(%pairs) == 1) {
  1307.     set %cat 1 | push %tb $get(%pairs,0)
  1308.     foreach %d %distinct { if ($len(%tb) < 4) { if (%d != $get(%pairs,0)) { push %tb %d } } }
  1309.   } else {
  1310.     set %cat 0
  1311.     foreach %d %distinct { if ($len(%tb) < 5) { push %tb %d } }
  1312.   }
  1313.   ; ---- pack: category, then five base-15 tiebreak digits (zero-padded) ----
  1314.   set %s %cat
  1315.   set %i 0
  1316.   foreach %t %tb { if (%i < 5) { set %s $calc(%s * 15 + %t) | set %i $calc(%i + 1) } }
  1317.   while (%i < 5) { set %s $calc(%s * 15) | set %i $calc(%i + 1) }
  1318.   return %s
  1319. }
  1320.  
  1321. ; Best straight high card from a space-separated list of rank values; 0 if none.
  1322. ; Wheel-aware: an ace (14) also fills the low end so A-2-3-4-5 scores as a 5-high straight.
  1323. alias poker_straighthi {
  1324.   set %p $map()
  1325.   foreach %v $1- { setat %p %v 1 }
  1326.   if ($get(%p,14) == 1) { setat %p 1 1 }
  1327.   set %hi 14
  1328.   while (%hi > 4) {
  1329.     if ($get(%p,%hi) == 1) { if ($get(%p,$calc(%hi - 1)) == 1) { if ($get(%p,$calc(%hi - 2)) == 1) { if ($get(%p,$calc(%hi - 3)) == 1) { if ($get(%p,$calc(%hi - 4)) == 1) { return %hi } } } } }
  1330.     set %hi $calc(%hi - 1)
  1331.   }
  1332.   return 0
  1333. }
  1334.  
  1335. ; hand category NAME for the rank badge (derived from the score: category is the
  1336. ; leading base-15 digit floor(score / 15^5); the next digit is the straight-flush
  1337. ; high card, so an ace-high straight flush reads as ROYAL FLUSH).
  1338. alias poker_handcat {
  1339.   set %sc $poker_handscore($1-)
  1340.   set %c $int($calc(%sc / 759375))
  1341.   if (%c == 8) {
  1342.     if ($mod($int($calc(%sc / 50625)), 15) == 14) { return ROYAL FLUSH }
  1343.     return STRAIGHT FLUSH
  1344.   }
  1345.   elseif (%c == 7) { return FOUR OF A KIND }
  1346.   elseif (%c == 6) { return FULL HOUSE }
  1347.   elseif (%c == 5) { return FLUSH }
  1348.   elseif (%c == 4) { return STRAIGHT }
  1349.   elseif (%c == 3) { return THREE OF A KIND }
  1350.   elseif (%c == 2) { return TWO PAIR }
  1351.   elseif (%c == 1) { return PAIR }
  1352.   return HIGH CARD
  1353. }
  1354.  
  1355. alias poker_showdown {
  1356.   ; score every non-folded hand (best 5 of hole+board)
  1357.   set %score $map()
  1358.   foreach %fp %seats {
  1359.     if ($get(%folded,%fp) != 1) { setat %score %fp $poker_handscore($get(%hole,%fp) $join(%board)) }
  1360.   }
  1361.   ; reveal every non-folded hand so the showdown is visible on EVERY client, not just the host
  1362.   ; (hole cards are otherwise host-only and never broadcast). Folded hands stay mucked.
  1363.   set %reveal $map()
  1364.   foreach %fp %seats { if ($get(%folded,%fp) != 1) { setat %reveal %fp $get(%hole,%fp) } }
  1365.   ; distinct sorted contribution levels define the side-pot layers
  1366.   set %tmp $list()
  1367.   foreach %fp %seats { if ($get(%contrib,%fp) > 0) { push %tmp $get(%contrib,%fp) } }
  1368.   set %tmp $sort(%tmp)
  1369.   set %levels $list()
  1370.   set %prev -1
  1371.   foreach %lv %tmp { if (%lv != %prev) { push %levels %lv | set %prev %lv } }
  1372.  
  1373.   set %prevlv 0
  1374.   set %winners $list()
  1375.   set %awarded $map()      ; name -> chips actually won, so the banner can show each amount
  1376.   foreach %lv %levels {
  1377.     ; this layer = (lv - prevlv) chips from every player who put in at least lv
  1378.     set %width $calc(%lv - %prevlv)
  1379.     set %cnt 0
  1380.     foreach %fp %seats { if ($get(%contrib,%fp) >= %lv) { set %cnt $calc(%cnt + 1) } }
  1381.     set %layer $calc(%width * %cnt)
  1382.     ; best eligible (non-folded, contributed into this layer) score
  1383.     set %bsc -1
  1384.     foreach %fp %seats {
  1385.       if ($get(%folded,%fp) != 1) { if ($get(%contrib,%fp) >= %lv) {
  1386.         if ($get(%score,%fp) > %bsc) { set %bsc $get(%score,%fp) }
  1387.       } }
  1388.     }
  1389.     ; split this layer among all eligible players tied at the best score
  1390.     set %nwin 0
  1391.     foreach %fp %seats {
  1392.       if ($get(%folded,%fp) != 1) { if ($get(%contrib,%fp) >= %lv) {
  1393.         if ($get(%score,%fp) == %bsc) { set %nwin $calc(%nwin + 1) }
  1394.       } }
  1395.     }
  1396.     if (%nwin > 0) {
  1397.       ; integer chips only: floor the share and hand the odd chip(s) to the earliest eligible
  1398.       ; seats in seat order. This keeps a split pot whole (no fractional stacks, nothing created
  1399.       ; or destroyed): share*nwin + remainder == layer.
  1400.       set %share $idiv(%layer, %nwin)
  1401.       set %rem $calc(%layer - $calc(%share * %nwin))
  1402.       foreach %fp %seats {
  1403.         if ($get(%folded,%fp) != 1) { if ($get(%contrib,%fp) >= %lv) {
  1404.           if ($get(%score,%fp) == %bsc) {
  1405.             set %award %share
  1406.             if (%rem > 0) { set %award $calc(%share + 1) | set %rem $calc(%rem - 1) }
  1407.             setat %stack %fp $calc($get(%stack,%fp) + %award)
  1408.             setat %awarded $get(%name,%fp) $calc($get(%awarded,$get(%name,%fp)) + %award)
  1409.             if ($has(%winners, $get(%name,%fp)) == false) { push %winners $get(%name,%fp) }
  1410.           }
  1411.         } }
  1412.       }
  1413.     } else {
  1414.       ; no eligible (non-folded) player reached this layer - eg an uncalled over-bet whose bettor
  1415.       ; then folded. Those chips belong to nobody at showdown, so return each contributor's share
  1416.       ; of THIS layer to them rather than letting it vanish. width chips came from each of the
  1417.       ; %cnt contributors, so refund width to each: width*cnt == layer, chips stay conserved.
  1418.       foreach %fp %seats {
  1419.         if ($get(%contrib,%fp) >= %lv) { setat %stack %fp $calc($get(%stack,%fp) + %width) }
  1420.       }
  1421.     }
  1422.     set %prevlv %lv
  1423.   }
  1424.   ; announce from who actually took chips and how much. One winner reads "Alice wins 150"; a
  1425.   ; genuine split or several SEPARATE side pots each show their own amount ("Alice 150, Bob 300"),
  1426.   ; so the banner never claims one wrong combined total. Guard the zero-winner case (every layer
  1427.   ; refunded) by falling back to the top-stack seat, who holds the chips.
  1428.   if ($len(%winners) == 0) {
  1429.     set %fallbackfp
  1430.     set %fbstk -1
  1431.     foreach %fp %seats { if ($get(%stack,%fp) > %fbstk) { set %fbstk $get(%stack,%fp) | set %fallbackfp %fp } }
  1432.     set %winnertext $get(%name,%fallbackfp) wins %pot
  1433.   }
  1434.   elseif ($len(%winners) < 2) {
  1435.     set %w0 $get(%winners,0)
  1436.     set %winnertext %w0 wins $get(%awarded,%w0)
  1437.   } else {
  1438.     set %wnames
  1439.     foreach %wn %winners {
  1440.       set %seg %wn $get(%awarded,%wn)
  1441.       if ($len(%wnames) == 0) { set %wnames %seg } else { set %wnames %wnames, %seg }
  1442.     }
  1443.     set %winnertext pot: %wnames
  1444.   }
  1445.   set %revealseed %seed
  1446.   set %pot 0                 ; chips are now in the winners' stacks; clear the pot for the lobby
  1447.   set %started 0
  1448.   set %street lobby
  1449.   poker_checkover
  1450.   signal poker_win
  1451.   poker_broadcast            ; push the final stacks, pot=0 and winner line to every client
  1452.   poker_render
  1453. }
  1454.  
  1455. on SIGNAL:poker_win {
  1456.   ; %winnertext is the formatted result: one winner ("Eck wins 140") or a split
  1457.   ; ("split pot: Eck, Ada (140)"); %winners lists the names. The table banner shows the
  1458.   ; same text. Add a personal note when you're among the winners.
  1459.   set %me $age.me
  1460.   if ($has(%winners, $get(%name,%me)) == true) { echo %chan *** you're in the money - %winnertext }
  1461.   else { echo %chan *** %winnertext }
  1462.   if (%gameover == 1) {
  1463.     echo %chan *** game over - %champion takes the table
  1464.   } else {
  1465.     ; keep a practice session flowing: auto-deal the next hand after a short pause
  1466.     if (%practice == 1) { timer 2500 poker_next }
  1467.   }
  1468. }
  1469.  
  1470. ; Deal the next hand of an ongoing session (host-driven in a real game; auto in practice).
  1471. on SIGNAL:poker_next {
  1472.   if (%gameover == 1) { return }
  1473.   if (%started == 1) { return }
  1474.   if (%practice == 1) { poker_deal }
  1475. }
  1476.  
  1477. ; Start a fresh session: reset every seated player's stack and deal hand 1 again.
  1478. on SIGNAL:poker_newgame {
  1479.   poker_sethost
  1480.   if (%ishost == 0) { toast Only the host can start a new game | return }
  1481.   set %gameover 0
  1482.   set %champion
  1483.   set %button 0
  1484.   set %handid 0
  1485.   foreach %fp %seats { setat %stack %fp %startstack }
  1486.   poker_deal
  1487. }
  1488.  
  1489. ; ============================================================================
  1490. ; the table view
  1491. ; The view DSL supports if/elseif/else + foreach, so the table is state-aware.
  1492. ; Multi-word dynamic text is quoted ("…") so it survives as a single label.
  1493. ; ============================================================================
  1494. ; The host fires this when the device rotates while our view is mounted: re-render so the
  1495. ; table swaps between the portrait stadium and the landscape/TV ring immediately instead of
  1496. ; waiting for the next game action to repaint. Guard on %closed == 0 exactly: unset (never
  1497. ; opened) expands to "", so a rotation before the first poker_open cannot pop the table, and
  1498. ; poker_render's own %closed == 1 latch covers the closed-with-X case.
  1499. on SIGNAL:screenchange {
  1500.   if (%closed == 0) { poker_render }
  1501. }
  1502.  
  1503. alias poker_render {
  1504.   ; The table was closed with the X. Inbound state/deltas, clock ticks and bot steps all render, so
  1505.   ; without this latch any of them would pop the table straight back open. Re-opening from the
  1506.   ; sidebar (poker_open) clears it.
  1507.   if (%closed == 1) { return }
  1508.   set %me $age.me
  1509.   set %seated 0
  1510.   if ($has(%name,%me) == true) { set %seated 1 }
  1511.   set %turnfp $get(%seats,%turn)
  1512.   ; dealer button follows the rotating button; blinds were set for real by poker_postblinds,
  1513.   ; so only derive a preview for the lobby (no hand in progress yet).
  1514.   set %dealerfp $get(%seats,%button)
  1515.   if (%started == 0) {
  1516.     set %sbi $poker_nextin($calc(%button + 1))
  1517.     set %sbfp $get(%seats, %sbi)
  1518.     set %bbfp $get(%seats, $poker_nextin($calc(%sbi + 1)))
  1519.   }
  1520.   set %nseat $len(%seats)
  1521.  
  1522.   ; ---- action context (decide here; the view only reads flags/labels) ----
  1523.   set %active 0
  1524.   if (%started == 1) { set %active 1 }
  1525.  
  1526.   set %ismyturn 0
  1527.   if (%active == 1) { if (%turnfp == %me) { if ($get(%folded,%me) != 1) { set %ismyturn 1 } } }
  1528.  
  1529.   set %mybet $get(%bet,%me)
  1530.   set %need $calc(%tocall - %mybet)
  1531.   if (%need < 0) { set %need 0 }
  1532.   set %mystack $get(%stack,%me)
  1533.   set %calllabel Check
  1534.   if (%need > 0) { set %calllabel Call %need }
  1535.   if (%need > 0) { if (%need >= %mystack) { set %calllabel All-in %mystack } }
  1536.   ; folding when a check is free is never right, so offer Fold only when there's a bet to face
  1537.   set %canfold 0
  1538.   if (%need > 0) { set %canfold 1 }
  1539.   set %tocalllabel Check is free
  1540.   if (%need > 0) { set %tocalllabel To call %need }
  1541.   ; raise bounds: at least the minimum raise (the dealer's figure, or bet + big blind from an older
  1542.   ; dealer), at most all-in; no raise when the dealer says this seat may only call
  1543.   set %rmaxme $calc(%mybet + $get(%stack,%me))
  1544.   set %rminme %minraiseto
  1545.   if (%ishost == 1) { if (%started == 1) { set %rminme $poker_minraise } }
  1546.   if ($len(%rminme) == 0) { set %rminme $calc(%tocall + %bb) }
  1547.   set %canraise 1
  1548.   if (%rminme == 0) { set %canraise 0 }
  1549.   if (%rmaxme <= %tocall) { set %canraise 0 }
  1550.   if (%betamount < %rminme) { set %betamount %rminme }
  1551.   if (%betamount > %rmaxme) { set %betamount %rmaxme }
  1552.   set %raiselabel Raise to %betamount
  1553.   if (%betamount >= %rmaxme) { set %raiselabel All-in %rmaxme }
  1554.  
  1555.   ; Host action gating. Keying the table (age.host) only needs the host seated - a lone host must be
  1556.   ; able to open the table so peers can join encrypted; dealing a hand needs at least two seats. So
  1557.   ; canstart is true for the host in the lobby when either the table is not yet keyed (open it) or it
  1558.   ; is keyed and enough players are seated (deal). Without the pre-key case a solo host could never
  1559.   ; open the table and real multiplayer would deadlock, showing "Join Table" again after joining.
  1560.   ; Host action gating. Before any table exists nobody is host yet, so ANY seated player may open one
  1561.   ; (whoever taps becomes the host). Gating this on %ishost was the no-host deadlock: with the host
  1562.   ; elected by fingerprint, the tapper wasn't allowed to open and the elected owner never tapped.
  1563.   ; Once a table is keyed, only its host may deal, and only with enough players seated.
  1564.   set %canstart 0
  1565.   if (%active == 0 && %gameover == 0) {
  1566.     if (%hostlocked == 0) { set %canstart 1 }
  1567.     elseif (%ishost == 1 && %hosted == 1 && %nseat > 1) { set %canstart 1 }
  1568.   }
  1569.   set %startlabel Open Table
  1570.   if (%hosted == 1) { set %startlabel Deal Hand }
  1571.   if (%handid > 0) { set %startlabel Next Hand }
  1572.   set %hostlabel Start a table
  1573.   if (%hosted == 1) { set %hostlabel You're the host }
  1574.  
  1575.   ; The dealer can end the table whenever it is keyed: mid-hand, at showdown, or while waiting in
  1576.   ; the lobby. Gating this on the lobby-only %canstart made End Table useless exactly when a stuck
  1577.   ; table needs ending, so it lives in the header and is driven by its own flag.
  1578.   set %canend 0
  1579.   if (%practice == 0 && %ishost == 1 && %hosted == 1) { set %canend 1 }
  1580.  
  1581.   ; A player seated in the lobby who can't act yet (a non-host waiting on the host, or the host who
  1582.   ; has opened the table and is waiting for players) gets a status line - never the "Join Table"
  1583.   ; button again, which reads as though their join silently failed.
  1584.   set %seatwait Waiting for the host to start the hand
  1585.   if (%ishost == 1) { set %seatwait Table open · waiting for players to join }
  1586.  
  1587.   ; game over: one player has all the chips
  1588.   set %isover 0
  1589.   if (%gameover == 1) { set %isover 1 }
  1590.   set %cannewgame 0
  1591.   if (%isover == 1) { if (%ishost == 1) { set %cannewgame 1 } }
  1592.   set %overlabel %champion wins the table
  1593.   if ($len(%champion) == 0) { set %overlabel Game over }
  1594.  
  1595.   set %waiting 0
  1596.   if (%active == 1) { if (%ismyturn == 0) { set %waiting 1 } }
  1597.   set %waitlabel Waiting for $get(%name,%turnfp)…
  1598.  
  1599.   ; per-turn shot-clock label (blank unless a live hand is counting down)
  1600.   set %clocklabel
  1601.   if (%active == 1) { if (%clockleft > 0) { set %clocklabel ⏱ %clockleft s } }
  1602.   ; shot-clock bar: filled part is time left, turning red for the last ten seconds
  1603.   set %clocktotal $int($calc(%actclockms / 1000))
  1604.   set %clockw1 %clockleft
  1605.   if (%clockw1 <= 0) { set %clockw1 0.01 }
  1606.   set %clockw2 $calc(%clocktotal - %clockleft)
  1607.   if (%clockw2 <= 0) { set %clockw2 0.01 }
  1608.   set %clockcol #ffd166
  1609.   if (%clockleft <= 10) { set %clockcol #ed4245 }
  1610.   set %showclock 0
  1611.   if (%active == 1) { if (%clockleft > 0) { if (%practice == 0) { set %showclock 1 } } }
  1612.   set %lobbyline $len(%seats) seated · Blinds %sb/%bb
  1613.   if (%waiting == 1) { if (%clockleft > 0) { set %waitlabel Waiting for $get(%name,%turnfp)… · ⏱ %clockleft s } }
  1614.  
  1615.   set %haswinner 0
  1616.   set %winlen $len(%winnertext)
  1617.   if (%winlen > 0) { set %haswinner 1 }
  1618.  
  1619.   set %streetlabel WAITING
  1620.   if (%street == preflop) { set %streetlabel PRE-FLOP }
  1621.   elseif (%street == flop) { set %streetlabel FLOP }
  1622.   elseif (%street == turn) { set %streetlabel TURN }
  1623.   elseif (%street == river) { set %streetlabel RIVER }
  1624.   elseif (%street == lobby) { set %streetlabel LOBBY }
  1625.   set %blindslabel Blinds %sb/%bb · Pot %pot
  1626.  
  1627.   ; ---- per-seat display (precompute into maps) ----
  1628.   set %seatborder $map()
  1629.   set %seatborderw $map()
  1630.   set %seatbadge $map()
  1631.   set %seatbadgebg $map()
  1632.   set %seatstatus $map()
  1633.   set %seatav $map()
  1634.   foreach %fp %seats {
  1635.     set %bc #3a3350
  1636.     set %bw 1
  1637.     if (%fp == %turnfp) { if (%active == 1) { set %bc #ffd166 | set %bw 4 } }
  1638.     setat %seatborder %fp %bc
  1639.     setat %seatborderw %fp %bw
  1640.  
  1641.     set %badge
  1642.     set %badgebg #00000000
  1643.     if (%fp == %dealerfp) { set %badge D | set %badgebg #f0c020 }
  1644.     elseif (%fp == %sbfp) { set %badge SB | set %badgebg #6c7bdc }
  1645.     elseif (%fp == %bbfp) { set %badge BB | set %badgebg #6c7bdc }
  1646.     setat %seatbadge %fp %badge
  1647.     setat %seatbadgebg %fp %badgebg
  1648.  
  1649.     set %sline
  1650.     if ($get(%bet,%fp) > 0) { set %sline BET $get(%bet,%fp) }
  1651.     if ($get(%allin,%fp) == 1) { set %sline ALL-IN }
  1652.     if ($get(%folded,%fp) == 1) { set %sline FOLD }
  1653.     ; a player with no chips who isn't all-in this hand is eliminated
  1654.     if ($get(%stack,%fp) <= 0) { if ($get(%allin,%fp) != 1) { set %sline OUT } }
  1655.     setat %seatstatus %fp %sline
  1656.  
  1657.     set %av #6c5ce7
  1658.     if ($get(%folded,%fp) == 1) { set %av #3a3350 }
  1659.     setat %seatav %fp %av
  1660.   }
  1661.  
  1662.   ; my hole cards (split "c1 c2"); show backs until dealt
  1663.   set %myc $split($get(%myhole,me))
  1664.   set %hashole 0
  1665.   if ($len(%myc) > 1) { set %hashole 1 }
  1666.   set %h1 $get(%myc,0)
  1667.   set %h2 $get(%myc,1)
  1668.  
  1669.   ; ---- hand-rank badges: mine always, others only once their hole is revealed ----
  1670.   set %bn $len(%board)
  1671.   set %mycat
  1672.   if (%hashole == 1) { if (%bn > 0) { set %mycat $poker_handcat($get(%myhole,me) $join(%board)) } }
  1673.   set %hasmycat 0
  1674.   if ($len(%mycat) > 0) { set %hasmycat 1 }
  1675.   set %seatrank $map()
  1676.   set %seathasrank $map()
  1677.   set %seatc1 $map()        ; revealed hole cards per seat, populated only at showdown
  1678.   set %seatc2 $map()
  1679.   set %seatreveal $map()
  1680.   set %seatemoji $map()
  1681.   foreach %fp %seats {
  1682.     set %rk
  1683.     ; prefer the broadcast reveal (present on every client at showdown), fall back to the local
  1684.     ; hole map (the host has it live). This is why opponents' ranks/cards now show for everyone.
  1685.     set %hh $get(%reveal,%fp)
  1686.     if ($len(%hh) == 0) { set %hh $get(%hole,%fp) }
  1687.     if ($len(%hh) > 0) { if (%bn > 0) { set %rk $poker_handcat(%hh $join(%board)) } }
  1688.     setat %seatrank %fp %rk
  1689.     set %hr 0
  1690.     if ($len(%rk) > 0) { set %hr 1 }
  1691.     setat %seathasrank %fp %hr
  1692.     ; the actual two cards to show under an opponent's seat at showdown
  1693.     set %shown 0
  1694.     set %rv $get(%reveal,%fp)
  1695.     if ($len(%rv) > 0) {
  1696.       set %rc $split(%rv)
  1697.       setat %seatc1 %fp $get(%rc,0)
  1698.       setat %seatc2 %fp $get(%rc,1)
  1699.       set %shown 1
  1700.     }
  1701.     setat %seatreveal %fp %shown
  1702.     ; stable per-player emoji avatar from the first hex nibble of their fingerprint hash
  1703.     setat %seatemoji %fp $get(%emojimap, $lower($left($age.sha(%fp),1)))
  1704.   }
  1705.  
  1706.   ; ---- ring seat order: hero first so the ring drops us at the bottom-centre (child 0),
  1707.   ; opponents fanning out around the oval like Discord's table. Not seated -> natural order. ----
  1708.   ; opponents sit along the top edge; the hero is shown in the hand panel at the bottom.
  1709.   set %topseats $list()
  1710.   foreach %fp %seats { if (%fp != %me) { push %topseats %fp } }
  1711.   ; Ring order: YOU first. ScriptView.Ring anchors child 0 at the bottom of the ellipse and walks the
  1712.   ; rest around it, so hero-first puts you at the near edge with everyone facing you across the felt.
  1713.   set %ringseats $list()
  1714.   if (%seated == 1) { push %ringseats %me }
  1715.   foreach %fp %topseats { push %ringseats %fp }
  1716.   ; ---- orientation-aware table geometry. TUNE ON DEVICE. --------------------------------------
  1717.   ; One layout, two axes: the seats sit on the perimeter of a CAPSULE (stadium), and the ratio
  1718.   ; picks the axis. Portrait: vertical, you on the bottom cap, opponents up the straight sides.
  1719.   ; Landscape / TV: horizontal, opponents across the top edge facing you. The renderer grows
  1720.   ; the table with the seat count so seats can never overlap, and it sizes the felt to the
  1721.   ; exact seat path, so every pod straddles the rail: players AT the table, not floating above.
  1722.   if (%land == 1) {
  1723.     ; landscape / TV: horizontal capsule (ratio < 1 picks the axis), opponents across the top
  1724.     ; edge facing you. The radius scales with the screen so a 16:9 TV gets a proper wide table.
  1725.     set %ringr $int($calc(($screen.width - 400) / 2))
  1726.     if (%ringr > 260) { set %ringr 260 }
  1727.     if (%ringr < 130) { set %ringr 130 }
  1728.     set %ringratio 0.5
  1729.   }
  1730.   else {
  1731.     ; portrait: vertical capsule (ratio >= 1), you on the bottom cap, opponents flanking the
  1732.     ; straight sides with an odd opponent at the top apex.
  1733.     set %ringr 92
  1734.     set %ringratio 1.4
  1735.   }
  1736.   ; The felt is the ring child flagged `felt` below: the RENDERER sizes it to the exact seat
  1737.   ; path (and grows the table with the seat count), so nothing here needs to mirror renderer
  1738.   ; geometry. The huge corner radius clamps to a capsule in either orientation.
  1739.  
  1740.   view {
  1741.     surface gradient linear:#1e2138:#0a0c18 bg #0a0c18 pad 7 {
  1742.       column gap 8 pad 2 align center fill {
  1743.  
  1744.         ; ---- header: blurple crest · title · street pill ----
  1745.         row gap 9 align center fill {
  1746.           surface circle width 32 height 32 gradient linear:#5865f2:#4752c4 elevation 5 {
  1747.             column align center { text "♠" bold color #ffffff textsize 16 }
  1748.           }
  1749.           column gap 0 weight 1 {
  1750.             text "POKER NIGHT" bold color #ffffff textsize 15
  1751.             text "%blindslabel" color #8a91a8 textsize 10
  1752.           }
  1753.           surface gradient linear:#5865f2:#4752c4 radius 20 pad 6 elevation 3 {
  1754.             text "%streetlabel" bold color #ffffff textsize 10
  1755.           }
  1756.           if (%canend == 1) { button "End" poker_stop bg #2b3150 color #ed4245 radius 12 height 34 }
  1757.         }
  1758.  
  1759.         ; ---- table: opponents along the top edge, a compact square felt below. The hero sits in
  1760.         ; the hand panel at the bottom (further down), a phone-friendly top-vs-bottom table. ----
  1761.         surface gradient linear:#151934:#0d1022 bg #12152b radius 24 pad 10 elevation 10 border #262b4d 1 fill {
  1762.           column align center gap 9 fill {
  1763.             ; The table proper: an elliptical felt with a seat pod for every player arranged around
  1764.             ; its rim (you at the bottom). Replaces the old opponents-across-the-top strip, which read
  1765.             ; as a list of avatars rather than a table.
  1766.             stack align center {
  1767.               ring size %ringr ratio %ringratio stadium {
  1768.               ; Felt first, flagged `felt`: the renderer sizes it to the exact path the seats
  1769.               ; sit on, so every pod straddles the rail with half its avatar on the felt -
  1770.               ; players AT the table, not floating above it.
  1771.               surface felt radius 999 gradient radial:#2c9c6a:#0f4a37 bg #12633f border #0a3327 5 elevation 6 {
  1772.                 column align center gap 5 fill {
  1773.                   spacer weight 1
  1774.                   if (%haswinner == 1) {
  1775.                     surface gradient linear:#2fbf71:#12833f radius 14 pad 6 elevation 5 {
  1776.                       column align center gap 0 {
  1777.                         text "🏆" textsize 14
  1778.                         text "%winnertext" bold color #ffffff textsize 11
  1779.                       }
  1780.                     }
  1781.                   }
  1782.                   else {
  1783.                   surface bg #0b2418 radius 14 pad 5 border #2f7d54 1 elevation 3 {
  1784.                     row gap 6 align center {
  1785.                       stack {
  1786.                         surface circle width 12 height 12 bg #c0392b border #ffffff 2 offsety 5 { spacer }
  1787.                         surface circle width 12 height 12 bg #2980b9 border #ffffff 2 offsety 3 { spacer }
  1788.                         surface circle width 12 height 12 bg #f0c020 border #ffffff 2 { spacer }
  1789.                       }
  1790.                       column align center gap 0 {
  1791.                         text "POT" bold color #7fd6a2 textsize 8
  1792.                         text %pot bold color #ffffff textsize 15
  1793.                       }
  1794.                     }
  1795.                   }
  1796.                   }
  1797.                   row gap 3 align center {
  1798.                     foreach %idx $range(0,4) {
  1799.                       if (%idx < %bn) { card $get(%board,%idx) width 22 elevation 4 }
  1800.                       else { card "" back width 22 elevation 2 }
  1801.                     }
  1802.                   }
  1803.                   spacer weight 1
  1804.                 }
  1805.               }
  1806.                 foreach %fp %ringseats {
  1807.                   column align center gap 2 {
  1808.                     stack {
  1809.                       if ($len($get(%avatar,%fp)) > 0) {
  1810.                         surface circle width 34 height 34 elevation 4 border $get(%seatborder,%fp) $get(%seatborderw,%fp) {
  1811.                           image $get(%avatar,%fp) circle width 34 height 34 crop
  1812.                         }
  1813.                       }
  1814.                       else {
  1815.                         surface circle width 34 height 34 elevation 4 bg $get(%seatav,%fp) border $get(%seatborder,%fp) $get(%seatborderw,%fp) {
  1816.                           column align center { text "$get(%seatemoji,%fp)" textsize 19 }
  1817.                         }
  1818.                       }
  1819.                       surface circle width 14 height 14 bg $get(%seatbadgebg,%fp) border #101430 1 align bottom {
  1820.                         text "$get(%seatbadge,%fp)" bold color #101430 textsize 7
  1821.                       }
  1822.                     }
  1823.                     surface bg #1b2040 radius 8 pad 3 border $get(%seatborder,%fp) $get(%seatborderw,%fp) elevation 2 {
  1824.                       column align center gap 0 {
  1825.                         text "$get(%name,%fp)" bold color #ffffff textsize 9
  1826.                         row gap 2 align center {
  1827.                           surface circle width 7 height 7 bg #f2c14e border #d99a2b 1 { spacer }
  1828.                           text $get(%stack,%fp) bold color #ffd76b textsize 9
  1829.                         }
  1830.                       }
  1831.                     }
  1832.                     ; after a move, the pod says what they did: what they put in, or that they are out,
  1833.                     ; or the hand they are showing once the board makes one readable.
  1834.                     if ($get(%folded,%fp) == 1) { surface bg #241d33 radius 7 pad 2 { text "FOLD" bold color #7a7a8a textsize 8 } }
  1835.                     elseif ($len($get(%lastact,%fp)) > 0) {
  1836.                       surface bg #2a2140 radius 9 pad 2 border #f0c020 1 {
  1837.                         row gap 3 align center {
  1838.                           text "$get(%lastact,%fp)" bold color #e6e9f2 textsize 8
  1839.                           if ($get(%bet,%fp) > 0) { text $get(%bet,%fp) bold color #ffd166 textsize 8 }
  1840.                         }
  1841.                       }
  1842.                     }
  1843.                     elseif ($get(%bet,%fp) > 0) {
  1844.                       surface bg #2a2140 radius 9 pad 2 border #f0c020 1 {
  1845.                         row gap 2 align center {
  1846.                           surface circle width 7 height 7 bg #f0c020 border #ffffff 1 { spacer }
  1847.                           text $get(%bet,%fp) bold color #ffd166 textsize 8
  1848.                         }
  1849.                       }
  1850.                     }
  1851.                     elseif ($get(%seathasrank,%fp) == 1) { surface bg #0a0a0a radius 6 pad 2 { text "$get(%seatrank,%fp)" bold color #f5f5f5 textsize 8 } }
  1852.                     ; every box holds cards: yours face up, everyone else face down until showdown turns
  1853.                     ; them over. A folded player shows none at all.
  1854.                     if (%fp == %me) { spacer }
  1855.                     elseif ($get(%seatreveal,%fp) == 1) {
  1856.                       row gap 2 align center { card $get(%seatc1,%fp) width 16 elevation 3 | card $get(%seatc2,%fp) width 16 elevation 3 }
  1857.                     }
  1858.                     elseif ($get(%folded,%fp) != 1) {
  1859.                       ; != 1, not == 0: an unset map entry expands to empty, so a player who simply
  1860.                       ; hasn't folded reads as "" and would fail an == 0 test.
  1861.                       if (%started == 1) { row gap 2 align center { card "" back width 16 elevation 2 | card "" back width 16 elevation 2 } }
  1862.                     }
  1863.                   }
  1864.                 }
  1865.               }
  1866.             }
  1867.           }
  1868.         }
  1869.  
  1870.         ; ---- your hand: big hole cards + rank (avatar/name/stack already show in the ring seat) ----
  1871.         if (%seated == 1) {
  1872.           surface gradient linear:#1a1e3c:#141733 bg #171232 radius 18 pad 9 elevation 6 border $get(%seatborder,%me) $get(%seatborderw,%me) fill {
  1873.             row gap 12 align center {
  1874.               column gap 4 weight 1 {
  1875.                 text "YOUR HAND" bold color #8a91a8 textsize 9
  1876.                 if (%hasmycat == 1) { surface bg #2a2140 radius 8 pad 4 border #f2c14e 1 { text "%mycat" bold color #ffe08a textsize 12 } }
  1877.                 elseif (%hashole == 1) { text "Waiting for the flop" color #8a91a8 textsize 11 }
  1878.                 else { text "Cards come with the next deal" color #8a91a8 textsize 11 }
  1879.                 row gap 4 align center {
  1880.                   surface circle width 10 height 10 bg #f2c14e border #d99a2b 1 { spacer }
  1881.                   text %mystack bold color #ffd76b textsize 12
  1882.                 }
  1883.               }
  1884.               row gap 7 {
  1885.                 if (%hashole == 1) { card %h1 width 52 elevation 8 | card %h2 width 52 elevation 8 }
  1886.                 else { card "" back width 52 elevation 4 | card "" back width 52 elevation 4 }
  1887.               }
  1888.             }
  1889.           }
  1890.         }
  1891.  
  1892.         ; ---- action bar (state-aware) ----
  1893.         surface gradient linear:#1a1e3c:#141733 bg #171232 radius 20 pad 11 elevation 8 fill {
  1894.           if (%isover == 1) {
  1895.             column gap 7 fill align center {
  1896.               surface gradient linear:#f2c14e:#e0a52e radius 14 pad 6 elevation 4 { text "🏆 %overlabel" bold color #3a2e08 textsize 13 }
  1897.               if (%cannewgame == 1) { button "New Game" poker_newgame bg #5865f2 color #ffffff radius 14 bold fill height 52 }
  1898.               else { text "Waiting for the host to start a new game" color #8a91a8 textsize 11 }
  1899.             }
  1900.           }
  1901.           elseif (%ismyturn == 1) {
  1902.             column gap 9 fill {
  1903.               row gap 8 align center fill {
  1904.                 text "YOUR TURN" bold color #ffd76b textsize 11
  1905.                 text "%tocalllabel · Pot %pot" color #b9c0d4 textsize 11 weight 1
  1906.                 if (%showclock == 1) { text "%clockleft s" bold color %clockcol textsize 11 }
  1907.               }
  1908.               if (%showclock == 1) {
  1909.                 row gap 0 fill {
  1910.                   surface bg %clockcol radius 3 height 4 weight %clockw1 { spacer }
  1911.                   surface bg #2b3150 radius 3 height 4 weight %clockw2 { spacer }
  1912.                 }
  1913.               }
  1914.               row gap 8 fill {
  1915.                 if (%canfold == 1) { button "Fold" poker_fold bg #3a3f52 color #e6e9f2 radius 14 bold weight 1 height 52 }
  1916.                 button "%calllabel" poker_call bg #3ba55d color #ffffff radius 14 bold weight 1 height 52
  1917.               }
  1918.               if (%canraise == 1) {
  1919.                 row gap 6 align center fill {
  1920.                   button "−" poker_dec bg #2b3150 color #e6e9f2 radius 14 bold width 52 height 52
  1921.                   button "%raiselabel" poker_raise bg #f2c14e color #3a2e08 radius 14 bold weight 1 height 52
  1922.                   button "+" poker_inc bg #2b3150 color #e6e9f2 radius 14 bold width 52 height 52
  1923.                 }
  1924.                 row gap 5 fill {
  1925.                   button "Min" poker_min bg #2b3150 color #cdd6e6 radius 12 weight 1 height 40
  1926.                   button "½ Pot" poker_h bg #2b3150 color #cdd6e6 radius 12 weight 1 height 40
  1927.                   button "Pot" poker_pot bg #2b3150 color #cdd6e6 radius 12 weight 1 height 40
  1928.                   button "All-in" poker_allin bg #5a2230 color #ffb3b8 radius 12 bold weight 1 height 40
  1929.                 }
  1930.               }
  1931.             }
  1932.           }
  1933.           elseif (%canstart == 1) {
  1934.             column gap 7 fill align center {
  1935.               text "%hostlabel" bold color #b9c0d4 textsize 12
  1936.               if (%hosted == 1) { text "%lobbyline" color #8a91a8 textsize 10 }
  1937.               button "%startlabel" poker_start bg #5865f2 color #ffffff radius 14 bold fill height 52
  1938.             }
  1939.           }
  1940.           elseif (%waiting == 1) {
  1941.             column gap 6 fill {
  1942.               row gap 6 align center { text "%waitlabel" color #b9c0d4 textsize 12 }
  1943.               if (%showclock == 1) {
  1944.                 row gap 0 fill {
  1945.                   surface bg %clockcol radius 3 height 3 weight %clockw1 { spacer }
  1946.                   surface bg #2b3150 radius 3 height 3 weight %clockw2 { spacer }
  1947.                 }
  1948.               }
  1949.             }
  1950.           }
  1951.           elseif (%seated == 1) {
  1952.             column gap 3 fill align center {
  1953.               text "%seatwait" color #b9c0d4 textsize 12
  1954.               text "%lobbyline" color #8a91a8 textsize 10
  1955.             }
  1956.           }
  1957.           else {
  1958.             column gap 7 fill align center {
  1959.               text "Tap to take a seat" color #b9c0d4 textsize 12
  1960.               button "Join Table" poker_join bg #5865f2 color #ffffff radius 14 bold fill height 52
  1961.               button "Practice vs Bots" poker_practice bg #2b3150 color #e6e9f2 radius 14 fill height 48
  1962.             }
  1963.           }
  1964.         }
  1965.  
  1966.       }
  1967.     }
  1968.   }
  1969. }

Raw Paste

Comments 0
Login to post a comment.
  • No comments yet. Be the first.
Login to post a comment. Login or Register
We use cookies. To comply with GDPR in the EU and the UK we have to show you these.

We use cookies and similar technologies to keep this website functional (including spam protection via Google reCAPTCHA or Cloudflare Turnstile), and — with your consent — to measure usage and show ads. See Privacy.