Compare commits

..
Author SHA1 Message Date
jheapsandClaude Opus 5 cd57c16050 Let the table tell the dealer who won
An option — off by default, and off means the tool is exactly what it was.

Turn it on and the community cards go on the felt. Each street asks for the cards as
it is dealt: the picker opens on the flop the moment the flop button is pressed, and
again on the turn and the river, because the moment a dealer is holding those cards is
the only moment they know what they are without turning the board round. Three taps,
then one, then one. The picker is the same sheet as the hole cards, which now knows
about the middle of the table too — the seven of clubs cannot be on the flop and in
somebody's hand, and until now it could.

Turning the players' cards over is unchanged. That already worked the way it should.

What is new is what happens next. Resolve Pot stops asking who won and says so:

    Alexandra wins $50 with three of a kind, nines.

with every hand at the table read out under its player's name, the winner already
ticked, and the button reading "Pay Alexandra". A chop comes out as "Christopher and
Mike from work split it, $22.50 each, with a pair of aces", both ticked. The dealer
still confirms — the tool reads the cards, a person still says the pot is good, and a
hand entered wrong is corrected by unticking rather than by starting over.

It declines rather than guesses. A board that isn't five cards, a player who hasn't
turned over, the same card entered in two places: each says which of those it is and
hands the question back, and the wizard is the one it always was. Who is *ahead* and
who *won* are different claims and only the second one can pay somebody.

Side pots are read per round, not once. The best hand takes the main pot and is then
out of the question; the side pot goes to the best of who is left, which is a different
answer and the one the tool has to ask for again.

handRank.js is the only module here that can pay the wrong person without anybody
noticing, so it is built to be checkable rather than clever: rank five cards, then take
the best of the twenty-one five-card hands in seven. Beside the written cases — every
category against every other, the wheel and the steel wheel, three kickers deep, the
counterfeited two pair, the board that plays — it is checked against a second evaluator
written a different way, on twenty thousand random seven-card hands and four thousand
random pairs of them. An ace that keeps its value in the wheel, a dropped two-pair
kicker and a flush read only by its top card were each introduced on purpose and each
caught.

The board takes the middle of the felt, sized from the room the seat ring actually
leaves — measured against every seat rather than the ring's widest point, which is only
the answer for a seat sitting exactly on the horizontal axis and had two pucks on top
of the board while claiming 77px of clearance either side. Where there is no middle to
take, it moves to a strip above the table: a phone on its side has a felt 528x83 with
55px pucks, so the ring closes over the centre entirely and a board in it is a board
with players painted on top.

That strip found an older bug. It costs the felt height, and a felt that changes size
had only ever been re-measured, never laid out again: the seats follow it on their own,
being placed in percentages, but a bet chip anchored inside a seat is placed in pixels
off that seat's centre. Measured at 640x360, the chips were positioned for a felt 83px
tall and painted on one of 60 — seat 3's $5 came to rest on seat 4's puck, and two
pairs of seat pucks were overlapping. The bar growing mid-hand does the same thing: a
side pot appearing is 55px off the felt. Both fixed.

The sweep grew a third table — the same five players in the same nine chairs as the
second, with the board on, so the only thing that differs between those two rows is the
board itself. It earned its place on the first run.

728 unit tests. 216 audits: what is left is the seat ring hanging past the rail on a
landscape phone, the known residual, plus five or six pixels more of it on the layouts
where the strip takes the felt's height, and a blind badge over a stack on a packed
twelve-seat portrait table.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-04 11:18:33 -06:00
jheapsandClaude Opus 5 2a080eab6a Give every bet on the felt somewhere to be
The chips were the last thing on the table nobody had measured, and the sweep had
never seen one: it audited a table that had never had a bet placed on it, so a third
of what is on the felt during a hand went unlooked at for the tool's whole life. It
posts blinds, deals and calls three times now before it measures anything.

What that found, and what this fixes:

- Chips accumulated. Seats are kept and updated in place rather than rebuilt, so
  clearing the bets layer stopped clearing the ones anchored inside a seat and
  nothing else ever did. An iPhone 14 had one chip per seat after the deal and five
  by the third render; a dealer's every tap left another disc on the felt.

- The ring-or-cling decision asked how wide the window was. A phone held sideways is
  844px across and gives the felt 117px: it passed the width test, took the ring, and
  every chip on it was painted under a puck — the seats carry z-index 1 and the bets
  layer carries none, so a chip that lands under one is gone, and with it the only
  number saying what that player has in. Measured now, and only measured.

- Getting clear of a box was `edgeReach(puck) + edgeReach(chip)`, which is right only
  straight up, down or sideways. Two axis-aligned boxes are clear when they are apart
  on one axis, so the travel is the reach of the box you get by adding their widths
  and their heights. At 768x1024 a $10 leaving a seat on the diagonal wanted 88px and
  got 77, and came to rest 11px inside its own player's puck — every seat off the four
  compass points, which is most of them.

- Every chip was laid out at the first chip's size. A chip is as wide as the number on
  it: "$5" is 21px and "$10" is 27px on a phone, so each $10 was placed as if it were
  6px narrower than it is. The widest is no better: at 768x1024 one 47px chip made the
  whole table give up a ring the other four had room for.

- Anchored chips settled where they landed. At 640x360 the felt is 528x83 and a puck
  is 55 of those pixels tall: clearing it takes 41px, the players facing each other are
  70px apart, and both chips set off 41px into a gap that is 70 wide. Three overlapping
  pairs on a twelve-handed table. Each chip now gives ground only to something it is
  actually standing on, a pixel at a time — a midline rule or a single scale factor
  both punish the seats at the ends of a rail, which were never going to hit anything.

- Nothing knew the pot total was there. Seat 1's $10 was sitting on "Pot $65".

Two things off the felt, from the same sweep:

- The toast outlived its news. "Next hand — button on seat 2. [Undo]" stayed up while
  the hand was dealt and three players called: an offer to move the button, wired to a
  snapshot that predates the hand, so taking it would have thrown the hand away without
  saying so. It was also in the way of thirty small screens' seats and controls. The
  bar drops it as it takes the next action; the bar's own Undo names what it would
  actually take back.

- The pot dialog cut a name off. Three players in the pot on a Galaxy S8, two rows
  visible, the third below a hairline that reads as the end of the list — a dealer
  ticking the two they could see would have paid two thirds of a three-way pot. The
  85vh budget was still subtracting the action bar's height from a dialog that has sat
  above the bar since its z-index was fixed, and a player's ceiling moves beside their
  name on a short screen. All three fit now, and where a list does run on, it runs on
  under a fade rather than stopping dead on a row boundary.

The pot badge goes on a phone held sideways: 86x66 of a 692x113 felt, for a number the
action bar prints three inches below it, standing in the only band a bet chip has.

The audit stopped calling one thing another. An element clipped away by a panel that
scrolls is not covered by whatever is painted at that height — the wizard's third
winner came back for four viewports as "fully covered by button Confirm Winner(s)".

190 audits: 25 failing configurations to 7, and every one of those seven is the seat
ring hanging past the rail on a landscape phone, which is the known residual from the
last round. 663 unit tests, 44 of them new.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-03 17:05:47 -06:00
jheapsandClaude Opus 5 f93e0935ef Give every seat its own pixels
Six players at a nine-handed table is the most ordinary table this tool draws, and on
every phone in the sweep one of them had their stack painted under the player next to
them. Measured across nine viewports and six table sizes: seventeen of fifty-four
tables hid a name or a stack behind something belonging to another seat.

Two causes, and the layout only knew about a third of one of them.

The felt decided how big a puck could be from a single number — the straight-line
distance between the closest two *neighbouring* seats, judged against a fraction of a
puck's width. Distance has one number in it and a puck is half again as wide as it is
tall, so the same 84px was generous side by side and nowhere near enough on the
diagonal. And neighbours are the wrong pairs to ask about: on a phone held sideways the
felt is 528x87, the ring is very nearly a straight line, and the seat that lands on top
of you is the one across the table. Ten of the tables in the sweep had a collision that
a neighbours-only check cannot see — seats 1 and 7, overlapping by 68px, while every
adjacent pair had room.

seatsCollide() asks the real question instead: do any two of these boxes want the same
pixels. Two equal axis-aligned boxes overlap exactly when their centres are closer than
one box in both axes, so it is an answer rather than a proxy, and it looks at every
pair.

The second cause was the small blind badge, sitting at `left: -6px` — hanging off its
own puck's left corner onto whatever was beside it. On an iPhone Pro Max at six seats,
with the pucks not touching at all, "SB" was painted across the next player's $1,137.
All three badges now sit inside the puck's width, and in the same place as each other:
a seat only ever wears one, so two positions bought nothing except making the dealer's
eye find which of two spots this seat was using before it could read which blind it is.

Then the layout had to be able to act on the answer, and it couldn't. It chose between
two widths — 96px or 58px — and if neither fitted it widened the ring and let the seats
overlap, on the reasoning that a dealer can see an overhang but cannot see a tap landing
on the wrong player. That trade is real; it was also a false choice, because the tables
that overlapped did not want either number. At nine seats a Galaxy S8 had room for a
61px puck, an iPhone 14 for 68, a Pixel 7 for 74, an iPhone Pro Max for 79. Three media
queries declared three more of these numbers — 78px, 64px, 62px — at three breakpoints,
guessing at something a media query cannot see: the same 390px phone has room for a 90px
puck at four seats and 61 at nine.

So the width is searched for now, not chosen. render.js walks candidates from the top,
applies each one, measures what the browser actually drew, and takes the widest that
leaves every seat its own box. There was a width that worked on every table in the
sweep; the code was never asking for it. Ten candidates is ten forced layouts, so the
result is cached against the felt's size, the seat count and the names — measured 12.5ms
cold, 0.8ms warm, and renderSeats runs after every tap.

Three things this got wrong on the way, all caught by measuring rather than reading:

  The badge overhang was folded into the space between two seats. That collapsed the
  ring on a phone held sideways — 87px of height, and 18px of badge is most of the room
  the ring has to move in — until a six-handed landscape table was unsatisfiable at any
  width. It didn't belong there: the badge points *away* from the table at both ends, so
  two seats facing each other across the felt wear them back to back.

  box-sizing: border-box, which the puck needed so the searched number means the width
  it is drawn at, quietly turned every min-height from a content height into a drawn one.
  An empty chair went from a 52px tap target to a 42px one on every phone in the sweep.
  The audit found it; the four min-heights have each gained the padding and border they
  used to be quoted without.

  The new audit check reported a name under a neighbour on a table whose seats were 9px
  apart. A puck's name is a `-webkit-box` with `line-clamp`, and getClientRects() hands
  back a rect for every line the text *would* have taken, including the ones the clamp
  throws away — so the probe was hit-testing 30px below the puck, where nothing is
  painted. It clips to what is painted now.

uiAudit gains "no seat covers another seat's writing", the complement of the check
already there for a puck's own decoration on its own name — which is why nothing caught
this: seatLabelsClear() only ever looked inside one seat. Fault-injected against the
previous version: eighteen configurations, naming both causes.

And the sweep itself now runs two table shapes. It had run one for its whole life —
five players at a nine-handed table — and how crowded the felt is depends on how many
people are sitting down far more than on anything a viewport can report. A full table
was never once looked at.

632 tests, 0 failures. 190 audits across thirteen viewports at two table shapes, with a
mouse and with a thumb. Every table from two seats to twelve now keeps its own text on
every viewport in the sweep. One configuration still reports: a dozen players on a
640x360 phone, where the felt is 87px tall and two rows of 55px pucks cannot both fit
and stay on the rail — the ring grows 8px past the edge to keep the seats off each
other, which is the trade the old code named and got right. Left reported rather than
tuned away.

Names on a crowded phone table truncate harder than they did, because the puck is now
sized to fit instead of allowed to overlap: "Christopher" is "Christ…" at nine seats on
an iPhone 14. The full name is in the DOM, in the seat's form and in the sidebar. The
next lever on that is the seat layer's inset, which is still a fixed 44px of "half a
puck" for a puck that is no longer 96px wide — worth 54px to 60px where it was measured.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-03 13:23:31 -06:00
jheaps 190ccebf6c Merge pull request 'Hold'em dealer: a reachable Confirm, a table that fits, offline, and a quieter first screen' (#117) from polish/holdem-offline-and-render into master
Build and Deploy / build-deploy (push) Successful in 1m42s
Reviewed-on: #117
2026-09-03 12:24:00 -06:00
jheapsandClaude Opus 5 c052ee32c8 Put the Confirm button back on screen
Opened the pot wizard — the one dialog in this tool that divides money — and its
Confirm button was below a scroll. Not on a tall table, not on one screen: at
every size I measured, with six players and a side pot.

  iPhone 14 390x844   244px of the dialog below the fold
  Galaxy S8 360x640   417px
  844x390 landscape   583px
  desktop 1280x900    172px

Nothing on screen said there was anything under the list of names, so a dealer
with the table waiting had to scroll a list of players to find the only control
that finishes the hand.

Two goes at this, and the first was wrong. A sticky footer is the obvious
answer and it cannot work here: the actions were the last child of the
scrolling content, so their containing block ended exactly where they did and
`bottom` had no room to lift them. Sticky on the *header* did work, for the
mirror-image reason — its container extends below it — which is what made the
failure confusing to read. Capping the player list wasn't enough either; the
pot breakdown and the log still overflowed on a short screen.

So the dialog is a proper column now: a title that doesn't move, a body that
scrolls, and a footer outside the scroll. potWizard.js appends its buttons to
the footer instead of into the body, and clears both together so a step can't
inherit the previous step's buttons. Measured after: Confirm on screen and
hit-testable at all six configurations, twelve-handed on a Galaxy S8 included,
and the dialog itself no longer scrolls at all.

The checkboxes are painted now, too. `accent-color` only ever coloured the tick
— the box around it stayed the platform's own bright white square, which on a
near-black dialog was the loudest thing on screen and the last raw control in a
tool where everything else had been drawn. Same surface ramp, same corner
radius, and a tick drawn with clip-path so it can't pick up a substituted font.

uiAudit gains "an open dialog's buttons are on screen", which hit-tests rather
than trusting geometry — a button can be inside the viewport and still be under
something. Fault-injected: putting the footer back inside the scrolling body
reports Confirm 105px below the fold.

Two things checked and left alone, because they turned out to be right: the
standings table hides three columns on narrow screens through a container query
keyed to the sidebar rather than the viewport, which is why a desktop shows
fewer columns than an iPad — the sidebar is the narrower box there. And In/Won/
Net read $0 for hands settled outside the wizard, which the comment above them
already explains.

Caught by my own guard on the way past: the token test read `scroll-padding` as
`padding` and failed the spacing scale. Correct by its rules, wrong in substance
— those values are a sticky bar's measured height, not a step in the rhythm — so
the lookbehind now rejects a hyphen as well as a word character. Re-fault-
injected to confirm it still catches a real ad-hoc gap.

619 tests, 0 failures. 65 layout audits across 13 viewports x 5 table sizes and
35 across the five overlays. The whole wizard walked end to end: side pot
resolved, hand logged, $1,560 on the table before and after.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-03 12:20:02 -06:00
jheapsandClaude Opus 5 1f3dda180f Make the table big enough for the game around it
Looked at the felt at three times scale and the seats were falling off it. Not
sitting at a rail — hanging past the outer edge of the table into the page,
half a puck on green and half on nothing. Measured:

  1280x900, nine-handed   five of nine seats past the rail, worst 49px
  844x390,  six-handed    all six, worst 20px
  430x932,  six-handed    two, worst 12px
  360x640,  nine-handed   none

The ring sat at a flat 44% by 42% of the seat layer at every size, two numbers
picked against a phone. A fixed pair can only be right for one ratio of puck to
felt, and the felt's ratio changes with every viewport — so it was a different
amount of wrong on each one, which is exactly what makes something look like a
mistake rather than a choice.

The radius is derived now: the widest ring whose outermost seat still finishes
inside the table, worked out from the measured table, seat layer and puck. It
can only ever pull seats in — the old pair is kept as the ceiling — and it falls
back to that pair whenever there is nothing to measure, which is every call from
the unit tests and the first render before the felt is laid out.

Three things this turned up on the way, each caught by the sweep:

  * The seat layer is not centred on the table. Its insets differ top from
    bottom, so the first version — which assumed symmetry and worked from half
    widths — left a phone with 12px still over the rail. It works in absolute
    pixels against the nearer edge now.

  * The radius and the puck size depend on each other: the ring is limited by
    how big a puck is, the puck is sized by the `seatsTight` class, and that
    class was decided from the gaps between seats, measured at a radius that
    hadn't been worked out yet. Fixing the gap measurement then made a
    nine-handed phone overhang that had been fine, because the two were chasing
    each other. It is settled by trying the candidates in preference order
    instead: the roomy layout if everything fits, the tight one if not, and if
    neither fits, tight pucks on a ring widened only as far as it takes to stop
    seats colliding — because two seats fighting over a tap is a worse failure
    than a puck over the rail. A dealer can see an overhang; they cannot see
    that the seat they pressed wasn't the one that answered.

  * The spacing threshold was a flat 84px, the figure a 96px puck was judged
    against. Asking a 68px tight puck to keep a 96px puck's distance is a test
    it can never pass, so every landscape table fell through to the fallback and
    took an overhang it didn't need. It is a ratio now, not a number.

Result: worst overhang anywhere goes 49px to 9px, and 59 of 65 configurations
are completely clean. Desktop, tablet and every phone held upright: nothing over
the rail at all.

Residual, reported rather than tuned away: six configurations still overhang by
1-9px, all of them landscape at 640x360 and 667x375, where the felt is about
110-125px tall and no ring puts readable pucks inside that. The audit check is
left strict so they stay visible.

uiAudit gains "seats and chips stay on the table", which runs at every viewport
in the sweep. Fault-injected: putting the flat 44/42 back reproduces the original
failure exactly, including seat 3 at 49px.

Faster, too, because the measuring got hoisted out of the per-seat loops while I
was in there:

  renderSeats   7.3ms -> 1.8ms
  renderAll    12.4ms -> 6.8ms

619 tests, 0 failures. 65 layout audits across 13 viewports x 5 table sizes.
Offline re-verified: a whole hand with the network cut, $800 conserved.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-03 11:55:51 -06:00
jheapsandClaude Opus 5 3ffce9d7c1 Stop the empty table shouting, and point at the next step
The first screen a dealer ever sees was the one nobody had looked at. Opened
fresh, with nothing saved, the tool showed:

  * the word EMPTY, in capitals, ten times across the felt
  * Resolve Pot as the accent-green primary — on a table with no players and no
    pot, so the loudest control on screen was the one that could do least
  * Next Hand, with no button to move
  * no indication anywhere of what to do first, except a grey caption under the
    felt saying "tap a seat to edit"

An empty state is the one screen a new user is guaranteed to meet, and this one
described itself ten times without once saying what to do.

**The felt stops repeating itself.** An open chair is already dashed instead of
solid, faded, and has no stack under it — that reads at a glance, which is how a
dealer looks at a felt, and it reads the same on the one open chair at a full
table, which is the case the label was actually for. The word is gone from all
ten, and the seat numbers underneath it are now the thing you see. What the word
carried for anyone reading by ear moves to an aria-label on the seat, which now
says more than the sighted version ever did: "Seat 3, empty", "Seat 1, Ann".

**The bar says what the table is.** It used to hide itself when nobody was
seated — silent at exactly the moment a dealer has never used this before. It
now says "Nobody's at the table yet." with one full-width button, Seat a player,
which opens the seat editor on the first free chair. That is the same panel
tapping a seat gives them, so the button teaches the gesture rather than
replacing it.

**Two dead controls stop pretending.** Resolve Pot and Next Hand are disabled
until somebody is at the table, which takes the accent green off the button that
cannot work and leaves the only green on screen on the one that can. Disabled
rather than hidden: hiding them would move the header the moment the first
player is named, and a control that vanishes teaches nothing about what it was
for. Next Hand's own explanatory title is kept and handed back when it
re-enables.

One bug of my own, found by walking the flow rather than by reading it: after
typing a name both header buttons stayed greyed out, still captioned "nobody is
at the table yet". commitSeatChange refreshes narrowly on purpose — a full
render on every keystroke takes the name field out from under the dealer
mid-word — and the comment directly above it already warns about this exact trap
for the action bar. The header needed the same line.

609 tests, 0 failures. 65 layout audits across 13 viewports x 5 table sizes,
0 failures — the empty table is now one of those sizes, and had never been
audited before. Re-verified with the network cut: the first-run screen, the CTA
and seating a player all work offline.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-03 11:14:30 -06:00
jheapsandClaude Opus 5 5d5093f3cc Make the dealer tool work with no signal, and stop it shouting
Three findings this round, all measured on the running page.

**1. The tool needed the internet to exist.**

The night already survived anything — it lives in localStorage — but the page
did not. Reload in somebody's back room with one bar of signal and a dealer
holding a phone in one hand and a deck in the other got a browser error page
with nine players waiting. Verified: with no worker, an offline reload is
net::ERR_INTERNET_DISCONNECTED.

There is now a service worker (wwwroot/casino/sw.js) and a manifest, so the
tool installs to a home screen and runs with the network switched off. Measured
end to end: 19 assets cached from one ordinary visit, then with the context
offline the page loads, draws six seats, applies its CSS, and plays a whole
hand — blinds posted, four calls, $800 still on the table.

Three decisions worth writing down:

  * The precache list is read off the document rather than kept in the worker.
    Every stylesheet and script is already in the DOM; a hand-written file list
    stays right until somebody adds a script tag, and then the tool is quietly
    offline-broken until a dealer finds out at a table.
  * No skipWaiting. A new worker taking over a live page can hand it assets
    from a different release than the ones it started with, and this page loads
    seventeen scripts that expect to agree with each other.
  * Stale-while-revalidate for assets, not cache-first — see finding 3.

Scope is /casino/ rather than /casino/texasholdem/, because a scope has to be a
prefix of the page it controls and "/casino/texasholdem" does not start with
"/casino/texasholdem/". Anything in scope the worker wasn't told about goes
straight to the network.

Program.cs needed .webmanifest added to the MIME map: an unknown extension is
not served with the wrong type, it is not served at all, and a 404 manifest is
exactly the silent failure that stops a browser ever offering "Add to Home
Screen".

**2. A screen reader read out the whole action bar after every tap.**

The bar carried aria-live on the element whose entire contents render() rebuilds
each action. Measured, after one tap:

  "PRE-FLOP Pot $15 9 players Bob · $250 behind 0:00 ↶ dealing the hand U
   Fold Call $10 Raise"

Nothing in it is wrong; it is unusable at the speed a hand is dealt, and it is
the documented anti-pattern — a live region has to be a stable element whose
text changes, not a container that gets replaced. There is now a small
role="status" element that exists from page load and says one sentence:
"Dee to act, $10 to call. Pot $15." Guarded on the sentence rather than on the
state, because render() runs for many reasons that don't change whose turn it
is, and a live region handed the same words twice reads them twice.

**3. Every tap rebuilt ninety DOM nodes.**

renderSeats did `innerHTML = ""` and then cloned a template, attached three sets
of listeners and set a dozen attributes per chair — on every render, and
renderAll runs after every action. Profiled on a nine-handed table:

  renderSeats   7.3ms -> 4.0ms
  renderAll    12.4ms -> 9.5ms

The pucks are built once and updated in place, which is what the rest of that
function was already doing to their contents. A seat's node belongs to its index
for as long as the table is that size, so the listeners still close over the
index; only a change in the number of chairs rebuilds the row. Verified that
listeners don't stack: one click after six renders fires the hook exactly once,
and resizing 9 -> 4 -> 10 renumbers correctly.

Found along the way and deliberately left alone: ViewData["cssVersion"] renders
empty on every page of the site, so the ?v= cache-busting has never worked. It
is inert — Program.cs sends Cache-Control: no-store on all static files — and
the service worker was the only reason to care, which is why it uses
stale-while-revalidate instead. Noted in TexasHoldem.cshtml.

608 tests, 0 failures, including a new announcing.test.js. 52 layout audits
across 13 viewports x 4 table sizes: 0 failures, and the action bar still
doesn't change height mid-hand. Gestures re-verified after the seat refactor:
double-tap fold, long-press menu, give-the-button, and the active dealer chip.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-03 10:51:27 -06:00
jheaps aaf96543a8 Merge pull request 'Hold'em dealer: blind fix, design tokens, and the decrowd' (#116) from fix/naming-a-blind-deals-the-hand into master
Build and Deploy / build-deploy (push) Successful in 1m36s
Reviewed-on: #116
2026-09-03 10:26:50 -06:00
jheapsandClaude Opus 5 2e9c55af21 Give the felt back the screen the chrome was using
Measured on a 390x844 phone, six-handed, same table before and after:

                        before   after
  header                  193px    120px
  felt starts at          225px    152px
  controls on screen         27       18
  bordered elements          37       22
  text elements              61       49

A quarter of the screen went on chrome before the dealer saw the table.

**The header.** Six equally weighted buttons in two rows, of which two are
per-hand controls. The other four have gone where they belong rather than into
a "more" menu — that relocates crowding instead of removing it. Reset Table is
in the Session panel now, beside Clear history and the save/load pair: it is
the control that throws the night away and it was sitting in the same weight as
Resolve Pot, the most-pressed button in a session. Quick Split is down with
Common rulings, where the other "open something else" link already lived. The
way back to the site is a quiet link at the top, where a back link goes.

The subtitle is gone. It was one sentence of orientation on a tool used
nightly, and the landscape and short-phone rules already hid it — the layout
had decided it was expendable on every screen this is actually used on.

**Teaching copy, once.** Table Setup shipped open, so the first screen was the
most crowded one; it now opens only on a table nobody has set up yet, decided
once at load so it cannot reopen itself under a dealer who just shut it. The
gesture hint under the felt goes after the first deal of the session — keyed to
the hand number, not to bettingOpen, which was the obvious test and the wrong
one: it would have appeared and disappeared twice a hand, shunting the panel
stack up and down all night.

**Borders.** Panels had a border, a lighter background and a shadow — three
ways of drawing one edge. The standings had a rule under every row, which is
what makes a list read as ruled paper. Both drop the line and keep the
grouping; the standings header keeps its rule, because that one marks a change
of kind. Fields and buttons keep theirs: those say "interactive", which is not
decoration.

**The felt itself.** Names wrap to two lines instead of ellipsising, so
"Christopher" and "Mike from work" are readable rather than "Chri..." and "Mike
fro..." — the truncation was eating exactly the half a dealer typed to tell two
Mikes apart. And a stack of $1,234,567 rendered at 7px; it now drops the
thousands separators before it drops the type size, so the same number is eight
characters at 10px with every digit intact. The comment above fitAmount was
right that abbreviating loses precision — but precision the dealer cannot read
is not precision.

Two things tried and reverted, both measured:
  * Reserving the second name line made every puck the height of the tallest
    (69-73px became a uniform 88). Fifteen pixels on all nine seats is felt
    spent on chrome, which is what this round is trying to give back.
  * Dropping the name a type step to fit more on one line still did not fit
    "Christopher" on the button seat, where the dealer chip takes 22px of the
    row — so it cost legibility and bought nothing.

Known limit: a single word too long for a puck breaks across the two lines, and
gets a hyphen only where the browser has hyphenation dictionaries. Real phones
do; headless Chromium does not, so audit screenshots show "Christo / pher". The
whole name is visible either way, which it was not before.

599 tests, 0 failures. 52 layout audits across 13 viewports x 4 table sizes
(2, 6, 9, 12 seats) and 20 across the five overlays: 0 failures, and the action
bar still does not change height mid-hand at any of them. The back link was
caught by the audit at 56x13 when it stopped being a button; its hit area is
44px now, paid for with negative margins so the header keeps the 73px.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-03 10:17:08 -06:00
jheapsandClaude Opus 5 8b43614b1c Give the stylesheet a vocabulary, and stop the bar moving
The tool read as crowded on screens where nothing overlapped, and the reason
turned out to be arithmetic rather than taste: holdem.css used 42 different
spacing values, 31 font sizes, 14 border-radii and 139 colours, and defined
three custom properties. Every number had been picked by hand at the moment it
was needed. A 0.42rem gap beside a 0.45rem gap beside a 0.5rem gap gives the
eye no rhythm to lock onto, so it reads the whole surface as noise.

So: constrained scales, and everything snapped to them. Seven spacing steps on
an 8px rhythm, eight type sizes, four corners, and a four-step surface ramp
that stays off pure black — shadows are invisible on #000 and white-on-black
smears on the OLED phone this is used on. 661 values rewritten; colour mentions
halved, 381 to 174. Nothing here changes what the tool does.

Two things were measurably moving under the dealer's thumb, and both are fixed
by reserving space rather than by animating anything:

  * The undo pill named the last action, so it resized on every single tap.
    Measured across one hand: 148, 110, 109, 108, 109, 110, 120px. It is now a
    fixed 10rem, with the label in its own element so it can ellipsize without
    truncating through the keycap beside it.

  * The action bar is fixed to the bottom, so anything that changes its height
    moves its top edge. The status row wraps, and it wrapped differently as the
    street and pot changed. It now holds two lines' worth of room whenever a
    hand is running. Across 13 viewports x 3 table sizes, the bar no longer
    changes height mid-hand at all.

Numbers that change while the dealer watches — pot, stacks, bets, standings —
are now set in tabular figures, so a pot ticking $18 to $21 stops shuffling its
digits sideways.

Two regressions the sweeps caught on the way, both from the snapping:
  * The Add Chips field cleared 44px by way of its font size plus its padding,
    so moving either dropped it to 42. It states its own min-height now; a
    touch target shouldn't be an accident of two other numbers.
  * The bar came out 2px shorter in landscape, which grew the felt, which
    lifted the top seat's dealer button 2px into the header. That clearance was
    structurally 1-7px, so the top seat inset became a floor rather than a
    ceiling instead of chasing the 2px.

tests/holdem/designTokens.test.js keeps the scales honest — a new value has to
be a step or an exception with a reason. Fault-injected four ways.

599 tests, 0 failures. 39 layout audits across 13 viewports and 3 table sizes,
plus 35 across the five overlays: 0 failures.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-03 03:11:13 -06:00
jheapsandClaude Opus 5 42b9e83e8f Don't deal the hand when the dealer names a blind
The seat menu's "Make small blind" / "Make big blind" / "Blinds follow the
button again" all re-posted the blinds whenever `Betting.onlyBlindsIn(state)`
was true. That condition means "nothing has happened in this hand except the
blinds" — which is true of a hand one second old and equally true of a table
sitting in setup with no cards out and nothing committed.

So naming a blind before the deal ran repostBlinds -> beginHand: betting
opened, two stacks docked, the action bar up and waiting on the seat after the
big blind. The dealer had said where the blinds go and the tool heard "deal".

Betting.blindsArePosted() is the question these three actually wanted — the
blinds are down only once a hand is open — and it's the guard makeDealer was
already using by hand. Before the deal, naming a blind now moves a badge and
nothing else; the toast says "Dee has the small blind next hand." rather than
claiming she posted it. Mid-hand behaviour is unchanged: chips come back and
go in again from the new positions, and the chip count stays straight.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 11:11:34 -06:00
jheaps 419c1de2a0 Merge pull request 'Hold'em dealer: 55 polish rounds, one merge' (#101) from release/casino-holdem-polish into master
Build and Deploy / build-deploy (push) Successful in 1m32s
Reviewed-on: #101
2026-09-02 10:00:14 -06:00
jheaps 470fbc0d26 Add the seat-name round to the release 2026-09-02 09:52:35 -06:00
jheapsandClaude Opus 5 c4e842f3e3 Stop the button's chip sitting on top of the name underneath it
A phone screenshot, mid-hand, eight-handed: the seat with the button reads
"Christop" and then a white D. The name is centred across the whole puck and the
chip sits in its top-right corner on a layer above, so a long name runs
underneath and stops — measured, "Christopher" lost 20px of its 64px box.

The bad part is the silence. The text believed it had the room it was being
painted out of, so no ellipsis appeared: nothing on screen said the name went on.
On the one seat at the table a dealer looks at most.

The name now keeps out of the chip's corner on the seat that has the button, so a
long one ends in an ellipsis before it gets there. Only that seat — every other
puck has its full width, because the chip on those is invisible.

And the audit has a check for it now. Nothing it had would have caught this: the
occlusion check is about controls a thumb has to reach, and this is a label a
dealer has to read. The new one measures every seat's name against its own chip
and badges, and the fix was undone by hand to confirm it fires — "20px under
button.dealerChip.active".

182 audits across 13 viewports, both input kinds, plain and straddled tables,
every overlay: clean.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 09:52:00 -06:00
jheaps 1d9353c94e Add the hidden-means-hidden round to the release 2026-09-02 09:37:29 -06:00
jheapsandClaude Opus 5 8616636212 Make hidden mean hidden, and check that it does
Three rounds inside the money, so this one was a look at the thing. On a desktop
screenshot of a table mid-session there is a small empty box under the bank
check: 21 pixels wide, 44 tall, no text, no purpose. It is the "Take $600 from 3
players" button from three rounds ago, which sets `hidden` when there is nothing
to record — and `hidden` was losing.

The attribute carries its `display: none` from the browser's own stylesheet,
which is the weakest rule in the cascade, so any class that sets a display beats
it. Every button class here sets `inline-flex`. This is not a new discovery in
this file either: seven overlays already carry their own `[hidden] { display:
none }`, each one presumably found the same way. One global rule now covers all
of them, so there is no ninth.

The audit had been telling me. Its touch check reported the box as "could not be
probed (drawn 21x44)" — in the warnings, which my sweeps printed only sometimes
and never failed on. So the check now says the plainer thing: an element that
claims to be hidden and is drawn anyway is a fault, not a note. It is in runAll
with the rest, and the bug was put back by hand to confirm it fires.

The same warning stream had a second thing in it: the waiting list's Add button
was 43px wide. Three letters, one pixel under the rule, and a thumb doesn't know
the word is short.

182 audits across 13 viewports, both input kinds, every overlay and a table with
a rake, a cash-out, a waiting list and six logged hands on it: clean, and the
only note left is the one that says the 44px rule stood itself down on a mouse.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 09:36:51 -06:00
jheaps 6174981cdc Add the assumed-contributions round to the release 2026-09-02 09:21:57 -06:00
jheapsandClaude Opus 5 4db6f6e4d3 Take the chips the pot was priced with, not just pay them out
Two rounds of asking where the tool disagrees with itself, and here is the last
of it — the one that was actually creating money.

There are two ways a contribution gets in. Tapping the action moves chips: the
bet leaves the stack, sits in front of the player, and is swept into their hand
total. The other is the "without live betting" panel — a base pot amount, or
chips counted out on a seat — for a dealer recording a hand they are watching
rather than driving. Nothing leaves anybody's stack there.

The pot wizard prices both the same way, and awarding it credits the winner. So
in the second mode the table simply grew. Measured at a three-handed table with a
$50 base pot: stacks 200, 200, 200 before, pot priced at $150, and afterwards
350, 200, 200 — six hundred dollars of chips became seven hundred and fifty, and
the bank check, newly able to see it, blamed a rebuy nobody had made.

So before the pot is pushed, whatever was assumed rather than taken comes off the
stacks that assumed it, and is recorded where a swept bet lives. Chips already
committed or swept are left alone — they have been paid once, and taking them
twice is the same bug the other way round. A base pot on top of a live bet
collects only the difference. Nobody is charged more than they are holding, and
an empty chair or a seat sitting out is charged nothing at all.

The same hand now ends 300, 150, 150: the table has the six hundred it started
with, and the bank check is balanced before, during and after.

13 new tests, with the already-paid test disabled on purpose to confirm five of
them catch the double charge. Walked through the UI in base-pot mode: pot badge
$150, wizard pricing three seats at $50 each, and afterwards the felt holding
exactly what it held before.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 09:21:19 -06:00
jheaps 0ad5592687 Add the one-stack-rule round to the release 2026-09-02 09:06:07 -06:00
jheapsandClaude Opus 5 1c2e716508 Ask the same two questions the same way everywhere
The round before this found the bank check and the standings reading a seat's own
stack where the felt reads the table's starting stack — two parts of the tool
disagreeing about how much money was on the table. That was worth a sweep, and
the sweep found more.

The colour-up panel had the same fault. It is the panel that says "count out
2×$100 for this player", and on a table opened the ordinary way — a starting
stack and some names — it showed nothing at all. The one table where every stack
is a round number made of the largest chips there are was the table it had
nothing to say about.

The other question, "is anybody in this chair", existed in four spellings: in the
seat count, in the seat menu twice, in the waiting list, and twice more in the
state module. Three of them looked at name, chips and cash; one also looked at a
hand being dealt. A chair that counts as occupied for one and empty for another
is how somebody's chips get given away — measured, a seat marked in hand with no
name and no stack yet was on offer to the next person in the waiting queue, on
top of whoever was already playing it.

Both questions now have one implementation and one name:

    "What is this seat holding?"   HoldemState.chipsHeldBy
    "Is anybody in this chair?"    HoldemState.seatInPlay

10 new tests, including one that pins the bank check, the standings and the
settle-up plan to the same total, and one that pins the seat count and the open
seats to the same set of empty chairs. The occupancy test was cut back to its old
three-part form on purpose to confirm the waiting-list case fails.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 09:05:32 -06:00
jheaps 236c52567e Add the starting-stack accounting round to the release 2026-09-02 08:53:35 -06:00
jheapsandClaude Opus 5 1689ecb4f0 Count the chips the table is actually playing with
"Starting stack" is how a night opens. The setup panel offers it and says what it
means — "seats without their own stack start here" — and everything a dealer
looks at reads it: the puck, the action bar, what a player is allowed to bet.

The money side didn't. The bank check and the standings read `seat.stack`
directly, which is null for exactly those seats. Measured on a three-handed table
with a $200 starting stack and nobody's own stack typed in: the felt played for
$600, the bank check reported no chips in play and pronounced itself balanced,
and the standings — the list a dealer settles the night from — listed nobody at
all. Three players, six hundred dollars, and the tool's own accounting said the
table was empty.

Both now ask the same question the felt asks. The check reports $600 in play
against nothing taken, which is the truth: those chips have not been paid for.
Empty chairs are excluded, or the starting stack would make every one of them
look like somebody holding two hundred dollars — a ten-seat table would have
opened with $2,000 of imaginary chips.

Being told is only half of it. The verdict names the seats rather than saying
"somebody's rebuy probably wasn't recorded", because the dealer's next move is to
go to a particular chair and the tool knows which. And the seats holding the
table's starting stack — the dealer's own instruction, said once in the setup
panel — can be written down in one tap instead of six trips through Add chips.
Only those: what somebody's forgotten rebuy was is a question only the dealer can
answer, and guessing it would be the tool inventing money, which is the fault
this round is about.

14 new tests, with the stack source and the empty-chair test broken on purpose to
confirm they fail. Walked through in the browser from a cleared table: set the
starting stack, name three seats, and the panel goes from "balanced, no chips" to
"$600 more in chips than cash taken. Ann, Ben and Cal are holding chips with no
buy-in written down" — then to balanced, with the buy-ins recorded and undoable.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 08:52:56 -06:00
jheaps b8655be258 Add the waiting-list round to the release 2026-09-02 08:38:21 -06:00
jheapsandClaude Opus 5 55eb569d3b Keep the list of who's next, instead of leaving it on a napkin
A full home game always has two or three people standing behind the chairs, and
the list of who's next lives on a napkin or in the dealer's head. That is where
the argument an hour later comes from. The tool had just learned to open a chair
— somebody cashes out and the seat is free — and had nothing to say about who
should sit in it.

The Session panel keeps the list in order of arrival, which is the only ordering
anybody has ever agreed to. Whoever is at the front is offered the first open
chair by number, and everybody else waits their turn: a list that isn't kept in
order is a pile of names, and jumping the queue is the thing a dealer gets
shouted at for. With the table full it says so rather than offering a seat that
doesn't exist. The same offer appears on the empty chair's own menu — "Seat
Priya" — because tapping the chair somebody is about to sit in is what a dealer's
hand does anyway.

Sitting somebody down puts their name on the chair and nothing else. No stack, no
buy-in, not dealt in: they haven't paid yet, and inventing chips for them would
put money on the table nobody has handed over, which is the one thing the bank
check exists to catch. Add chips is the next thing the dealer does, and it is one
tap away in the same menu.

Two people called Mike are two people — the list is keyed by id, not by name.
Names are trimmed, blanks are refused, and a saved list from a table that never
had one comes back empty rather than undefined.

15 new tests, with the occupied-chair guard removed and a stack handed to the new
player on purpose to confirm they fail. Walked through the browser: two names
added to a full table, a player cashed out to open seat 2, the front of the queue
seated there with nothing in front of them, the bank still balanced, and the
second name taken off the list. 156 audits with the list populated, including a
name long enough to test the row.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 08:37:44 -06:00
jheaps 7e420ce747 Add the misdeal round to the release 2026-09-02 08:24:05 -06:00
jheapsandClaude Opus 5 86886ac126 Take a hand back, which the rulings sheet has been asking for all along
This tool has told dealers to redeal on a misdeal since the rulings sheet was
written — first card to the wrong seat, a seat entitled to a hand dealt out, one
of the first two cards exposed — and it had no way to do it. The only control
that ended a live hand was Next Hand, which says out loud that it takes the money
off the table without paying anybody. That is the right answer for an abandoned
pot and the wrong one for a misdeal, where the blinds and the calls belong to the
people who put them in.

Undo covers the first second of it: "↶ dealing the hand" is one tap. But the
action history lives in memory, so a dealer who is three calls in, or who has
refreshed the page mid-hand, has nothing — and a refresh mid-hand is exactly the
situation this tool has spent rounds making survivable everywhere else.

Misdeal appears in the header while a hand is out and goes away when it isn't:
before the deal there is nothing to take back, and afterwards it would be
offering to unwind a hand that has already been paid. It says what it will do to
the money — "$25 goes back to the players who put it in, cards are cleared, and
the same button deals again" — and adds a note when two or more players have
already acted, because most rooms let a deal stand at that point. It doesn't
refuse: which conditions make a misdeal is the dealer's call and the sheet is
right there.

What comes back is everything, including chips already swept into hand totals on
an earlier street — the first version returned only the current street's and
would have quietly kept a flop's betting. What stays is the button, the blinds,
the straddle and anyone posting in: a misdeal is the same hand dealt again, not
the next one, so the hand number doesn't move and nothing is logged.

13 new tests, with the sweep and the straddle broken on purpose to confirm they
catch it. Measured through the UI: pot $25 with three players in, take it back,
every stack is exactly $200 again, the bank still balances, and dealing again
posts the same blinds on the same players from the same button. 156 audits with
the button live, including a landscape header that stays one row at 46px.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 08:23:27 -06:00
jheaps c36d7f60bd Add the cash-out round to the release 2026-09-02 08:09:26 -06:00
jheapsandClaude Opus 5 f966d8c340 Pay somebody out and keep the chair, the cash and the record straight
The most ordinary thing that happens at a home game after midnight — somebody
counts up and goes home — and the tool had nothing for it. Freeing the chair
meant wiping the seat by hand, and the bank check then declared their whole stack
missing: "someone has paid for chips they haven't been given", for the rest of
the night. Measured on a balanced table, cashing a player out with $350 in front
of them left the check $350 short. Wiping their buy-in as well silenced it, at
the price of losing their entire night from the standings and from the file the
dealer hands over at the end.

Cashing out is two facts, and both have to survive the empty chair: the box took
their cash, and the box handed their chips back. Both are kept now, so the chair
opens and the money still adds up.

Cash out… is in the seat menu. It says what to count — "$350 — 3×$100, 2×$25" —
what they bought in for, and whether they leave up or down, because that is the
sentence the dealer says while their hands are moving. The bank check gains a
Paid out line and reads "balanced ... once the $350 paid out to players who have
left is counted", alongside the discards and the house's cut. The standings keep
them with a stripe and the words "· paid out", so nobody counts money out to them
twice at 2am, and the export marks them the same way.

It refuses to pay anybody with money still in the middle: taking chips out of a
pot other people can win, or handing the same chips over twice, are both worse
than waiting for the hand to finish. The chair gets a fresh id, because the
person who had it has gone and the next player to sit down is not them.

Two things this turned up. The first draft worked out what a seat was holding by
itself, read `Number(null)` as a perfectly good zero, and offered to pay a player
with no stack set nothing at all — it asks Betting now, which owns that rule.
The second was mine and the audit caught it: marking the departed row with
opacity took the In and Won cells to 3.83:1, under AA, on the very list a dealer
settles from. It is a stripe instead.

19 new tests, with the departed buy-in dropped from the check and the pot guard
disabled on purpose to confirm they fail. Walked through in the browser: menu,
confirm, payout, bank, standings, undo, and the refusal.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 08:08:46 -06:00
jheaps 15cec18256 Add the clock round to the release 2026-09-02 05:40:45 -06:00
jheapsandClaude Opus 5 0e2821257f Run the clock on a player, instead of counting in your head
The bar has had a stopwatch on the acting seat for a while: how long this player
has been thinking, so the dealer knows when it's worth a nudge. What it never had
was the thing a dealer actually does about it. Calling the clock is a procedure —
a player asks, the dealer grants it, the player gets a set time and then a
countdown said out loud, and if they still haven't acted the hand is decided for
them. Running that from this tool meant counting in your head while the table
argued about whether it had been thirty seconds yet.

Thirty and then ten, which is the common form and what the TDA writes down. The
countdown is the part the table hears, so it is marked apart rather than being
ten more seconds of the same: the readout switches to a bare number and turns
red. At zero the bar says the ruling in the dealer's own words and offers it as
one button.

The ruling depends on what they were facing, and getting that backwards is the
part worth being careful about. Facing a bet, the hand is dead. Facing nothing,
it is checked — nobody gets folded for being slow when checking was free.

Three things about where it sits. The button appears only once somebody has been
thinking long enough for the table to start asking, which is the same threshold
the stopwatch already marks, so an ordinary hand costs no room at all: measured
at 390x844, the bar is 152px with or without it. It is 44px like everything else
a thumb has to find — it was drawn at 36 and the audit called it at every touch
viewport the moment the check ran, which is the rule doing its job on a control
that kills a hand. And once the count is over the Stop button goes, because there
is nothing left to stop: at 640x360 its 94px pushed the undo control onto a
second line and the taller bar covered the two bottom seats.

The ordinary Fold/Check/Raise stay underneath the ruling. A player who speaks up
as the count ends is still acting, and whether it was in time is the dealer's
call, not the tool's.

11 new tests, and both halves of the ruling were inverted on purpose to check
they catch it. Watched end to end in the browser at shortened intervals: the
button appears, the count runs down, the ruling lands, and the hand is killed —
or checked — with the undo control naming what happened.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 05:40:06 -06:00
jheaps 9c8d981e2d Add the house-take round to the release 2026-09-02 05:13:11 -06:00
jheapsandClaude Opus 5 c19575ab10 Count the house's cut instead of calling it missing chips
A game that takes a rake has chips leaving the table every hand, and the bank
check had no idea. It added up the buy-ins, added up the chips on the felt, and
told the dealer somebody had been paid for chips they were never given — a
shortfall that grows all night and points at a miscount that never happened.
Every home game that takes a drop for the beer fund hits this on hand one.

So the tool takes it, rather than watching it go. Under Table Setup: a
percentage, an optional cap, and "no flop, no drop" — the rule almost everyone
plays, on by default, where a hand that ends before the flop pays nothing. Zero
percent is a game that doesn't rake, which is most of them and the default, and
nothing about that game changes.

Where it shows up is the point. The pot wizard says "House takes $2 of $40 — 5%,
capped at $5" above the payouts, before a chip moves, because the summary is the
dealer's last chance to disagree with the arithmetic and money taken quietly is
the one thing a tool like this must never do. The bank check gets a House take
line and says "balanced ... once the $2 in the house's cut is counted". The hand
log keeps the pot as the table saw it with the cut recorded beside it, and the
export has a column for it, so the night's total is one sum in a spreadsheet.

Two decisions worth stating. The rake rounds *down* to a chip the table actually
has: a house that can't make 40c takes nothing and the players keep it, which is
the only way to be wrong about this that nobody argues with. And on a split pot
it comes off the top, then what is left is shared in proportion — with the
rounding leftovers going back to the winners rather than to the house, which
asked for a number and gets that number, not that number plus dust.

Measured end to end through the UI: 5% capped at $5 on a $40 pot pays $38 and
banks $2; four stacks plus the cut come to exactly the $800 bought in; the bank
check reads balanced. With no-flop-no-drop on, a hand folded round pre-flop pays
the full $15 and takes nothing; with it off the same hand pays $14 and takes $1.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 05:12:33 -06:00
jheaps 907e0165db Add the stadium ring round to the release 2026-09-02 04:59:37 -06:00
jheapsandClaude Opus 5 8aa90e90a4 Give a phone on its side the table shape it needs
The last two rounds left one thing failing and said so: a landscape phone with
six or twelve seats stacked two of them 25px apart at each end of the felt, with
pucks 64px tall. It has been there since seats were first spaced by distance
rather than by angle. Three things were wrong at once, and it needed all three.

The rim is the wrong shape when the table is very flat. An ellipse 616px wide and
96px tall has nowhere to put the seats near its ends: the curve doubles back on
itself, so two seats a long walk apart come out one above the other. Past two and
a half times wider than tall the rim is now a stadium — two straight rails with a
half-round cap at each end, which is how a real poker table is built and exactly
why it is built that way. A cap is a half-circle of the felt's own height, so an
end takes one seat and the rest is rail. Only past that ratio: measured, the
cut-off lands between a landscape phone at 4.4 and every other layout the tool
has, 1.45 at 1280x900 and 1.0 to 1.4 upright, so no working table changes shape.

The ring had less height than the felt did. The seat layer is inset by half a
puck to keep the outermost seats on screen, and 26px off the top and bottom of a
96px felt left 44px to work with — less than half the table, which is why no rim
shape could have fixed it alone. The inset is a percentage where the felt is
short. The landscape branch never had that rule at all, because it is matched on
height while the inset lives in a width query, so an 844px-wide phone on its side
drew its ring against the felt's whole box; with a flat-topped stadium rail that
put a dealer button over Resolve Pot in the header.

And the puck was a line too tall. In the tight state the hole cards give up their
row: of the four things on a puck, the cards are the one the dealer is holding in
their other hand, and the seat editor still shows them. That took the puck from
64px to 55px, which is what finally cleared the ends.

Measured across 36 combinations of nine viewports and 2, 6, 9 and 12 seats: the
closest two seats at 640x360 go from 25px apart to 55px, and every combination is
clean. Then 216 audits across thirteen viewports, three seat counts and both a
mouse and a thumb: no failures, no console errors.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 04:58:59 -06:00
jheaps 86e1570618 Add the phone felt round to the release 2026-09-02 04:34:05 -06:00
jheapsandClaude Opus 5 dc5db16ffd Let the phone table use the width it has
Last round capped the felt so the ring would clear the action bar, and capped the
wrong dimension. The wide layout sizes the felt from its width, so capping the
width is how you shorten it there — on a phone the felt is already the full width
of the column, and capping that threw away 96px of a 360px screen: a 240x240
table inside a 336px space, with nine pucks crowding it.

A max-height instead leaves the width alone and lets the aspect ratio give way,
which turns a short screen into a wide oval — the shape a poker table is. At
360x640: 336x240 rather than 240x240, same clearance over the bar, and the
twelve-seat ring that was crowded at 240 comes out clean, which closes the one
combination left failing last round. Where the room isn't the binding constraint,
390x844 and up, nothing changes and the table stays round. The landscape branch
now says max-height: none, because it already spends the same measured room on
its own height and applying it twice took the felt to the floor value.

The measurement that decides whether pucks shrink was also wrong, in a way that
only showed up once it was asked a hard question. Rim length per seat measures
the walk between two seats, not the gap between them, and on a long oval the rim
doubles back at the ends: twelve seats at 640x360 had 193px of rim each and sat
60px apart. It now measures the closest two neighbours directly, off the ring
itself — and off the seat layer rather than the felt, because the layer is inset
by half a puck on a phone and the felt's box put the answer out by 30px.

That makes the rule geometric rather than about screen size, so it is no longer
scoped to a phone media query: a wide landscape felt crowds at its ends while its
rim claims there is room, and now it is told so.

Pucks still touch at nine and twelve seats on a small screen. Tried 46px against
58px: on a roomy phone 46 cleared every overlap where 58 left two, but in a hand
with a side pot, where the bar has grown and the felt has shrunk to suit, 46
overlapped four times and 58 twice. That is the felt being small, not the puck
being wide, and paying for it with an ellipsis on every long name buys nothing.
What has to hold is that each seat keeps its own centre, and that is measured at
every size.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 04:33:25 -06:00
jheaps 6df400322e Add the audit round to the release 2026-09-02 04:03:25 -06:00
jheapsandClaude Opus 5 b9b2237dbe Run the two checks the audit had and never used
runAll() did not include the contrast check — it simply wasn't in the list — and
touch targets sat behind an opt-in flag nothing passed. So "the audit is clean"
has meant nine checks rather than eleven for a long run of rounds, and the two
left out are the two whose faults a dealer meets in a dim room with their thumb.
Both were written, tested, and then never called; the contrast checker was built
across two rounds and every sweep since has been silent about colour.

The standalone runner had a second version of the same hole: the 44px rule
stands itself down where `hover: hover` says there's a pointer, and a headless
desktop browser is a pointer, so a single pass had never measured a touch target
at any viewport. It now runs every viewport twice, once with a mouse and once
with a thumb.

A check that decides it doesn't apply now says so, rather than reporting an empty
offenders list — which reads exactly like a pass.

Faded text is measured instead of filed as unchecked. `opacity` on a box fades
the box and its text together onto whatever is behind it, so a dimmed seat is not
grey text on a dark puck: it is a faded puck and faded text both landing on the
page. Both halves are composited that way now. Two exemptions remain and both say
so out loud: a disabled control, which WCAG itself excuses, and a link inside a
sentence, whose size is set by the line it sits in.

What running them found, and this round fixes:

  - the chair number on every seat: #8a8a8a at 9px, 3.39:1 once the empty seat's
    fade is composited, on the label that answers "which seat is that?";
  - Quick Split's amount field at 37px tall and its delete button at 30px across,
    on a page whose targets had never been measured;
  - and on a 360x640 phone with the bar grown by a side pot, the bottom seat
    sitting 38px inside it.

That last one brings back a cap this project measured and rejected once: capping
the felt to the room left fixed the six-seat ring and broke the nine-seat one.
That trade was real then and isn't now — seats are spaced by distance around the
rim rather than by angle, so a shorter felt no longer piles them up. Re-measured
across 30 combinations of five phone sizes and 2 to 12 seats: every one clean
except twelve seats at 360x640, where a 240px felt and a 64px puck cannot both be
true. Where the rim can't give each seat a puck's width, the pucks come down a
size, measured from the rim itself rather than from a media query.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-02 04:02:43 -06:00
jheaps ca9ac7b6af Add the straddle round to the release 2026-09-02 03:32:58 -06:00
jheaps 80dae56f0d Add the landscape round to the release 2026-09-02 03:13:05 -06:00
jheaps 6ca99fde6b Bring master's already-merged rounds into the release branch
Master merged #58-#61 (manual deal, less guessing, seat editor, landscape
table) while the stack kept going. Those commits are already in this branch's
history; this merge just reconciles the two shapes so the release can go in as
one.
2026-09-02 01:19:56 -06:00
jheaps b2262f8604 Merge pull request 'Wait to be told to deal, instead of guessing' (#58) from fix/casino-holdem-manual-deal into master
Build and Deploy / build-deploy (push) Successful in 1m10s
Reviewed-on: #58
2026-09-01 10:57:23 -06:00
jheaps 6ad9923aae Merge pull request 'Stop the last two things the table did behind the dealer's back' (#59) from fix/casino-holdem-less-guessing into fix/casino-holdem-manual-deal
Reviewed-on: #59
2026-09-01 10:57:17 -06:00
jheaps 168e8a380c Merge pull request 'Tapping a seat gives you that seat' (#60) from feature/casino-holdem-seat-editor into fix/casino-holdem-less-guessing
Reviewed-on: #60
2026-09-01 10:57:10 -06:00
jheaps edc08d7213 Merge pull request 'Let the landscape table use the width it has' (#61) from fix/casino-holdem-landscape-table into feature/casino-holdem-seat-editor
Reviewed-on: #61
2026-09-01 10:57:01 -06:00
46 changed files with 9101 additions and 820 deletions
+135 -9
View File
@@ -7,27 +7,37 @@
<div id="holdemApp">
<header id="holdemHeader">
@* Six equally-weighted buttons used to sit here in two rows, and on a 390px
phone the felt did not start until 225px down — a quarter of the screen spent
before the dealer saw the table. Only two of the six are per-hand controls.
The rest have gone where they belong rather than into a "more" menu, which
would have relocated the crowding rather than removed it: Reset Table to the
Session panel beside Clear history and the save/load pair, Quick Split down
with Common rulings where the other "open something else" link already lives,
and the way back to the site up top where a back link goes. *@
<div id="holdemHeaderLeft">
<a href="/casino" class="holdemBackLink">← Casino</a>
<h1>Texas Hold'em Dealer</h1>
<p class="holdemSubtitle">Seat your players, track the action, split the pot.</p>
<span id="handCounterBadge" class="handCounterBadge">Hand #1</span>
</div>
<div id="holdemHeaderActions">
<a href="/casino/texasholdem/quicksplit" class="holdemBtn" title="Chop a pot without setting up a table">Quick Split</a>
<button id="misdealBtn" class="holdemBtn" title="Take this hand back — every chip returns to the player who put it in, and the same button deals again" hidden>Misdeal</button>
<button id="nextHandBtn" class="holdemBtn" title="Move the button, small blind and big blind to the next occupied seat">Next Hand ⟳</button>
<button id="resolvePotBtn" class="holdemBtn holdemBtnAccent">Resolve Pot</button>
<button id="resetTableBtn" class="holdemBtn holdemBtnDanger">Reset Table</button>
<a href="/casino" class="holdemBtn holdemBtnGhost">← Casino</a>
</div>
</header>
<div id="holdemLayout">
<section id="tableSection">
<div id="boardStrip" hidden></div>
<div id="pokerTableWrap">
<div id="pokerTable">
<div id="potBadge">
<span id="potBadgeLabel">Pot</span>
<span id="potBadgeAmount">$0</span>
<div id="tableCentre">
<div id="boardRow" hidden aria-label="Community cards"></div>
<div id="potBadge">
<span id="potBadgeLabel">Pot</span>
<span id="potBadgeAmount">$0</span>
</div>
</div>
</div>
<div id="betsLayer" aria-hidden="true"></div>
@@ -36,6 +46,7 @@
<p id="tableHint" class="tableHint"></p>
<p class="tableHintActions">
<button type="button" id="openRulingsBtn" class="linkBtn">Common rulings</button>
<a href="/casino/texasholdem/quicksplit" class="linkBtn" title="Chop a pot without setting up a table">Quick Split</a>
</p>
</section>
@@ -51,7 +62,11 @@
</div>
</section>
<details class="sidebarPanel" open>
@* Not `open` in the markup any more. Whether this panel starts open is a
question about the table, so main.js answers it after the state has
loaded: open on a table nobody has set up yet, shut on one already
half-way through a night. *@
<details class="sidebarPanel" id="tableSetupPanel">
<summary>Table Setup</summary>
<div class="panelBody">
<label class="fieldRow">
@@ -70,6 +85,11 @@
<input type="checkbox" id="dedicatedDealerToggle" />
</label>
<p class="fieldHint">Turn this on if a person outside the game deals — no seat shows the dealer button, but blinds still rotate automatically each hand.</p>
<label class="fieldRow">
<span>Track the board and read the showdown</span>
<input type="checkbox" id="trackBoardToggle" />
</label>
<p class="fieldHint">Puts the community cards on the felt and asks for them as each street is dealt. Turn the players&rsquo; cards over at showdown and Resolve Pot works out who won and how much, instead of asking you.</p>
<div class="blindsRow">
<label class="fieldRow">
<span>Small blind</span>
@@ -86,6 +106,32 @@
</label>
<p class="fieldHint">Blinds post themselves each hand. Seats without their own stack start here.</p>
<details class="subPanel">
<summary>House take</summary>
<div class="subPanelBody">
<div class="blindsRow">
<label class="fieldRow">
<span>Rake (%)</span>
<input type="number" id="rakePercentInput" min="0" max="100" step="0.5" placeholder="0" />
</label>
<label class="fieldRow">
<span>Cap ($)</span>
<input type="number" id="rakeCapInput" min="0" step="1" placeholder="none" />
</label>
</div>
<label class="fieldRow">
<span>No flop, no drop</span>
<input type="checkbox" id="rakeNoFlopInput" />
</label>
<p class="fieldHint">
Taken from the pot when it's awarded, and shown before anything is pushed.
Rounded down to a chip the table has, so the players keep what the house
can't make. Leave the percentage at zero for a game that doesn't rake.
</p>
<p class="fieldHint" id="rakeTakenHint" hidden></p>
</div>
</details>
<details class="subPanel">
<summary>Without live betting</summary>
<div class="subPanelBody">
@@ -119,6 +165,14 @@
</div>
<p id="standingsEmptyHint" class="fieldHint">Everyone who has bought in shows up here, with what they'd be owed if the night ended now.</p>
<h3 class="panelSubhead">Waiting list</h3>
<form id="waitingListForm" class="waitingAdd">
<input type="text" id="waitingNameInput" maxlength="24" placeholder="Who's waiting?" autocomplete="off" />
<button type="submit" id="waitingAddBtn" class="holdemBtn holdemBtnSmall">Add</button>
</form>
<ol id="waitingList" class="waitingList"></ol>
<p id="waitingEmptyHint" class="fieldHint">Nobody waiting. Add the people standing behind the chairs, and the tool will offer them the next seat that opens.</p>
<div id="bankReconcile" class="bankReconcile" hidden>
<div class="bankReconcileRow">
<span>Cash taken</span>
@@ -132,7 +186,16 @@
<span>Taken off the table</span>
<span id="bankDiscarded"></span>
</div>
<div class="bankReconcileRow" id="bankRakedRow" hidden>
<span>House take</span>
<span id="bankRaked"></span>
</div>
<div class="bankReconcileRow" id="bankPaidOutRow" hidden>
<span>Paid out</span>
<span id="bankPaidOut"></span>
</div>
<p id="bankReconcileVerdict" class="bankReconcileVerdict"></p>
<button type="button" id="bankRecordBuyInsBtn" class="holdemBtn holdemBtnSmall" hidden></button>
</div>
<div id="settleUp" hidden>
@@ -165,6 +228,11 @@
<button id="saveTableBtn" class="holdemBtn holdemBtnSmall">Save table file</button>
<button id="loadTableBtn" class="holdemBtn holdemBtnSmall">Load table file</button>
<input id="loadTableInput" type="file" accept="application/json,.json" hidden />
@* Down from the header, where it sat in the same weight as Resolve Pot
— the most-pressed control in a session next to the one that throws
the night away. Here it is beside Clear history, which is the other
thing that destroys records, and behind a panel you have to open. *@
<button id="resetTableBtn" class="holdemBtn holdemBtnSmall holdemBtnDanger">Reset table</button>
</div>
</div>
</details>
@@ -361,6 +429,23 @@
</p>
</section>
<section class="ruling" data-short="Clock">
<h3>Calling the clock on a player</h3>
<p>
Any player may ask for a clock once a decision is taking unreasonably
long; it is the dealer, not the table, who grants it. The player then
gets a set time and a countdown out loud — thirty seconds and ten is the
usual form.
</p>
<p>
If the count reaches zero with no action, the hand is <em>dead</em> if
they were facing a bet, and <em>checked</em> if they were not: nobody is
folded for slowness when checking was free. The action bar runs the
count once you tap <em>Call the clock</em>, and offers the ruling as one
button when it ends.
</p>
</section>
<section class="ruling" data-short="Straddle">
<h3>A straddle is a blind raise</h3>
<p>
@@ -504,7 +589,17 @@
</div>
</div>
<div id="actionBar" aria-live="polite" hidden></div>
@* No aria-live here any more. This element's entire contents are rebuilt on every
action, so a live region on it announced the whole bar every time — measured, after
one tap: "PRE-FLOP Pot $15 9 players Bob · $250 behind 0:00 ↶ dealing the hand U
Fold Call $10 Raise". That is what a screen reader read out after every single fold.
A live region has to be a stable element whose *text* changes; the one below is. *@
<div id="actionBar" hidden></div>
@* Whose turn it is, in a sentence. Empty in the markup and only ever written to, so
assistive tech is already watching it when the first update lands — a live region
created at the moment it has something to say is one the screen reader misses. *@
<div id="actionAnnouncer" role="status" aria-live="polite" class="visuallyHidden"></div>
<div id="toastHost" aria-live="polite"></div>
@@ -526,13 +621,43 @@
<button id="closePotWizardBtn" data-modal-close class="holdemBtn holdemBtnGhost">✕</button>
</div>
<div id="potWizardBody"></div>
@* The buttons live outside the scrolling body on purpose. This is the one
dialog that divides money, and its Confirm sat below a scroll at every screen
size — 244px off the bottom on an iPhone, 583 on a phone held sideways. A
sticky footer cannot fix that from inside: the actions were the last child of
the scrolling content, so their containing block ended exactly where they did
and `bottom` had no room to lift them. Out here they simply don't scroll. *@
<div id="potWizardFooter"></div>
</div>
</div>
@section Styles {
<link href="/css/casino/holdem.css?v=@ViewData["cssVersion"]" rel="stylesheet" type="text/css" />
@* Installable, and works with no signal — see the service worker registration at the
foot of main.js. A dealer running a night in somebody's back room is on the worst
network there is, and the tool being a *website* was the last thing that could
take it away from them mid-game. *@
<link rel="manifest" href="/casino/holdem.webmanifest" />
@* iOS reads none of the manifest's icons and only this. *@
<link rel="apple-touch-icon" href="/images/casino/holdem-apple-touch.png" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="Hold'em" />
@* Paints the phone's chrome the same near-black as the felt's ground, so an
installed copy doesn't sit under a white status bar. *@
<meta name="theme-color" content="#141414" />
}
@* A note for whoever reads the ?v= below and assumes it works: it doesn't. ViewData
["cssVersion"] is assigned in _Layout's own code block, which runs after these
sections are handed their values, so every one of these renders as a bare "?v=" —
on this page and on Chess, Particles and Memory Lane too. It is inert rather than
broken: Program.cs sends `Cache-Control: no-store` on every static file, so nothing
is being browser-cached for a version string to bust in the first place.
Left alone deliberately. Fixing it is a one-line change to a file every page on the
site shares, and the service worker was the reason to care — that now uses stale-
while-revalidate, which needs no version to stay current. *@
@section Scripts {
<script src="~/js/casino/holdem/money.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/feedback.js?v=@ViewData["cssVersion"]"></script>
@@ -540,6 +665,7 @@
<script src="~/js/casino/holdem/state.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/settleUp.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/render.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/handRank.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/cardPicker.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/seatMenu.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/addChips.js?v=@ViewData["cssVersion"]"></script>
+9
View File
@@ -1,6 +1,7 @@
using JoshHeaps.Net.Hubs;
using JoshHeaps.Net.Services.Implementations;
using JoshHeaps.Net.Services.Interfaces;
using Microsoft.AspNetCore.StaticFiles;
var builder = WebApplication.CreateBuilder(args);
@@ -52,8 +53,16 @@ if (!app.Environment.IsDevelopment())
app.UseHttpsRedirection();
// .webmanifest isn't in the default MIME map, and an unknown extension isn't served
// with the wrong type — it isn't served at all. Without this the Hold'em tool's
// manifest 404s, and a 404 manifest is exactly the silent failure that stops a browser
// ever offering "Add to Home Screen": nothing is logged and no prompt appears.
var contentTypes = new FileExtensionContentTypeProvider();
contentTypes.Mappings[".webmanifest"] = "application/manifest+json";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = contentTypes,
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
@@ -0,0 +1,32 @@
{
"name": "Texas Hold'em Dealer",
"short_name": "Hold'em",
"description": "Seat your players, track the action, split the pot. Works with no signal.",
"start_url": "/casino/texasholdem",
"scope": "/casino/",
"display": "standalone",
"orientation": "any",
"background_color": "#141414",
"theme_color": "#141414",
"categories": ["utilities"],
"icons": [
{
"src": "/images/casino/holdem-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/images/casino/holdem-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/images/casino/holdem-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
+125
View File
@@ -0,0 +1,125 @@
// Keeps the dealer tool working when the network doesn't.
//
// A home game is the worst network in the world: somebody's back room, one bar of
// signal, a router two floors away. The tool already keeps the whole night in
// localStorage, so the *table* survives anything — but the page didn't. Reload with no
// signal, or open it fresh when the wifi has dropped, and a dealer holding a phone in
// one hand and a deck in the other got a browser error page with nine players waiting.
//
// This is the one thing standing between "a website about poker" and "a tool you can
// rely on at a table", so it is worth the moving part.
//
// Scope is /casino/ rather than /casino/texasholdem/, because a scope has to be a
// prefix of the page it controls and "/casino/texasholdem" does not start with
// "/casino/texasholdem/". Anything in that scope this worker has not been told about
// goes straight to the network, so the other casino pages behave exactly as they did.
// Bumped whenever the shape of what is cached changes. The asset *version* rides in
// the URLs themselves (?v=1.0.8 from _Layout), so a normal release makes new keys
// without touching this.
const CACHE = "holdem-shell-v1";
// What this worker will keep. Anything else in scope — a form post, an API call, a
// page it was never told about — goes straight to the network and behaves exactly as
// it did before the worker existed.
const CACHEABLE = new Set(["script", "style", "image", "font", "manifest"]);
// The page hands over the exact list of URLs it was built from — see registerWorker()
// in main.js. Deriving it from the document instead of keeping a list here is the
// whole trick: a hand-written manifest of files drifts from the markup the first time
// somebody adds a script tag, and the failure mode is a tool that is offline-capable
// right up until the release that quietly broke it.
async function precache(urls) {
const cache = await caches.open(CACHE);
// Individually rather than cache.addAll, which rejects the whole batch if any one
// URL 404s — one stale entry in the list would leave the dealer with nothing.
await Promise.all(urls.map(async url => {
try {
const res = await fetch(url, { cache: "reload" });
if (res.ok) await cache.put(url, res);
} catch {
// Offline while installing. The runtime handler below picks these up on
// the next online visit.
}
}));
}
// No install handler, and deliberately no skipWaiting(). A new worker taking over a
// live page can hand it assets from a different release than the ones it started with,
// and this page loads seventeen separate scripts that expect to agree with each other.
// Waiting costs a dealer nothing — the update lands the next time they open the tool —
// and it cannot leave them with a half-swapped app in the middle of a hand.
self.addEventListener("activate", event => {
event.waitUntil((async () => {
const keys = await caches.keys();
await Promise.all(keys
.filter(key => key.startsWith("holdem-shell-") && key !== CACHE)
.map(key => caches.delete(key)));
await self.clients.claim();
})());
});
self.addEventListener("message", event => {
if (event.data && event.data.type === "precache" && Array.isArray(event.data.urls)) {
event.waitUntil(precache(event.data.urls));
}
});
// Only GETs, and only same-origin. A cross-origin request has opaque responses that
// can't be inspected, and caching one would mean serving a failure forever.
function handles(request) {
if (request.method !== "GET") return false;
const url = new URL(request.url);
return url.origin === self.location.origin;
}
self.addEventListener("fetch", event => {
const { request } = event;
if (!handles(request)) return;
// The page itself: network first, so an online dealer always gets the current
// build, and the cached copy is there the moment they aren't.
if (request.mode === "navigate") {
event.respondWith((async () => {
try {
const fresh = await fetch(request);
if (fresh.ok) (await caches.open(CACHE)).put(request, fresh.clone());
return fresh;
} catch {
const cached = await caches.match(request, { ignoreSearch: true });
if (cached) return cached;
throw new Error("offline and this page was never cached");
}
})());
return;
}
// Assets: stale while revalidate. The cached copy answers immediately — which is
// the whole point, a dealer opening this between hands should not wait for a
// network — and a fresh copy is fetched in the background for next time.
//
// Cache-first would be the obvious choice, on the reasoning that these URLs carry
// ?v= from the layout and so a hit is always the right file. They don't: the
// version renders empty (see the note in TexasHoldem.cshtml), so every release
// reuses the same URLs. Cache-first against unversioned URLs is how a tool gets
// frozen on a build from three months ago with no way for anyone to tell. This
// strategy needs no version to be correct: worst case a dealer is one launch
// behind, which for a tool that runs entirely in the browser is nothing.
if (!CACHEABLE.has(request.destination)) return;
event.respondWith((async () => {
const cache = await caches.open(CACHE);
const cached = await cache.match(request);
const fresh = fetch(request).then(res => {
if (res.ok) cache.put(request, res.clone());
return res;
}).catch(() => null);
if (cached) return cached;
const res = await fresh;
if (res) return res;
throw new Error("offline and not cached: " + request.url);
})());
});
File diff suppressed because it is too large Load Diff
@@ -148,9 +148,13 @@ button,
color: #8f8f8f;
}
/* 37px tall, on the field a dealer types every amount into. The touch rule has been
44px everywhere else since the round that set it; this page never got measured for
it, because the audit only ran the target check when asked and nothing asked. */
.unevenAmount {
flex: 1;
min-width: 0;
min-height: 46px;
background: none;
border: none;
outline: none;
@@ -180,10 +184,12 @@ button,
color: #ffd6d6;
}
/* 30px across, and it deletes a player's entry — the one control on the row where a
near miss costs something. The amount field beside it gives up the 16px. */
.unevenRemoveBtn {
flex: none;
width: 30px;
height: 44px;
width: 46px;
height: 46px;
border: none;
background: none;
/* Was #6a6a6a — 3.66:1, the worst on the page, on a control that deletes a
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@@ -37,6 +37,10 @@ const ActionBar = {
this.publishFeltRoom(height);
};
// Kept so anything that moves the table without touching the bar can ask for
// the felt to be measured again — the board strip appearing above it does
// exactly that, and the felt's height is worked out from where the table starts.
this.publishHeight = publish;
if (typeof ResizeObserver === "function") {
this.heightWatcher = new ResizeObserver(publish);
this.heightWatcher.observe(host);
@@ -86,9 +90,27 @@ const ActionBar = {
// header in normal flow, so its own height never moves its top and this can't
// chase itself around the screen.
const topInDocument = wrap.getBoundingClientRect().top + window.scrollY;
document.documentElement.style.setProperty(
"--feltRoomPx",
`${this.feltRoomFor(window.innerHeight, barHeight, topInDocument)}px`);
const root = document.documentElement;
const was = root.style.getPropertyValue("--feltRoomPx");
const now = `${this.feltRoomFor(window.innerHeight, barHeight, topInDocument)}px`;
root.style.setProperty("--feltRoomPx", now);
// The felt has just changed size, so how much rim each seat gets has changed
// with it. Told rather than left to be noticed on the next render, which on a
// bar that grew mid-hand could be several actions away.
if (typeof Render === "undefined" || !Render.state) return;
if (Render.updateSeatDensity) Render.updateSeatDensity();
// And when it really did change size, the seats are laid out again rather than
// only re-measured.
//
// The seats follow a felt on their own — they are placed in percentages of it —
// but a bet chip anchored inside a seat is placed in pixels off that seat's
// centre, worked out against the felt as it was. Nothing re-ran that. Measured
// at 640x360 with five players: the chips were positioned for a felt 83px tall,
// painted on one of 60, and seat 3's $5 came to rest on seat 4's puck. The bar
// growing mid-hand does this too — a side pot appearing is 55px off the felt —
// so it is not only the board strip that could reach it.
if (now !== was && Render.renderSeats) Render.renderSeats();
},
// Anything to act on? A hand with nobody dealt in doesn't get a bar — and that
@@ -109,12 +131,19 @@ const ActionBar = {
if (!host) return;
host.innerHTML = "";
// A table with nobody at it used to hide this bar altogether, which meant the
// one moment a dealer has never used the tool before is the one moment it says
// nothing at all. What they got instead was a felt printing EMPTY ten times and
// a green Resolve Pot button that would resolve nothing.
//
// An empty table is a state with an obvious next step, so it says what it is.
if (!this.isRunning()) {
host.hidden = true;
document.body.classList.remove("hasActionBar");
document.documentElement.style.setProperty("--actionBarHeight", "0px");
host.hidden = false;
document.body.classList.add("hasActionBar");
host.appendChild(this.renderEmptyTable());
this.stopTankTimer();
this.tankSeatIndex = null;
this.announce();
return;
}
host.hidden = false;
@@ -138,6 +167,79 @@ const ActionBar = {
}
this.syncTankTimer();
this.announce();
},
// The empty table. One sentence and one button, in the place every other prompt in
// this tool appears, so a dealer who has never opened it before is looking at the
// next step rather than at ten chairs labelled EMPTY.
renderEmptyTable() {
const wrap = document.createElement("div");
wrap.className = "dealPrompt";
const line = document.createElement("p");
line.className = "dealPromptLine";
line.textContent = "Nobody's at the table yet.";
wrap.appendChild(line);
const buttons = document.createElement("div");
buttons.className = "dealPromptButtons";
const seat = document.createElement("button");
seat.type = "button";
seat.className = "actionBtn actionDeal";
seat.textContent = "Seat a player";
seat.addEventListener("click", () => this.hooks.seatFirstPlayer());
buttons.appendChild(seat);
wrap.appendChild(buttons);
return wrap;
},
// One sentence, for anyone running this by ear.
//
// The bar used to carry aria-live itself, and because render() rebuilds the whole
// thing every action, a screen reader read the lot out after every tap — street,
// pot, player count, who's short, the clock, the undo label and all three buttons.
// Nothing in that is wrong; it is just unusable at the speed a hand is dealt.
//
// What a dealer actually needs from the tool between taps is who is on the clock
// and what it costs them. That is what this says, into a small element that exists
// from page load and only ever has its text replaced.
//
// Guarded on the sentence itself rather than on the state, because render() is
// called for a great many reasons that don't change whose turn it is — resizing the
// window, opening a panel, editing a note — and a live region that repeats itself
// is read out again every time.
announce() {
const target = document.getElementById("actionAnnouncer");
if (!target) return;
const said = this.announcement();
if (said === this.lastAnnouncement) return;
this.lastAnnouncement = said;
target.textContent = said;
},
announcement() {
const state = this.state;
if (!this.isRunning()) return "Nobody's at the table yet.";
if (!state.bettingOpen) {
const preview = Betting.blindPreview(state);
return preview ? "Ready to deal." : "";
}
if (Betting.isHandOver(state)) return "Hand over. Resolve the pot.";
const index = state.actingSeatIndex;
if (index === null || index === undefined) {
return `${Betting.streetLabel(state.street)} betting is done.`;
}
const player = state.seats[index];
const name = HoldemState.displayName(player, index);
const owed = Betting.toCall(state, player);
const cost = owed > 0 ? `${Money.format(owed)} to call` : "checked to them";
return `${name} to act, ${cost}. Pot ${Money.format(Betting.potSoFar(state))}.`;
},
renderStatus() {
@@ -190,6 +292,32 @@ const ActionBar = {
tank.title = "How long this player has been thinking";
tank.textContent = "0:00";
row.appendChild(tank);
// Rendered every time and shown by the tick once the wait is long enough
// to be worth it, so a clock never costs a re-render at the moment the
// dealer reaches for it — and never occupies the bar in the ordinary case
// where nobody is holding anybody up.
const clock = document.createElement("button");
clock.type = "button";
clock.id = "actionClockBtn";
clock.className = "actionClockBtn";
// Once the count is over there is nothing to stop: the ruling has been
// made, and the dealer either carries it out or takes an ordinary action,
// both of which end the clock themselves. Leaving the button there also
// cost real room — at 640x360 its 94px pushed the undo control onto a
// second line, and the taller bar covered the two bottom seats.
const expiredNow = this.clockRunning() && this.clockLeft() === 0;
clock.hidden = !this.clockRunning() || expiredNow;
if (this.clockRunning()) {
clock.textContent = "Stop the clock";
clock.title = "Put the decision back in the player's own time";
clock.addEventListener("click", () => { this.stopClock(); this.render(); });
} else {
clock.textContent = "Call the clock";
clock.title = `${this.CLOCK_THINK_S} seconds, then a ${this.CLOCK_COUNTDOWN_S}-second countdown`;
clock.addEventListener("click", () => this.callClock());
}
row.appendChild(clock);
}
// A standing control rather than a toast per action: a dealer taps this bar
@@ -201,7 +329,17 @@ const ActionBar = {
undo.type = "button";
undo.className = "actionUndo";
undo.title = `Undo ${undoLabel}`;
undo.textContent = `↶ ${undoLabel}`;
// The label goes in its own element rather than straight onto the button.
// The pill is a fixed width — it names the last action, so its text changes
// on every tap, and a control that resizes under the dealer's thumb reads
// as the interface twitching. Fixed width means long labels have to
// ellipsize, and only a real element can: as a bare text node the label
// truncated *through* the keycap below it, which then sat squashed against
// the cut-off text looking like a rendering fault.
const label = document.createElement("span");
label.className = "actionUndoLabel";
label.textContent = `↶ ${undoLabel}`;
undo.appendChild(label);
// U undoes, and nothing said so — this control was the only place a dealer
// could have learned it, and it was the one action bar control without its
// key printed on it.
@@ -229,6 +367,74 @@ const ActionBar = {
NUDGE_AFTER_S: 30,
SLOW_AFTER_S: 60,
// ---- Calling the clock ----
//
// The stopwatch above says how long somebody has been thinking. This is what a
// dealer does about it, and it is a procedure with a shape: a player asks for a
// clock, the dealer grants it, the player gets a set time and then a countdown,
// and if they still haven't acted the hand is decided for them — dead if they were
// facing a bet, checked if they weren't.
//
// The tool knew none of that. A dealer running it had to count in their head while
// the table argued about whether it had been thirty seconds, which is the moment
// the count needs to be somewhere everybody can see.
//
// Thirty seconds and then a ten-second countdown is the common form of the rule and
// what the TDA writes down. The countdown is the part the table hears out loud, so
// it is marked separately rather than being ten more seconds of the same.
CLOCK_THINK_S: 30,
CLOCK_COUNTDOWN_S: 10,
clockSeatIndex: null,
clockStartedAt: null,
clockRunning() {
return this.clockSeatIndex !== null &&
this.clockSeatIndex === this.state.actingSeatIndex &&
this.clockStartedAt !== null;
},
// Seconds left before the hand is decided, or null when no clock is running.
// Negative is impossible: it stops at zero and stays there until the dealer acts.
clockLeft(now = Date.now()) {
if (!this.clockRunning()) return null;
const total = this.CLOCK_THINK_S + this.CLOCK_COUNTDOWN_S;
return Math.max(0, total - Math.floor((now - this.clockStartedAt) / 1000));
},
// What happens when it reaches zero, in the words the dealer says out loud.
// Facing a bet, the hand is dead. Facing none, it is checked — a player who could
// have checked for free is not folded for being slow.
clockRuling() {
const index = this.state.actingSeatIndex;
if (index === null || index === undefined) return null;
const player = this.state.seats[index];
const owed = Betting.toCall(this.state, player);
const who = HoldemState.displayName(player, index);
return owed > 0
? { index, who, verb: "fold", label: `Time — ${who}'s hand is dead`, say: `${who} is facing ${Money.format(owed)}, so the hand is dead.` }
: { index, who, verb: "check", label: `Time — check for ${who}`, say: `${who} had nothing to call, so the hand is checked.` };
},
callClock() {
const index = this.state.actingSeatIndex;
if (index === null || index === undefined) return;
this.clockSeatIndex = index;
this.clockStartedAt = Date.now();
this.clockExpiredShown = false;
this.render();
},
stopClock() {
this.clockSeatIndex = null;
this.clockStartedAt = null;
this.clockExpiredShown = false;
},
// Whether the bar has already been rebuilt into its "time is up" shape, so the
// one-second tick doesn't rebuild it again every second afterwards.
clockExpiredShown: false,
tankSeatIndex: null,
tankStartedAt: null,
tankInterval: null,
@@ -258,6 +464,11 @@ const ActionBar = {
if (this.tankSeatIndex !== null) this.tankUnknownFor = null;
this.tankSeatIndex = index;
this.tankStartedAt = Date.now();
// A clock belongs to one player's decision. The moment the action moves —
// because they acted, or because the dealer took something back — it is
// over, and leaving it running would put the next player on a countdown
// nobody called on them.
this.stopClock();
}
if (!this.tankInterval) {
@@ -279,6 +490,36 @@ const ActionBar = {
const el = document.getElementById("actionTank");
if (!el || this.tankStartedAt === null) return;
// A clock takes the readout over: the number the table is waiting on is no
// longer how long this has taken but how long is left. At zero the bar has to
// change shape — a ruling and the button that carries it out — so that one
// gets a full render, once, rather than being painted in by the tick.
const left = this.clockLeft();
if (left !== null) {
if (left === 0 && !this.clockExpiredShown) {
this.clockExpiredShown = true;
this.render();
return;
}
el.textContent = left <= this.CLOCK_COUNTDOWN_S ? `${left}` : this.formatTank(left);
el.title = "Time left before the hand is decided";
el.classList.toggle("tankNudge", left > this.CLOCK_COUNTDOWN_S);
el.classList.toggle("tankSlow", left <= this.CLOCK_COUNTDOWN_S);
return;
}
// The button that starts a clock is offered once somebody has been thinking
// long enough for the table to start asking — which is the same threshold the
// stopwatch already marks. Before that it is a control nobody needs, and this
// bar is docked over the seats.
const nudge = document.getElementById("actionClockBtn");
if (nudge && !this.clockRunning()) {
const waited = Math.floor((Date.now() - this.tankStartedAt) / 1000);
nudge.hidden = this.tankUnknownFor === this.tankSeatIndex
? false
: waited < this.NUDGE_AFTER_S;
}
if (this.tankUnknownFor !== null && this.tankSeatIndex === this.tankUnknownFor) {
el.textContent = "—";
el.title = "The action was already on this seat when the page loaded, so there's nothing to time from yet. The clock starts when the action next moves.";
@@ -388,6 +629,19 @@ const ActionBar = {
// recorded so it can be taken back. A misclick on Fold is the one mistake in this
// tool a dealer can't talk their way out of.
commit(label, mutate) {
// A toast is news about the last thing that happened, and this is the next
// thing: whatever it says is now out of date. Two reasons it goes rather than
// waiting out its eight seconds. It lies — "Next hand — button on seat 2.
// [Undo]" reads as an offer to move the button back, but the snapshot behind
// that Undo predates the hand you have since dealt, so taking it would throw
// the hand away without saying so. And it is in the way: measured across the
// sweep, a toast left up over a dealt table covered seats, the clock button
// or the bar's own Undo on thirty of the small screens it was checked at,
// because there is nowhere on a 360x640 phone for a 560px strip to go. The
// bar's own Undo control takes over from here, and it names the step it
// would actually take back.
if (typeof Toast !== "undefined" && Toast.dismiss) Toast.dismiss();
this.hooks.beginAction(label);
mutate();
this.hooks.save(this.state);
@@ -401,6 +655,36 @@ const ActionBar = {
const stack = Betting.stackOf(this.state, player);
const who = HoldemState.displayName(player, index);
// Time is up. The ruling goes on the bar in the words the dealer says out loud,
// with the one action that carries it out — and the ordinary buttons stay
// underneath, because a player who speaks up as the count ends is still acting
// and the dealer is the one who decides whether it was in time.
const expired = this.clockLeft() === 0 ? this.clockRuling() : null;
const wrap = document.createElement("div");
if (expired) {
const line = document.createElement("p");
line.className = "clockExpired";
// The ruling in one sentence. `label` is the same call in three words for
// the button beside it; saying both left the line doubling back on itself
// — "Time — Dee's hand is dead — Dee is facing $2, so the hand is dead."
line.textContent = `Time — ${expired.say}`;
wrap.appendChild(line);
const enforce = document.createElement("div");
enforce.className = "actionButtons";
enforce.appendChild(this.button(
expired.verb === "fold" ? `Kill ${expired.who}'s hand` : `Check for ${expired.who}`,
"actionEnforceClock",
() => this.commit(
expired.verb === "fold" ? `${expired.who}'s hand killed on the clock` : `${expired.who}'s check on the clock`,
() => {
this.stopClock();
if (expired.verb === "fold") Betting.fold(this.state, index);
else Betting.check(this.state, index);
})));
wrap.appendChild(enforce);
}
const row = document.createElement("div");
row.className = "actionButtons";
@@ -427,7 +711,9 @@ const ActionBar = {
}));
}
return row;
if (!expired) return row;
wrap.appendChild(row);
return wrap;
},
// Quick amounts first, keypad second — a dealer calling "raise to sixty" wants a
@@ -862,6 +1148,10 @@ const ActionBar = {
return;
}
this.commit(`dealing the ${Betting.streetLabel(Betting.STREETS[Betting.STREETS.indexOf(this.state.street) + 1]).toLowerCase()}`, () => Betting.closeStreet(this.state));
// The cards that just came off the deck. Asked for here rather than left
// for the dealer to remember, because the moment they are holding them is
// the only moment they know what they are without turning the board round.
if (this.state.trackBoard && typeof Render !== "undefined") Render.openBoardPicker();
}));
wrap.appendChild(row);
@@ -13,6 +13,15 @@
const Betting = {
STREETS: ["preflop", "flop", "turn", "river"],
// How many community cards are face up once a street has been dealt. The flop is
// three at once and everything after it is one at a time, which is why this is a
// table rather than an index.
BOARD_CARDS: { preflop: 0, flop: 3, turn: 4, river: 5 },
boardCardsFor(street) {
return this.BOARD_CARDS[street] ?? 0;
},
streetLabel(street) {
return { preflop: "Pre-flop", flop: "Flop", turn: "Turn", river: "River" }[street] || "Pre-flop";
},
@@ -459,6 +468,116 @@ const Betting = {
return (state.street || "preflop") === "preflop" && state.seats.every(p => !p.hasActed);
},
// Are the blinds actually down? Moving the button or naming a blind means two
// completely different things depending on the answer, and `onlyBlindsIn` alone
// cannot tell them apart: a table sitting in setup, with no cards out and nothing
// committed, satisfies it just as well as a hand that has only just been dealt.
//
// With a hand open, the blinds are chips on the felt. Re-aiming them has to take
// those chips back and post them again from the new positions, or the badges and
// the money disagree.
//
// Before the deal it is a marker being slid round a table with nothing in the
// middle. Re-posting there would *deal the hand* — betting opened, blinds taken off
// two stacks, action on the seat after the big blind — which is not what a dealer
// means by "she's the big blind this one". Setting the positions is how a dealer
// gets ready to deal; the cards come out when they press the button, and not a
// moment before.
blindsArePosted(state) {
return !!state.bettingOpen && this.onlyBlindsIn(state);
},
// Chips the pot has been priced with but nobody has actually paid.
//
// Two ways a contribution gets into this tool. Tapping the action moves chips: the
// bet leaves the stack, sits in front of the player, and is swept into their hand
// total at the end of the street. The other way is the "without live betting" panel
// — a base pot amount, or chips counted out on a seat — where the dealer is
// recording a hand they are watching rather than driving, and nothing ever leaves
// anybody's stack.
//
// The pot wizard prices both the same way, and awarding it credits the winner. So
// in that second mode the table simply grew: measured at a three-handed table with
// a $50 base pot, paying the pot took the chips on the table from $600 to $750 and
// left the bank check blaming a rebuy that never happened.
//
// So before the pot is pushed, whatever was assumed rather than taken comes off the
// stacks that assumed it. Chips already committed or swept are left alone; they
// have been paid once already, and taking them twice is the same bug the other way
// round.
collectAssumedContributions(state) {
const taken = [];
state.seats.forEach((player, index) => {
const priced = HoldemState.computeContribution(player, state.chipLegend, state.basePotAmount);
const alreadyPaid = this.round(this.committed(player) + (Number(player.amountOverride) || 0));
const owed = this.round(priced - alreadyPaid);
if (owed <= this.EPSILON_CHIPS) return;
// Never more than they are holding. A seat priced above its own stack is a
// dealer's typo or a player who is short, and inventing the difference is
// what this whole function exists to stop.
const moved = this.round(Math.min(owed, this.stackOf(state, player)));
if (moved <= this.EPSILON_CHIPS) return;
player.stack = this.round(this.stackOf(state, player) - moved);
// Recorded where a swept bet lives, so the money is in exactly the place
// the rest of the tool looks for chips that are in the middle this hand.
player.amountOverride = this.round((Number(player.amountOverride) || 0) + moved);
taken.push({ index, name: HoldemState.displayName(player, index), amount: moved });
});
return { taken, total: this.round(taken.reduce((sum, row) => sum + row.amount, 0)) };
},
// A misdeal: the hand never happened, so every chip goes back where it came from.
//
// The rulings sheet in this tool has told dealers to redeal since the day it was
// written — first card to the wrong seat, a seat entitled to a hand dealt out, one
// of the first two cards exposed — and the tool had no way to do it. The only
// control that ended a live hand was Next Hand, which says out loud that it takes
// the money off the table without paying anybody. That is right for an abandoned
// pot and wrong for a misdeal, where the blinds and any calls belong to the people
// who put them in.
//
// Undo covers the first second of it — "↶ dealing the hand" is one tap — but only
// while the action history is still there. It lives in memory, so a dealer who
// refreshes the page mid-hand, or who is three calls in, has nothing.
//
// What is deliberately kept: the button, the blinds, the straddle and anyone
// posting in. A misdeal is the *same* hand dealt again, not the next one.
takeHandBack(state) {
const returned = [];
state.seats.forEach((player, index) => {
const back = this.round(this.committed(player) + (Number(player.amountOverride) || 0));
if (back > 0) {
player.stack = this.round(this.stackOf(state, player) + back);
returned.push({ index, name: HoldemState.displayName(player, index), amount: back });
}
player.committed = 0;
player.amountOverride = null;
player.hasActed = false;
player.folded = false;
player.cards = ["", ""];
});
state.bettingOpen = false;
state.street = "preflop";
state.currentBet = 0;
state.lastRaiseSize = 0;
state.actingSeatIndex = null;
state.streetAggressorIndex = null;
state.handAggressorIndex = null;
HoldemState.clearBoard(state);
// Nothing was posted, as far as the next rotation is concerned: the hand this
// would have counted as is being dealt again from the same button.
state.postedBlinds = null;
state.postedStraddles = [];
return {
returned,
total: this.round(returned.reduce((sum, row) => sum + row.amount, 0)),
};
},
// Pulls the blinds back off the table and posts them again from wherever the
// button and the blind assignment now say they belong. Refunding first is what
// keeps the chip count straight when the button gets passed round three or four
@@ -484,6 +603,10 @@ const Betting = {
state.street = "preflop";
state.currentBet = 0;
state.lastRaiseSize = 0;
// A fresh deal starts on an empty felt. Dealing without moving the button —
// after a misdeal, or a table set up and dealt twice — would otherwise leave
// the last hand's board sitting there being ranked against the new cards.
HoldemState.clearBoard(state);
// Posting a blind isn't aggression — a hand limped and checked all the way
// down has no aggressor at all, which is exactly the case the showdown rule
// sends to the seat left of the button.
@@ -16,45 +16,97 @@ const CardPicker = {
state: null,
hooks: null,
// Which set of slots is being filled: a seat's two hole cards, or the five
// community cards. The grid, the duplicate check and the tap-to-fill behaviour are
// the same job either way — what changes is where the card is written and how many
// slots there are to walk along.
target: null,
seatIndex: null,
cardIndex: 0,
open(state, hooks, seatIndex, cardIndex) {
this.state = state;
this.hooks = hooks;
this.target = "seat";
this.seatIndex = seatIndex;
this.cardIndex = cardIndex;
this.render();
document.getElementById("cardPickerOverlay").hidden = false;
},
// The board. `limit` is how many of the five are actually out — three on the flop,
// four on the turn — so the sheet never offers a slot for a card the dealer has not
// turned over yet.
openBoard(state, hooks, cardIndex, limit = 5) {
this.state = state;
this.hooks = hooks;
this.target = "board";
this.seatIndex = null;
this.boardLimit = Math.max(1, Math.min(5, limit));
this.cardIndex = Math.min(cardIndex, this.boardLimit - 1);
this.render();
document.getElementById("cardPickerOverlay").hidden = false;
},
onBoard() {
return this.target === "board";
},
// The slots the sheet is filling, whichever set that is.
slotValues() {
return this.onBoard()
? (this.state.board || []).slice(0, this.boardLimit)
: this.state.seats[this.seatIndex].cards;
},
write(index, card) {
if (this.onBoard()) {
if (!Array.isArray(this.state.board)) this.state.board = ["", "", "", "", ""];
this.state.board[index] = card;
return;
}
this.state.seats[this.seatIndex].cards[index] = card;
},
close() {
document.getElementById("cardPickerOverlay").hidden = true;
},
// Every card sitting in front of anyone else. The slot being edited is excluded,
// so re-picking the card that's already there isn't treated as a duplicate.
// Every card already dealt somewhere — in front of a player or face up in the
// middle. The slot being edited is excluded, so re-picking the card that's already
// there isn't treated as a duplicate.
//
// The board belongs in here as much as the hands do, and in both directions: the
// seven of clubs cannot be on the flop and in somebody's hand, whichever of the two
// the dealer is filling in at the time.
cardsInUse() {
const used = new Map();
this.state.seats.forEach((player, seat) => {
(player.cards || []).forEach((card, slot) => {
if (!card) return;
if (seat === this.seatIndex && slot === this.cardIndex) return;
if (!this.onBoard() && seat === this.seatIndex && slot === this.cardIndex) return;
used.set(card.toUpperCase(), HoldemState.displayName(player, seat));
});
});
(this.state.board || []).forEach((card, slot) => {
if (!card) return;
if (this.onBoard() && slot === this.cardIndex) return;
used.set(card.toUpperCase(), "the board");
});
return used;
},
assign(card) {
const player = this.state.seats[this.seatIndex];
player.cards[this.cardIndex] = card;
this.write(this.cardIndex, card);
this.hooks.onPick(this.seatIndex, this.cardIndex, card);
// Straight on to the second card — a dealer picking hole cards is always
// picking two, and making them re-open the picker doubles the taps.
if (this.cardIndex === 0 && !player.cards[1]) {
this.cardIndex = 1;
// Straight on to the next empty slot — a dealer picking hole cards is always
// picking two and a flop is always three, and making them re-open the picker
// between each one multiplies the taps by the only thing the sheet is for.
const values = this.slotValues();
const next = values.findIndex((value, i) => i > this.cardIndex && !value);
if (next !== -1) {
this.cardIndex = next;
this.render();
return;
}
@@ -62,29 +114,37 @@ const CardPicker = {
},
clearSlot() {
const player = this.state.seats[this.seatIndex];
player.cards[this.cardIndex] = "";
this.write(this.cardIndex, "");
this.hooks.onPick(this.seatIndex, this.cardIndex, "");
this.render();
},
render() {
const player = this.state.seats[this.seatIndex];
const used = this.cardsInUse();
// What this slot is called out loud: the flop's three cards, then the turn, then
// the river — which is what a dealer is holding when they open this, rather than
// "card 4".
boardSlotLabel(slot) {
return ["Flop 1", "Flop 2", "Flop 3", "Turn", "River"][slot] || `Card ${slot + 1}`;
},
document.getElementById("cardPickerTitle").textContent =
`${HoldemState.displayName(player, this.seatIndex)} — card ${this.cardIndex + 1}`;
render() {
const used = this.cardsInUse();
const values = this.slotValues();
document.getElementById("cardPickerTitle").textContent = this.onBoard()
? `Board — ${this.boardSlotLabel(this.cardIndex).toLowerCase()}`
: `${HoldemState.displayName(this.state.seats[this.seatIndex], this.seatIndex)} — card ${this.cardIndex + 1}`;
// Which slot the next tap fills, switchable without closing the sheet.
const slots = document.getElementById("cardPickerSlots");
slots.innerHTML = "";
[0, 1].forEach(slot => {
values.forEach((_, slot) => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pickerSlot";
btn.classList.toggle("active", slot === this.cardIndex);
const value = player.cards[slot] || "";
const value = values[slot] || "";
btn.textContent = value || "—";
if (this.onBoard()) btn.title = this.boardSlotLabel(slot);
btn.classList.toggle("cardRed", /[HD]$/i.test(value));
btn.addEventListener("click", () => {
this.cardIndex = slot;
@@ -105,8 +165,12 @@ const CardPicker = {
btn.className = "pickerCard";
btn.classList.toggle("cardRed", suit.red);
btn.disabled = !!takenBy;
if (takenBy) btn.title = `Already dealt to ${takenBy}`;
if ((player.cards[this.cardIndex] || "").toUpperCase() === card) {
if (takenBy) {
btn.title = takenBy === "the board"
? "Already face up on the board"
: `Already dealt to ${takenBy}`;
}
if ((values[this.cardIndex] || "").toUpperCase() === card) {
btn.classList.add("selected");
}
@@ -20,7 +20,11 @@ const HandHistoryExport = {
// who owes what — doesn't work without cleaning every cell first. The commas were
// quoted correctly, so the file parsed; it just wouldn't add up.
toCsv(handHistory, standings = [], { notes = "" } = {}) {
const rows = [["Hand #", "Time", "Pot", "Payouts"]];
// The rake gets its own column rather than being folded into the pot: the two
// numbers answer different questions — what was in the middle, and what the
// house took out of it — and a night's worth of the second one is what the box
// is counted against.
const rows = [["Hand #", "Time", "Pot", "House take", "Payouts"]];
// handHistory is stored newest-first; the export reads better oldest-first.
[...handHistory].reverse().forEach(entry => {
const payouts = (entry.payouts || [])
@@ -30,6 +34,7 @@ const HandHistoryExport = {
entry.handNumber,
this.formatTimestamp(entry.timestamp),
Money.forSheet(entry.pot),
Money.forSheet(entry.rake || 0),
payouts,
]);
});
@@ -49,7 +54,10 @@ const HandHistoryExport = {
rows.push(["Player", "Paid In", "Won", "Net", "Bought In", "Chips Now", "Up/Down", "Notes"]);
standings.forEach(row => {
rows.push([
row.name,
// Somebody who has gone home is marked in the file the same way the
// panel marks them, because this is the copy that gets read at the
// end of the night when nobody remembers who has already been paid.
row.cashedOut ? `${row.name} (paid out)` : row.name,
Money.forSheet(row.in),
Money.forSheet(row.won),
Money.forSheet(row.net),
@@ -0,0 +1,285 @@
// What beats what.
//
// The dealer has always been the one who decides who won: the pot wizard asks "who won
// the hand?" and pays whoever gets ticked. That is the right default — most hands are
// won without a showdown, and at a home game the table reads the cards out loud between
// them. But when the board is on the felt and the hands are on their backs, the tool
// knows the answer, and reading it off a screen beats three people counting kickers.
//
// Cards are the same two-character strings the rest of the tool has always stored:
// a rank from `RANKS` and a suit from S, H, D, C. Case is not significant.
//
// Nothing in here touches the DOM, the table, or money. It compares cards, and the pot
// wizard decides what to do about it.
const HandRank = {
RANKS: "23456789TJQKA",
// High to low. The number is the hand's category and nothing else — kickers and
// the rest of the tie-breaking live in the `tiebreak` array beside it.
STRAIGHT_FLUSH: 8,
FOUR_OF_A_KIND: 7,
FULL_HOUSE: 6,
FLUSH: 5,
STRAIGHT: 4,
THREE_OF_A_KIND: 3,
TWO_PAIR: 2,
ONE_PAIR: 1,
HIGH_CARD: 0,
// 2 through 14. Null for anything that isn't a card, which is how a half-filled
// slot gets told apart from a bad one.
rankValue(card) {
if (typeof card !== "string" || card.length < 2) return null;
const index = this.RANKS.indexOf(card[0].toUpperCase());
return index < 0 ? null : index + 2;
},
suitOf(card) {
if (typeof card !== "string" || card.length < 2) return null;
const suit = card[card.length - 1].toUpperCase();
return "SHDC".includes(suit) ? suit : null;
},
isCard(card) {
return this.rankValue(card) !== null && this.suitOf(card) !== null;
},
// Singular and plural, for reading a hand out loud.
NAMES: {
14: ["ace", "aces"], 13: ["king", "kings"], 12: ["queen", "queens"],
11: ["jack", "jacks"], 10: ["ten", "tens"], 9: ["nine", "nines"],
8: ["eight", "eights"], 7: ["seven", "sevens"], 6: ["six", "sixes"],
5: ["five", "fives"], 4: ["four", "fours"], 3: ["three", "threes"],
2: ["two", "twos"],
},
name(rank, plural = false) {
const pair = this.NAMES[rank];
return pair ? pair[plural ? 1 : 0] : "?";
},
// ---- The five-card hand -------------------------------------------------------
// Exactly five cards, ranked. Everything else is built on this.
//
// Five rather than seven because five is the hand a player actually holds, and it
// is small enough to check by hand — which is the whole argument for doing it this
// way. The seven-card version below tries all twenty-one five-card hands and keeps
// the best, which is a hand of poker's own definition of "your best five" written
// out literally. A dealer resolves one pot a hand with at most a dozen players in
// it; two hundred and fifty comparisons of five cards is not a cost worth trading
// a subtler algorithm's correctness for.
evaluate5(cards) {
if (!Array.isArray(cards) || cards.length !== 5) return null;
if (!cards.every(card => this.isCard(card))) return null;
const ranks = cards.map(card => this.rankValue(card)).sort((a, b) => b - a);
const suits = cards.map(card => this.suitOf(card));
const flush = suits.every(suit => suit === suits[0]);
// How many of each rank, ordered by how many first and by rank second — so
// the front of this list is always the rank that decides the hand.
const counts = new Map();
ranks.forEach(rank => counts.set(rank, (counts.get(rank) || 0) + 1));
const groups = [...counts.entries()]
.sort((a, b) => (b[1] - a[1]) || (b[0] - a[0]));
const shape = groups.map(([, count]) => count);
const byGroup = groups.map(([rank]) => rank);
const straightHigh = this.straightHigh(ranks);
const made = (category, tiebreak) => ({ category, tiebreak, cards: [...cards] });
if (flush && straightHigh) return made(this.STRAIGHT_FLUSH, [straightHigh]);
if (shape[0] === 4) return made(this.FOUR_OF_A_KIND, byGroup);
if (shape[0] === 3 && shape[1] === 2) return made(this.FULL_HOUSE, byGroup);
if (flush) return made(this.FLUSH, ranks);
if (straightHigh) return made(this.STRAIGHT, [straightHigh]);
if (shape[0] === 3) return made(this.THREE_OF_A_KIND, byGroup);
if (shape[0] === 2 && shape[1] === 2) return made(this.TWO_PAIR, byGroup);
if (shape[0] === 2) return made(this.ONE_PAIR, byGroup);
return made(this.HIGH_CARD, ranks);
},
// The top card of the straight these five ranks make, or null.
//
// The wheel is the exception the rest of the ordering has to be told about: A-2-3-4-5
// is a straight, and it is the *lowest* one, so its ace counts as five rather than
// as fourteen. Getting that wrong is how A-2-3-4-5 comes to beat 10-J-Q-K-A.
straightHigh(sortedDesc) {
const distinct = [...new Set(sortedDesc)];
if (distinct.length !== 5) return null;
if (distinct[0] - distinct[4] === 4) return distinct[0];
// Ace, five, four, three, two.
if (distinct[0] === 14 && distinct[1] === 5 && distinct[4] === 2) return 5;
return null;
},
// ---- The best five out of however many ----------------------------------------
// The best five-card hand available from five, six or seven cards — hole cards and
// board together, which is what Hold'em asks for. Returns null if there aren't five
// real cards, which is the ordinary state of a hand still being dealt.
best(cards) {
const real = (cards || []).filter(card => this.isCard(card));
if (real.length < 5) return null;
// A card in two places at once is a mis-entry, not a hand — say so rather than
// ranking a board that has the same king on it twice.
if (new Set(real.map(card => card.toUpperCase())).size !== real.length) return null;
let best = null;
this.eachFive(real, five => {
const hand = this.evaluate5(five);
if (!best || this.compare(hand, best) > 0) best = hand;
});
return best;
},
// Every five-card subset, without building an array of them.
eachFive(cards, visit) {
const n = cards.length;
for (let a = 0; a < n - 4; a++) {
for (let b = a + 1; b < n - 3; b++) {
for (let c = b + 1; c < n - 2; c++) {
for (let d = c + 1; d < n - 1; d++) {
for (let e = d + 1; e < n; e++) {
visit([cards[a], cards[b], cards[c], cards[d], cards[e]]);
}
}
}
}
}
},
// Positive if `a` wins, negative if `b` does, zero for a chop. A chop is a real
// answer here rather than a rounding of one: two players playing the same board
// split the pot, and the fifth card decides it far more often than a table expects.
compare(a, b) {
if (!a && !b) return 0;
if (!a) return -1;
if (!b) return 1;
if (a.category !== b.category) return a.category - b.category;
const length = Math.max(a.tiebreak.length, b.tiebreak.length);
for (let i = 0; i < length; i++) {
const diff = (a.tiebreak[i] || 0) - (b.tiebreak[i] || 0);
if (diff !== 0) return diff;
}
return 0;
},
// ---- Saying it out loud -------------------------------------------------------
// What a dealer says when they turn the hand over. Named to the level that settles
// it and no further: "two pair, aces and eights" is the call, and the kicker only
// gets a mention where the tool has had to use one to break a tie.
describe(hand) {
if (!hand) return "";
const [first, second] = hand.tiebreak;
switch (hand.category) {
case this.STRAIGHT_FLUSH:
return first === 14 ? "Royal flush" : `Straight flush, ${this.name(first)} high`;
case this.FOUR_OF_A_KIND:
return `Four of a kind, ${this.name(first, true)}`;
case this.FULL_HOUSE:
return `Full house, ${this.name(first, true)} full of ${this.name(second, true)}`;
case this.FLUSH:
return `Flush, ${this.name(first)} high`;
case this.STRAIGHT:
return `Straight, ${this.name(first)} high`;
case this.THREE_OF_A_KIND:
return `Three of a kind, ${this.name(first, true)}`;
case this.TWO_PAIR:
return `Two pair, ${this.name(first, true)} and ${this.name(second, true)}`;
case this.ONE_PAIR:
return `Pair of ${this.name(first, true)}`;
default:
return `${this.name(first).charAt(0).toUpperCase()}${this.name(first).slice(1)} high`;
}
},
// The same call with the article a table would put in front of it. Not derivable
// from the first letter: it is "a full house" and "a flush", but "four of a kind"
// and "two pair" take none at all, and "an ace high" is not something anybody says.
// So it belongs to the category, like the name does.
ARTICLED: {
8: hand => (hand.tiebreak[0] === 14 ? "a royal flush" : "a"),
7: () => null,
6: () => "a",
5: () => "a",
4: () => "a",
3: () => null,
2: () => null,
1: () => "a",
0: () => null,
},
// "wins with X" — the phrase, ready to drop into a sentence.
phrase(hand) {
if (!hand) return "the best hand";
const described = this.describe(hand);
const article = (this.ARTICLED[hand.category] || (() => null))(hand);
if (article === null) return described.toLowerCase();
if (article !== "a") return article;
return `a ${described.toLowerCase()}`;
},
// ---- The showdown -------------------------------------------------------------
// Rank a set of players against a board.
//
// `players` is [{ id, cards }, ...] — the two in front of each of them. Every player
// is returned whether or not they could be ranked, in the order they were given, so
// the caller can show a row for each and say which ones it could not read. `place`
// is 1 for the winner and shared by a chop; a player whose cards aren't known has a
// null hand and no place.
//
// `complete` is the question the pot wizard actually asks: can this be trusted to
// pay the table. It is only true when the board is all five cards and every single
// player handed in has two of their own — one unknown hand and the tool cannot say
// who won, only who is winning so far, which is not the same thing and must not be
// dressed up as it.
showdown(board, players) {
const boardCards = (board || []).filter(card => this.isCard(card));
const boardComplete = boardCards.length === 5;
const ranked = (players || []).map(player => {
const hole = (player.cards || []).filter(card => this.isCard(card));
const hand = hole.length === 2 && boardComplete
? this.best([...hole, ...boardCards])
: null;
return { id: player.id, cards: hole, hand, place: null };
});
const readable = ranked.filter(row => row.hand);
// A duplicated card anywhere means somebody has been mis-entered, and the
// ranking would be of a deck that doesn't exist.
const all = [...boardCards, ...ranked.flatMap(row => row.cards)].map(c => c.toUpperCase());
const duplicated = new Set(all).size !== all.length;
const sorted = [...readable].sort((a, b) => this.compare(b.hand, a.hand));
let place = 0;
sorted.forEach((row, i) => {
if (i === 0 || this.compare(row.hand, sorted[i - 1].hand) !== 0) place = i + 1;
row.place = place;
});
const winners = sorted.filter(row => row.place === 1);
const complete = boardComplete && !duplicated &&
ranked.length > 0 && readable.length === ranked.length;
return {
players: ranked,
winners: complete ? winners.map(row => row.id) : [],
boardComplete,
duplicated,
complete,
// Who the tool could not read, so the dialog can name them rather than
// just declining to help.
unknown: ranked.filter(row => !row.hand).map(row => row.id),
};
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = HandRank;
}
+251 -17
View File
@@ -56,6 +56,35 @@ document.addEventListener("DOMContentLoaded", () => {
},
onSeatLongPress: index => SeatMenu.open(state, seatMenuHooks, index),
// The waiting list, from the Session panel and from an empty chair's menu.
// The state change goes inside runUndoable, not before it: the snapshot is
// taken as the first thing that happens, so anything done ahead of it is
// already baked into what Undo would restore.
seatWaiting: (id, index) => {
const entry = (state.waitingList || []).find(row => row.id === id);
const seat = state.seats[index];
if (!entry || !seat) {
Toast.show("They aren't on the list any more.", { duration: 3000 });
hooks.rerender();
return;
}
const occupied = HoldemState.seatInPlay(seat);
if (occupied) {
Toast.show(`${HoldemState.displayName(seat, index)} is already in that seat.`, { duration: 3500 });
hooks.rerender();
return;
}
runUndoable(`${entry.name} takes seat ${index + 1}. Add their chips when they buy in.`,
() => HoldemState.seatFromWaitingList(state, id, index));
},
dropWaiting: id => {
const entry = (state.waitingList || []).find(row => row.id === id);
if (!entry) return;
runUndoable(`${entry.name} taken off the waiting list.`,
() => HoldemState.removeFromWaitingList(state, id));
},
onGiveButton: index => seatMenuHooks.makeDealer(index),
};
@@ -96,6 +125,39 @@ document.addEventListener("DOMContentLoaded", () => {
});
},
// Somebody is done for the night. The dealer counts their chips out, the chair
// opens, and both halves of what happened stay on the record — the cash the box
// took from them, and the chips it handed back. Wiping the seat by hand did
// neither: it left the bank check declaring their whole stack missing for the
// rest of the night.
cashOut: async index => {
const allowed = HoldemState.canCashOut(state, index);
if (!allowed.ok) {
Toast.show(allowed.reason, { duration: 4000 });
return;
}
const preview = HoldemState.cashOutPreview(state, index);
const result = preview.net === 0
? "even for the night"
: preview.net > 0
? `up ${Money.format(preview.net)}`
: `down ${Money.format(Math.abs(preview.net))}`;
const chips = preview.breakdown ? ` — ${preview.breakdown}` : "";
const ok = await Dialog.confirm({
title: `Cash out ${preview.name}?`,
message: `Count out ${Money.format(preview.chips)}${chips}. They bought in for ` +
`${Money.format(preview.boughtIn)}, so they leave ${result}. The chair opens up, and the ` +
`night's record keeps both their buy-in and this payout so the bank still balances.`,
confirmLabel: `Pay ${Money.format(preview.chips)}`,
});
if (!ok) return;
runUndoable(`${preview.name} cashed out for ${Money.format(preview.chips)}.`,
() => HoldemState.cashOut(state, index));
},
// Two players change chairs. Undoable like every other seat action, because a
// swap is easy to aim wrong and the seats look alike at a glance.
swapSeats: (from, to) => {
@@ -114,8 +176,7 @@ document.addEventListener("DOMContentLoaded", () => {
// After it, the blinds have to follow the button or the badges and the
// money disagree — but that's a real thing happening to real chips, and
// the dealer gets told rather than finding out later.
const willRepost = state.bettingOpen && Betting.onlyBlindsIn(state) &&
HoldemState.unresolvedContributions(state) > Betting.EPSILON_CHIPS;
const willRepost = Betting.blindsArePosted(state);
seatAction(index, willRepost
? `Button on ${nameOf(index)} — blinds taken back and re-posted.`
@@ -142,18 +203,29 @@ document.addEventListener("DOMContentLoaded", () => {
if (partner === index || partner === null) partner = Betting.nextLiveIndex(state, index);
const label = which === "sb" ? "small blind" : "big blind";
seatAction(index, `${nameOf(index)} posts the ${label}.`, () => {
// Only a hand that is already open has blinds to move. Before the deal this
// is aiming the next hand, and re-posting would have dealt it — the dealer
// says who the blind is well before they say "cards".
const posted = Betting.blindsArePosted(state);
seatAction(index, posted
? `${nameOf(index)} posts the ${label}.`
: `${nameOf(index)} has the ${label} next hand.`, () => {
state.blindOverride = which === "sb"
? { sbIndex: index, bbIndex: partner }
: { sbIndex: partner, bbIndex: index };
if (Betting.onlyBlindsIn(state)) Betting.repostBlinds(state);
if (posted) Betting.repostBlinds(state);
});
},
clearBlindOverride: () => seatAction(state.dealerSeatIndex, "Blinds follow the button again.", () => {
state.blindOverride = null;
if (Betting.onlyBlindsIn(state)) Betting.repostBlinds(state);
}),
clearBlindOverride: () => {
const posted = Betting.blindsArePosted(state);
seatAction(state.dealerSeatIndex, posted
? "Blinds follow the button again — taken back and re-posted."
: "Blinds follow the button again.", () => {
state.blindOverride = null;
if (posted) Betting.repostBlinds(state);
});
},
editSeat: index => Render.toggleSeatEditor(index),
@@ -185,6 +257,22 @@ document.addEventListener("DOMContentLoaded", () => {
Render.mount(state, hooks);
// Table Setup used to ship open, so the tool's first screen was its most crowded
// one: seat count, blind direction, dedicated dealer, both blinds, starting stack
// and two sub-panels, all under a felt the dealer had come here to look at. It is
// the right panel to have open on a table nobody has touched, and the wrong one to
// have open on the fourth hand of a night.
//
// Decided once, here, rather than on every render — a panel that reopened itself
// whenever the table emptied would fight the dealer who had just shut it.
(() => {
const panel = document.getElementById("tableSetupPanel");
if (!panel) return;
const fresh = (Number(state.handNumber) || 1) === 1 &&
!state.seats.some(seat => HoldemState.seatInPlay(seat));
panel.open = fresh;
})();
const openPotWizard = () => {
// Chips still in front of players belong in the pot being priced, so bank them
// before the wizard reads anyone's contribution.
@@ -192,11 +280,20 @@ document.addEventListener("DOMContentLoaded", () => {
hooks.save(state);
Render.renderAll();
PotWizard.open(state, payouts => {
PotWizard.open(state, (payouts, { rake = 0 } = {}) => {
const paid = payouts.map(p => `${p.label} ${Money.format(p.amount)}`).join(", ");
runUndoable(paid ? `Paid ${paid}.` : "Hand closed with nothing to pay out.", () => {
const withRake = rake > 0 ? `${paid}, house ${Money.format(rake)}` : paid;
runUndoable(withRake ? `Paid ${withRake}.` : "Hand closed with nothing to pay out.", () => {
if (rake > 0) {
state.rakeTaken = Money.round((Number(state.rakeTaken) || 0) + rake);
}
// Anything the pot was priced with but nobody actually paid — the
// base pot and counted chips of the no-live-betting flow — comes off
// the stacks that owe it before the winner is paid. Otherwise the
// table gains the whole pot out of nowhere.
Betting.collectAssumedContributions(state);
if (payouts.length > 0) {
HoldemState.recordHand(state, payouts);
HoldemState.recordHand(state, payouts, rake);
// Winnings go straight back in front of the player, so the next
// hand's stacks are already right.
Betting.creditWinnings(state, payouts);
@@ -220,6 +317,16 @@ document.addEventListener("DOMContentLoaded", () => {
rerender: hooks.rerender,
resolvePot: openPotWizard,
// The first thing a dealer does on a table nobody is sitting at. Opens the
// seat editor on the first free chair — the same panel tapping the seat gives
// them, so the button teaches the gesture rather than replacing it.
seatFirstPlayer: () => {
const index = state.seats.findIndex(seat => !HoldemState.seatInPlay(seat));
Render.toggleSeatEditor(index < 0 ? 0 : index);
const panel = document.getElementById("seatEditorPanel");
if (panel) panel.scrollIntoView({ block: "nearest", behavior: "smooth" });
},
beginAction: label => {
actionHistory.push({ label, snapshot: snapshotState() });
if (actionHistory.length > MAX_UNDO_STEPS) actionHistory.shift();
@@ -300,12 +407,11 @@ document.addEventListener("DOMContentLoaded", () => {
// in progress. Shrinking the table throws these away permanently, and it also
// orphans them in the session standings, where they keep their winnings but lose
// the stack and buy-in the settle-up is worked out from.
const seatHasSomeoneIn = player =>
!!(player.name && player.name.trim()) ||
player.inHand ||
(Number(player.stack) || 0) > 0 ||
(Number(player.buyIns) || 0) > 0 ||
(Number(player.amountOverride) || 0) > 0;
// One question, asked in one place. This predicate existed here, in the seat menu,
// in the action bar and twice in the state module, in four slightly different
// spellings — and a chair that counts as occupied for the waiting list but empty
// for the seat count is how somebody's chips get thrown away.
const seatHasSomeoneIn = player => HoldemState.seatInPlay(player);
document.getElementById("seatCountInput").addEventListener("change", async e => {
const requested = Math.max(2, Math.min(24, Math.floor(Number(e.target.value)) || state.seatCount));
@@ -349,6 +455,15 @@ document.addEventListener("DOMContentLoaded", () => {
Render.renderTableHint();
});
document.getElementById("trackBoardToggle").addEventListener("change", e => {
state.trackBoard = e.target.checked;
// Turning it off leaves whatever was entered in place rather than wiping it —
// a dealer who taps this by mistake mid-hand can tap it back and the flop is
// still there. The next hand clears it the way it clears everything else.
hooks.save(state);
Render.renderAll();
});
document.getElementById("tableNotes").addEventListener("input", e => {
state.notes = e.target.value;
hooks.save(state);
@@ -364,6 +479,59 @@ document.addEventListener("DOMContentLoaded", () => {
Render.renderAll();
});
// A misdeal. Everything in the middle goes back to whoever put it there, and the
// same button deals the same hand again.
// The seats holding the table's starting stack, written down as cash taken.
document.getElementById("bankRecordBuyInsBtn").addEventListener("click", async () => {
const starting = HoldemState.seatsOwingCash(state).filter(row => row.fromStartingStack);
if (starting.length === 0) return;
const total = Money.round(starting.reduce((sum, row) => sum + row.chips, 0));
const ok = await Dialog.confirm({
title: `Write down ${Money.format(total)} taken?`,
message: `${starting.map(row => `${row.name} ${Money.format(row.chips)}`).join(", ")} — the starting stack ` +
`each of them is playing with. Only do this if the cash is actually in the box.`,
confirmLabel: "Write it down",
});
if (!ok) return;
runUndoable(`${Money.format(total)} recorded from ${starting.length} ${starting.length === 1 ? "player" : "players"}.`,
() => HoldemState.recordStartingBuyIns(state));
});
document.getElementById("waitingListForm").addEventListener("submit", e => {
e.preventDefault();
const field = document.getElementById("waitingNameInput");
const name = field.value.trim();
if (!name) return;
field.value = "";
runUndoable(`${name} added to the waiting list.`, () => HoldemState.addToWaitingList(state, name));
field.focus();
});
document.getElementById("misdealBtn").addEventListener("click", async () => {
const inPlay = HoldemState.unresolvedContributions(state);
const acted = state.seats.filter(p => p.hasActed).length;
const ok = await Dialog.confirm({
title: "Misdeal — take the hand back?",
message: inPlay > Betting.EPSILON_CHIPS
? `${Money.format(inPlay)} goes back to the players who put it in, cards are cleared, and the same ` +
`button deals again.${acted > 1 ? " Note that most rooms let a deal stand once two players have acted." : ""}`
: "Cards are cleared and the same button deals again. Nothing has been put in yet, so no chips move.",
confirmLabel: "Take it back",
});
if (!ok) return;
// The label is both the toast a dealer reads now and the words on the undo
// control afterwards, so it says what happened to the money rather than naming
// the ruling: "the misdeal" told a table nothing about where their chips went.
const label = inPlay > Betting.EPSILON_CHIPS
? `Misdeal — ${Money.format(inPlay)} returned, same button deals again.`
: "Misdeal — nothing was in yet, same button deals again.";
runUndoable(label, () => Betting.takeHandBack(state));
});
document.getElementById("nextHandBtn").addEventListener("click", async () => {
// Moving on wipes every seat's contribution, so an unresolved pot is simply
// destroyed — measured at a four-handed table, pressing this with $8 in the
@@ -462,6 +630,25 @@ document.addEventListener("DOMContentLoaded", () => {
});
});
// The house's cut. Kept as a group rather than three loose fields, because
// migrate() guarantees the shape and half a rake object would be a table nobody
// could read back.
const readRake = () => {
const percent = Number(document.getElementById("rakePercentInput").value);
const cap = Number(document.getElementById("rakeCapInput").value);
state.rake = {
percent: Number.isFinite(percent) ? Math.min(100, Math.max(0, percent)) : 0,
cap: Number.isFinite(cap) && cap > 0 ? Money.round(cap) : null,
noFlopNoDrop: document.getElementById("rakeNoFlopInput").checked,
};
hooks.save(state);
Render.renderAll();
};
["rakePercentInput", "rakeCapInput"].forEach(id => {
document.getElementById(id).addEventListener("input", readRake);
});
document.getElementById("rakeNoFlopInput").addEventListener("change", readRake);
document.getElementById("closeSeatEditorBtn").addEventListener("click", () => Render.closeSeatEditor());
document.getElementById("addChipsConfirmBtn").addEventListener("click", () => AddChips.confirm());
@@ -695,4 +882,51 @@ document.addEventListener("DOMContentLoaded", () => {
"The saved table couldn't be read, so this one started empty.",
{ duration: 12000 });
}
// ---- Working with no signal ----
//
// The night already survives anything — it lives in localStorage — but the page
// did not. Reload in a back room with one bar of signal and a dealer with nine
// players waiting got a browser error page. The worker below keeps the tool itself
// on the phone; see wwwroot/casino/sw.js for what it does and doesn't cache.
//
// The list of files to keep is read off this document rather than written down in
// the worker. Every stylesheet and script the page actually loaded is right here in
// the DOM, already carrying the ?v= release string from _Layout — so the list
// cannot drift from the markup, which is the way a hand-kept one always fails: it
// stays right until somebody adds a script tag, and then the tool is quietly
// offline-broken until a dealer finds out the hard way.
const registerWorker = () => {
if (!("serviceWorker" in navigator)) return;
const shell = [
location.pathname,
"/casino/holdem.webmanifest",
...[...document.querySelectorAll('link[rel="stylesheet"][href]')].map(el => el.href),
...[...document.querySelectorAll("script[src]")].map(el => el.src),
].filter(url => new URL(url, location.origin).origin === location.origin);
navigator.serviceWorker.register("/casino/sw.js", { scope: "/casino/" })
.then(reg => {
// The worker that will answer for this page — `controller` is still null
// on the very first visit, before activate has claimed it.
const worker = reg.active || navigator.serviceWorker.controller;
if (worker) {
worker.postMessage({ type: "precache", urls: shell });
return;
}
navigator.serviceWorker.ready.then(ready => {
if (ready.active) ready.active.postMessage({ type: "precache", urls: shell });
});
})
.catch(() => {
// No worker means no offline, and nothing else. Every other part of the
// tool works exactly as it did, so this is not worth a toast at a table.
});
};
// After load, not during it: registering competes with the page's own scripts for
// the network, and the first paint matters more than the second visit does.
if (document.readyState === "complete") registerWorker();
else window.addEventListener("load", registerWorker, { once: true });
});
@@ -86,6 +86,21 @@ const Money = {
return this.fromCents(Math.ceil(cents / step) * step);
},
// And down, for money coming *out* of a pot rather than going into it.
//
// The rake is the one amount in this tool that leaves the table, so the direction
// of the rounding is a decision about whose money it is. Down: a house that can't
// make 40c out of its chips takes nothing rather than a dollar, and the players
// keep the difference. Being wrong in the players' favour is the only way to be
// wrong about this that nobody has to argue about.
downToChip(amount, legend) {
const step = this.chipStepCents(legend);
if (step <= 0) return this.round(amount);
const cents = this.toCents(amount);
if (cents <= 0) return 0;
return this.fromCents(Math.floor(cents / step) * step);
},
chipBreakdown(amount, legend) {
let cents = this.toCents(amount);
if (cents <= 0) return { chips: [], remainder: 0 };
@@ -76,6 +76,39 @@ const PotWizard = {
},
renderStep() {
this.renderStepInto();
this.markOverflow();
},
// Say when the list runs on past the bottom of the dialog.
//
// The body scrolls and the footer stays put, which is the right shape and was as far
// as it went: nothing on screen said there was anything below. Measured on a Galaxy
// S8, a three-way pot showed two names and cut the third off on a row boundary, just
// under a hairline that reads as the end of the list. A dealer would have ticked the
// two they could see. On the dialog that pays the table, a list that silently
// continues is not a small thing.
markOverflow() {
const body = document.getElementById("potWizardBody");
const modal = document.getElementById("potWizardModal");
if (!body || !modal) return;
const update = () => {
const below = body.scrollHeight - body.clientHeight - body.scrollTop;
modal.classList.toggle("potWizardMoreBelow", below > 1);
};
if (!this.watchingOverflow) {
body.addEventListener("scroll", update, { passive: true });
window.addEventListener("resize", update);
this.watchingOverflow = true;
}
update();
// Again once the browser has laid the step out — on the first open the body has
// no height yet, and an answer taken then is always "nothing below".
requestAnimationFrame(update);
},
renderStepInto() {
// Auto-resolve any round where only one player is left standing — nothing to ask.
let contenders = PotCalculator.getContenders(this.entries);
while (contenders.length === 1) {
@@ -87,6 +120,11 @@ const PotWizard = {
const body = document.getElementById("potWizardBody");
body.innerHTML = "";
// The footer is a sibling of the body, outside the scroll — see the note in
// TexasHoldem.cshtml. Cleared alongside it so a step can never inherit the
// previous step's buttons.
const footer = this.footer();
footer.innerHTML = "";
if (this.log.length === 0) body.appendChild(this.renderBreakdown());
body.appendChild(this.renderLog());
@@ -119,13 +157,25 @@ const PotWizard = {
const round = document.createElement("div");
round.className = "potWizardRound";
const showdown = this.readShowdown(contenders);
const decided = showdown && showdown.complete ? new Set(showdown.winners) : null;
const handById = new Map((showdown ? showdown.players : []).map(p => [p.id, p.hand]));
const prompt = document.createElement("p");
prompt.className = "potWizardPrompt";
prompt.innerHTML = this.log.length === 0
? `Who won the hand? <strong>${Money.format(remaining)}</strong> is in play.`
: `That side pot still leaves <strong>${Money.format(remaining)}</strong> unassigned — who's next best?`;
prompt.innerHTML = decided
// It has read the hands, so it stops asking a question it knows the answer
// to. The list stays — the dealer confirms, and a hand entered wrong is
// corrected by unticking rather than by starting over.
? `<strong>${Money.format(remaining)}</strong> in play.`
: this.log.length === 0
? `Who won the hand? <strong>${Money.format(remaining)}</strong> is in play.`
: `That side pot still leaves <strong>${Money.format(remaining)}</strong> unassigned — who's next best?`;
round.appendChild(prompt);
const verdict = this.renderVerdict(showdown, contenders);
if (verdict) round.appendChild(verdict);
const choices = document.createElement("div");
choices.className = "potWizardChoices";
contenders.forEach(c => {
@@ -135,6 +185,10 @@ const PotWizard = {
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = c.id;
if (decided && decided.has(c.id)) {
checkbox.checked = true;
label.classList.add("chosen");
}
// The row is the target, not the box — so the row has to look chosen too.
checkbox.addEventListener("change", () => {
label.classList.toggle("chosen", checkbox.checked);
@@ -149,11 +203,25 @@ const PotWizard = {
name.textContent = this.nameById.get(c.id);
text.appendChild(name);
// How this hand was read, under the name — on every row rather than only
// the winning one, because a dealer checking the tool's answer is reading
// the losers' hands, and a row that says nothing is a row they have to work
// out for themselves. It takes the line the ceiling used to have; the
// ceiling moves out beside the name, which is where the phone layout had
// already put it to save exactly this line.
const read = handById.get(c.id);
if (read) {
const ranked = document.createElement("span");
ranked.className = "potWizardChoiceHand";
ranked.textContent = HandRank.describe(read);
text.appendChild(ranked);
}
label.appendChild(text);
const upTo = document.createElement("span");
upTo.className = "potWizardChoiceUpTo";
upTo.textContent = `up to ${Money.format(c.remaining)}`;
text.appendChild(upTo);
label.appendChild(text);
label.appendChild(upTo);
// Cards sit apart from the name rather than inside it, so a dealer reading
// a row across the table sees the hand, not a sentence.
@@ -182,7 +250,11 @@ const PotWizard = {
const confirmBtn = document.createElement("button");
confirmBtn.className = "holdemBtn holdemBtnAccent";
confirmBtn.textContent = "Confirm Winner(s)";
confirmBtn.textContent = decided
? (showdown.winners.length === 1
? `Pay ${this.nameById.get(showdown.winners[0])}`
: "Split the pot")
: "Confirm Winner(s)";
confirmBtn.addEventListener("click", () => {
const selected = Array.from(choices.querySelectorAll("input:checked")).map(i => i.value);
if (selected.length === 0) return;
@@ -191,9 +263,91 @@ const PotWizard = {
this.entries = result.updatedEntries;
this.renderStep();
});
round.appendChild(confirmBtn);
body.appendChild(round);
footer.appendChild(confirmBtn);
},
// How the tool reads the hands still in for this round of the pot.
//
// Asked per round rather than once for the whole hand, because a side pot has its
// own contenders: the player who won the main pot is out of the question for the
// next one, and the best hand among who is left is a different answer.
//
// Only when the dealer asked to track the board — everything here is off by default
// and the wizard behaves exactly as it always has.
readShowdown(contenders) {
if (!this.state.trackBoard || typeof HandRank === "undefined") return null;
return HandRank.showdown(this.state.board, contenders.map(c => ({
id: c.id,
cards: this.cardsById.get(c.id) || [],
})));
},
// What the winners would actually be paid if this round were confirmed now.
//
// Worked out from the same function that does the paying rather than from a second
// one that agrees with it today — a preview that can drift from the payout is worse
// than no preview, because it is the number the dealer says out loud.
previewPayout(winnerIds) {
try {
const result = PotCalculator.resolveRound(this.entries, this.orderFromButton(winnerIds));
return result.perWinner || [];
} catch {
return [];
}
},
// "Alexandra wins $25 with a full house, kings full of threes."
//
// The whole point of the feature, in one line: who won and how much. It goes above
// the list rather than replacing it, because the dealer still confirms — the tool
// reads the cards, a person still says the pot is good.
renderVerdict(showdown, contenders) {
if (!showdown) return null;
const line = document.createElement("p");
line.className = "potWizardVerdict";
if (!showdown.boardComplete) {
line.classList.add("potWizardVerdictUnsure");
line.textContent = "The board isn't all five cards yet, so pick the winner yourself — or fill it in on the felt and this will read it.";
return line;
}
if (showdown.duplicated) {
line.classList.add("potWizardVerdictUnsure");
line.textContent = "The same card is in two places, so this can't be read. Check the cards on the felt.";
return line;
}
if (!showdown.complete) {
const missing = showdown.unknown.map(id => this.nameById.get(id)).filter(Boolean);
line.classList.add("potWizardVerdictUnsure");
line.textContent = missing.length
? `${this.listOf(missing)} ${missing.length === 1 ? "hasn't" : "haven't"} turned over, so who won is still yours to say.`
: "Not enough cards to read this one.";
return line;
}
const paid = this.previewPayout(showdown.winners);
const amount = paid.length ? Money.format(paid[0].amount) : "";
const names = showdown.winners.map(id => this.nameById.get(id)).filter(Boolean);
const hand = showdown.players.find(p => p.id === showdown.winners[0]);
const described = HandRank.phrase(hand && hand.hand);
line.classList.add("potWizardVerdictSure");
line.textContent = names.length === 1
? `${names[0]} wins ${amount} with ${described}.`
: `${this.listOf(names)} split it, ${amount} each, with ${described}.`;
return line;
},
listOf(names) {
if (names.length <= 1) return names[0] || "";
return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
},
// The row of buttons that never scrolls away.
footer() {
return document.getElementById("potWizardFooter");
},
recordRound(result) {
@@ -232,6 +386,24 @@ const PotWizard = {
return wrap;
},
// What the house takes out of this pot, and what is left to push.
//
// Worked out here rather than at the end so the dealer sees it before anything
// moves: the summary is the last chance to disagree with the arithmetic, and a
// rake that only appeared in the hand log afterwards would be the tool taking
// money quietly.
rakeSplit() {
const gross = Array.from(this.totals.entries()).map(([id, amount]) => ({
id,
label: this.playerLabelById.get(id),
amount,
}));
const pot = gross.reduce((sum, p) => sum + p.amount, 0);
const sawFlop = (this.state.street || "preflop") !== "preflop";
const rake = HoldemState.rakeOn(this.state, pot, sawFlop);
return { pot, sawFlop, ...HoldemState.applyRake(gross, rake) };
},
renderSummary() {
const wrap = document.createElement("div");
wrap.className = "potWizardSummary";
@@ -240,6 +412,20 @@ const PotWizard = {
heading.textContent = "Final Payouts";
wrap.appendChild(heading);
const split = this.rakeSplit();
const rakeSet = Number((this.state.rake || {}).percent) > 0;
if (rakeSet && this.totals.size > 0) {
const line = document.createElement("p");
line.className = "potWizardRake";
const cap = Number(this.state.rake.cap) > 0 ? `, capped at ${Money.format(this.state.rake.cap)}` : "";
line.textContent = split.rake > 0
? `House takes ${Money.format(split.rake)} of ${Money.format(split.pot)} — ${this.state.rake.percent}%${cap}.`
: split.sawFlop
? `No rake on this one — ${this.state.rake.percent}% of ${Money.format(split.pot)} doesn't make a chip the table has.`
: "No flop, no drop — nothing taken from a pot that ended before the flop.";
wrap.appendChild(line);
}
if (this.totals.size === 0) {
const empty = document.createElement("p");
empty.className = "fieldHint";
@@ -248,7 +434,7 @@ const PotWizard = {
} else {
const legend = (this.state && this.state.chipLegend) || [];
const list = document.createElement("ul");
for (const [id, amount] of this.totals.entries()) {
for (const { id, amount } of split.payouts) {
const li = document.createElement("li");
li.textContent = `${this.playerLabelById.get(id)} — ${Money.format(amount)}`;
@@ -275,13 +461,12 @@ const PotWizard = {
applyBtn.className = "holdemBtn holdemBtnAccent";
applyBtn.textContent = "Start Next Hand";
applyBtn.addEventListener("click", () => {
const payouts = Array.from(this.totals.entries()).map(([id, amount]) => ({
id,
label: this.playerLabelById.get(id),
amount,
}));
// Recomputed rather than reused from the render: the same numbers, but
// taken at the moment the dealer commits rather than when they last
// looked at the screen.
const paid = this.rakeSplit();
this.close();
this.onFinished(payouts);
this.onFinished(paid.payouts, { rake: paid.rake, pot: paid.pot });
});
actions.appendChild(applyBtn);
@@ -300,12 +485,10 @@ const PotWizard = {
const note = document.createElement("p");
note.className = "fieldHint potWizardPendingNote";
note.textContent = "Nothing has been paid out yet. Start Next Hand pushes the pot and logs the hand.";
wrap.appendChild(actions);
wrap.appendChild(note);
return wrap;
}
wrap.appendChild(actions);
this.footer().appendChild(actions);
return wrap;
},
};
File diff suppressed because it is too large Load Diff
@@ -47,6 +47,27 @@ const SeatMenu = {
run: () => this.hooks.toggleDealtIn(index),
});
// An empty chair with people waiting: the dealer taps the chair somebody is
// about to sit in, which is what their hand is doing anyway. Only the front of
// the queue is offered, for the same reason the panel only offers them — a list
// that isn't kept in order is just a pile of names.
const waiting = (this.state.waitingList || [])[0];
const emptyChair = !HoldemState.seatInPlay(player);
if (waiting && emptyChair) {
actions.push({
label: `Seat ${waiting.name}`,
className: "menuAccent",
run: () => this.hooks.seatWaiting(waiting.id, index),
});
}
// Leaving for the night, which is a different thing from sitting out a hand:
// the chips go back over the rail and the chair opens. Offered only for a seat
// that has somebody in it, since an empty chair has nobody to pay.
if (HoldemState.seatInPlay(player)) {
actions.push({ label: "Cash out…", run: () => this.hooks.cashOut(index) });
}
if (!this.state.dedicatedDealer && index !== this.state.dealerSeatIndex) {
actions.push({ label: "Give the button", run: () => this.hooks.makeDealer(index) });
}
+379 -8
View File
@@ -58,6 +58,14 @@ const HoldemState = {
bigBlind: 2,
defaultStack: null,
street: "preflop",
// The community cards, in the order they hit the felt: three, then one,
// then one. Empty strings for the ones that haven't been turned yet, the
// same way a seat's two hole cards are stored.
board: ["", "", "", "", ""],
// Whether the dealer wants to be asked for them at all. Off is the tool as
// it has always been: no board on the felt, and the pot wizard asks who
// won. On, it reads the showdown and answers that question itself.
trackBoard: false,
currentBet: 0,
lastRaiseSize: 0,
actingSeatIndex: null,
@@ -104,6 +112,21 @@ const HoldemState = {
// announced hand by hand, so this is cleared with every other one-deal
// decision rather than standing until somebody turns it off.
straddleCount: 0,
// What the house takes, if it takes anything. Percent zero is a game that
// doesn't rake, which is nearly all of them and the default.
rake: { percent: 0, cap: null, noFlopNoDrop: true },
// What it has taken so far tonight. A session total, not a per-hand one:
// it is the number the box is checked against at the end.
rakeTaken: 0,
// People who have taken their chips and gone. Kept for the night rather
// than forgotten with the seat: the box took their cash and paid it back
// out, and both halves have to stay on the record or the bank check reads
// as a shortfall for the rest of the evening.
cashedOut: [],
// People standing behind the chairs. A dealer at a full table keeps this
// list on a napkin; keeping it here means the tool can offer the next seat
// that opens to whoever has been waiting longest.
waitingList: [],
// Which seats actually put a straddle out when the hand was dealt, so the
// felt can badge them. Read off the deal rather than worked out again
// later, the same way the posted blinds are.
@@ -201,6 +224,11 @@ const HoldemState = {
// A table saved before the dead button existed has neither flag. False is
// the right guess for both: it means the rotation carries on the ordinary
// way, which is what that table was already doing.
// A table saved before the board existed has no board and was not tracking
// one. Off is also the right guess for a dealer who never asked for it.
parsed.trackBoard = parsed.trackBoard === true;
parsed.board = this.normaliseBoard(parsed.board);
parsed.deadButton = parsed.deadButton === true;
parsed.deadSmallBlind = parsed.deadSmallBlind === true;
// An old save has no record of who was dealt last hand. Empty is the
@@ -213,6 +241,36 @@ const HoldemState = {
// whatever is in front of those players is already in their committed
// chips, and nothing is owed on top of it.
if (!(Number(parsed.straddleCount) > 0)) parsed.straddleCount = 0;
// A table saved before the house took anything takes nothing, which is
// also the right answer for one that never will.
const rake = parsed.rake && typeof parsed.rake === "object" ? parsed.rake : {};
parsed.rake = {
percent: Math.min(100, Math.max(0, Number(rake.percent) || 0)),
cap: Number(rake.cap) > 0 ? Money.round(Number(rake.cap)) : null,
noFlopNoDrop: rake.noFlopNoDrop !== false,
};
parsed.rakeTaken = Math.max(0, Money.round(Number(parsed.rakeTaken) || 0));
parsed.waitingList = Array.isArray(parsed.waitingList)
? parsed.waitingList
.map(row => (typeof row === "string" ? { id: null, name: row } : row))
.filter(row => row && String(row.name || "").trim())
.map(row => ({
id: row.id || this.makeId("waiting"),
name: String(row.name).trim().slice(0, 24),
addedAt: Number(row.addedAt) || 0,
}))
: [];
parsed.cashedOut = Array.isArray(parsed.cashedOut)
? parsed.cashedOut
.filter(row => row && row.id)
.map(row => ({
id: row.id,
name: String(row.name || "").slice(0, 40),
buyIns: Math.max(0, Money.round(Number(row.buyIns) || 0)),
chips: Math.max(0, Money.round(Number(row.chips) || 0)),
at: Number(row.at) || 0,
}))
: [];
if (!Array.isArray(parsed.postedStraddles)) parsed.postedStraddles = [];
// A table saved before dealing and betting were separate has no flag, and
@@ -660,6 +718,7 @@ const HoldemState = {
// that stayed on would take chips off somebody who never said the word.
state.straddleCount = 0;
state.postedStraddles = [];
this.clearBoard(state);
state.seats.forEach(p => {
p.folded = false;
p.cards = ["", ""];
@@ -672,6 +731,21 @@ const HoldemState = {
this.ensureButtonOnPlayer(state);
},
// Exactly five slots of either a two-character card or an empty string, whatever
// arrived. A board read off a file is the one that has been somewhere this tool
// cannot see.
normaliseBoard(board) {
const source = Array.isArray(board) ? board : [];
return Array.from({ length: 5 }, (_, i) => {
const card = typeof source[i] === "string" ? source[i].trim().toUpperCase() : "";
return /^[23456789TJQKA][SHDC]$/.test(card) ? card : "";
});
},
clearBoard(state) {
state.board = ["", "", "", "", ""];
},
// Appends a resolved-pot record to the running session log a dealer can point to
// for chip-count disputes, then advances the hand counter. `payouts` is
// [{ id, label, amount }, ...] — who got paid what out of this hand's pot(s).
@@ -679,11 +753,15 @@ const HoldemState = {
// Must be called before startNextHand() clears the seats: the per-player `ledger`
// it stores alongside the payouts is what session standings are summed from later,
// and it needs this hand's contributions while they're still on the table.
recordHand(state, payouts) {
recordHand(state, payouts, rake = 0) {
if (typeof state.handNumber !== "number") state.handNumber = 1;
if (!Array.isArray(state.handHistory)) state.handHistory = [];
const pot = payouts.reduce((sum, p) => sum + p.amount, 0);
// The pot as it was, house cut included — the number the table saw in the
// middle. What each player took is separately recorded and is net of it, so
// the two together say where every chip went.
const taken = Money.round(Math.max(0, Number(rake) || 0));
const pot = Money.round(payouts.reduce((sum, p) => sum + p.amount, 0) + taken);
const wonById = new Map(payouts.map(p => [p.id, p.amount]));
const ledger = state.seats
.map((player, index) => ({
@@ -698,6 +776,7 @@ const HoldemState = {
handNumber: state.handNumber,
timestamp: Date.now(),
pot,
rake: taken,
payouts,
ledger,
});
@@ -733,6 +812,15 @@ const HoldemState = {
// Cash bought in and chips currently in front don't come from the hand log at
// all, so they're read off the seat rather than summed — a rebuy isn't a hand.
const seatById = new Map(state.seats.map(p => [p.id, p]));
// And for anyone who has gone home, off the record their cash-out left behind.
// Without this they read as a player who bought in for nothing and is holding
// nothing, in the very list the dealer settles the night from.
const goneById = new Map((state.cashedOut || []).map(row => [row.id, row]));
goneById.forEach((row, id) => {
if (totals.has(id)) return;
totals.set(id, { id, name: row.name, in: 0, won: 0 });
});
// Anyone who has money in the game belongs in the settle-up, whether or not
// they've been in a logged hand yet. Building the list from the hand log alone
@@ -744,7 +832,7 @@ const HoldemState = {
if (totals.has(player.id)) return;
const hasMoneyInPlay =
(Number(player.buyIns) || 0) > 0 ||
(Number(player.stack) || 0) > 0 ||
this.chipsHeldBy(state, player) > 0 ||
(Number(player.amountOverride) || 0) > 0 ||
(Number(player.committed) || 0) > 0;
if (!hasMoneyInPlay) return;
@@ -754,8 +842,16 @@ const HoldemState = {
return Array.from(totals.values())
.map(t => {
const seat = seatById.get(t.id);
const boughtIn = seat ? Money.round(Number(seat.buyIns) || 0) : 0;
const chipsNow = seat ? Money.round(Number(seat.stack) || 0) : 0;
const gone = goneById.get(t.id);
const boughtIn = seat
? Money.round(Number(seat.buyIns) || 0)
: (gone ? gone.buyIns : 0);
// What a departed player is "holding" is what the box handed them on
// the way out. It is no longer on the table, so it is marked as paid
// rather than counted again at the end of the night.
const chipsNow = seat
? this.chipsHeldBy(state, seat)
: (gone ? gone.chips : 0);
// Chips already pushed into the hand in progress are still this
// player's money until it's won. Leaving them out makes the cash
// position disagree with the hand log for as long as a hand is open —
@@ -786,6 +882,10 @@ const HoldemState = {
// a $340 stack read as "$140" at the exact moment cash changed
// hands.
chipsInFront: Money.round(chipsNow + inFrontOfThem),
// Set once they have taken their chips and left, so the panel and
// the export can say so rather than showing a player still sitting
// there with a stack.
cashedOut: !!gone && !seat,
cashPosition: Money.round(chipsNow + inFrontOfThem - boughtIn),
notes,
};
@@ -818,12 +918,273 @@ const HoldemState = {
//
// Chips in play counts everything a player could hand back: what's in front of
// them and what's in the middle waiting to be won.
// ---- The people standing behind the chairs ----
//
// A full home game always has a couple of them, and the list lives on a napkin or
// in the dealer's head — which is where the argument comes from an hour later about
// who said they were next. Kept in order of arrival, because that is the only
// ordering anybody has ever agreed to.
addToWaitingList(state, name) {
const trimmed = String(name || "").trim().slice(0, 24);
if (!trimmed) return null;
if (!Array.isArray(state.waitingList)) state.waitingList = [];
const entry = { id: this.makeId("waiting"), name: trimmed, addedAt: Date.now() };
state.waitingList.push(entry);
return entry;
},
removeFromWaitingList(state, id) {
if (!Array.isArray(state.waitingList)) return null;
const index = state.waitingList.findIndex(row => row.id === id);
if (index < 0) return null;
return state.waitingList.splice(index, 1)[0];
},
// Chairs with nobody in them, in seat order. What "a seat has opened" means, and
// the same question the deal prompt answers when it counts the players.
openSeats(state) {
return state.seats
.map((player, index) => ({ player, index }))
.filter(({ player }) => !this.seatInPlay(player))
.map(({ index }) => index);
},
// Sit the next person down. Their name goes on the chair and nothing else does:
// they haven't bought in yet, and guessing a stack for them would put chips on the
// table that nobody has paid for — which is the one thing the bank check exists to
// catch.
seatFromWaitingList(state, id, index) {
const seat = state.seats[index];
if (!seat) return { ok: false, reason: "There's no such seat." };
if (this.seatInPlay(seat)) {
return { ok: false, reason: `${this.displayName(seat, index)} is already in that seat.` };
}
const entry = this.removeFromWaitingList(state, id);
if (!entry) return { ok: false, reason: "They aren't on the list any more." };
seat.name = entry.name;
// Not dealt in and holding nothing: the next thing that happens is the dealer
// taking their money, and Add chips is what says so.
seat.inHand = false;
return { ok: true, name: entry.name, index };
},
// ---- Somebody leaving with their chips ----
//
// The most ordinary thing that happens at a home game after midnight, and the tool
// had nothing for it. A dealer's only way to free the chair was to wipe the seat by
// hand, and then the bank check — which adds up cash taken against chips on the
// table — declared the departing player's whole stack missing: "someone has paid
// for chips they haven't been given", for the rest of the night. Wiping their
// buy-in as well silenced it, at the price of losing their night from the standings
// and the file the dealer hands over.
//
// Cashing out is two facts, and both have to survive the empty chair: the box took
// their cash, and the box paid their chips back out.
// Can this seat be cashed out right now?
canCashOut(state, index) {
const player = state.seats[index];
if (!player) return { ok: false, reason: "There's nobody in that seat." };
const inPot = Money.round((Number(player.committed) || 0) + (Number(player.amountOverride) || 0));
if (inPot > 0) {
return {
ok: false,
// Paying someone out with money still in the middle would either take
// chips out of a pot other people can win, or hand them chips twice.
reason: `${this.displayName(player, index)} has ${Money.format(inPot)} in the pot. Finish the hand first.`,
};
}
return { ok: true };
},
// What the dealer counts out, and what the seat's night comes to.
cashOutPreview(state, index) {
const player = state.seats[index];
if (!player) return null;
// Betting owns the answer to "what is this seat holding" — including the rule
// that a seat which has never been given a stack is holding the table's
// starting one. Asking it rather than working it out again here: the first
// draft of this did, read `Number(null)` as a perfectly good zero, and offered
// to pay a player nothing.
const chips = Money.round(Math.max(0, Betting.stackOf(state, player)));
const boughtIn = Money.round(Math.max(0, Number(player.buyIns) || 0));
return {
index,
name: this.displayName(player, index),
chips,
boughtIn,
// Their result for the night, in the direction a banker says it: positive
// means the box is paying out more than it took from them.
net: Money.round(chips - boughtIn),
breakdown: Money.formatChipBreakdown(chips, state.chipLegend),
};
},
// Hand them their chips and free the chair, keeping both halves on the record.
cashOut(state, index) {
const allowed = this.canCashOut(state, index);
if (!allowed.ok) return allowed;
const preview = this.cashOutPreview(state, index);
const leavingId = state.seats[index].id;
if (!Array.isArray(state.cashedOut)) state.cashedOut = [];
state.cashedOut.push({
id: leavingId,
name: preview.name,
buyIns: preview.boughtIn,
chips: preview.chips,
at: Date.now(),
});
// The chair opens for the next player. A fresh id, because the person who had
// it has gone and their night is now filed under the old one — reusing it would
// merge two people's results the moment somebody new sits down.
const seat = this.makePlayer();
state.seats[index] = seat;
// Anyone owed a hand by this seat is no longer owed one.
state.postingIn = (state.postingIn || []).filter(id => id !== leavingId);
return { ok: true, ...preview };
},
// ---- The house's cut ----
//
// A game that takes a rake or a time charge has chips leaving the table every hand,
// and until now the bank check called them missing: it added up the buy-ins,
// added up the chips on the felt, and told the dealer somebody had been paid for
// chips they never got. The house's cut is the one thing on this table that is
// supposed to go and not come back, so it is counted rather than mourned.
//
// Percentage with a cap, which is what nearly every room and home game runs. Zero
// percent is a game that doesn't rake, which is the default and the common case.
// What the house takes from a pot of this size.
//
// "No flop, no drop" is the rule almost everyone plays: a hand that ends before the
// flop pays nothing, because the players never got a hand out of it. It is on by
// default and can be turned off for a house that rakes every pot.
rakeOn(state, pot, sawFlop = true) {
const rake = state.rake || {};
const percent = Number(rake.percent) || 0;
const amount = Money.round(Number(pot) || 0);
if (percent <= 0 || amount <= 0) return 0;
if (rake.noFlopNoDrop !== false && !sawFlop) return 0;
const uncapped = (amount * percent) / 100;
const cap = Number(rake.cap);
const capped = cap > 0 ? Math.min(uncapped, cap) : uncapped;
// Never more than the pot, however the numbers were typed in.
return Money.downToChip(Math.min(capped, amount), state.chipLegend);
},
// The same payouts with the house's cut taken out of them.
//
// Off the top of the whole pot, then shared out in proportion — which for the hand
// a dealer actually deals, with one winner, is just "winner gets the pot less the
// rake". Split pots take it proportionally, and whatever the rounding leaves over
// goes back to the winners in turn rather than to the house: the house asked for a
// number, and it gets that number, not that number plus dust.
applyRake(payouts, rake) {
const total = payouts.reduce((sum, p) => sum + p.amount, 0);
const taken = Money.round(Math.min(Math.max(0, rake), total));
if (taken <= 0) return { payouts: payouts.map(p => ({ ...p })), rake: 0 };
const kept = Money.toCents(total) - Money.toCents(taken);
const shares = payouts.map(p => {
const exact = (Money.toCents(p.amount) * kept) / Money.toCents(total);
return { payout: p, cents: Math.floor(exact) };
});
// Floor everybody, then hand the leftover cents out one at a time, biggest
// share first — the same shape as the odd-chip rule the split calculator uses.
let spare = kept - shares.reduce((sum, s) => sum + s.cents, 0);
[...shares]
.sort((a, b) => b.payout.amount - a.payout.amount)
.forEach(share => { if (spare > 0) { share.cents += 1; spare -= 1; } });
return {
payouts: shares.map(share => ({ ...share.payout, amount: Money.fromCents(share.cents) })),
rake: taken,
};
},
// Is anybody actually in this chair? A seat with a name on it, chips in front of
// it, cash against it or a hand dealt to it. Empty chairs are not players, which
// matters the moment the table's starting stack starts standing in for a seat that
// has never been given one — every empty chair would otherwise look like somebody
// holding two hundred dollars.
seatInPlay(player) {
if (!player) return false;
return !!(player.name || "").trim() ||
(Number(player.buyIns) || 0) > 0 ||
(Number(player.stack) || 0) > 0 ||
(Number(player.committed) || 0) > 0 ||
(Number(player.amountOverride) || 0) > 0 ||
player.inHand === true;
},
// What a seat is holding, the way the felt and the betting see it — which includes
// the table's starting stack standing in for a seat that has never been given one.
//
// This is the number the money side of the tool was missing. "Starting stack" is
// offered in the setup panel as the ordinary way to open a table, and everything a
// dealer looks at — the puck, the bar, what a player can bet — reads it. The bank
// check and the standings read `seat.stack` directly instead, which is null for
// exactly those seats: measured on a three-handed table with a $200 starting stack
// and nobody's own stack set, the felt played for $600 while the bank check said
// "no chips in play, balanced" and the standings listed nobody at all.
chipsHeldBy(state, player) {
if (!this.seatInPlay(player)) return 0;
return Math.max(0, Money.round(Betting.stackOf(state, player)));
},
// Seats playing with chips the box has no cash against.
//
// Two kinds, and they are not the same problem. A seat holding the table's starting
// stack has never been given chips of its own — the dealer set "everyone starts
// with 200" and sat people down, which is the ordinary way to open a table and the
// reason this whole gap existed. A seat with its own stack and no buy-in is a
// rebuy somebody forgot to write down, and only the dealer knows what it was.
seatsOwingCash(state) {
return state.seats
.map((player, index) => ({ player, index }))
.filter(({ player }) => this.chipsHeldBy(state, player) > 0 &&
!((Number(player.buyIns) || 0) > 0))
.map(({ player, index }) => ({
index,
name: this.displayName(player, index),
chips: this.chipsHeldBy(state, player),
// True when they are holding the table's starting stack rather than one
// the dealer typed for them.
fromStartingStack: player.stack === null || player.stack === undefined ||
String(player.stack).trim() === "",
}));
},
// Write down the cash for the seats that are holding the table's starting stack.
// Only those: what somebody else's unrecorded rebuy was is a question only the
// dealer can answer, and guessing it would be the tool inventing money.
recordStartingBuyIns(state) {
const owed = this.seatsOwingCash(state).filter(row => row.fromStartingStack);
owed.forEach(row => { state.seats[row.index].buyIns = row.chips; });
return {
seats: owed.length,
total: Money.round(owed.reduce((sum, row) => sum + row.chips, 0)),
};
},
bankReconciliation(state) {
const cashIn = state.seats.reduce((sum, p) => sum + Math.max(0, Number(p.buyIns) || 0), 0);
const gone = Array.isArray(state.cashedOut) ? state.cashedOut : [];
// Cash the box took from people who have since left counts as taken: it is in
// the box, and forgetting it with the seat is what used to make a cash-out read
// as a shortfall all night.
const cashIn = state.seats.reduce((sum, p) => sum + Math.max(0, Number(p.buyIns) || 0), 0) +
gone.reduce((sum, row) => sum + Math.max(0, Number(row.buyIns) || 0), 0);
const chipsInPlay = state.seats.reduce(
(sum, p) =>
sum +
Math.max(0, Number(p.stack) || 0) +
this.chipsHeldBy(state, p) +
Math.max(0, Number(p.committed) || 0) +
Math.max(0, Number(p.amountOverride) || 0),
0
@@ -837,11 +1198,21 @@ const HoldemState = {
// hunting for a miscount that never happened.
const discarded = Math.max(0, Money.round(Number(state.discarded) || 0));
const difference = Money.round(chipsInPlay + discarded - cashIn);
// Chips the house has taken. Off the table for good, like the discards, and
// for a better reason: the box is supposed to have them.
const raked = Math.max(0, Money.round(Number(state.rakeTaken) || 0));
// Chips handed back over the rail. Off the table like the other two, and the
// one the dealer can point at when somebody asks where the money went.
const paidOut = Money.round(gone.reduce((sum, row) => sum + Math.max(0, Number(row.chips) || 0), 0));
const difference = Money.round(chipsInPlay + discarded + raked + paidOut - cashIn);
return {
cashIn: Money.round(cashIn),
chipsInPlay: Money.round(chipsInPlay),
discarded,
raked,
paidOut,
difference,
// Half a cent of float dust isn't a discrepancy worth alarming anyone over.
balanced: Math.abs(difference) <= Money.EPSILON,
+68 -6
View File
@@ -20,6 +20,8 @@ other in the page, in the load order from `TexasHoldem.cshtml`.
| `betting.test.js` | Blinds, street completion, raises reopening the action, all-in run-outs |
| `state.test.js` | Button rotation, which seats post blinds, session standings |
| `splitCalculator.test.js` | Chopped pots, odd chips, unmakeable denominations |
| `handRank.test.js` | What beats what: categories, the wheel, kickers, best five of seven |
| `readingTheShowdown.test.js` | The board, the picker that fills it, and who wins a side pot |
| `invariants.test.js` | 1000 randomised hands per property (see below) |
## The layout audit
@@ -33,13 +35,56 @@ node tests/holdem/runUiAudit.js # needs Playwright and the site running
It checks WCAG AA contrast, touch target sizes, touch-action and tap highlights, that fields stay selectable and are large
enough not to trigger iOS zoom, that nothing important is covered or off-screen with
no way to scroll to it, that no grid column has collapsed to nothing, and that no
text is painted outside its box. It runs over the table, all five overlays and Quick
Split, at thirteen viewports from a 360px phone to a 1600px desktop and the same
phones on their side.
no way to scroll to it, that no grid column has collapsed to nothing, that no
text is painted outside its box, that no seat covers another seat's writing, and that
no bet chip is hidden behind a seat or another chip. It
runs over the table, all five overlays and Quick Split, at thirteen viewports from a
360px phone to a 1600px desktop and the same phones on their side — each viewport
twice, once with a mouse and once with a thumb, and at three table shapes, mid-hand:
the sweep posts blinds, deals and calls three times before it measures anything, so
the bets layer has chips on it. It used to audit a table nobody had ever bet at,
which is a third of what is on the felt during a hand left unlooked at.
Deliberately not in CI: the unit suite is dependency-free and runs in a second, while
this one needs a browser and a running site. Run it after any change that adds or
"Covered" and "out of view" are told apart before anything is hit-tested. An element
clipped away by a panel that scrolls is not covered by whatever happens to be painted
at that height, and reporting it that way is a diagnosis of something that isn't
happening: the pot wizard's third winner, below the fold in a list, came back for four
viewports running as "fully covered by button Confirm Winner(s)".
More than one table shape is also newer than it sounds. The sweep ran on one — five
players at a nine-handed table — for its whole life, and how much room the felt has
depends on how many people are sitting down far more than on anything a viewport can
report. A full table is where the seats crowd and it had never been looked at: the
first sweep that did found one player's name or stack painted under another on eighteen
of the configurations, on every phone in the list.
The third shape is the same five players with the board turned on and five cards on it.
It is deliberately the same roster in the same chairs as the second, so the only thing
that differs between the two rows is the board — a seventh player would have told us
that a seven-handed table crowds, which is true, already known, and not what that row
is there to find out. It earned its place immediately: the board takes the middle of
the felt, or a strip above it where the middle is too small, and the strip costs the
felt height. The seats follow a felt that changes size on their own, being placed in
percentages of it; the chips anchored inside them do not, being placed in pixels. They
were laid out for a felt 23px taller than the one they were painted on.
That last part, and two of those checks, are newer than this paragraph claiming them.
`runAll()` did not include the contrast check at all, and touch targets sat behind an
opt-in flag nothing passed, so "the audit is clean" meant nine checks rather than
eleven for a long run of rounds. Both were written and tested and simply never called.
The mouse/thumb pair matters for the same reason: the 44px rule stands itself down
where `hover: hover` says there is a pointer, and a headless desktop browser is a
pointer, so a single pass had never measured a touch target at any viewport. Between
them they found a 9px seat label at 3.39:1, a 37px-tall amount field and a 30px delete
button on Quick Split.
A check that decides it doesn't apply says so in the output rather than reporting no
offenders, which reads identically to a pass. The same goes for the two exemptions
that exist: a disabled control, which WCAG itself excuses, and a link inside a
sentence, whose size is set by the line it sits in.
Deliberately not in CI: the unit suite is dependency-free and runs in about five
seconds, while this one needs a browser and a running site. Run it after any change that adds or
resizes a control. With no Playwright to hand, paste `uiAudit.js` into devtools and
call `LayoutAudit.runAll()`.
@@ -62,6 +107,23 @@ something changed, and each time they only covered whatever had just been touche
That is how the standings table shipped with a player-name column zero pixels wide
and kept it for two rounds.
## Why the hand evaluator is tested the way it is
`handRank.js` is the only module here that can pay the wrong person without anybody
noticing. A pot wizard that asks "who won?" is never more wrong than the dealer ticking
the box; one that answers the question itself is wrong on its own account, silently,
and a table that has come to trust it will not check.
So besides the hand-written cases — every category against every other, the wheel, three
kickers deep, the counterfeited two pair, the board that plays — it is checked against a
second evaluator written a different way, on twenty thousand random seven-card hands and
four thousand random pairs of them. The second one is in the test file and shares no
helper with the module: it scores a hand by counting ranks into a sortable list rather
than by asking about shapes. That pass is most of the suite's running time and it is
worth it; three deliberately introduced bugs — an ace that keeps its value in the wheel,
a dropped two-pair kicker, a flush read only by its top card — are each caught by it as
well as by the cases written for them.
## Why the randomised suite exists
Every correctness bug found in this tool so far has been shape-dependent: blinds posted
+128
View File
@@ -0,0 +1,128 @@
// Saying who the blind is, before saying "cards".
//
// A dealer sets the table up out loud — button here, she's the small blind, he's the
// big blind — and only then deals. The seat menu offers "Make small blind" for exactly
// that, and it was answering by dealing the hand: betting opened, two stacks docked,
// the action bar up and waiting on the seat after the big blind. The dealer had said
// where the blinds go, and the tool heard "deal".
//
// The condition it was asking is `onlyBlindsIn`, which means "nothing has happened in
// this hand except the blinds" — true of a hand one second old, and equally true of a
// table in setup with no cards out and nothing committed. Those two need telling apart,
// which is what `blindsArePosted` is for.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Betting, HoldemState, makeTable, chipsOnTable } = require("./load");
describe("before the deal", () => {
test("the blinds are not down, however much the table looks ready", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3] });
assert.equal(state.bettingOpen, false);
// The old condition, on its own, says yes here — this is the whole bug.
assert.equal(Betting.onlyBlindsIn(state), true);
assert.equal(Betting.blindsArePosted(state), false);
});
test("a table straight out of setup, with nobody seated, is the same answer", () => {
assert.equal(Betting.blindsArePosted(HoldemState.createDefault()), false);
});
test("re-posting would have dealt the hand, which is why it is guarded", () => {
// Not a rule, a demonstration: repostBlinds ends in beginHand. Calling it in
// setup is the deal, and nothing about naming a blind should reach it.
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3] });
Betting.repostBlinds(state);
assert.equal(state.bettingOpen, true, "chips off two stacks and the action bar up");
assert.notEqual(state.actingSeatIndex, null);
});
test("naming a blind moves a badge and no chips", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3] });
const before = chipsOnTable(state);
// What the seat menu does: pin the override, repost only if the blinds are down.
state.blindOverride = { sbIndex: 3, bbIndex: 0 };
if (Betting.blindsArePosted(state)) Betting.repostBlinds(state);
assert.equal(state.bettingOpen, false, "still setup — the dealer hasn't dealt");
assert.equal(state.actingSeatIndex, null, "nobody is being asked to act");
assert.deepEqual(state.seats.map(p => Betting.committed(p)), [0, 0, 0, 0, 0, 0]);
assert.equal(chipsOnTable(state), before);
// And the badges say what the dealer just said.
const blinds = HoldemState.getBlindSeats(state);
assert.equal(blinds.sbIndex, 3);
assert.equal(blinds.bbIndex, 0);
});
test("and the hand that follows posts from where they were aimed", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], smallBlind: 1, bigBlind: 2 });
state.blindOverride = { sbIndex: 3, bbIndex: 0 };
if (Betting.blindsArePosted(state)) Betting.repostBlinds(state);
Betting.beginHand(state);
assert.equal(Betting.committed(state.seats[3]), 1);
assert.equal(Betting.committed(state.seats[0]), 2);
});
test("giving the button away is a marker moving too", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3] });
const before = chipsOnTable(state);
const willRepost = Betting.blindsArePosted(state);
state.dealerSeatIndex = 2;
if (willRepost) Betting.repostBlinds(state);
assert.equal(willRepost, false);
assert.equal(state.bettingOpen, false);
assert.equal(chipsOnTable(state), before);
});
});
describe("once the hand is dealt", () => {
test("the blinds are down, and re-aiming them moves real chips", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
const before = chipsOnTable(state);
Betting.beginHand(state);
assert.equal(Betting.blindsArePosted(state), true);
assert.equal(Betting.committed(state.seats[1]), 1);
state.blindOverride = { sbIndex: 3, bbIndex: 0 };
if (Betting.blindsArePosted(state)) Betting.repostBlinds(state);
assert.equal(Betting.committed(state.seats[1]), 0, "the old small blind got their chip back");
assert.equal(Betting.committed(state.seats[3]), 1);
assert.equal(Betting.committed(state.seats[0]), 2);
assert.equal(chipsOnTable(state), before, "no chips created or lost in the shuffle");
});
test("but not once somebody has answered them", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, state.actingSeatIndex);
assert.equal(Betting.blindsArePosted(state), false, "there is a call to unpick now");
});
test("nor on a later street", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
state.street = "flop";
assert.equal(Betting.blindsArePosted(state), false);
});
test("and a misdealt hand goes back to being a table in setup", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.takeHandBack(state);
assert.equal(Betting.blindsArePosted(state), false, "nothing is posted until the dealer deals again");
});
test("as does a hand that has been paid out", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.sweepToHandTotals(state);
HoldemState.startNextHand(state);
assert.equal(Betting.blindsArePosted(state), false);
});
});
+135
View File
@@ -0,0 +1,135 @@
// What the tool says out loud between taps.
//
// The action bar carried `aria-live="polite"` on the element whose entire contents
// render() rebuilds every action, so a screen reader read the whole bar after every
// single tap. Measured, after one:
//
// "PRE-FLOP Pot $15 9 players Bob · $250 behind 0:00 ↶ dealing the hand U
// Fold Call $10 Raise"
//
// Nothing in that is wrong. It is just unusable at the speed a hand is dealt, and it
// is the documented anti-pattern: a live region has to be a stable element whose text
// changes, not a container that gets replaced.
//
// What a dealer running this by ear needs is who is on the clock and what it costs
// them. These are the sentences.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { ActionBar, Betting, HoldemState, makeTable } = require("./load");
const barOn = (state) => {
ActionBar.state = state;
ActionBar.lastAnnouncement = undefined;
return ActionBar;
};
describe("before the cards are out", () => {
test("a table that could be dealt says so", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3] });
assert.equal(barOn(state).announcement(), "Ready to deal.");
});
test("and an empty table says what it is, rather than nothing", () => {
// This used to announce "" — silence being the honest answer when the bar was
// hidden on a table nobody was sitting at. The bar isn't hidden any more: an
// empty table is the one state a dealer meets before they know how any of this
// works, so it says so and offers the next step.
const state = HoldemState.createDefault();
assert.equal(barOn(state).announcement(), "Nobody's at the table yet.");
});
test("and a table with one named player has moved on from that", () => {
const state = HoldemState.createDefault();
state.seats[0].name = "Ann";
assert.notEqual(barOn(state).announcement(), "Nobody's at the table yet.");
});
});
describe("while a hand is running", () => {
const dealt = () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], smallBlind: 1, bigBlind: 2 });
state.seats.forEach((p, i) => { p.name = ["Ann", "Ben", "Cal", "Dee"][i] || ""; });
Betting.beginHand(state);
return state;
};
test("names who is on the clock, what it costs, and the pot", () => {
const state = dealt();
const said = barOn(state).announcement();
assert.match(said, /to act/);
assert.match(said, /\$2 to call/);
assert.match(said, /Pot \$3\./);
});
test("it is the seat that is actually acting, not the one after it", () => {
const state = dealt();
const name = HoldemState.displayName(state.seats[state.actingSeatIndex], state.actingSeatIndex);
assert.ok(barOn(state).announcement().startsWith(name + " to act"));
});
test("says checked to them rather than $0 to call", () => {
// A number nobody owes is a number a dealer has to stop and parse.
const state = dealt();
state.currentBet = 0;
assert.match(barOn(state).announcement(), /checked to them/);
assert.doesNotMatch(barOn(state).announcement(), /\$0 to call/);
});
test("a street with nobody left to act says the street is done", () => {
const state = dealt();
state.actingSeatIndex = null;
state.street = "flop";
assert.equal(barOn(state).announcement(), "Flop betting is done.");
});
test("and a finished hand points at the pot", () => {
const state = dealt();
state.seats.forEach((p, i) => { if (i !== 0) p.folded = true; });
assert.equal(Betting.isHandOver(state), true);
assert.equal(barOn(state).announcement(), "Hand over. Resolve the pot.");
});
});
describe("how often it speaks", () => {
// A live region that is handed the same sentence twice reads it out twice, and
// render() runs for a great many reasons that have nothing to do with whose turn
// it is — a resize, a panel opening, a note being typed.
const stubTarget = () => {
const el = { textContent: "" };
global.document = { getElementById: id => (id === "actionAnnouncer" ? el : null) };
return el;
};
test("says nothing new when nothing changed", () => {
const el = stubTarget();
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], smallBlind: 1, bigBlind: 2 });
Betting.beginHand(state);
const bar = barOn(state);
bar.announce();
const first = el.textContent;
assert.ok(first.length > 0);
el.textContent = "CLEARED"; // if announce() writes again, this comes back
bar.announce();
assert.equal(el.textContent, "CLEARED", "the same sentence was not written twice");
delete global.document;
});
test("but does when the action moves", () => {
const el = stubTarget();
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], smallBlind: 1, bigBlind: 2 });
Betting.beginHand(state);
const bar = barOn(state);
bar.announce();
const first = el.textContent;
Betting.call(state, state.actingSeatIndex);
bar.announce();
assert.notEqual(el.textContent, first);
assert.match(el.textContent, /to act/);
delete global.document;
});
});
+175
View File
@@ -0,0 +1,175 @@
// Chips the pot was priced with that nobody actually paid.
//
// There are two ways a contribution gets into this tool. Tapping the action moves
// chips: the bet leaves the stack, sits in front of the player, and is swept into their
// hand total at the end of the street. The other is the "without live betting" panel —
// a base pot amount, or chips counted out on a seat — where the dealer is recording a
// hand they are watching rather than driving, and nothing ever leaves a stack.
//
// The pot wizard prices both the same way and awarding it credits the winner, so in
// that second mode the table simply grew.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Money, Betting, HoldemState, chipsOnTable } = require("./load");
const basePotTable = (base = 50, stack = 200) => {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 4);
state.basePotAmount = base;
["Ann", "Ben", "Cal"].forEach((name, i) => {
state.seats[i].name = name;
state.seats[i].inHand = true;
state.seats[i].stack = stack;
state.seats[i].buyIns = stack;
});
return state;
};
const pricedPot = (state) => state.seats.reduce(
(sum, p) => sum + HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount), 0);
describe("what nobody paid", () => {
test("comes off the stacks that owe it", () => {
const state = basePotTable();
const collected = Betting.collectAssumedContributions(state);
assert.equal(collected.total, 150);
assert.deepEqual(collected.taken.map(row => row.name), ["Ann", "Ben", "Cal"]);
assert.deepEqual(state.seats.slice(0, 3).map(p => p.stack), [150, 150, 150]);
});
test("and lands where the rest of the tool looks for chips in the middle", () => {
const state = basePotTable();
Betting.collectAssumedContributions(state);
assert.deepEqual(state.seats.slice(0, 3).map(p => p.amountOverride), [50, 50, 50]);
assert.equal(HoldemState.unresolvedContributions(state), 150);
});
test("chips counted out on a seat are money too", () => {
const state = basePotTable(0);
state.seats[0].chipCounts = { red: 4 }; // four $5 chips
const collected = Betting.collectAssumedContributions(state);
assert.equal(collected.total, 20);
assert.equal(state.seats[0].stack, 180);
});
});
describe("what has already been paid", () => {
test("a live bet is left exactly alone", () => {
const state = basePotTable(0);
state.smallBlind = 5;
state.bigBlind = 10;
Betting.beginHand(state);
const before = state.seats.map(p => Betting.stackOf(state, p));
const collected = Betting.collectAssumedContributions(state);
assert.equal(collected.total, 0, "the blinds are already off their stacks");
assert.deepEqual(state.seats.map(p => Betting.stackOf(state, p)), before);
});
test("nor is a swept street taken a second time", () => {
const state = basePotTable(0);
state.smallBlind = 5;
state.bigBlind = 10;
Betting.beginHand(state);
Betting.sweepToHandTotals(state);
const before = state.seats.map(p => Betting.stackOf(state, p));
assert.equal(Betting.collectAssumedContributions(state).total, 0);
assert.deepEqual(state.seats.map(p => Betting.stackOf(state, p)), before);
});
test("a base pot on top of a live bet only collects the difference", () => {
// The base pot says "assume everyone is in for fifty". Somebody who has already
// put twenty in owes thirty of it, not fifty.
const state = basePotTable(50);
state.seats[0].committed = 20;
state.seats[0].stack = 180;
const collected = Betting.collectAssumedContributions(state);
const ann = collected.taken.find(row => row.name === "Ann");
assert.equal(ann.amount, 30);
assert.equal(state.seats[0].stack, 150, "fifty in the middle, either way");
});
});
describe("what it will not do", () => {
test("take more than a player is holding", () => {
const state = basePotTable(50);
state.seats[1].stack = 20;
Betting.collectAssumedContributions(state);
assert.equal(state.seats[1].stack, 0, "all of it, and no further");
assert.equal(state.seats[1].amountOverride, 20);
});
test("touch an empty chair", () => {
const state = basePotTable();
const before = { ...state.seats[3] };
Betting.collectAssumedContributions(state);
assert.equal(state.seats[3].stack, before.stack);
assert.equal(state.seats[3].amountOverride, before.amountOverride);
});
test("or a seat that isn't in the hand", () => {
// The base pot stands in for "everyone put the same in", and somebody sitting
// out did not.
const state = basePotTable();
state.seats[2].inHand = false;
const collected = Betting.collectAssumedContributions(state);
assert.deepEqual(collected.taken.map(row => row.name), ["Ann", "Ben"]);
assert.equal(state.seats[2].stack, 200);
});
});
describe("the whole hand", () => {
test("conserves the chips on the table, which it did not before", () => {
const state = basePotTable();
const total = chipsOnTable(state);
const pot = pricedPot(state);
Betting.collectAssumedContributions(state);
Betting.creditWinnings(state, [{ id: state.seats[0].id, label: "Ann", amount: pot }]);
HoldemState.startNextHand(state);
assert.equal(chipsOnTable(state), total, "six hundred before, six hundred after");
assert.deepEqual(state.seats.slice(0, 3).map(p => p.stack), [300, 150, 150]);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
test("and the bank check stays balanced all the way through", () => {
const state = basePotTable();
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
Betting.collectAssumedContributions(state);
assert.equal(HoldemState.bankReconciliation(state).balanced, true, "chips are in the middle, not gone");
Betting.creditWinnings(state, [{ id: state.seats[0].id, label: "Ann", amount: 150 }]);
HoldemState.startNextHand(state);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
test("a live-betting hand is unchanged by any of this", () => {
const state = basePotTable(0);
state.smallBlind = 5;
state.bigBlind = 10;
const total = chipsOnTable(state);
Betting.beginHand(state);
[3, 0, 1, 2].forEach(() => { if (state.actingSeatIndex !== null) Betting.call(state, state.actingSeatIndex); });
Betting.sweepToHandTotals(state);
const pot = HoldemState.unresolvedContributions(state);
Betting.collectAssumedContributions(state);
Betting.creditWinnings(state, [{ id: state.seats[0].id, label: "Ann", amount: pot }]);
HoldemState.startNextHand(state);
assert.equal(chipsOnTable(state), total);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
test("collecting twice takes nothing the second time", () => {
// The pot wizard can be opened, cancelled and opened again.
const state = basePotTable();
Betting.collectAssumedContributions(state);
const stacks = state.seats.map(p => p.stack);
const again = Betting.collectAssumedContributions(state);
assert.equal(again.total, 0);
assert.deepEqual(state.seats.map(p => p.stack), stacks);
});
});
+108
View File
@@ -0,0 +1,108 @@
// The sums the contrast check runs on, tested away from a browser.
//
// The check itself needs a page to look at, but the arithmetic underneath it doesn't —
// and the arithmetic is the part that decides whether a real fault is reported or
// waved through. Faded text used to be filed as "not checked" rather than measured;
// this is the compositing that replaced that.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const LayoutAudit = require("./uiAudit");
const WHITE = { r: 255, g: 255, b: 255, a: 1 };
const BLACK = { r: 0, g: 0, b: 0, a: 1 };
const PAGE = { r: 28, g: 28, b: 28, a: 1 }; // the felt page behind everything
const PUCK = { r: 44, g: 44, b: 44, a: 1 }; // a seat's own background
describe("the ratio itself", () => {
test("black on white is the full 21:1, either way round", () => {
assert.ok(Math.abs(LayoutAudit.contrastRatio(BLACK, WHITE) - 21) < 0.01);
assert.ok(Math.abs(LayoutAudit.contrastRatio(WHITE, BLACK) - 21) < 0.01);
});
test("a colour against itself is 1:1", () => {
assert.ok(Math.abs(LayoutAudit.contrastRatio(PUCK, PUCK) - 1) < 0.001);
});
});
describe("text on a box that is being faded", () => {
// opacity on a box fades the box and its text together onto whatever is behind
// it — so a dimmed seat is not grey text on a dark puck, it is a faded puck and
// faded text both landing on the page.
const fade = alpha => ({ alpha, behind: PAGE });
test("at full strength nothing is composited", () => {
const painted = LayoutAudit.asPainted(WHITE, PUCK, { alpha: 1, behind: PAGE });
assert.deepEqual(painted.fg, WHITE);
assert.deepEqual(painted.bg, PUCK);
});
test("fading moves both the text and its background, not just the text", () => {
const painted = LayoutAudit.asPainted(WHITE, PUCK, fade(0.7));
assert.ok(painted.fg.r < WHITE.r, "the text dims");
assert.ok(painted.bg.r < PUCK.r, "and so does what it sits on");
assert.ok(painted.bg.r > PAGE.r, "but not all the way to the page");
});
test("which is what stops a fade being reported as a fault it isn't", () => {
// Dimming light text on a dark puck over a dark page costs contrast, but far
// less than measuring the faded text against the *unfaded* puck would claim.
const honest = LayoutAudit.asPainted(WHITE, PUCK, fade(0.7));
const wrong = { fg: LayoutAudit.over({ ...WHITE, a: 0.7 }, PUCK), bg: PUCK };
assert.ok(LayoutAudit.contrastRatio(honest.fg, honest.bg) >
LayoutAudit.contrastRatio(wrong.fg, wrong.bg));
});
test("a fade all the way out lands everything on the page behind", () => {
const painted = LayoutAudit.asPainted(WHITE, PUCK, fade(0));
assert.deepEqual(painted.fg, PAGE);
assert.deepEqual(painted.bg, PAGE);
});
test("with nothing known to be behind it, the fade is left alone", () => {
// Better to measure the unfaded pair than to invent a backdrop.
const painted = LayoutAudit.asPainted(WHITE, PUCK, { alpha: 0.5, behind: null });
assert.deepEqual(painted.fg, WHITE);
assert.deepEqual(painted.bg, PUCK);
});
});
describe("a fade makes small grey text worse, which is the fault it went looking for", () => {
// Deliberately not asserting a particular CSS colour here: the page's own greys are
// measured in the browser, against the real gradients, where they live. What this
// pins is the direction — that dimming a box costs its text contrast, which is why
// filing faded text as "not checked" hid faults rather than avoiding false ones.
test("the same grey scores lower once its box is dimmed", () => {
const grey = LayoutAudit.parseColour("rgb(138, 138, 138)");
const solid = LayoutAudit.asPainted(grey, PUCK, { alpha: 1, behind: PAGE });
const dimmed = LayoutAudit.asPainted(grey, PUCK, { alpha: 0.7, behind: PAGE });
assert.ok(LayoutAudit.contrastRatio(dimmed.fg, dimmed.bg) <
LayoutAudit.contrastRatio(solid.fg, solid.bg));
});
test("and a lighter grey scores higher at the same fade", () => {
const at = colour => {
const painted = LayoutAudit.asPainted(LayoutAudit.parseColour(colour), PUCK, { alpha: 0.7, behind: PAGE });
return LayoutAudit.contrastRatio(painted.fg, painted.bg);
};
assert.ok(at("rgb(174, 174, 174)") > at("rgb(138, 138, 138)"));
});
});
describe("reading a colour off the page", () => {
test("rgb and rgba both come back as numbers", () => {
assert.deepEqual(LayoutAudit.parseColour("rgb(1, 2, 3)"), { r: 1, g: 2, b: 3, a: 1 });
assert.deepEqual(LayoutAudit.parseColour("rgba(1, 2, 3, 0.5)"), { r: 1, g: 2, b: 3, a: 0.5 });
});
test("a gradient gives up every stop, because text could be over any of them", () => {
const stops = LayoutAudit.gradientStops("linear-gradient(rgb(203, 170, 240), rgb(169, 127, 214))");
assert.equal(stops.length, 2);
assert.deepEqual(stops[0], { r: 203, g: 170, b: 240, a: 1 });
assert.deepEqual(stops[1], { r: 169, g: 127, b: 214, a: 1 });
});
test("no background image, no stops", () => {
assert.deepEqual(LayoutAudit.gradientStops("none"), []);
});
});
+473
View File
@@ -0,0 +1,473 @@
// Where a player's bet sits on the felt.
//
// The chips were the last thing on the table nobody had measured. They were laid out on
// a ring of their own at a fixed 27/44 of the seat's reach — a fraction picked when the
// seat ring was itself fixed — and the choice between that ring and clinging to the
// puck was made by asking how wide the *window* was. Neither of those is a question
// about the felt. A phone held sideways is 844px across and gives the felt 117px of
// height: it passed the width test, took the ring, and every chip on it was painted
// behind a seat. The seats carry `z-index: 1` and the bets layer carries none, so a
// chip under a puck is not dimmed or half-hidden — it is gone, and with it the only
// number saying what that player has in.
//
// Everything below is geometry, so it runs without a browser. The felts are the ones
// measured on real screens: 692x117 is a phone on its side, 300x216 a phone upright.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Render } = require("./load");
const RADII = { rx: 44, ry: 42 };
const PUCK = { width: 96, height: 64 };
const CHIP = { width: 44, height: 22 };
const felt = (width, height) => ({ width, height });
const spacingOn = (box, puck = PUCK, chip = CHIP) =>
({ box, puck, chip, clearance: Render.BET_CLEARANCE_PX });
// A chip's centre in pixels on a given felt.
const chipPixels = (index, count, box, spacing, radii = RADII) => {
const pos = Render.betPosition(index, count, box.width / box.height, radii, spacing);
return { x: (pos.left / 100) * box.width, y: (pos.top / 100) * box.height };
};
const seatPixels = (index, count, box, radii = RADII) => {
const pos = Render.seatPosition(index, count, box.width / box.height, radii);
return { x: (pos.left / 100) * box.width, y: (pos.top / 100) * box.height };
};
// Two axis-aligned boxes, by their centres. The same test the seats settle among
// themselves — see seatFootprint.test.js — because it is the same question.
const boxesOverlap = (a, b, sizeA, sizeB) =>
Math.abs(a.x - b.x) < (sizeA.width + sizeB.width) / 2 - 0.5 &&
Math.abs(a.y - b.y) < (sizeA.height + sizeB.height) / 2 - 0.5;
describe("reaching the edge of a box", () => {
test("straight out the side is half the width, straight up half the height", () => {
assert.equal(Render.edgeReach(96, 64, 1, 0), 48);
assert.equal(Render.edgeReach(96, 64, 0, -1), 32);
assert.equal(Render.edgeReach(96, 64, -1, 0), 48);
});
test("a corner is whichever edge the ray meets first", () => {
// 45° out of a 96x64 box: the top and bottom are nearer than the sides, so the
// ray leaves through one of those. A single radius — half the diagonal, 57.7 —
// would put a chip 25px further out than it needs to be, which on a 117px felt
// is the difference between clear of the puck and off the table.
const diagonal = Render.edgeReach(96, 64, Math.SQRT1_2, Math.SQRT1_2);
assert.ok(Math.abs(diagonal - 32 / Math.SQRT1_2) < 1e-9, `got ${diagonal}`);
assert.ok(diagonal < 48, "and never further than the wider half-edge");
});
test("a square is the same in every direction it is asked about", () => {
const straight = Render.edgeReach(50, 50, 0, 1);
assert.equal(Render.edgeReach(50, 50, 1, 0), straight);
});
});
describe("getting one box clear of another", () => {
const PUCK96 = { width: 96, height: 88 };
const CHIP50 = { width: 50, height: 21 };
// Travel `t` along `u` from the puck's centre, then ask whether the two boxes are
// apart. This is the question clearanceReach is supposed to answer, asked the long
// way round so the answer can be checked rather than restated.
const apart = (t, ux, uy) =>
Math.abs(t * ux) >= (PUCK96.width + CHIP50.width) / 2 - 1e-9 ||
Math.abs(t * uy) >= (PUCK96.height + CHIP50.height) / 2 - 1e-9;
test("straight up and down it is what adding the two half-heights gives", () => {
assert.equal(Render.clearanceReach(PUCK96, CHIP50, 0, -1), (88 + 21) / 2);
assert.equal(Render.clearanceReach(PUCK96, CHIP50, 1, 0), (96 + 50) / 2);
});
test("on a diagonal it is more than the two reaches added together", () => {
// The bug this replaced. Two axis-aligned boxes are clear when they are apart on
// one axis, and the travel that achieves that is the reach of the box you get by
// adding their widths and their heights — which is never less, and on a diagonal
// is more, than adding the two boxes' own reaches. At 768x1024 the difference was
// 11px, and 11px is how far inside its own player's puck the chip came to rest.
const dirs = [[0.83, 0.56], [0.6, 0.8], [0.9, 0.44], [Math.SQRT1_2, Math.SQRT1_2]];
let shortfalls = 0;
dirs.forEach(([ux, uy]) => {
const summed = Render.edgeReach(PUCK96.width, PUCK96.height, ux, uy) +
Render.edgeReach(CHIP50.width, CHIP50.height, ux, uy);
const proper = Render.clearanceReach(PUCK96, CHIP50, ux, uy);
assert.ok(proper >= summed - 1e-9, `${ux},${uy}: ${proper} < ${summed}`);
if (proper <= summed + 1e-9) return;
// Where they differ, the old answer was not merely smaller — it was wrong:
// travelling that far leaves the two boxes still on top of each other.
shortfalls++;
assert.ok(!apart(summed, ux, uy),
`${ux},${uy}: adding the reaches gave ${summed.toFixed(1)}, which is enough after all`);
});
assert.ok(shortfalls >= 2, "expected the two to actually differ on some of these");
});
test("and it is exactly enough — a hair less is not", () => {
const dirs = [[0, -1], [1, 0], [0.83, 0.56], [0.6, -0.8], [-0.9, 0.44]];
dirs.forEach(([ux, uy]) => {
const t = Render.clearanceReach(PUCK96, CHIP50, ux, uy);
assert.ok(apart(t, ux, uy), `${ux},${uy}: ${t}px still overlaps`);
assert.ok(!apart(t - 0.5, ux, uy), `${ux},${uy}: ${t}px is further than needed`);
});
});
});
describe("a chip on the ring", () => {
test("with nothing measured it keeps the proportions the ring always used", () => {
// The unit suite and the very first render both call it this way. 27/44 and
// 25/42 of the seat's own reach, so the chips move with the ring rather than
// with the felt.
const seat = Render.seatPosition(3, 9, 1.4, RADII);
const chip = Render.betPosition(3, 9, 1.4, RADII, null);
assert.ok(Math.abs((chip.left - 50) - (seat.left - 50) * (27 / 44)) < 1e-9);
assert.ok(Math.abs((chip.top - 50) - (seat.top - 50) * (25 / 42)) < 1e-9);
});
test("measured, it sits just clear of its own puck rather than at a fixed fraction", () => {
const box = felt(560, 400);
const spacing = spacingOn(box);
for (let i = 0; i < 9; i++) {
const seat = seatPixels(i, 9, box);
const chip = chipPixels(i, 9, box, spacing);
assert.ok(!boxesOverlap(seat, chip, PUCK, CHIP),
`seat ${i + 1}'s own chip is under its own puck`);
}
});
test("and never wanders into the pot badge in the middle", () => {
// The floor: 38% of the way out. Without it a chip walked in past a puck that
// is 96px wide on a felt whose reach is 90px would land on the pot total, which
// is the same fault at the other end of the spoke.
const box = felt(300, 216);
const spacing = spacingOn(box, { width: 200, height: 150 });
for (let i = 0; i < 6; i++) {
const seat = seatPixels(i, 6, box);
const chip = chipPixels(i, 6, box, spacing);
const seatReach = Math.hypot(seat.x - box.width / 2, seat.y - box.height / 2);
const chipReach = Math.hypot(chip.x - box.width / 2, chip.y - box.height / 2);
assert.ok(chipReach >= seatReach * 0.38 - 0.5,
`chip ${i + 1} is ${chipReach.toFixed(1)}px out of a possible ${seatReach.toFixed(1)}`);
}
});
test("a seat sitting dead centre gets its chip put somewhere, not NaN", () => {
const box = felt(400, 300);
const pos = Render.betPosition(0, 1, box.width / box.height, { rx: 0, ry: 0 }, spacingOn(box));
assert.ok(Number.isFinite(pos.left) && Number.isFinite(pos.top), JSON.stringify(pos));
});
});
describe("deciding whether a ring of chips fits at all", () => {
// The shape the layout works in: one entry per chip on the felt, carrying its own
// measured size, because a chip is as wide as the number printed on it.
const tableOf = (count, chip = CHIP) => {
Render.state = { seatCount: count, seats: Array.from({ length: count }, () => ({})) };
return Array.from({ length: count }, (_, i) =>
({ index: i, width: chip.width, height: chip.height }));
};
test("a desktop felt has room for one", () => {
const box = felt(700, 500);
const all = tableOf(9);
assert.equal(Render.chipsClearTheSeats(all, box.width / box.height, RADII, spacingOn(box)), true);
});
test("a phone on its side has not, whatever the window's width says about it", () => {
// 692x117, measured on an 844px-wide phone in landscape — a viewport that sails
// past a `max-width: 700px` test. The ring is a slot: the 38% floor puts a chip
// on the seat across the table from it.
const box = felt(692, 117);
const all = tableOf(9);
assert.equal(Render.chipsClearTheSeats(all, box.width / box.height, RADII, spacingOn(box)), false,
"this is the felt where every chip was painted behind a puck");
});
test("its answer is the one the geometry gives", () => {
// Not a restatement of the two cases above: whatever it returns, it has to agree
// with laying the chips out and measuring them against every puck on the felt.
const shapes = [felt(700, 500), felt(692, 117), felt(300, 216), felt(1000, 620), felt(480, 300)];
shapes.forEach(box => {
const all = tableOf(9);
const spacing = spacingOn(box);
const aspect = box.width / box.height;
const clear = all.every(({ index: i }) => {
const chip = chipPixels(i, 9, box, spacing);
return all.every(({ index: j }) => !boxesOverlap(chip, seatPixels(j, 9, box), CHIP, PUCK));
});
assert.equal(Render.chipsClearTheSeats(all, aspect, RADII, spacing), clear,
`${box.width}x${box.height}`);
});
});
test("each chip is asked about at its own size", () => {
// A chip is as wide as the number on it: at 768x1024, four players' chips were
// 40px and one holding a four-figure bet was 47. Answering the question once, at
// the widest, told the whole felt it had no room for a ring — and dropped all
// five chips onto their own players' stacks to solve a problem four of them
// did not have.
// The felt and the pucks are the iPad's own, measured: 672x672, pucks 96x88.
const box = felt(672, 672);
const narrow = { width: 40, height: 20 };
const huge = { width: 420, height: 380 };
const spacing = { box, puck: { width: 96, height: 88 }, clearance: Render.BET_CLEARANCE_PX };
const aspect = box.width / box.height;
assert.equal(Render.chipsClearTheSeats(tableOf(9, narrow), aspect, RADII, spacing), true,
"a felt this size has room for a ring of ordinary chips");
assert.equal(Render.chipsClearTheSeats(tableOf(9, huge), aspect, RADII, spacing), false,
"and none at all for a ring of chips that size");
// Now one of each. The answer has to come from the sizes in the list, not from
// one size standing in for all of them: with one huge chip the ring is off, and
// taking that chip out of the question puts it back.
const mixed = tableOf(9, narrow);
mixed[0] = { index: 0, ...huge };
assert.equal(Render.chipsClearTheSeats(mixed, aspect, RADII, spacing), false);
assert.equal(Render.chipsClearTheSeats(mixed.slice(1), aspect, RADII, spacing), true,
"the eight ordinary ones were never the problem");
});
test("and at the chips against each other", () => {
// The ring is a smaller circle than the seats' one and holds the same number of
// things, so it is the tighter fit of the two. Measured on a Pixel 7 with twelve
// players, two $10s on the ring sat on top of each other while every puck on the
// felt was clear — so a check that only looks at the pucks says yes to a layout
// that hides one player's bet behind another's.
// The Pixel 7's own numbers, measured: a 300x336 felt on a ring of 44 by 40.84,
// pucks 44x55, a pot badge 64x53, and the seven players who had put chips in.
const box = felt(300, 336);
const radii = { rx: 44, ry: 40.84 };
const puck = { width: 44, height: 55 };
const pot = { x: 150, y: 168, width: 64, height: 53 };
const spacing = { box, puck, pot, clearance: Render.BET_CLEARANCE_PX };
const aspect = box.width / box.height;
Render.state = { seatCount: 12, seats: Array.from({ length: 12 }, () => ({})) };
const bettors = [2, 3, 4, 5, 6, 7, 8];
const all = bettors.map(index => ({ index, width: index === 2 ? 44.1 : 49.7, height: 21 }));
const chips = all.map(entry => ({
...entry,
...chipPixels(entry.index, 12, box,
{ ...spacing, chip: { width: entry.width, height: entry.height } }, radii),
}));
const seats = [...Array(12).keys()].map(i => seatPixels(i, 12, box, radii));
assert.equal(chips.some(chip => seats.some(seat => boxesOverlap(chip, seat, chip, puck))), false,
"this table is chosen so the pucks are not the problem");
assert.equal(chips.some(chip => boxesOverlap(chip, pot, chip, pot)), false,
"nor the pot");
assert.ok(chips.some((chip, i) => chips.some((other, j) => i !== j &&
boxesOverlap(chip, other, chip, other))), "and so the chips are");
assert.equal(Render.chipsClearTheSeats(all, aspect, radii, spacing), false);
});
test("it looks at every puck, not just the chip's own", () => {
// The rule this replaced walked each chip in until it was clear of its *own*
// seat and stopped there, which says nothing about the eight other pucks on the
// felt. 560x190 is a felt where that rule is satisfied and the ring is still no
// good: every chip clears the puck it belongs to, and one of them is sitting on
// a stranger's.
const box = felt(560, 190);
const all = tableOf(9);
const spacing = spacingOn(box);
const chips = all.map(({ index: i }) => chipPixels(i, 9, box, spacing));
all.forEach(({ index: i }) => assert.ok(!boxesOverlap(chips[i], seatPixels(i, 9, box), CHIP, PUCK),
`chip ${i + 1} is under its own puck, so this felt does not make the point`));
assert.ok(all.some(({ index: i }) => all.some(({ index: j }) => i !== j &&
boxesOverlap(chips[i], seatPixels(j, 9, box), CHIP, PUCK))),
"expected a chip on somebody else's puck — what the old rule could not see");
assert.equal(Render.chipsClearTheSeats(all, box.width / box.height, RADII, spacing), false);
});
});
describe("a chip clinging to its puck", () => {
// The fallback when there is no room for a ring: the chip hangs off the puck on the
// side facing the empty middle of the felt.
//
// The felts the app actually draws, with the puck size each one settles on — read
// off the running site at each viewport rather than guessed here, because the tight
// felts shrink the puck too, and a test that holds the desktop's 96x64 puck against
// a 528x83 felt is describing a table the app never draws.
const REAL = [
["Galaxy S8 on its side", felt(528, 83), { width: 44, height: 55 }],
["iPhone on its side", felt(692, 113), { width: 72, height: 55 }],
["Galaxy S8 upright, six-handed", felt(248, 280), { width: 78, height: 88 }],
["Galaxy S8 upright, packed", felt(248, 280), { width: 44, height: 55 }],
];
// Chips are 21x17 everywhere they are anchored — the amount is the only thing on
// one at that size.
const TIGHT = { puck: { width: 44, height: 55 }, chip: { width: 21, height: 17 } };
// What each chip is told to do, worked out for the whole table at once.
const placeAll = (count, box, puck, chip = TIGHT.chip, radii = RADII) => {
Render.state = { seatCount: count, seats: Array.from({ length: count }, () => ({})) };
const indices = [...Array(count).keys()];
const entries = indices.map(i => ({ index: i, width: chip.width, height: chip.height }));
const spacing = { box, puck, clearance: Render.BET_CLEARANCE_PX };
const offs = Render.anchoredChipTravel(entries, count, box.width / box.height, RADII, spacing);
return indices.map(i => {
const seat = Render.seatPosition(i, count, box.width / box.height, radii);
const at = { x: (seat.left / 100) * box.width, y: (seat.top / 100) * box.height };
const off = offs[i];
return { seat: at, chip: { x: at.x + off.x, y: at.y + off.y }, off, puck };
});
};
test("on its own, a chip asks to sit just clear of its puck", () => {
const box = felt(692, 113);
const puck = { width: 72, height: 55 };
const seat = Render.seatPosition(0, 9, box.width / box.height, RADII);
const off = Render.anchoredChipOffset(seat, puck, TIGHT.chip, box, RADII);
const travel = Math.hypot(off.x, off.y);
const ux = off.x / travel, uy = off.y / travel;
assert.ok(Math.abs(travel -
(Render.clearanceReach(puck, TIGHT.chip, ux, uy) + Render.BET_CLEARANCE_PX)) < 1e-6, `travelled ${travel}`);
});
test("and gets it, where nothing else is in the way", () => {
// 692x113 is the roomier of the two landscape felts. Every chip clears its own
// puck and none of them has to give ground.
placeAll(9, felt(692, 113), { width: 72, height: 55 }).forEach((row, i) => {
assert.ok(!boxesOverlap(row.seat, row.chip, row.puck, TIGHT.chip),
`seat ${i + 1}'s chip is inside its own puck, and nothing made it go there`);
});
});
test("it goes off the rim, not down the spoke", () => {
// On a felt 692x113 the two are nowhere near the same direction. A seat on the
// top rail has a spoke pointing diagonally inward — which along a slot this flat
// runs sideways into the next seat — while off the rim is very nearly straight
// down, into the empty middle. This is the seam that put two chips on top of
// each other on a Galaxy S8.
const box = felt(692, 113);
const rows = placeAll(9, box, { width: 72, height: 55 });
const top = rows.find(r => r.seat.y < box.height * 0.3 && r.seat.x > box.width * 0.7);
assert.ok(top, "expected a seat up on the right of the top rail");
assert.ok(Math.abs(top.off.y) > Math.abs(top.off.x) * 2,
`chip went ${top.off.x.toFixed(1)},${top.off.y.toFixed(1)} — that is along the rail, not off it`);
assert.ok(top.off.y > 0, "and downward, toward the middle of the felt");
});
test("no two chips on a full table land on each other", () => {
// Four sides gave three seams. There are no sides now, and this is what that is
// worth — on every felt the app actually draws, at every table size.
REAL.forEach(([name, box, puck]) => {
[6, 9, 12].forEach(count => {
const rows = placeAll(count, box, puck);
for (let a = 0; a < rows.length; a++) {
for (let b = a + 1; b < rows.length; b++) {
assert.ok(!boxesOverlap(rows[a].chip, rows[b].chip, TIGHT.chip, TIGHT.chip),
`${name}, ${count} seats: chips ${a + 1} and ${b + 1} overlap`);
}
}
});
});
});
test("a chip only gives ground when it is standing on something", () => {
// The point of pulling chips back one at a time rather than by a rule that
// applies to all of them. Stopping every chip at the felt's midline, or scaling
// them all by one factor, takes travel from the seats at the ends of a long
// rail — measured at 692x113, that parked two chips on their own player's stack
// to solve a collision that did not exist.
//
// So: every chip either got everything it asked for, or putting the last step
// back reintroduces a collision it is part of. The step goes back for all of
// them at once, because a facing pair gives ground together and the pass that
// finally separates such a pair moves both ends of it.
const step = Render.CHIP_PULLBACK_STEP_PX;
REAL.forEach(([name, box, puck]) => {
[6, 9, 12].forEach(count => {
const rows = placeAll(count, box, puck).map(row => {
const travel = Math.hypot(row.off.x, row.off.y);
const dir = travel < 1e-6 ? { x: 0, y: 0 } : { x: row.off.x / travel, y: row.off.y / travel };
const asked = travel < 1e-6 ? 0 :
Render.clearanceReach(puck, TIGHT.chip, dir.x, dir.y) +
Render.BET_CLEARANCE_PX;
const back = Math.min(asked, travel + step);
return { ...row, travel, asked,
undone: { x: row.seat.x + dir.x * back, y: row.seat.y + dir.y * back } };
});
rows.forEach((row, i) => {
if (row.travel < 1e-6 || row.travel >= row.asked - 1e-6) return;
const onSomething = rows.some((other, j) => j !== i && (
boxesOverlap(row.undone, other.undone, TIGHT.chip, TIGHT.chip) ||
boxesOverlap(row.undone, other.seat, TIGHT.chip, puck)));
assert.ok(onSomething,
`${name}, ${count} seats: chip ${i + 1} stopped ${(row.asked - row.travel).toFixed(1)}px short of nothing`);
});
});
});
});
test("nobody is pushed further out than they asked to go", () => {
// The pull-back only ever takes travel away. A chip pushed past its clearance
// would be floating out on the felt with nothing to say whose it is.
REAL.forEach(([name, box, puck]) => {
placeAll(12, box, puck).forEach((row, i) => {
const travel = Math.hypot(row.off.x, row.off.y);
if (travel < 1e-6) return;
const ux = row.off.x / travel, uy = row.off.y / travel;
const asked = Render.clearanceReach(puck, TIGHT.chip, ux, uy) +
Render.BET_CLEARANCE_PX;
assert.ok(travel <= asked + 0.5,
`${name}: chip ${i + 1} went ${travel.toFixed(1)}px when ${asked.toFixed(1)} was asked for`);
});
});
});
test("the direction turns smoothly all the way round the ring", () => {
// The property a set of discrete sides cannot have, and the reason there are
// none: neighbouring seats get neighbouring directions, with no step anywhere.
const box = felt(560, 400);
const angles = Array.from({ length: 24 }, (_, i) => {
const seat = Render.seatPosition(i, 24, box.width / box.height, RADII);
const off = Render.anchoredChipOffset(seat, PUCK, CHIP, box, RADII);
return Math.atan2(off.y, off.x);
});
angles.forEach((angle, i) => {
const next = angles[(i + 1) % angles.length];
let turn = Math.abs(next - angle);
if (turn > Math.PI) turn = 2 * Math.PI - turn;
assert.ok(turn < Math.PI / 4,
`between seats ${i + 1} and ${i + 2} the chip jumps ${(turn * 180 / Math.PI).toFixed(0)}°`);
});
});
test("it stops short of the pot total as well", () => {
// The other thing in the middle of the felt, and the one number on the table
// that belongs to everybody. A seat on the middle of a rail sends its chip
// straight at it: on a Galaxy S8 on its side, seat 1's $10 was sitting on
// "Pot $65". The badge is measured rather than assumed to be at the centre —
// it lives on the table, not on either overlay, and the two are not concentric.
const box = felt(528, 83);
const pot = { x: 264, y: 40, width: 96, height: 34 };
Render.state = { seatCount: 12, seats: Array.from({ length: 12 }, () => ({})) };
const indices = [...Array(12).keys()];
const entries = indices.map(i =>
({ index: i, width: TIGHT.chip.width, height: TIGHT.chip.height }));
const spacing = { box, puck: TIGHT.puck, clearance: Render.BET_CLEARANCE_PX, pot };
const offs = Render.anchoredChipTravel(entries, 12, box.width / box.height, RADII, spacing);
indices.forEach(i => {
const seat = Render.seatPosition(i, 12, box.width / box.height, RADII);
const chip = { x: (seat.left / 100) * box.width + offs[i].x,
y: (seat.top / 100) * box.height + offs[i].y };
assert.ok(!boxesOverlap(chip, pot, TIGHT.chip, pot),
`chip ${i + 1} is on the pot total`);
});
});
test("a seat with no rim to be off still gets an answer", () => {
const box = felt(400, 300);
const off = Render.anchoredChipOffset({ left: 50, top: 50 }, PUCK, CHIP, box, RADII);
assert.ok(Number.isFinite(off.x) && Number.isFinite(off.y), JSON.stringify(off));
assert.ok(off.y < 0, "upward, which is where a puck's own writing is not");
});
});
+118
View File
@@ -0,0 +1,118 @@
// The community cards, as a thing the table remembers.
//
// The board is the one part of a hand this tool never had a place for: hole cards go on
// a seat, chips go in the middle, and the five cards everybody plays lived only on the
// felt in front of the dealer. It is opt-in, because most nights nobody wants to enter
// cards at all — and everything that reads it has to behave exactly as it always did
// when it is off.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Betting, HoldemState, makeTable } = require("./load");
const dealt = (over = {}) => {
const state = { ...makeTable({ seatCount: 6, stack: 200, smallBlind: 1, bigBlind: 2 }), ...over };
Betting.beginHand(state);
return state;
};
describe("a new table", () => {
test("has five empty slots and is not tracking them", () => {
const state = HoldemState.createDefault();
assert.deepEqual(state.board, ["", "", "", "", ""]);
assert.equal(state.trackBoard, false,
"off by default: a dealer who never asked for this should not be asked for cards");
});
});
describe("how many cards are out", () => {
test("none, three, four, five", () => {
assert.equal(Betting.boardCardsFor("preflop"), 0);
assert.equal(Betting.boardCardsFor("flop"), 3);
assert.equal(Betting.boardCardsFor("turn"), 4);
assert.equal(Betting.boardCardsFor("river"), 5);
});
test("and nothing at all for a street that isn't one", () => {
assert.equal(Betting.boardCardsFor("showdown"), 0);
assert.equal(Betting.boardCardsFor(undefined), 0);
});
test("it matches the streets the betting engine actually deals", () => {
// If a street is ever added, this is the table that has to hear about it —
// a street with no entry silently draws no cards.
Betting.STREETS.forEach(street => {
assert.ok(Object.prototype.hasOwnProperty.call(Betting.BOARD_CARDS, street),
`${street} has no card count`);
});
});
});
describe("clearing it", () => {
test("the next hand takes the board with it", () => {
const state = dealt();
state.board = ["AH", "KD", "9C", "4S", "2H"];
HoldemState.startNextHand(state);
assert.deepEqual(state.board, ["", "", "", "", ""]);
});
test("so does a misdeal", () => {
const state = dealt();
state.board = ["AH", "KD", "9C", "", ""];
Betting.takeHandBack(state);
assert.deepEqual(state.board, ["", "", "", "", ""]);
});
test("and so does dealing a hand, however the table got here", () => {
// Dealing twice off the same button — after a misdeal, or a table set up and
// then dealt again — would otherwise rank the last hand's board against this
// hand's cards, and it would look exactly like a real answer.
const state = dealt();
state.board = ["AH", "KD", "9C", "4S", "2H"];
Betting.beginHand(state);
assert.deepEqual(state.board, ["", "", "", "", ""]);
});
test("but turning the tracking off does not", () => {
// A dealer who taps the toggle mid-hand can tap it back; wiping the flop on
// the way past would cost them cards they had already entered.
const state = dealt({ trackBoard: true });
state.board = ["AH", "KD", "9C", "", ""];
state.trackBoard = false;
assert.deepEqual(state.board, ["AH", "KD", "9C", "", ""]);
});
});
describe("a board off a file", () => {
const migrated = board => HoldemState.migrate({
seats: [HoldemState.makePlayer()], board,
}).board;
test("a table saved before boards existed gets an empty one, not tracked", () => {
const parsed = HoldemState.migrate({ seats: [HoldemState.makePlayer()] });
assert.deepEqual(parsed.board, ["", "", "", "", ""]);
assert.equal(parsed.trackBoard, false);
});
test("it is always five slots, however many arrived", () => {
assert.equal(migrated(["AH"]).length, 5);
assert.equal(migrated(["AH", "KD", "9C", "4S", "2H", "3D", "5S"]).length, 5);
assert.equal(migrated("not an array").length, 5);
assert.equal(migrated(null).length, 5);
});
test("anything that isn't a card becomes an empty slot", () => {
assert.deepEqual(migrated(["AH", "ZZ", 7, null, "10H"]), ["AH", "", "", "", ""]);
});
test("and a real one keeps its place, upper-cased", () => {
assert.deepEqual(migrated(["ah", " kd ", "9c", "", ""]), ["AH", "KD", "9C", "", ""]);
});
test("tracking is only on if the file said so, in so many words", () => {
const on = HoldemState.migrate({ seats: [HoldemState.makePlayer()], trackBoard: true });
const truthy = HoldemState.migrate({ seats: [HoldemState.makePlayer()], trackBoard: "yes" });
assert.equal(on.trackBoard, true);
assert.equal(truthy.trackBoard, false, "a string is a file that has been edited, not a yes");
});
});
+129
View File
@@ -0,0 +1,129 @@
// Calling the clock on a player.
//
// The bar already had a stopwatch saying how long somebody had been thinking. This is
// what a dealer does about it: a procedure with a shape — a set time, a countdown said
// out loud, and a ruling at the end that depends on what the player was facing.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { ActionBar, Betting, makeTable } = require("./load");
// The bar rebuilds the DOM when a clock starts; none of the rules below need it.
const onTable = (state) => {
ActionBar.state = state;
ActionBar.render = () => {};
ActionBar.stopClock();
return ActionBar;
};
const dealt = () => {
const state = makeTable({ seatCount: 6, stack: 200, smallBlind: 1, bigBlind: 2, dealerSeatIndex: 0 });
Betting.beginHand(state);
return state;
};
describe("starting one", () => {
test("it runs on the player who is actually on the clock", () => {
const state = dealt();
const bar = onTable(state);
assert.equal(bar.clockRunning(), false, "nothing runs until it is called");
bar.callClock();
assert.equal(bar.clockRunning(), true);
assert.equal(bar.clockSeatIndex, state.actingSeatIndex);
});
test("with nobody to act there is nothing to call", () => {
const state = dealt();
state.actingSeatIndex = null;
const bar = onTable(state);
bar.callClock();
assert.equal(bar.clockRunning(), false);
assert.equal(bar.clockLeft(), null);
});
test("the dealer can put it away again", () => {
const bar = onTable(dealt());
bar.callClock();
bar.stopClock();
assert.equal(bar.clockRunning(), false);
assert.equal(bar.clockLeft(), null);
});
});
describe("the count", () => {
const at = (bar, seconds) => bar.clockLeft(bar.clockStartedAt + seconds * 1000);
test("is the player's own time and then a countdown", () => {
const bar = onTable(dealt());
bar.callClock();
assert.equal(at(bar, 0), bar.CLOCK_THINK_S + bar.CLOCK_COUNTDOWN_S);
assert.equal(at(bar, 30), bar.CLOCK_COUNTDOWN_S, "thirty gone, the countdown starts");
assert.equal(at(bar, 35), 5);
});
test("stops at zero rather than going negative", () => {
const bar = onTable(dealt());
bar.callClock();
assert.equal(at(bar, 40), 0);
assert.equal(at(bar, 600), 0, "ten minutes later it is still just up");
});
});
describe("what happens at zero", () => {
test("facing a bet, the hand is dead", () => {
const state = dealt();
const bar = onTable(state);
// Whoever is up pre-flop is facing the big blind.
const ruling = bar.clockRuling();
assert.equal(ruling.verb, "fold");
assert.match(ruling.label, /hand is dead/);
assert.match(ruling.say, /facing \$2/);
});
test("facing nothing, it is checked — slowness doesn't fold a free hand", () => {
const state = dealt();
// Everyone calls round to the big blind, who has nothing to call.
[3, 4, 5, 0, 1].forEach(seat => Betting.call(state, seat));
const bar = onTable(state);
assert.equal(state.actingSeatIndex, 2, "the big blind is up");
const ruling = bar.clockRuling();
assert.equal(ruling.verb, "check");
assert.match(ruling.label, /check for/i);
});
test("the ruling names the player, because the dealer has to say it out loud", () => {
const state = dealt();
state.seats[state.actingSeatIndex].name = "Priya";
const ruling = onTable(state).clockRuling();
assert.match(ruling.label, /Priya/);
assert.match(ruling.say, /Priya/);
});
test("with nobody to act there is no ruling to make", () => {
const state = dealt();
state.actingSeatIndex = null;
assert.equal(onTable(state).clockRuling(), null);
});
});
describe("what ends it", () => {
test("the player acting", () => {
const state = dealt();
const bar = onTable(state);
bar.callClock();
const wasOn = state.actingSeatIndex;
Betting.call(state, wasOn);
assert.notEqual(state.actingSeatIndex, wasOn, "the action has moved");
assert.equal(bar.clockRunning(), false, "so the clock is no longer this player's");
});
test("and it doesn't follow the action to the next player", () => {
// A clock is called on one decision. Left running it would put a countdown on
// somebody nobody asked about.
const state = dealt();
const bar = onTable(state);
bar.callClock();
Betting.call(state, state.actingSeatIndex);
assert.equal(bar.clockLeft(), null);
});
});
+229
View File
@@ -0,0 +1,229 @@
// Somebody leaving with their chips.
//
// The most ordinary thing that happens at a home game after midnight, and the tool had
// nothing for it. Freeing the chair meant wiping the seat by hand, and then the bank
// check — cash taken against chips on the table — declared the departing player's whole
// stack missing for the rest of the night. Wiping their buy-in too silenced it, at the
// price of losing their night from the standings and the file the dealer hands over.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Money, HoldemState, Betting, makeTable } = require("./load");
const table = () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 200 });
["Ann", "Ben", "Cal", "Dee"].forEach((name, i) => {
state.seats[i].name = name;
state.seats[i].buyIns = 200;
});
return state;
};
describe("counting them out", () => {
test("the preview is what the dealer's hands follow", () => {
const state = table();
state.seats[0].stack = 350;
const preview = HoldemState.cashOutPreview(state, 0);
assert.equal(preview.name, "Ann");
assert.equal(preview.chips, 350, "what they are holding");
assert.equal(preview.boughtIn, 200);
assert.equal(preview.net, 150, "up for the night");
assert.match(preview.breakdown, /\d+×\$\d+/, "and the chips that make it");
});
test("a player who is down reads as down, not as a smaller stack", () => {
const state = table();
state.seats[1].stack = 60;
assert.equal(HoldemState.cashOutPreview(state, 1).net, -140);
});
test("a seat that never set a stack is holding the table's starting stack", () => {
const state = table();
state.defaultStack = 200;
state.seats[2].stack = null;
assert.equal(HoldemState.cashOutPreview(state, 2).chips, 200);
});
});
describe("what it refuses", () => {
test("paying somebody with money still in the middle", () => {
const state = table();
Betting.beginHand(state);
const bb = state.seats.findIndex(p => (Number(p.committed) || 0) > 0);
const refusal = HoldemState.canCashOut(state, bb);
assert.equal(refusal.ok, false);
assert.match(refusal.reason, /in the pot/);
// And the refusal is the whole story: nothing moved.
assert.equal(HoldemState.cashOut(state, bb).ok, false);
assert.equal((state.cashedOut || []).length, 0);
assert.ok(state.seats[bb].name, "the seat is untouched");
});
test("an empty chair, which has nobody to pay", () => {
const state = table();
const refusal = HoldemState.canCashOut(state, 99);
assert.equal(refusal.ok, false);
});
});
describe("the chair afterwards", () => {
test("is empty and ready for the next player", () => {
const state = table();
state.seats[0].stack = 350;
HoldemState.cashOut(state, 0);
const seat = state.seats[0];
assert.equal(seat.name, "");
assert.equal(seat.stack, null);
assert.equal(seat.buyIns, 0);
assert.equal(seat.inHand, false);
});
test("belongs to somebody new, so two people's nights can't merge", () => {
const state = table();
const wasId = state.seats[0].id;
HoldemState.cashOut(state, 0);
assert.notEqual(state.seats[0].id, wasId);
});
test("and isn't owed the blind the person before them was posting", () => {
const state = table();
state.postingIn = [state.seats[0].id, state.seats[1].id];
HoldemState.cashOut(state, 0);
assert.deepEqual(state.postingIn, [state.seats[1].id]);
});
});
describe("the bank check", () => {
test("balanced before, balanced after — the chips went somewhere known", () => {
const state = table();
state.seats[0].stack = 350;
state.seats[1].stack = 50;
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
HoldemState.cashOut(state, 0);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.paidOut, 350);
assert.equal(bank.cashIn, 800, "their buy-in is still cash the box took");
assert.equal(bank.chipsInPlay, 450);
assert.equal(bank.balanced, true);
});
test("this is the fault it fixes: wiping the seat by hand loses $350", () => {
const state = table();
state.seats[0].stack = 350;
state.seats[1].stack = 50; // so the table starts out balanced
// What a dealer had to do before: empty the chair themselves.
state.seats[0].name = "";
state.seats[0].stack = null;
state.seats[0].inHand = false;
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, false);
assert.equal(bank.difference, -350, "the tool called it missing money");
});
test("chips that really are missing still show as missing", () => {
// Counting a cash-out must not become a way of swallowing a genuine shortfall.
const state = table();
state.seats[0].stack = 350;
state.seats[1].stack = 50; // balanced to start with
HoldemState.cashOut(state, 0);
state.seats[2].stack = 150; // and now fifty chips have gone astray
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, false);
assert.equal(bank.difference, -50);
});
test("a rake and a cash-out are counted apart", () => {
const state = table();
state.seats[0].stack = 350;
state.rakeTaken = 12;
state.seats[1].stack = 38; // the rake came out of Ben's stack
HoldemState.cashOut(state, 0);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.raked, 12);
assert.equal(bank.paidOut, 350);
assert.equal(bank.balanced, true);
});
});
describe("the record of their night", () => {
test("they stay in the standings with what they bought and what they left with", () => {
const state = table();
state.seats[0].stack = 350;
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 150 }]);
HoldemState.cashOut(state, 0);
const ann = HoldemState.sessionStandings(state).find(row => row.name === "Ann");
assert.ok(ann, "still on the list");
assert.equal(ann.boughtIn, 200);
assert.equal(ann.chipsInFront, 350, "what the box handed over");
assert.equal(ann.cashPosition, 150);
assert.equal(ann.cashedOut, true, "and marked, so nobody pays them twice");
});
test("somebody still sitting there is not marked", () => {
const state = table();
HoldemState.cashOut(state, 0);
const ben = HoldemState.sessionStandings(state).find(row => row.name === "Ben");
assert.equal(ben.cashedOut, false);
});
test("two people leaving are both kept", () => {
const state = table();
state.seats[0].stack = 350;
state.seats[1].stack = 50;
HoldemState.cashOut(state, 0);
HoldemState.cashOut(state, 1);
assert.equal(state.cashedOut.length, 2);
assert.equal(HoldemState.bankReconciliation(state).paidOut, 400);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
test("a table saved before any of this existed has nobody cashed out", () => {
const parsed = JSON.parse(JSON.stringify(table()));
delete parsed.cashedOut;
const migrated = HoldemState.migrate(parsed);
assert.deepEqual(migrated.cashedOut, []);
assert.equal(HoldemState.bankReconciliation(migrated).paidOut, 0);
});
test("nonsense in a saved record is cleaned up rather than trusted", () => {
const parsed = JSON.parse(JSON.stringify(table()));
parsed.cashedOut = [
{ id: "a", name: "Ann", buyIns: -5, chips: "350", at: "nope" },
{ name: "no id" },
null,
];
const migrated = HoldemState.migrate(parsed);
assert.equal(migrated.cashedOut.length, 1);
assert.equal(migrated.cashedOut[0].buyIns, 0);
assert.equal(migrated.cashedOut[0].chips, 350);
assert.equal(migrated.cashedOut[0].at, 0);
});
});
describe("the table carries on", () => {
test("the next hand deals round the empty chair", () => {
const state = table();
state.seats[0].stack = 350;
HoldemState.cashOut(state, 0);
HoldemState.startNextHand(state);
Betting.beginHand(state);
assert.equal(state.seats[0].inHand, false, "nobody is in the empty chair");
assert.equal(Betting.liveSeats(state).length, 3);
assert.ok(state.actingSeatIndex !== null, "somebody is on the clock");
});
test("and the money still adds up once it has", () => {
const state = table();
state.seats[0].stack = 350;
state.seats[1].stack = 50;
HoldemState.cashOut(state, 0);
HoldemState.startNextHand(state);
Betting.beginHand(state);
const bank = HoldemState.bankReconciliation(state);
assert.equal(Money.round(bank.chipsInPlay + bank.paidOut), bank.cashIn);
assert.equal(bank.balanced, true);
});
});
+158
View File
@@ -0,0 +1,158 @@
// The stylesheet has to keep picking from the scales.
//
// Before the token block went in, holdem.css used 42 different spacing values, 31 font
// sizes, 14 border-radii and 139 colours, and defined three custom properties. None of
// that was anybody's decision — each number was chosen at the moment it was needed, and
// the result read as crowded even where nothing overlapped, because a 0.42rem gap next
// to a 0.45rem gap next to a 0.5rem gap gives the eye no rhythm to lock onto.
//
// A one-off cleanup would last until the next `padding: 0.35rem`. So the scales are
// checked here instead: a new value has to be a step on one of them, or an exception
// with a reason written next to it.
//
// This reads the stylesheet as text rather than through a CSS parser, on purpose — the
// rest of this suite has no dependencies and runs in a second, and a regex over
// declarations is enough to catch the thing that actually happens, which is somebody
// (me) typing a number instead of reaching for a token.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
const path = require("path");
const CSS_PATH = path.join(__dirname, "..", "..", "JoshHeaps.Net", "wwwroot", "css", "casino", "holdem.css");
const css = fs.readFileSync(CSS_PATH, "utf8");
// Comments carry measurements and rationale — "measured at 342px tall on a phone" —
// and none of that is a declaration. Strip them before looking for values.
const declarations = css.replace(/\/\*[\s\S]*?\*\//g, "");
// Everything after the token block. The :root block is where the raw values are
// supposed to be.
const body = declarations.slice(declarations.indexOf("#potBadgeAmount,"));
const valuesIn = (properties, source = body) => {
const found = [];
// The lookbehind rejects a hyphen as well as a word character, so `scroll-padding`
// isn't read as `padding`. It caught the pot wizard's scroll-padding the moment
// that went in — correctly by its own rules, wrongly in substance: those two values
// are the measured heights of the dialog's sticky header and footer, a clearance
// like the action bar's, not a step in the spacing rhythm.
const re = new RegExp(`(?<![\\w-])(${properties.join("|")})\\s*:([^;}]*)`, "g");
let m;
while ((m = re.exec(source)) !== null) {
const [, prop, value] = m;
// calc() and env() do their own arithmetic on tokens; the tokens inside them
// are still checked, because the regex below looks at bare numbers only.
(value.match(/(?<![\w-])[0-9.]+(rem|px|em)\b/g) || []).forEach(v => found.push({ prop, value: v }));
}
return found;
};
describe("the spacing scale", () => {
// Hairlines and structural clearances, each one deliberate:
// 0px/1px/3px/4px/22px — borders, hairline offsets, and the 22px of room a seat
// puck's name gives the dealer button beside it.
// 5rem/9rem — how far the page has to scroll past the fixed action
// bar. Not rhythm; clearance for a thing of a known size.
const ALLOWED = new Set(["0px", "1px", "2px", "3px", "4px", "22px", "5rem", "9rem"]);
test("every gap, margin and padding comes off the scale", () => {
const offenders = valuesIn(
["padding", "padding-top", "padding-right", "padding-bottom", "padding-left",
"margin", "margin-top", "margin-right", "margin-bottom", "margin-left",
"gap", "row-gap", "column-gap"])
.filter(v => !ALLOWED.has(v.value));
assert.deepEqual(offenders, [],
"use var(--sp-0 … --sp-6), or add the value to ALLOWED with a reason");
});
test("and the scale is the one the tokens define", () => {
["--sp-0", "--sp-1", "--sp-2", "--sp-3", "--sp-4", "--sp-5", "--sp-6"]
.forEach(token => assert.match(css, new RegExp(`\\${token}:`), `${token} is not defined`));
});
});
describe("the type scale", () => {
// 16px — the size below which iOS zooms the page when a field is focused, so
// every text input states it. Not a typographic choice.
// 1.05em, 0.44rem — relative bumps inside a component, and the shrink-to-fit for
// a six-figure stack on a 58px seat puck.
const ALLOWED = new Set(["16px", "1.05em", "0.44rem"]);
test("every font-size comes off the scale", () => {
const offenders = valuesIn(["font-size"]).filter(v => !ALLOWED.has(v.value));
assert.deepEqual(offenders, [],
"use var(--fs-2xs … --fs-2xl), or add the value to ALLOWED with a reason");
});
test("and the scale is the one the tokens define", () => {
["--fs-2xs", "--fs-xs", "--fs-sm", "--fs-base", "--fs-md", "--fs-lg", "--fs-xl", "--fs-2xl"]
.forEach(token => assert.match(css, new RegExp(`\\${token}:`), `${token} is not defined`));
});
});
describe("the corner scale", () => {
test("every border-radius comes off it", () => {
const offenders = valuesIn(["border-radius"]).filter(v => v.value !== "2px");
assert.deepEqual(offenders, [], "use var(--r-sm | --r-md | --r-lg | --r-pill)");
});
});
describe("the tokens themselves", () => {
test("every var() the stylesheet reaches for exists", () => {
const used = new Set((css.match(/var\((--[a-zA-Z0-9-]+)/g) || []).map(s => s.slice(4)));
// Published from JS at runtime rather than declared here — see actionBar.js for
// the first two, render.js for the seat width and the chip's denomination colour,
// which is picked per chip from the amount on it.
const fromScript = new Set([
"--actionBarHeight", "--feltRoomPx", "--seatPuckW", "--betChipColour",
]);
// Defined by the site's own stylesheet, not this one.
const fromSite = new Set(["--font-mono"]);
const missing = [...used].filter(t =>
!fromScript.has(t) && !fromSite.has(t) && !new RegExp(`\\${t}\\s*:`).test(css));
assert.deepEqual(missing, []);
});
test("and the dark surfaces stay off pure black", () => {
// Shadows are invisible on #000, so depth has to come from a lighter surface —
// and white text on true black is the pairing that smears on an OLED phone,
// which is what this tool is used on.
const surfaces = [...css.matchAll(/--surface-\d+:\s*(#[0-9a-fA-F]{3,8})/g)].map(m => m[1].toLowerCase());
assert.ok(surfaces.length >= 4, "the surface ramp should have four steps");
surfaces.forEach(hex => {
assert.notEqual(hex, "#000");
assert.notEqual(hex, "#000000");
});
});
});
describe("numbers that change while the dealer watches", () => {
test("are set in tabular figures", () => {
// A "1" is narrower than an "8" in a proportional face, so a pot ticking from
// $18 to $21 shuffles its digits sideways and the eye reads movement where
// there is only arithmetic.
assert.match(css, /font-variant-numeric:\s*tabular-nums/);
["#potBadgeAmount", ".seatPuckStack", ".actionPot", ".standingsRow"]
.forEach(sel => assert.ok(css.includes(sel),
`${sel} should be in the tabular-figures list`));
});
});
describe("controls that must not resize under a thumb", () => {
test("the undo pill has a fixed width, not a content width", () => {
// It names the last action, so its label changes on every tap. Measured across
// one hand before this: 148, 110, 109, 108, 109, 110, 120.
const rule = css.match(/\.actionUndo\s*\{[^}]*\}/);
assert.ok(rule, ".actionUndo rule not found");
assert.match(rule[0], /width:\s*[0-9.]+rem/);
});
test("and its label is the part that ellipsizes", () => {
const rule = css.match(/\.actionUndoLabel\s*\{[^}]*\}/);
assert.ok(rule, ".actionUndoLabel rule not found");
assert.match(rule[0], /text-overflow:\s*ellipsis/);
});
});
+71
View File
@@ -71,3 +71,74 @@ describe("a window with room to spare", () => {
assert.equal(room(844.4, 127.6, 223.2) % 1, 0);
});
});
describe("when the felt changes size, so does everything on it", () => {
// The felt is published as a custom property and the seats follow it on their own,
// because they are placed in percentages of it. A bet chip anchored inside a seat
// is not: it is placed in pixels off that seat's centre, worked out against the felt
// as it was, and nothing re-ran that when the felt moved.
//
// Measured at 640x360 with five players, on a felt that lost 23px of height: the
// chips were positioned for the old one and painted on the new, and seat 3's $5 came
// to rest on seat 4's puck. The seat pucks had the same problem — they are searched
// for a width the felt no longer has — and two pairs of them were overlapping.
//
// A side pot appearing does this too: it is 55px off the felt, mid-hand.
const fakeDom = (windowHeight = 900) => {
const root = { style: { values: {},
setProperty(k, v) { this.values[k] = v; },
getPropertyValue(k) { return this.values[k] || ""; } } };
global.document = {
documentElement: root,
getElementById: id => (id === "pokerTableWrap"
? { getBoundingClientRect: () => ({ top: 146 }) }
: null),
};
global.window = { innerHeight: windowHeight, scrollY: 0 };
return root;
};
const spyRender = () => {
const calls = { density: 0, seats: 0 };
global.Render = {
state: {},
updateSeatDensity() { calls.density++; },
renderSeats() { calls.seats++; },
};
return calls;
};
test.afterEach(() => {
delete global.document;
delete global.window;
delete global.Render;
});
test("a felt that changed height lays the seats out again", () => {
fakeDom();
const calls = spyRender();
ActionBar.publishFeltRoom(117);
assert.equal(calls.seats, 1, "first publish sets a height it did not have");
ActionBar.publishFeltRoom(172);
assert.equal(calls.seats, 2, "and a side pot grew the bar by 55px");
});
test("a felt that did not change is left alone", () => {
fakeDom();
const calls = spyRender();
ActionBar.publishFeltRoom(117);
ActionBar.publishFeltRoom(117);
ActionBar.publishFeltRoom(117);
assert.equal(calls.seats, 1,
"re-laying the table on every resize tick would be work for nothing");
assert.equal(calls.density, 3, "the cheap re-measure still runs each time");
});
test("it publishes the height whether or not anything is listening", () => {
const root = fakeDom();
delete global.Render;
assert.doesNotThrow(() => ActionBar.publishFeltRoom(117));
assert.match(root.style.getPropertyValue("--feltRoomPx"), /^\d+px$/);
});
});
+415
View File
@@ -0,0 +1,415 @@
// What beats what.
//
// This is the one module in the tool that can pay the wrong person without anybody
// noticing. A pot wizard that asks "who won?" is only ever as wrong as the dealer
// ticking the box; one that answers the question itself is wrong on its own account,
// silently, and a table that has come to trust it will not check. So the ordering is
// tested from both ends: every category against every other, the traps that a
// hand-rolled evaluator gets wrong (the wheel, the counterfeited kicker, the board
// that plays), and then a lot of random seven-card hands against a second
// implementation written a different way.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { HandRank } = require("./load");
const best = (...cards) => HandRank.best(cards.flat());
const beats = (a, b) => HandRank.compare(a, b) > 0;
const chops = (a, b) => HandRank.compare(a, b) === 0;
// A hand written as one string, for the tests that list a lot of them.
const hand = str => str.trim().split(/\s+/);
describe("the five-card hand", () => {
const of = str => HandRank.evaluate5(hand(str));
test("each category is recognised", () => {
const cases = [
["AS KS QS JS TS", HandRank.STRAIGHT_FLUSH, "Royal flush"],
["9H 8H 7H 6H 5H", HandRank.STRAIGHT_FLUSH, "Straight flush, nine high"],
["7C 7D 7H 7S 2C", HandRank.FOUR_OF_A_KIND, "Four of a kind, sevens"],
["KC KD KH 3S 3C", HandRank.FULL_HOUSE, "Full house, kings full of threes"],
["AD JD 8D 5D 2D", HandRank.FLUSH, "Flush, ace high"],
["9C 8D 7H 6S 5C", HandRank.STRAIGHT, "Straight, nine high"],
["QC QD QH 7S 2C", HandRank.THREE_OF_A_KIND, "Three of a kind, queens"],
["AC AD 8H 8S 4C", HandRank.TWO_PAIR, "Two pair, aces and eights"],
["QC QD 9H 5S 2C", HandRank.ONE_PAIR, "Pair of queens"],
["AC JD 8H 5S 2C", HandRank.HIGH_CARD, "Ace high"],
];
cases.forEach(([cards, category, described]) => {
const ranked = of(cards);
assert.equal(ranked.category, category, cards);
assert.equal(HandRank.describe(ranked), described, cards);
});
});
test("the categories are in the right order", () => {
// Listed weakest first, then every pair checked both ways round. The order
// itself is the thing being asserted, so it is written out rather than derived
// from the constants it is meant to be checking.
const ladder = [
"AC JD 8H 5S 2C", // ace high
"2C 2D 8H 5S 3C", // a pair of deuces
"AC AD 8H 8S 4C", // two pair
"3C 3D 3H 7S 2C", // trips
"9C 8D 7H 6S 5C", // straight
"AD JD 8D 5D 2D", // flush
"2C 2D 2H 3S 3C", // full house
"7C 7D 7H 7S 2C", // quads
"9H 8H 7H 6H 5H", // straight flush
];
for (let low = 0; low < ladder.length; low++) {
for (let high = low + 1; high < ladder.length; high++) {
assert.ok(beats(of(ladder[high]), of(ladder[low])),
`${ladder[high]} should beat ${ladder[low]}`);
assert.ok(!beats(of(ladder[low]), of(ladder[high])),
`${ladder[low]} should not beat ${ladder[high]}`);
}
}
});
test("the same hand in different suits is a chop", () => {
assert.ok(chops(of("AC KD 8H 5S 2C"), of("AS KH 8D 5C 2H")));
assert.ok(chops(of("QC QD 9H 5S 2C"), of("QH QS 9D 5C 2H")));
});
test("nothing but five real cards is a hand", () => {
assert.equal(HandRank.evaluate5(hand("AC KD 8H 5S")), null, "four");
assert.equal(HandRank.evaluate5(hand("AC KD 8H 5S 2C 3D")), null, "six");
assert.equal(HandRank.evaluate5(["AC", "KD", "8H", "5S", "ZZ"]), null, "nonsense");
assert.equal(HandRank.evaluate5(["AC", "KD", "8H", "5S", ""]), null, "an empty slot");
assert.equal(HandRank.evaluate5(null), null);
});
test("case does not matter, because the picker is not the only way cards get in", () => {
assert.ok(chops(of("ac kd 8h 5s 2c"), of("AC KD 8H 5S 2C")));
});
});
describe("the wheel", () => {
const of = str => HandRank.evaluate5(hand(str));
// The straight that runs through the ace at the bottom. An evaluator that scores a
// straight by its top card and lets the ace keep its usual value makes A-2-3-4-5
// the best straight there is instead of the worst — which pays the wrong player
// every time it comes up against a broadway.
test("A-2-3-4-5 is a straight", () => {
assert.equal(of("AC 2D 3H 4S 5C").category, HandRank.STRAIGHT);
assert.equal(HandRank.describe(of("AC 2D 3H 4S 5C")), "Straight, five high");
});
test("and it is the lowest one", () => {
assert.ok(beats(of("6C 5D 4H 3S 2C"), of("AC 2D 3H 4S 5C")),
"six high beats the wheel");
assert.ok(beats(of("AC KD QH JS TC"), of("AC 2D 3H 4S 5C")),
"broadway beats the wheel");
});
test("the same goes for a steel wheel", () => {
const steel = of("AH 2H 3H 4H 5H");
assert.equal(steel.category, HandRank.STRAIGHT_FLUSH);
assert.equal(HandRank.describe(steel), "Straight flush, five high");
assert.ok(beats(of("6H 5H 4H 3H 2H"), steel));
assert.ok(beats(of("AS KS QS JS TS"), steel));
});
test("an ace with a four-card run either side of it is not a straight", () => {
// K-A-2-3-4 does not wrap.
assert.equal(of("KC AD 2H 3S 4C").category, HandRank.HIGH_CARD);
assert.equal(of("QC KD AH 2S 3C").category, HandRank.HIGH_CARD);
});
});
describe("kickers", () => {
const of = str => HandRank.evaluate5(hand(str));
test("the fifth card settles two pair", () => {
assert.ok(beats(of("AC AD 8H 8S KC"), of("AH AS 8D 8C QC")));
assert.ok(chops(of("AC AD 8H 8S KC"), of("AH AS 8D 8C KD")));
});
test("and a pair, three kickers deep", () => {
assert.ok(beats(of("9C 9D AH 7S 2C"), of("9H 9S KD 7C 2D")), "first kicker");
assert.ok(beats(of("9C 9D AH 7S 2C"), of("9H 9S AD 6C 2D")), "second");
assert.ok(beats(of("9C 9D AH 7S 3C"), of("9H 9S AD 7C 2D")), "third");
});
test("the higher pair beats the better kicker", () => {
assert.ok(beats(of("TC TD 3H 2S 4C"), of("9C 9D AH KS QC")));
});
test("two pair is read by its higher pair first", () => {
assert.ok(beats(of("KC KD 2H 2S 3C"), of("QC QD JH JS AC")));
});
test("a full house is read by its trips first", () => {
assert.ok(beats(of("3C 3D 3H 2S 2C"), of("2D 2H 2C AS AD")));
});
test("a flush is read all the way down", () => {
assert.ok(beats(of("AD KD 8D 5D 3D"), of("AH KH 8H 5H 2H")));
assert.ok(chops(of("AD KD 8D 5D 3D"), of("AH KH 8H 5H 3H")));
});
});
describe("the best five out of seven", () => {
test("it finds the flush the two hole cards do not both belong to", () => {
const ranked = best(["AH", "2C"], ["KH", "QH", "7H", "3H", "9S"]);
assert.equal(ranked.category, HandRank.FLUSH);
assert.equal(HandRank.describe(ranked), "Flush, ace high");
});
test("it plays the board when the board is better than anything you hold", () => {
// Nobody can beat a royal on the board; both hands are the board itself.
const board = ["AS", "KS", "QS", "JS", "TS"];
const one = best(["2C", "3D"], board);
const two = best(["7H", "8H"], board);
assert.equal(HandRank.describe(one), "Royal flush");
assert.ok(chops(one, two), "the board plays, so it is a chop");
});
test("it does not use three hole cards, because there are only two", () => {
const ranked = best(["AC", "AD"], ["AH", "KS", "KD", "2C", "3H"]);
assert.equal(HandRank.describe(ranked), "Full house, aces full of kings");
});
test("a counterfeited two pair falls back on the board", () => {
// Holding 6-5 on a board of 8-8-K-K-A: the player's two pair is counterfeited —
// the best five are the board's two pair with the ace, and the sixes never play.
const ranked = best(["6C", "5D"], ["8H", "8S", "KC", "KD", "AC"]);
assert.equal(HandRank.describe(ranked), "Two pair, kings and eights");
assert.deepEqual([...ranked.cards].sort(), ["8H", "8S", "AC", "KC", "KD"].sort());
});
test("five, six and seven cards are all rankable; four is not", () => {
assert.ok(best(["AC", "KD"], ["QH", "JS", "TC"]), "five");
assert.ok(best(["AC", "KD"], ["QH", "JS", "TC", "2D"]), "six");
assert.ok(best(["AC", "KD"], ["QH", "JS", "TC", "2D", "3H"]), "seven");
assert.equal(best(["AC", "KD"], ["QH", "JS"]), null, "four");
});
test("the same card twice is not a hand", () => {
// A mis-entry, not a monster. Ranking it would mean ranking a deck that does
// not exist, and the answer would look exactly as confident as a real one.
assert.equal(best(["AC", "AC"], ["KH", "QS", "JD", "2C", "3H"]), null);
assert.equal(best(["AC", "KD"], ["KD", "QS", "JD", "2C", "3H"]), null);
});
});
describe("the showdown", () => {
const board = ["AH", "KD", "9C", "4S", "2H"];
test("it names one winner and says how it read every hand", () => {
const result = HandRank.showdown(board, [
{ id: "a", cards: ["AS", "KC"] }, // two pair, aces and kings
{ id: "b", cards: ["9H", "9S"] }, // trips
{ id: "c", cards: ["AC", "3D"] }, // a pair of aces
]);
assert.equal(result.complete, true);
assert.deepEqual(result.winners, ["b"]);
assert.deepEqual(result.players.map(p => p.place), [2, 1, 3]);
assert.deepEqual(result.players.map(p => HandRank.describe(p.hand)), [
"Two pair, aces and kings",
"Three of a kind, nines",
"Pair of aces",
]);
});
test("a chop comes back as two winners on the same place", () => {
const result = HandRank.showdown(board, [
{ id: "a", cards: ["AS", "QC"] },
{ id: "b", cards: ["AD", "QH"] },
{ id: "c", cards: ["7H", "5S"] },
]);
assert.deepEqual(result.winners.sort(), ["a", "b"]);
assert.deepEqual(result.players.map(p => p.place), [1, 1, 3],
"and the player behind them is third, not second");
});
test("an incomplete board is not a showdown", () => {
const result = HandRank.showdown(["AH", "KD", "9C"], [
{ id: "a", cards: ["AS", "KC"] },
{ id: "b", cards: ["9H", "9S"] },
]);
assert.equal(result.boardComplete, false);
assert.equal(result.complete, false);
assert.deepEqual(result.winners, [], "it must not name one");
});
test("one unknown hand and it will not say who won", () => {
// Who is *ahead* and who *won* are different claims, and the second one is the
// only one that can pay somebody. A player who never turned their cards over
// could have anything.
const result = HandRank.showdown(board, [
{ id: "a", cards: ["AS", "KC"] },
{ id: "b", cards: ["", ""] },
]);
assert.equal(result.complete, false);
assert.deepEqual(result.winners, []);
assert.deepEqual(result.unknown, ["b"]);
assert.ok(result.players[0].hand, "but it still reads the hands it can");
assert.equal(result.players[1].hand, null);
});
test("a card in two places stops it dead", () => {
const result = HandRank.showdown(board, [
{ id: "a", cards: ["AH", "KC"] }, // the ace of hearts is on the board
{ id: "b", cards: ["9H", "9S"] },
]);
assert.equal(result.duplicated, true);
assert.equal(result.complete, false);
assert.deepEqual(result.winners, []);
});
test("no players at all is not a showdown either", () => {
const result = HandRank.showdown(board, []);
assert.equal(result.complete, false);
assert.deepEqual(result.winners, []);
});
});
describe("against a second opinion", () => {
// The strongest check available without a poker library: a completely separate
// ranking, written the other way round — every hand turned into a sortable string
// by counting ranks, with no shared helper between it and the module. Where the two
// disagree, one of them is wrong and the test says which hand it was.
const VALUE = { T: 10, J: 11, Q: 12, K: 13, A: 14 };
const val = card => VALUE[card[0]] || Number(card[0]);
function reference5(cards) {
const ranks = cards.map(val).sort((x, y) => y - x);
const suited = new Set(cards.map(c => c[1])).size === 1;
const tally = {};
ranks.forEach(r => { tally[r] = (tally[r] || 0) + 1; });
const bySize = Object.keys(tally)
.map(Number)
.sort((x, y) => tally[y] - tally[x] || y - x);
const sizes = bySize.map(r => tally[r]).join("");
const unique = [...new Set(ranks)];
let run = null;
if (unique.length === 5) {
if (unique[0] - unique[4] === 4) run = unique[0];
else if (unique.join(",") === "14,5,4,3,2") run = 5;
}
// [category, ...tiebreak], the same shape, arrived at from the group sizes
// rather than from a chain of ifs about shape[0] and shape[1].
if (suited && run !== null) return [8, run];
if (sizes === "41") return [7, ...bySize];
if (sizes === "32") return [6, ...bySize];
if (suited) return [5, ...ranks];
if (run !== null) return [4, run];
if (sizes === "311") return [3, ...bySize];
if (sizes === "221") return [2, ...bySize];
if (sizes === "2111") return [1, ...bySize];
return [0, ...ranks];
}
const worse = (a, b) => {
for (let i = 0; i < Math.max(a.length, b.length); i++) {
if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) < (b[i] || 0);
}
return false;
};
function referenceBest(cards) {
let top = null;
for (let a = 0; a < 3; a++) for (let b = a + 1; b < 4; b++)
for (let c = b + 1; c < 5; c++) for (let d = c + 1; d < 6; d++)
for (let e = d + 1; e < 7; e++) {
const score = reference5([cards[a], cards[b], cards[c], cards[d], cards[e]]);
if (!top || worse(top, score)) top = score;
}
return top;
}
// A deck, and a deterministic shuffle — a failure has to be reproducible or it is
// just an anecdote about one CI run.
const DECK = [];
"23456789TJQKA".split("").forEach(r => "SHDC".split("").forEach(s => DECK.push(r + s)));
let seed = 20260904;
const random = () => {
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
return seed / 0x7fffffff;
};
test("twenty thousand random seven-card hands rank the same way", () => {
const deck = [...DECK];
for (let round = 0; round < 20000; round++) {
// Seven off the top of a shuffle of only what it needs.
const drawn = [];
for (let i = 0; i < 7; i++) {
const pick = i + Math.floor(random() * (deck.length - i));
[deck[i], deck[pick]] = [deck[pick], deck[i]];
drawn.push(deck[i]);
}
const mine = HandRank.best(drawn);
const theirs = referenceBest(drawn);
assert.deepEqual([mine.category, ...mine.tiebreak], theirs,
`disagreed on ${drawn.join(" ")}`);
}
});
test("and four thousand random pairs of hands are ordered the same way", () => {
// The categories agreeing is not the same as the comparison agreeing: this is
// the half that pays somebody.
const deck = [...DECK];
for (let round = 0; round < 4000; round++) {
const drawn = [];
for (let i = 0; i < 9; i++) {
const pick = i + Math.floor(random() * (deck.length - i));
[deck[i], deck[pick]] = [deck[pick], deck[i]];
drawn.push(deck[i]);
}
const board = drawn.slice(0, 5);
const one = [...board, drawn[5], drawn[6]];
const two = [...board, drawn[7], drawn[8]];
const mine = Math.sign(HandRank.compare(HandRank.best(one), HandRank.best(two)));
const a = referenceBest(one), b = referenceBest(two);
const theirs = worse(a, b) ? -1 : worse(b, a) ? 1 : 0;
assert.equal(mine, theirs,
`board ${board.join(" ")}: ${drawn[5]}${drawn[6]} vs ${drawn[7]}${drawn[8]}`);
}
});
});
describe("saying it in a sentence", () => {
// The verdict line reads "Alexandra wins $25 with ___", so the phrase has to carry
// its own article. Which article is not something the first letter can answer: it
// is "a full house" and "a flush", but "four of a kind" and "two pair" take none,
// and nobody has ever said "an ace high".
test("every category takes the article a table would give it", () => {
const said = str => HandRank.phrase(HandRank.evaluate5(hand(str)));
assert.deepEqual([
said("AS KS QS JS TS"),
said("9H 8H 7H 6H 5H"),
said("7C 7D 7H 7S 2C"),
said("KC KD KH 3S 3C"),
said("AD JD 8D 5D 2D"),
said("9C 8D 7H 6S 5C"),
said("QC QD QH 7S 2C"),
said("AC AD 8H 8S 4C"),
said("QC QD 9H 5S 2C"),
said("AC JD 8H 5S 2C"),
], [
"a royal flush",
"a straight flush, nine high",
"four of a kind, sevens",
"a full house, kings full of threes",
"a flush, ace high",
"a straight, nine high",
"three of a kind, queens",
"two pair, aces and eights",
"a pair of queens",
"ace high",
]);
});
test("with nothing to say it says something", () => {
assert.equal(HandRank.phrase(null), "the best hand");
});
});
+7
View File
@@ -15,6 +15,7 @@ function load(name) {
}
const Money = load("money");
const HandRank = load("handRank");
const PotCalculator = load("potCalculator");
const SplitCalculator = load("splitCalculator");
const Betting = load("betting");
@@ -33,6 +34,10 @@ globalThis.HoldemState = HoldemState;
// its methods reach for both. Loaded last so nothing it touches is still undefined.
const ActionBar = load("actionBar");
// The picker's slot bookkeeping — which slots it is filling, what is already dealt —
// is plain state work and testable here. Only render() and open() touch the DOM.
const CardPicker = load("cardPicker");
// ---- Table builders ----------------------------------------------------------
// A table with `seatCount` chairs where `seated` (a list of seat indexes) are dealt
@@ -78,6 +83,7 @@ function contributions(state) {
module.exports = {
Money,
HandRank,
Render,
HandHistoryExport,
PotCalculator,
@@ -86,6 +92,7 @@ module.exports = {
Betting,
HoldemState,
ActionBar,
CardPicker,
makeTable,
chipsOnTable,
contributions,
+155
View File
@@ -0,0 +1,155 @@
// Taking a hand back.
//
// The rulings sheet in this tool has told dealers to redeal since the day it was
// written — first card to the wrong seat, a seat entitled to a hand dealt out, one of
// the first two cards exposed — and the tool had no way to do it. The only control that
// ended a live hand was Next Hand, which says out loud that it takes the money off the
// table without paying anybody. That is right for an abandoned pot and wrong for a
// misdeal, where the blinds and the calls belong to the people who put them in.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Money, Betting, HoldemState, makeTable, chipsOnTable } = require("./load");
const dealt = (extra = {}) => {
const state = makeTable({ seatCount: 6, stack: 200, smallBlind: 5, bigBlind: 10, dealerSeatIndex: 0, ...extra });
Betting.beginHand(state);
return state;
};
describe("the money", () => {
test("goes back to the people who put it in", () => {
const state = dealt();
const before = state.seats.map(p => Betting.stackOf(state, p) + Betting.committed(p));
Betting.takeHandBack(state);
assert.deepEqual(state.seats.map(p => Betting.stackOf(state, p)), before);
});
test("including calls and raises, not just the blinds", () => {
const state = dealt();
Betting.raiseTo(state, state.actingSeatIndex, 40);
Betting.call(state, state.actingSeatIndex);
assert.ok(Betting.potSoFar(state) > 50, "there is real money in the middle");
const taken = Betting.takeHandBack(state);
assert.equal(taken.total, 95, "blinds and both wagers");
assert.deepEqual(state.seats.map(p => Betting.stackOf(state, p)), [200, 200, 200, 200, 200, 200]);
});
test("and across streets, once chips have been swept into hand totals", () => {
const state = dealt();
[3, 4, 5, 0, 1, 2].forEach(seat => {
if (state.actingSeatIndex !== null) Betting.call(state, state.actingSeatIndex);
});
Betting.closeStreet(state);
assert.ok(state.seats.some(p => (Number(p.amountOverride) || 0) > 0), "the flop's money is banked");
Betting.takeHandBack(state);
assert.deepEqual(state.seats.map(p => Betting.stackOf(state, p)), [200, 200, 200, 200, 200, 200]);
assert.deepEqual(state.seats.map(p => p.amountOverride), [null, null, null, null, null, null]);
});
test("the table has exactly the chips it started with", () => {
const fresh = makeTable({ seatCount: 6, stack: 200, smallBlind: 5, bigBlind: 10 });
const total = chipsOnTable(fresh);
const state = dealt();
Betting.raiseTo(state, state.actingSeatIndex, 40);
Betting.takeHandBack(state);
assert.equal(chipsOnTable(state), total);
});
test("nothing is thrown away — the discard pile doesn't move", () => {
const state = dealt();
state.discarded = 8;
Betting.takeHandBack(state);
assert.equal(state.discarded, 8, "a misdeal is not an abandoned pot");
});
test("it says what went back and to whom", () => {
const state = dealt();
const taken = Betting.takeHandBack(state);
assert.equal(taken.returned.length, 2, "the two blinds");
assert.deepEqual(taken.returned.map(r => r.amount).sort((a, b) => a - b), [5, 10]);
assert.ok(taken.returned.every(r => r.name), "named, because the dealer says it out loud");
});
});
describe("the table afterwards", () => {
test("is waiting to deal the same hand again", () => {
const state = dealt();
Betting.takeHandBack(state);
assert.equal(state.bettingOpen, false, "the dealer says when");
assert.equal(state.street, "preflop");
assert.equal(state.actingSeatIndex, null);
assert.equal(state.currentBet, 0);
});
test("keeps the button where it was — a misdeal is not the next hand", () => {
const state = dealt({ dealerSeatIndex: 3 });
const handNumber = state.handNumber;
Betting.takeHandBack(state);
assert.equal(state.dealerSeatIndex, 3);
assert.equal(state.handNumber, handNumber, "no hand has been played");
assert.equal((state.handHistory || []).length, 0, "and none is logged");
});
test("keeps the straddle, which was announced and still stands", () => {
const state = makeTable({ seatCount: 6, stack: 200, smallBlind: 5, bigBlind: 10 });
state.straddleCount = 1;
Betting.beginHand(state);
assert.deepEqual(state.postedStraddles, [3]);
Betting.takeHandBack(state);
assert.equal(state.straddleCount, 1, "still on for the redeal");
assert.deepEqual(state.postedStraddles, [], "but nothing is out there yet");
Betting.beginHand(state);
assert.deepEqual(state.postedStraddles, [3], "and it goes out again");
});
test("clears the cards and the folds, because none of it happened", () => {
const state = dealt();
state.seats[3].cards = ["As", "Kd"];
Betting.fold(state, 3);
Betting.takeHandBack(state);
assert.deepEqual(state.seats[3].cards, ["", ""]);
assert.equal(state.seats[3].folded, false);
assert.ok(state.seats.every(p => !p.hasActed));
});
test("deals again cleanly, with the same blinds on the same players", () => {
const state = dealt();
const first = state.seats.map(p => Betting.committed(p));
Betting.takeHandBack(state);
Betting.beginHand(state);
assert.deepEqual(state.seats.map(p => Betting.committed(p)), first);
});
});
describe("the bank still balances", () => {
test("through a misdeal and the redeal after it", () => {
const state = dealt();
state.seats.forEach(p => { p.buyIns = 200; });
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
Betting.raiseTo(state, state.actingSeatIndex, 60);
Betting.takeHandBack(state);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
Betting.beginHand(state);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, true);
assert.equal(bank.cashIn, 1200);
});
});
describe("taking back a hand nobody had money in", () => {
test("is harmless: no blinds, nothing moves", () => {
const state = makeTable({ seatCount: 6, stack: 200, smallBlind: 0, bigBlind: 0 });
Betting.beginHand(state);
const taken = Betting.takeHandBack(state);
assert.equal(taken.total, 0);
assert.deepEqual(taken.returned, []);
assert.equal(state.bettingOpen, false);
});
});
+133
View File
@@ -0,0 +1,133 @@
// One question, one answer.
//
// The round before this found the bank check and the standings reading `seat.stack`
// where the felt reads the table's starting stack — two parts of the tool disagreeing
// about how much money is on the table. This is the sweep that followed: everywhere
// else the same two questions get asked, asked the same way.
//
// "What is this seat holding?" -> HoldemState.chipsHeldBy
// "Is anybody in this chair?" -> HoldemState.seatInPlay
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { HoldemState, Betting, SettleUp } = require("./load");
const openedOnTheDefault = (stack = 200) => {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 6);
state.defaultStack = stack;
["Ann", "Ben", "Cal"].forEach((name, i) => {
state.seats[i].name = name;
state.seats[i].inHand = true;
state.seats[i].buyIns = stack;
});
return state;
};
describe("what a seat is holding", () => {
test("is the same number the felt plays with", () => {
const state = openedOnTheDefault();
state.seats.forEach((player, i) => {
if (i > 2) return;
assert.equal(HoldemState.chipsHeldBy(state, player), Betting.stackOf(state, player));
});
});
test("and is nothing at all for an empty chair", () => {
const state = openedOnTheDefault();
// Betting's own answer for an empty chair is the table default, because it is
// only ever asked about seats that are in a hand. The money side has to ask
// about all ten chairs, so it checks whether anybody is in them first.
assert.equal(Betting.stackOf(state, state.seats[5]), 200);
assert.equal(HoldemState.chipsHeldBy(state, state.seats[5]), 0);
});
test("counts a stack the dealer typed over the table's default", () => {
const state = openedOnTheDefault();
state.seats[0].stack = 75;
assert.equal(HoldemState.chipsHeldBy(state, state.seats[0]), 75);
});
});
describe("is anybody in this chair", () => {
const empty = () => HoldemState.createDefault().seats[0];
test("an untouched chair is empty", () => {
assert.equal(HoldemState.seatInPlay(empty()), false);
assert.equal(HoldemState.seatInPlay(null), false);
});
test("a name, chips, cash, a bet or a dealt hand all count", () => {
[
["a name", p => { p.name = "Ann"; }],
["chips", p => { p.stack = 50; }],
["cash taken", p => { p.buyIns = 100; }],
["a bet in front of them", p => { p.committed = 5; }],
["money already swept in", p => { p.amountOverride = 20; }],
["a hand dealt to them", p => { p.inHand = true; }],
].forEach(([what, mark]) => {
const seat = empty();
mark(seat);
assert.equal(HoldemState.seatInPlay(seat), true, what);
});
});
test("whitespace is not a name", () => {
const seat = empty();
seat.name = " ";
assert.equal(HoldemState.seatInPlay(seat), false);
});
});
describe("the parts that used to disagree", () => {
test("the open seats and the seat count see the same empty chairs", () => {
const state = openedOnTheDefault();
// Three players, six chairs.
assert.deepEqual(HoldemState.openSeats(state), [3, 4, 5]);
const occupied = state.seats.filter(p => HoldemState.seatInPlay(p)).length;
assert.equal(occupied + HoldemState.openSeats(state).length, state.seats.length);
});
test("a chair holding only a dealt hand is not offered to the waiting list", () => {
// The old test looked at name, buy-ins and stack. A seat marked in-hand with
// none of those would have been handed to the next person in the queue, on top
// of whoever was already playing it.
const state = openedOnTheDefault();
state.seats[4].inHand = true;
assert.deepEqual(HoldemState.openSeats(state), [3, 5]);
HoldemState.addToWaitingList(state, "Priya");
const result = HoldemState.seatFromWaitingList(state, state.waitingList[0].id, 4);
assert.equal(result.ok, false);
});
test("the bank, the standings and the settle-up all price the night the same way", () => {
const state = openedOnTheDefault();
state.seats[0].stack = 320; // Ann is up
state.seats[1].stack = 80; // Ben is down
const bank = HoldemState.bankReconciliation(state);
const standings = HoldemState.sessionStandings(state);
const chipsFromStandings = standings
.filter(row => !row.cashedOut)
.reduce((sum, row) => sum + row.chipsInFront, 0);
assert.equal(bank.chipsInPlay, chipsFromStandings, "same chips on the table");
assert.equal(bank.balanced, true);
// And the payments the dealer is told to make add up to the same money.
const plan = SettleUp.plan(standings);
const owed = standings.reduce((sum, row) => sum + Math.max(0, row.cashPosition), 0);
const paid = plan.payments.reduce((sum, row) => sum + row.amount, 0);
assert.equal(paid + (plan.shortBy || 0) - (plan.overBy || 0), owed);
});
test("a player still holding the table's starting stack is in all three", () => {
const state = openedOnTheDefault();
const standings = HoldemState.sessionStandings(state);
assert.equal(standings.length, 3);
assert.deepEqual(standings.map(row => row.chipsInFront), [200, 200, 200]);
assert.equal(HoldemState.bankReconciliation(state).chipsInPlay, 600);
assert.deepEqual(SettleUp.plan(standings).payments, [], "everyone is even, so nobody pays anybody");
});
});
+230
View File
@@ -0,0 +1,230 @@
// The house's cut.
//
// A game that rakes has chips leaving the table every hand, and the bank check used to
// call them missing: buy-ins in, chips on the felt, and a dealer told somebody had been
// paid for chips they never got. The cut is the one thing here that is supposed to go
// and not come back.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Money, HoldemState, Betting, makeTable, chipsOnTable } = require("./load");
const raking = (rake, extra = {}) => {
const state = makeTable({ seatCount: 6, stack: 200, ...extra });
state.rake = { percent: 0, cap: null, noFlopNoDrop: true, ...rake };
return state;
};
describe("what the house takes", () => {
test("nothing, unless somebody says otherwise", () => {
const state = makeTable({ seatCount: 6 });
assert.equal(state.rake.percent, 0);
assert.equal(HoldemState.rakeOn(state, 100), 0);
});
test("a percentage of the pot", () => {
assert.equal(HoldemState.rakeOn(raking({ percent: 5 }), 100), 5);
assert.equal(HoldemState.rakeOn(raking({ percent: 10 }), 60), 6);
});
test("no more than the cap", () => {
const state = raking({ percent: 5, cap: 5 });
assert.equal(HoldemState.rakeOn(state, 100), 5);
assert.equal(HoldemState.rakeOn(state, 400), 5, "still five on a pot four times the size");
assert.equal(HoldemState.rakeOn(state, 40), 2, "under the cap it is just the percentage");
});
test("no flop, no drop", () => {
const state = raking({ percent: 5 });
assert.equal(HoldemState.rakeOn(state, 100, false), 0, "hand ended before the flop");
assert.equal(HoldemState.rakeOn(state, 100, true), 5);
});
test("unless the house rakes every pot", () => {
const state = raking({ percent: 5, noFlopNoDrop: false });
assert.equal(HoldemState.rakeOn(state, 100, false), 5);
});
test("nothing it can't make out of the table's chips, rounded the players' way", () => {
// 5% of $30 is $1.50, and this table's smallest chip is a dollar.
const state = raking({ percent: 5 });
assert.equal(HoldemState.rakeOn(state, 30), 1);
// 5% of $10 is 50c — under a chip, so the house takes nothing at all.
assert.equal(HoldemState.rakeOn(state, 10), 0);
});
test("never more than the pot, whatever gets typed in", () => {
assert.equal(HoldemState.rakeOn(raking({ percent: 100 }), 20), 20);
assert.equal(HoldemState.rakeOn(raking({ percent: 5, cap: 500 }), 20), 1);
});
test("nothing out of an empty pot", () => {
assert.equal(HoldemState.rakeOn(raking({ percent: 5 }), 0), 0);
});
});
describe("taking it out of the pot", () => {
const winner = amount => [{ id: "a", label: "Ann", amount }];
test("one winner just gets the pot less the cut", () => {
const { payouts, rake } = HoldemState.applyRake(winner(100), 5);
assert.equal(rake, 5);
assert.deepEqual(payouts.map(p => p.amount), [95]);
});
test("a split pot shares what's left, in proportion", () => {
const { payouts } = HoldemState.applyRake(
[{ id: "a", label: "Ann", amount: 60 }, { id: "b", label: "Ben", amount: 40 }], 10);
assert.deepEqual(payouts.map(p => p.amount), [54, 36]);
});
test("the rounding leftovers go back to the players, not to the house", () => {
// $100 split three ways less $7: 93 doesn't divide evenly, and every cent of
// it has to land on somebody.
const { payouts, rake } = HoldemState.applyRake([
{ id: "a", label: "Ann", amount: 34 },
{ id: "b", label: "Ben", amount: 33 },
{ id: "c", label: "Cal", amount: 33 },
], 7);
assert.equal(rake, 7);
assert.equal(Money.round(payouts.reduce((sum, p) => sum + p.amount, 0)), 93);
});
test("what goes out plus what the house keeps is what was in the middle", () => {
[[100, 5], [37.5, 1.25], [1000, 0], [9, 9]].forEach(([pot, rake]) => {
const result = HoldemState.applyRake(winner(pot), rake);
assert.equal(Money.round(result.payouts[0].amount + result.rake), pot, `${pot} less ${rake}`);
});
});
test("asking for more than the pot takes the pot, not more", () => {
const { payouts, rake } = HoldemState.applyRake(winner(20), 50);
assert.equal(rake, 20);
assert.deepEqual(payouts.map(p => p.amount), [0]);
});
test("no rake, no change — the same payouts come back", () => {
const { payouts, rake } = HoldemState.applyRake(winner(80), 0);
assert.equal(rake, 0);
assert.deepEqual(payouts.map(p => p.amount), [80]);
});
});
describe("what the box is checked against", () => {
test("raked chips are gone but not missing", () => {
const state = raking({ percent: 5 });
state.seats.forEach(p => { p.buyIns = 200; });
const before = HoldemState.bankReconciliation(state);
assert.equal(before.balanced, true);
// The house takes $10 out of the middle: somebody's stack is $10 lighter.
state.seats[0].stack = 190;
state.rakeTaken = 10;
const after = HoldemState.bankReconciliation(state);
assert.equal(after.raked, 10);
assert.equal(after.balanced, true, "the check still balances");
});
test("and are told apart from the ones that went astray", () => {
const state = raking({ percent: 5 });
state.seats.forEach(p => { p.buyIns = 200; });
state.seats[0].stack = 180;
state.rakeTaken = 10;
const check = HoldemState.bankReconciliation(state);
assert.equal(check.raked, 10);
assert.equal(check.difference, -10, "ten dollars really are missing");
assert.equal(check.balanced, false);
});
test("a table that has never raked reads exactly as it did before", () => {
const state = makeTable({ seatCount: 6 });
state.seats.forEach(p => { p.buyIns = 100; p.stack = 100; });
const check = HoldemState.bankReconciliation(state);
assert.equal(check.raked, 0);
assert.equal(check.balanced, true);
});
});
describe("the record of it", () => {
test("the hand log keeps the pot as the table saw it, and the cut beside it", () => {
const state = raking({ percent: 5 });
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "P1", amount: 95 }], 5);
const [entry] = state.handHistory;
assert.equal(entry.pot, 100, "the pot in the middle");
assert.equal(entry.rake, 5);
assert.equal(entry.payouts[0].amount, 95, "what the winner actually took");
});
test("a hand with no rake records a zero rather than nothing", () => {
const state = makeTable({ seatCount: 6 });
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "P1", amount: 40 }]);
assert.equal(state.handHistory[0].rake, 0);
assert.equal(state.handHistory[0].pot, 40);
});
test("a table saved before the house took anything takes nothing", () => {
const parsed = JSON.parse(JSON.stringify(makeTable({ seatCount: 6 })));
delete parsed.rake;
delete parsed.rakeTaken;
const migrated = HoldemState.migrate(parsed);
assert.equal(migrated.rake.percent, 0);
assert.equal(migrated.rake.noFlopNoDrop, true);
assert.equal(migrated.rakeTaken, 0);
});
test("nonsense in a saved rake is cleaned up rather than trusted", () => {
const parsed = JSON.parse(JSON.stringify(makeTable({ seatCount: 6 })));
parsed.rake = { percent: -5, cap: -1, noFlopNoDrop: false };
parsed.rakeTaken = -20;
const migrated = HoldemState.migrate(parsed);
assert.equal(migrated.rake.percent, 0);
assert.equal(migrated.rake.cap, null);
assert.equal(migrated.rake.noFlopNoDrop, false, "that one is a real choice");
assert.equal(migrated.rakeTaken, 0);
});
});
describe("the file the dealer hands over", () => {
const { HandHistoryExport } = require("./load");
test("has a column for what the house took", () => {
const state = raking({ percent: 5 });
HoldemState.recordHand(state, [{ id: "a", label: "Ann", amount: 95 }], 5);
HoldemState.recordHand(state, [{ id: "b", label: "Ben", amount: 40 }], 0);
// Oldest hand first, and money as bare numbers so a spreadsheet can total it.
const csv = HandHistoryExport.toCsv(state.handHistory);
const [header, raked, unraked] = csv.split("\n");
assert.match(header, /Pot,House take,Payouts/);
assert.match(raked, /,100\.00,5\.00,/, "the raked hand says how much was taken");
assert.match(unraked, /,40\.00,0\.00,/, "and the unraked one says nothing was");
});
});
describe("a raked hand, end to end", () => {
test("the chips add up: stacks plus the house's cut equal what was bought in", () => {
// 5/10 blinds, so six callers make a pot big enough for 5% to be a whole chip.
// At 1/2 the same hand makes $12, 5% of which is 60c and rounds away to
// nothing — which is the rule working, not a hand worth testing the bank on.
const state = raking({ percent: 5, cap: 5 }, { smallBlind: 5, bigBlind: 10 });
state.seats.forEach(p => { p.buyIns = 200; });
Betting.beginHand(state);
// Everyone calls the big blind, then it is checked down.
state.seats.forEach((p, i) => { if (p.inHand) Betting.putIn(state, i, Betting.toCall(state, p)); });
Betting.sweepToHandTotals(state);
const pot = state.seats.reduce((sum, p) => sum + (Number(p.amountOverride) || 0), 0);
const rake = HoldemState.rakeOn(state, pot, true);
assert.equal(pot, 60);
assert.equal(rake, 3);
const { payouts } = HoldemState.applyRake([{ id: state.seats[0].id, label: "P1", amount: pot }], rake);
state.rakeTaken = rake;
HoldemState.recordHand(state, payouts, rake);
Betting.creditWinnings(state, payouts);
HoldemState.startNextHand(state);
assert.equal(Money.round(chipsOnTable(state) + state.rakeTaken), 1200);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
});
+274
View File
@@ -0,0 +1,274 @@
// Reading the showdown: the picker that takes the cards in, and the pot maths that
// pays somebody on the strength of them.
//
// The evaluator is tested to death next door in handRank.test.js. What is tested here
// is the join — the two places where a correct ranking can still pay the wrong player:
// a side pot, where the question is asked again of a smaller field, and a card entered
// in two places, where the ranking is of a deck that does not exist.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { CardPicker, HandRank, HoldemState, PotCalculator, Money, makeTable } = require("./load");
describe("the picker, filling the board", () => {
const table = (board = ["", "", "", "", ""]) => {
const state = makeTable({ seatCount: 4, stack: 100 });
state.board = board;
return state;
};
// The sheet's own drawing is the DOM's business; the slot bookkeeping under it is
// not, and that is what these ask about.
const headless = () => { CardPicker.render = () => {}; CardPicker.close = () => {}; };
const onBoard = (state, cardIndex = 0, limit = 5) => {
headless();
CardPicker.state = state;
CardPicker.hooks = { onPick: () => {} };
CardPicker.target = "board";
CardPicker.boardLimit = limit;
CardPicker.cardIndex = cardIndex;
return CardPicker;
};
const onSeat = (state, seatIndex, cardIndex = 0) => {
headless();
CardPicker.state = state;
CardPicker.hooks = { onPick: () => {} };
CardPicker.target = "seat";
CardPicker.seatIndex = seatIndex;
CardPicker.cardIndex = cardIndex;
return CardPicker;
};
test("it only offers the slots that have actually been turned", () => {
const state = table();
assert.equal(onBoard(state, 0, 3).slotValues().length, 3, "the flop is three");
assert.equal(onBoard(state, 0, 4).slotValues().length, 4, "the turn makes four");
assert.equal(onBoard(state, 0, 5).slotValues().length, 5);
});
test("a card goes into the board, not into a seat", () => {
const state = table();
onBoard(state, 1, 3).assign("KD");
assert.deepEqual(state.board, ["", "KD", "", "", ""]);
assert.deepEqual(state.seats[0].cards, ["", ""]);
});
test("it walks on to the next empty slot, so a flop is three taps", () => {
const state = table();
const picker = onBoard(state, 0, 3);
picker.assign("KD");
assert.equal(picker.cardIndex, 1);
picker.assign("9C");
assert.equal(picker.cardIndex, 2);
picker.assign("4S");
assert.deepEqual(state.board.slice(0, 3), ["KD", "9C", "4S"]);
});
test("and it does not walk past the slots it was given", () => {
// Filling the turn must not run on to the river: that card is still in the deck.
const state = table(["KD", "9C", "4S", "", ""]);
const picker = onBoard(state, 3, 4);
picker.assign("AH");
assert.deepEqual(state.board, ["KD", "9C", "4S", "AH", ""]);
});
test("clearing a slot empties that one and nothing else", () => {
const state = table(["KD", "9C", "4S", "", ""]);
onBoard(state, 1, 3).clearSlot();
assert.deepEqual(state.board, ["KD", "", "4S", "", ""]);
});
});
describe("a card cannot be in two places", () => {
const table = () => {
const state = makeTable({ seatCount: 4, stack: 100 });
state.board = ["KD", "9C", "4S", "", ""];
state.seats[0].cards = ["AH", "AS"];
state.seats[1].cards = ["", ""];
return state;
};
const picker = (state, setup) => {
CardPicker.state = state;
CardPicker.hooks = { onPick: () => {} };
setup();
return CardPicker;
};
test("the board's cards are unavailable to a hand", () => {
// The half of this that did not exist before: the picker knew about every
// player's cards and nothing about the middle of the table, so the king of
// diamonds on the flop could be dealt to somebody as well.
const state = table();
const used = picker(state, () => {
CardPicker.target = "seat";
CardPicker.seatIndex = 1;
CardPicker.cardIndex = 0;
}).cardsInUse();
assert.equal(used.get("KD"), "the board");
assert.equal(used.get("9C"), "the board");
assert.ok(used.has("AH"), "and the other players' are still in there");
});
test("and a hand's cards are unavailable to the board", () => {
const state = table();
const used = picker(state, () => {
CardPicker.target = "board";
CardPicker.boardLimit = 5;
CardPicker.cardIndex = 3;
}).cardsInUse();
assert.ok(used.has("AH"), "the ace in seat 1's hand");
assert.ok(used.has("KD"), "and the rest of the board");
});
test("but the slot being edited is not competing with itself", () => {
const state = table();
const used = picker(state, () => {
CardPicker.target = "board";
CardPicker.boardLimit = 3;
CardPicker.cardIndex = 0;
}).cardsInUse();
assert.equal(used.has("KD"), false, "re-picking what is already there is not a duplicate");
assert.equal(used.has("9C"), true);
});
test("the same goes for a seat's own slot", () => {
const state = table();
const used = picker(state, () => {
CardPicker.target = "seat";
CardPicker.seatIndex = 0;
CardPicker.cardIndex = 0;
}).cardsInUse();
assert.equal(used.has("AH"), false);
assert.equal(used.has("AS"), true, "the player's other card still is");
});
});
describe("who wins a side pot", () => {
// The case a single ranking of the whole table gets wrong. The best hand takes the
// main pot and is then out of the question: the side pot goes to the best of who is
// left, which is a different answer, and it is the answer the wizard has to ask for
// again each round rather than reading off one list.
//
// Three players, and the short stack has the best hand of the three.
const board = ["KD", "9C", "4S", "AH", "2H"];
const hands = {
short: ["9H", "9S"], // trips — the best hand at the table
big: ["AS", "KC"], // two pair, aces and kings
other: ["AC", "3D"], // a pair of aces
};
const entries = () => PotCalculator.buildEntries([
{ id: "short", contribution: 20, folded: false },
{ id: "big", contribution: 100, folded: false },
{ id: "other", contribution: 100, folded: false },
]);
// What the wizard does: read the hands still in for *this* round.
const readRound = state => HandRank.showdown(board,
PotCalculator.getContenders(state).map(c => ({ id: c.id, cards: hands[c.id] })));
test("the short stack takes the main pot with the best hand", () => {
const round = readRound(entries());
assert.equal(round.complete, true);
assert.deepEqual(round.winners, ["short"]);
});
test("and the side pot goes to the best of the two who are left", () => {
const first = PotCalculator.resolveRound(entries(), ["short"]);
// 20 from each of three: the short stack is paid 60 and is out of it.
assert.equal(Money.round(first.perWinner[0].amount), 60);
const round = readRound(first.updatedEntries);
assert.deepEqual(round.winners, ["big"],
"not the trips, which are no longer eligible for this money");
assert.equal(round.players.length, 2, "and the short stack is not even offered");
const second = PotCalculator.resolveRound(first.updatedEntries, ["big"]);
assert.equal(Money.round(second.perWinner[0].amount), 160);
});
test("every chip is accounted for across the two rounds", () => {
const first = PotCalculator.resolveRound(entries(), ["short"]);
const second = PotCalculator.resolveRound(first.updatedEntries, ["big"]);
assert.equal(Money.round(first.payoutPool + second.payoutPool), 220);
assert.equal(PotCalculator.getContenders(second.updatedEntries).length, 0);
});
});
describe("what it refuses to answer", () => {
const board = ["KD", "9C", "4S", "AH", "2H"];
test("a folded player's cards are not in the running", () => {
// They are not a contender, so they are never handed in — which means a hand
// that would have won cannot take a pot its owner threw away.
const table = PotCalculator.buildEntries([
{ id: "live", contribution: 50, folded: false },
{ id: "mucked", contribution: 50, folded: true },
]);
const contenders = PotCalculator.getContenders(table);
assert.deepEqual(contenders.map(c => c.id), ["live"]);
const round = HandRank.showdown(board, contenders.map(c => ({ id: c.id, cards: ["7C", "5D"] })));
assert.deepEqual(round.winners, ["live"], "even holding nothing");
});
test("one hand not turned over and it hands the question back", () => {
const round = HandRank.showdown(board, [
{ id: "a", cards: ["9H", "9S"] },
{ id: "b", cards: ["", ""] },
]);
assert.equal(round.complete, false);
assert.deepEqual(round.winners, []);
assert.deepEqual(round.unknown, ["b"]);
});
test("a board still being dealt is not a showdown", () => {
const round = HandRank.showdown(["KD", "9C", "4S", "", ""], [
{ id: "a", cards: ["9H", "9S"] },
{ id: "b", cards: ["AS", "KC"] },
]);
assert.equal(round.complete, false);
assert.deepEqual(round.winners, []);
});
test("a card entered twice stops it rather than guessing", () => {
// The failure mode that matters: a mis-typed card produces a hand that ranks
// perfectly well and is not the one on the table. Refusing is the only honest
// answer, and the dealer picks the winner the way they always could.
const round = HandRank.showdown(board, [
{ id: "a", cards: ["9H", "9S"] },
{ id: "b", cards: ["KD", "QC"] }, // the king of diamonds is on the board
]);
assert.equal(round.duplicated, true);
assert.equal(round.complete, false);
assert.deepEqual(round.winners, []);
});
test("and two players holding the same card is caught as well", () => {
const round = HandRank.showdown(board, [
{ id: "a", cards: ["QH", "QS"] },
{ id: "b", cards: ["QH", "JC"] },
]);
assert.equal(round.duplicated, true);
assert.equal(round.complete, false);
});
});
describe("a table that never asked for any of this", () => {
test("has no board, tracks nothing, and reads no showdown", () => {
const state = HoldemState.createDefault();
assert.equal(state.trackBoard, false);
// Which is what the wizard checks before it reads anything at all — see
// readShowdown() in potWizard.js. With it off, an empty board would decline
// anyway, so the tool cannot start answering a question nobody asked.
const round = HandRank.showdown(state.board, [
{ id: "a", cards: ["9H", "9S"] },
{ id: "b", cards: ["AS", "KC"] },
]);
assert.equal(round.complete, false);
assert.deepEqual(round.winners, []);
});
});
+137 -49
View File
@@ -34,26 +34,55 @@ const OVERLAYS = [
];
// A table part-way through a real night: long names, uneven stacks, a hand log.
function seedTable() {
//
// Two of them. The sweep ran on one table shape for its whole life — five players at a
// nine-handed table — and how much room the felt has depends on how many people are
// sitting down more than on anything a viewport can tell you. A full table is where the
// seats crowd, and it was never once looked at: measured when it finally was, seventeen
// of fifty-four tables had one player's name or stack painted under another.
const TABLES = [
["half full", 9, [["Christopher", 1200], ["Mike from work", 800], ["Alexandra", 1500],
["Bob", 250], ["Dee", 600]], false],
["packed", 12, [["Christopher", 1200], ["Mike from work", 800], ["Alexandra", 1500],
["Bob", 250], ["Dee", 600], ["Sam", 900], ["Priya", 1100], ["Jonathan", 480],
["Al", 2000], ["Katarzyna", 340], ["Ted", 760], ["Wes", 1300]]],
// The half-full table again, with the board turned on and five cards on it. The
// board is furniture in the middle of the felt that nothing else was ever measured
// against — and where the middle cannot hold it, it moves to a strip above the
// table and takes the felt's height with it, which is the seats' problem too.
//
// Deliberately the same five players in the same nine chairs as the shape above, so
// the only thing that differs between them is the board. A seventh player would have
// told us that a seven-handed table crowds, which is true, already known, and not
// what this row is here to find out.
["board", 9, [["Christopher", 1200], ["Mike from work", 800], ["Alexandra", 1500],
["Bob", 250], ["Dee", 600]], true],
];
function seedTable([seats, players, board]) {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 9);
[["Christopher", 1200], ["Mike from work", 800], ["Alexandra", 1500], ["Bob", 250], ["Dee", 600]]
.forEach(([name, cash], i) => {
state.seats[i].name = name;
state.seats[i].inHand = true;
state.seats[i].buyIns = cash;
state.seats[i].stack = cash;
});
HoldemState.resizeSeats(state, seats);
players.forEach(([name, cash], i) => {
state.seats[i].name = name;
state.seats[i].inHand = true;
state.seats[i].buyIns = cash;
state.seats[i].stack = cash;
});
state.smallBlind = 5;
state.bigBlind = 10;
for (let hand = 1; hand <= 4; hand++) {
state.handHistory.push({
handNumber: hand, timestamp: Date.now(), pot: 120,
payouts: [{ id: state.seats[hand % 5].id, label: "P", amount: 120 }],
ledger: state.seats.slice(0, 5).map(p => ({ id: p.id, name: p.name, in: 30, won: 0 })),
payouts: [{ id: state.seats[hand % players.length].id, label: "P", amount: 120 }],
ledger: state.seats.slice(0, players.length)
.map(p => ({ id: p.id, name: p.name, in: 30, won: 0 })),
});
}
state.handNumber = 5;
if (board) {
state.trackBoard = true;
state.board = ["KD", "9C", "4S", "AH", "2H"];
}
HoldemState.save(state);
}
@@ -68,57 +97,116 @@ async function main() {
}
const browser = await chromium.launch();
const page = await browser.newPage();
const failures = [];
const warnings = [];
let checks = 0;
for (const [width, height, label] of VIEWPORTS) {
await page.setViewportSize({ width, height });
// Twice over: once with a mouse, once with a thumb. The 44px rule stands itself
// down where `hover: hover` says there's a pointer, and a headless desktop browser
// is a pointer — so a single pass here has never once measured a touch target,
// however many viewports it visited. The phone-sized ones are exactly the pass that
// needs it.
for (const touch of [false, true]) {
const context = await browser.newContext(touch
? { hasTouch: true, isMobile: true, deviceScaleFactor: 3 }
: {});
const page = await context.newPage();
const hand = touch ? "touch" : "mouse";
await page.goto(`${BASE}/Casino/TexasHoldem`);
await page.evaluate(seedTable);
await page.goto(`${BASE}/Casino/TexasHoldem`);
await page.click("#nextHandBtn");
await page.waitForTimeout(300);
await page.evaluate(() => document.querySelectorAll("details.sidebarPanel").forEach(d => { d.open = true; }));
await page.addScriptTag({ path: AUDIT });
for (const [width, height, rawLabel] of VIEWPORTS) {
await page.setViewportSize({ width, height });
const table = await page.evaluate(() => LayoutAudit.runAll());
checks++;
if (!table.clean) failures.push({ where: `table · ${label} ${width}x${height}`, offenders: table.failed.flatMap(f => f.offenders) });
table.warnings.forEach(w => warnings.push(`${label}: ${w}`));
for (const [shape, seats, players, board] of TABLES) {
const label = `${rawLabel} · ${shape} · ${hand}`;
await page.goto(`${BASE}/Casino/TexasHoldem`);
await page.evaluate(seedTable, [seats, players, board]);
await page.goto(`${BASE}/Casino/TexasHoldem`);
await page.click("#nextHandBtn");
await page.waitForTimeout(300);
// Deal it, and get chips in front of a few players. The sweep used to
// audit a table that had never had a bet on it, so the bets layer was
// empty at every viewport it visited and nothing it drew was ever looked
// at — which is a third of what is on the felt during a hand.
await page.evaluate(() => {
const deal = [...document.querySelectorAll("#actionBar button")]
.find(b => /post blinds/i.test(b.textContent));
if (deal) deal.click();
});
await page.waitForTimeout(220);
for (let i = 0; i < 3; i++) {
const acted = await page.evaluate(() => {
const btn = [...document.querySelectorAll("#actionBar button")]
.find(b => /^(Call|Check)/.test(b.textContent.trim()) && !b.disabled);
if (!btn) return false;
btn.click();
return true;
});
if (!acted) break;
await page.waitForTimeout(120);
}
if (board) {
await page.evaluate(() => {
const s = HoldemState.load();
s.street = "river";
s.board = ["KD", "9C", "4S", "AH", "2H"];
s.seats.filter(p => p.inHand).forEach((p, i) => {
p.cards = [["AS", "KC"], ["AC", "3D"], ["9H", "9S"],
["7C", "5D"], ["JD", "TS"]][i] || ["", ""];
});
HoldemState.save(s);
});
await page.reload();
await page.waitForTimeout(300);
}
await page.evaluate(() => document.querySelectorAll("details.sidebarPanel").forEach(d => { d.open = true; }));
await page.addScriptTag({ path: AUDIT });
for (const [name, open] of OVERLAYS) {
await page.evaluate(open);
await page.waitForTimeout(180);
checks++;
const result = await page.evaluate(() => {
const overlay = [...document.querySelectorAll("[id$='Overlay']")].find(o => !o.hidden);
if (!overlay) return { offenders: [] };
return LayoutAudit.occlusion(`#${overlay.id} button, #${overlay.id} a, #${overlay.id} input`);
});
await page.evaluate(() => document.querySelectorAll("[id$='Overlay']").forEach(o => { o.hidden = true; }));
if (result.offenders.length) failures.push({ where: `${name} · ${label} ${width}x${height}`, offenders: result.offenders });
const table = await page.evaluate(() => LayoutAudit.runAll());
checks++;
if (!table.clean) failures.push({ where: `table · ${label} ${width}x${height}`, offenders: table.failed.flatMap(f => f.offenders) });
table.warnings.forEach(w => warnings.push(`${label}: ${w}`));
// The overlays don't change with the table's shape, so they are only
// opened over the half-full one — twice the viewports is enough time
// spent already.
if (shape !== TABLES[0][0]) continue;
for (const [name, open] of OVERLAYS) {
await page.evaluate(open);
await page.waitForTimeout(180);
checks++;
const result = await page.evaluate(() => {
const overlay = [...document.querySelectorAll("[id$='Overlay']")].find(o => !o.hidden);
if (!overlay) return { offenders: [] };
return LayoutAudit.occlusion(`#${overlay.id} button, #${overlay.id} a, #${overlay.id} input`);
});
await page.evaluate(() => document.querySelectorAll("[id$='Overlay']").forEach(o => { o.hidden = true; }));
if (result.offenders.length) failures.push({ where: `${name} · ${label} ${width}x${height}`, offenders: result.offenders });
}
}
}
}
for (const [width, height, label] of VIEWPORTS.filter((_, i) => i % 4 === 0)) {
await page.setViewportSize({ width, height });
await page.goto(`${BASE}/Casino/TexasHoldem/QuickSplit`);
await page.evaluate(() => {
const button = [...document.querySelectorAll("button")].find(b => /all.?in/i.test(b.textContent));
if (button) button.click();
});
await page.addScriptTag({ path: AUDIT });
checks++;
const result = await page.evaluate(() => LayoutAudit.runAll({ occlusionSelector: "main button, main a, main input" }));
if (!result.clean) failures.push({ where: `quick split · ${label} ${width}x${height}`, offenders: result.failed.flatMap(f => f.offenders) });
for (const [width, height, rawLabel] of VIEWPORTS.filter((_, i) => i % 4 === 0)) {
const label = `${rawLabel} · ${hand}`;
await page.setViewportSize({ width, height });
await page.goto(`${BASE}/Casino/TexasHoldem/QuickSplit`);
await page.evaluate(() => {
const button = [...document.querySelectorAll("button")].find(b => /all.?in/i.test(b.textContent));
if (button) button.click();
});
await page.addScriptTag({ path: AUDIT });
checks++;
const result = await page.evaluate(() => LayoutAudit.runAll({ occlusionSelector: "main button, main a, main input" }));
if (!result.clean) failures.push({ where: `quick split · ${label} ${width}x${height}`, offenders: result.failed.flatMap(f => f.offenders) });
result.warnings.forEach(w => warnings.push(`quick split · ${label}: ${w}`));
}
await context.close();
}
await browser.close();
console.log(`${checks} audits across ${VIEWPORTS.length} viewports`);
console.log(`${checks} audits across ${VIEWPORTS.length} viewports, with a mouse and with a thumb`);
warnings.forEach(w => console.log(` note: ${w}`));
if (failures.length === 0) {
console.log("clean");
+174
View File
@@ -0,0 +1,174 @@
// Whether two seats can end up wanting the same pixels.
//
// The felt used to decide this from one number: the straight-line distance between the
// closest two *neighbouring* seats, judged against a fraction of a puck's width. Both
// halves of that were wrong, and the running page showed it. Measured across nine
// viewports and six table sizes:
//
// seventeen of fifty-four tables had one seat's name or stack painted under another
// ten of them had the collision between two seats that are not neighbours
//
// The second number is the interesting one. On a phone held sideways the felt is 528px
// wide and 87 tall, the ring is very nearly a straight line, and the seat that lands on
// top of you is the one across the table — seats 1 and 7, overlapping by 68px, while
// every neighbouring pair was fine and the check said the table was clean.
//
// The first is what a distance test can't fix even looking at every pair: distance has
// one number in it, and a puck is half again as wide as it is tall. 84px between centres
// is generous side by side and nowhere near enough on the diagonal.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
const path = require("path");
const { Render } = require("./load");
const CSS = fs.readFileSync(
path.join(__dirname, "..", "..", "JoshHeaps.Net", "wwwroot", "css", "casino", "holdem.css"), "utf8");
describe("two boxes on a ring", () => {
// A phone held sideways, once the action bar has taken its share: a felt far wider
// than it is tall, on which the ring is very nearly a straight line.
const felt = { width: 400, height: 70 };
const flat = { rx: 44, ry: 42 };
test("a pair that is not neighbours still counts", () => {
// Eight seats, a 48x60 puck. Every neighbouring pair is clear. Seats 1 and 5 are
// on top of each other, and so are 2 and 4, and 6 and 8 — the seat that lands on
// you here is the one across the table, because the rim doubles back at the ends
// of a shape this flat and a long walk apart is no distance at all.
assert.equal(Render.seatsCollide(8, felt, flat, 48, 60), true);
const neighbours = (count, w, h) => {
const points = Render.ringPositions(count, flat.rx, flat.ry, felt.width / felt.height)
.map(s => ({ x: (s.left / 100) * felt.width, y: (s.top / 100) * felt.height }));
return points.some((point, i) => {
const next = points[(i + 1) % points.length];
return Math.abs(point.x - next.x) < w && Math.abs(point.y - next.y) < h;
});
};
assert.equal(neighbours(8, 48 + Render.SEAT_CLEARANCE_PX, 60 + Render.SEAT_CLEARANCE_PX), false,
"no neighbouring pair overlaps, which is exactly why this had to look at all of them");
});
test("and the answer is the box, not a radius", () => {
// Two seats 60px apart across and 35px down, with a 64x40 puck. The distance
// between them is 69px, so the test this replaces — "are these two further apart
// than a puck is wide?" — called it clear. The boxes overlap by 4px by 5px.
const boxes = { width: 200, height: 100 };
const twoSeats = (dx, dy) => {
const original = Render.ringPositions;
Render.ringPositions = () => [
{ left: 50 - (dx / 2 / boxes.width) * 100, top: 50 - (dy / 2 / boxes.height) * 100 },
{ left: 50 + (dx / 2 / boxes.width) * 100, top: 50 + (dy / 2 / boxes.height) * 100 },
];
try {
return Render.seatsCollide(2, boxes, flat, 64, 40, 0);
} finally {
Render.ringPositions = original;
}
};
assert.ok(Math.hypot(60, 35) > 64, "and a distance test would have passed it");
assert.equal(twoSeats(60, 35), true, "60 across and 35 down, with a 64x40 puck");
assert.equal(twoSeats(60, 45), false, "far enough apart vertically");
assert.equal(twoSeats(66, 10), false, "far enough apart horizontally");
});
test("with daylight, so rounded corners don't read as touching", () => {
assert.ok(Render.SEAT_CLEARANCE_PX > 0);
});
test("a table nobody is sitting at can't collide with itself", () => {
assert.equal(Render.seatsCollide(1, felt, flat, 96, 60), false);
assert.equal(Render.seatsCollide(9, null, flat, 96, 60), false);
});
});
describe("the widths the felt may choose from", () => {
test("run widest first, because the widest that fits is the one wanted", () => {
const widths = Render.seatWidthCandidates();
widths.slice(1).forEach((w, i) => assert.ok(w < widths[i], `${widths[i]} then ${w}`));
});
test("and span the whole declared range", () => {
const widths = Render.seatWidthCandidates();
assert.equal(widths[0], Render.SEAT_WIDTH_MAX);
assert.equal(widths[widths.length - 1], Render.SEAT_WIDTH_MIN);
});
test("the floor is still a name, not a smudge", () => {
// At 44px the tight layout shows about five characters and an ellipsis. Below
// that a puck stops telling the dealer who is sitting there, which is the one
// thing on the felt it exists to say.
assert.ok(Render.SEAT_WIDTH_MIN >= 44);
assert.ok(Render.SEAT_TIGHT_BELOW_PX > Render.SEAT_WIDTH_MIN);
assert.ok(Render.SEAT_TIGHT_BELOW_PX < Render.SEAT_WIDTH_MAX);
});
test("and there are few enough of them to measure after every tap", () => {
// Each one costs a forced layout. Ten is the budget; the cache carries the rest.
assert.ok(Render.seatWidthCandidates().length <= 12);
});
});
describe("what the stylesheet has to keep holding up", () => {
test("the puck's width comes from the property, not from a breakpoint", () => {
// Three media queries used to declare it — 78px, 64px and 62px — three guesses
// at a number that depends on how many people are sitting down, which no media
// query can see. The same 390px phone has room for 90px at four seats and 61 at
// nine.
const declarations = CSS.replace(/\/\*[\s\S]*?\*\//g, "");
const seatRules = [...declarations.matchAll(/(^|[,}])\s*(\.seat)\s*\{([^}]*)\}/g)]
.map(m => m[3]);
const hardWidths = seatRules
.flatMap(body => body.match(/(?<![\w-])width:\s*[^;]+/g) || [])
.filter(decl => !decl.includes("var(--seatPuckW"));
assert.deepEqual(hardWidths, []);
});
test("the puck measures what it says it measures", () => {
// As content-box a 64px puck came out 74 across once its padding and border were
// counted, and the search compares that number against distances on the felt.
const rule = CSS.match(/\n\.seat \{[^}]*\}/);
assert.ok(rule, ".seat rule not found");
assert.match(rule[0], /box-sizing:\s*border-box/);
});
test("and a blind badge never reaches sideways off its own puck", () => {
// This is what makes the footprint the puck and nothing more. The badge's
// remaining overhang is vertical, and it points away from the table at both ends
// — `top` on the upper arc, `bottom` on the lower — so two seats facing each
// other across the felt wear their badges back to back.
//
// It was not always so: at `left: -6px` the small blind hung off the puck's left
// corner, and on an iPhone Pro Max at six seats — pucks not touching at all —
// "SB" was painted across the next player's $1,137.
const badges = [...CSS.matchAll(/\.(sb|bb|str)Badge\s*\{([^}]*)\}/g)];
assert.equal(badges.length, 3, "expected all three blind badges");
badges.forEach(([, which, body]) => {
const left = body.match(/(?<![\w-])left:\s*(-?[\d.]+)px/);
assert.ok(left, `.${which}Badge should place itself horizontally`);
assert.ok(Number(left[1]) >= 0,
`.${which}Badge sits at ${left[1]}px, off the left of its own puck`);
});
});
test("and all three sit in the same place, so there is one spot to look at", () => {
// Two badges in two positions means the dealer's eye has to find which of them
// this seat is using before it can read which blind it is, forty times a night.
// A seat only ever wears one: the blinds are different players by construction,
// and the straddle chain starts left of the big blind and stops short of the
// small one.
const lefts = [...CSS.matchAll(/\.(sb|bb|str)Badge\s*\{([^}]*)\}/g)]
.map(([, , body]) => (body.match(/(?<![\w-])left:\s*(-?[\d.]+px)/) || [])[1]);
assert.equal(new Set(lefts).size, 1, `badges sit at ${lefts.join(", ")}`);
});
});
describe("with no browser to measure", () => {
test("nothing here throws", () => {
assert.equal(Render.measuredSeatBox(), null);
assert.equal(Render.seatFootprint(null), null);
assert.deepEqual(Render.seatFootprint({ width: 64, height: 40 }), { width: 64, height: 40 });
});
});
+94
View File
@@ -92,6 +92,100 @@ describe("a felt wider than it is tall", () => {
});
});
describe("how close the closest two seats come", () => {
// What decides whether the pucks shrink. Rim length per seat was the first answer
// and it is the wrong question: it measures the walk between two seats, not the
// gap. On a long oval the rim doubles back at the ends, so two seats a long walk
// apart end up stacked one above the other.
const gap = (count, width, height) => Render.closestSeatGapPx(count, { width, height });
test("a flat table no longer stacks two seats at each end", () => {
// 616x96: the landscape felt on a 640x360 phone once the bar has grown. On an
// ellipse that flat the end pair came out 25px apart with 64px pucks. The rim
// is a stadium at this shape, so an end holds one seat.
assert.ok(gap(6, 616, 96) > 70, `${gap(6, 616, 96).toFixed(0)}px apart`);
assert.ok(gap(12, 616, 96) > 40, `${gap(12, 616, 96).toFixed(0)}px apart at twelve seats`);
});
test("an ellipse's ends are still closer than its rim suggests, which is why the shape changes", () => {
// Same felt, forced through the ellipse the tool uses for rounder tables.
const asEllipse = Render.ringAngles(6, 44, 42, 616 / 96).map(angle => ({
x: ((50 + 44 * Math.cos(angle)) / 100) * 616,
y: ((50 + 42 * Math.sin(angle)) / 100) * 96,
}));
const closest = asEllipse.reduce((least, point, i) => {
const next = asEllipse[(i + 1) % asEllipse.length];
return Math.min(least, Math.hypot(point.x - next.x, point.y - next.y));
}, Infinity);
assert.ok(closest < 70, `${closest.toFixed(0)}px`);
assert.ok(gap(6, 616, 96) > closest * 1.3,
`stadium ${gap(6, 616, 96).toFixed(0)}px against ellipse ${closest.toFixed(0)}px`);
});
test("a round table's neighbours are about as far apart as the rim says", () => {
const rim = (Math.PI * 2 * 0.43 * 400) / 9;
assert.ok(Math.abs(gap(9, 400, 400) - rim) < rim * 0.15);
});
test("more seats, less room, in that order", () => {
assert.ok(gap(12, 400, 400) < gap(9, 400, 400));
assert.ok(gap(9, 400, 400) < gap(6, 400, 400));
assert.ok(gap(6, 400, 400) < gap(6, 800, 800), "and a bigger table gives more");
});
test("nothing to measure between fewer than two seats", () => {
assert.equal(gap(1, 400, 400), Infinity);
assert.equal(gap(9, 0, 0), Infinity);
});
});
describe("which rim a table gets", () => {
// An ellipse until the table is much wider than tall, then a stadium: two rails
// and a half-round cap at each end, which is how a real poker table is built.
const shape = (width, height) => {
const aspect = width / height;
return 44 * aspect > 42 * Render.STADIUM_RATIO ? "stadium" : "ellipse";
};
test("every layout the tool had keeps the ellipse", () => {
assert.equal(shape(844, 608), "ellipse", "desktop");
assert.equal(shape(600, 600), "ellipse", "tablet");
assert.equal(shape(278, 314), "ellipse", "phone upright");
assert.equal(shape(336, 240), "ellipse", "short phone upright");
});
test("a phone on its side gets the stadium", () => {
assert.equal(shape(528, 73), "stadium");
assert.equal(shape(780, 113), "stadium");
});
test("the cap holds one seat instead of stacking two", () => {
// Six seats on a 616x96 rim: the walk between neighbours has to be longer than
// the cap, or two of them end up on the same half-circle.
const halfWidth = 44 * (616 / 96), halfHeight = 42;
const perimeter = 4 * (halfWidth - halfHeight) + 2 * Math.PI * halfHeight;
assert.ok(perimeter / 6 > Math.PI * halfHeight, "one seat per cap at six-handed");
});
test("seat one is still at the top centre, and the ring still mirrors", () => {
const seats = Array.from({ length: 8 }, (_, i) => Render.positionOnRing(i, 8, 44, 42, 616 / 96));
assert.ok(Math.abs(seats[0].left - 50) < 0.01);
assert.ok(seats[0].top < 50);
for (let seat = 1; seat < 4; seat++) {
const mirrored = seats[8 - seat];
assert.ok(Math.abs((seats[seat].left - 50) + (mirrored.left - 50)) < 0.01, `seat ${seat} across`);
assert.ok(Math.abs(seats[seat].top - mirrored.top) < 0.01, `seat ${seat} down`);
}
});
test("nobody is drawn off the felt", () => {
Array.from({ length: 12 }, (_, i) => Render.positionOnRing(i, 12, 44, 42, 616 / 96)).forEach((seat, i) => {
assert.ok(seat.left >= 5 && seat.left <= 95, `seat ${i + 1} across at ${seat.left.toFixed(1)}%`);
assert.ok(seat.top >= 7 && seat.top <= 93, `seat ${i + 1} down at ${seat.top.toFixed(1)}%`);
});
});
});
describe("the shape of the ring", () => {
test("is a mirror image left to right", () => {
const seats = ringPixels(10, 601, 126);
+110
View File
@@ -0,0 +1,110 @@
// How wide the ring of seats is allowed to be.
//
// It sat at a flat 44% by 42% of the seat layer at every size — two numbers picked
// against a phone, then asked to hold for a 754x543 felt on a desktop and a 686x141
// one on a phone held sideways. A fixed pair can only be right for one ratio of puck
// to felt, so measured on the running page:
//
// 1280x900, nine-handed five of nine pucks past the table's outer edge, worst 49px
// 844x390, six-handed all six, worst 20px
// 430x932, six-handed two, worst 12px
//
// Seats floating off the felt onto the page read as the table being too small for the
// game rather than as players at a rail, and it was a different amount of wrong on
// every screen — which is what made it look like a mistake instead of a choice.
//
// The radius is derived from what has to fit now. Whether it *actually* fits is a
// question about a laid-out browser, and it is checked there: uiAudit's "seats and
// chips stay on the table" runs at every viewport in the sweep. What is checked here
// is the contract that function has to honour, including the two ways it is allowed
// to give up.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Render } = require("./load");
describe("with no browser to measure", () => {
test("it falls back to the ring the tool has always used", () => {
// Every call from this suite has no DOM, and so does the very first render,
// before the felt has been laid out. Neither should throw or return nonsense.
assert.deepEqual(Render.seatRingRadii(), { rx: Render.RING_MAX_RX, ry: Render.RING_MAX_RY });
});
test("so seatPosition still answers", () => {
const pos = Render.seatPosition(0, 9, 1);
assert.ok(Number.isFinite(pos.left) && Number.isFinite(pos.top));
});
test("and nothing is measured for the puck height either", () => {
assert.equal(Render.tooTallForTheTable(), false);
});
});
describe("the ceiling and the floor", () => {
test("the old ring is the widest it can ever be", () => {
// Nothing gets looser than it was; this can only pull seats in.
assert.ok(Render.RING_MAX_RX <= 44);
assert.ok(Render.RING_MAX_RY <= 42);
});
test("and it never collapses the ring into the pot", () => {
// A puck wider than the table it sits on has no honest answer. Overhanging is
// the lesser evil — seats stacked on the pot would be unreadable, and the
// density rule shrinks the pucks before it ever gets this far.
assert.ok(Render.RING_MIN_R > 0);
assert.ok(Render.RING_MIN_R < Render.RING_MAX_RY);
});
test("with a margin that keeps the outermost seat off the rail", () => {
assert.ok(Render.SEAT_EDGE_MARGIN_PX > 0);
});
});
describe("the ring the radii describe", () => {
const spread = (radii, count = 9, aspect = 1.4) =>
Render.ringPositions(count, radii.rx, radii.ry, aspect);
test("a smaller radius puts every seat nearer the middle", () => {
const wide = spread({ rx: 44, ry: 42 });
const tight = spread({ rx: 30, ry: 28 });
wide.forEach((seat, i) => {
const wideOut = Math.hypot(seat.left - 50, seat.top - 50);
const tightOut = Math.hypot(tight[i].left - 50, tight[i].top - 50);
assert.ok(tightOut < wideOut, `seat ${i + 1} should have come in`);
});
});
test("and the seats stay evenly spread however far in they are", () => {
// Pulling the ring in must not bunch them: the spacing rule is arc length, and
// shrinking an ellipse uniformly keeps every gap in proportion.
const gaps = ring => ring.map((p, i) => {
const next = ring[(i + 1) % ring.length];
return Math.hypot(p.left - next.left, p.top - next.top);
});
const tight = gaps(spread({ rx: 30, ry: 28 }));
const smallest = Math.min(...tight), largest = Math.max(...tight);
assert.ok(largest / smallest < 1.35, `gaps ranged ${smallest.toFixed(1)}..${largest.toFixed(1)}`);
});
});
describe("the bets follow the seats", () => {
test("a chip sits on its own player's spoke, proportionally in", () => {
// The chip is a fraction of the seat's reach rather than of the felt, so when
// the ring pulls in the chips come with it instead of being left by the rail.
const radii = { rx: 30, ry: 28 };
const seat = Render.seatPosition(2, 8, 1.4, radii);
const bet = Render.betPosition(2, 8, 1.4, radii);
const seatOut = Math.hypot(seat.left - 50, seat.top - 50);
const betOut = Math.hypot(bet.left - 50, bet.top - 50);
assert.ok(betOut < seatOut, "the chip is nearer the pot than the player is");
assert.ok(betOut > seatOut * 0.4, "but still out on the player's side of the felt");
});
test("and it is the same spoke, not just the same distance", () => {
const radii = { rx: 30, ry: 28 };
const seat = Render.seatPosition(5, 9, 1.2, radii);
const bet = Render.betPosition(5, 9, 1.2, radii);
const angleOf = p => Math.atan2(p.top - 50, p.left - 50);
assert.ok(Math.abs(angleOf(seat) - angleOf(bet)) < 0.01);
});
});
+106
View File
@@ -0,0 +1,106 @@
// The toast that outlived the thing it was talking about.
//
// Toasts are news about the last action, and they carry an Undo. Take another action
// and both of those go wrong at once: the sentence describes a step that is now two
// steps back, and the Undo behind it restores a snapshot from before everything since.
// "Next hand — button on seat 2. [Undo]" left up while a hand is dealt and three
// players call is an offer to move the button, wired to a button that deletes the hand.
//
// It is also simply in the way. The toast is a fixed strip near the bottom of the
// screen; on a 360x640 phone there is nowhere for it to sit that is clear of both the
// felt and the action bar, so a stale one covers seats and controls for eight seconds.
//
// So the bar drops it as it takes the next action. These tests hold that funnel shut:
// every action a dealer can take from the bar goes through `commit`, and `commit`
// clears the toast before it does anything else.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
const path = require("path");
const { ActionBar, Betting, makeTable } = require("./load");
const SRC = path.join(__dirname, "..", "..", "JoshHeaps.Net", "wwwroot", "js", "casino", "holdem");
const barSource = fs.readFileSync(path.join(SRC, "actionBar.js"), "utf8");
// A bar sat at a real table, with the toast replaced by something that keeps a log
// and the re-render stubbed out — none of these rules need the DOM back.
function onTable() {
const state = makeTable({ seatCount: 6, stack: 200, smallBlind: 1, bigBlind: 2, dealerSeatIndex: 0 });
const log = [];
globalThis.Toast = {
onScreen: null,
show(message) { this.onScreen = message; log.push(`show ${message}`); },
dismiss() { this.onScreen = null; log.push("dismiss"); },
};
ActionBar.state = state;
ActionBar.render = () => {};
ActionBar.hooks = {
beginAction: label => log.push(`begin ${label}`),
save: () => log.push("save"),
rerender: () => log.push("rerender"),
};
return { bar: ActionBar, state, log };
}
test.afterEach(() => { delete globalThis.Toast; });
describe("a toast does not outlive its own news", () => {
test("the next action from the bar clears it", () => {
const { bar, state, log } = onTable();
Toast.show("Next hand — button on seat 2.");
bar.commit("dealing the hand", () => Betting.beginHand(state));
assert.equal(Toast.onScreen, null, "the hand is dealt; the sentence about seating the table is not news any more");
assert.ok(log.indexOf("dismiss") < log.indexOf("begin dealing the hand"),
`the toast goes before the action is recorded, so nothing shown during the action is swept up with it: ${log.join(", ")}`);
});
test("a toast raised by the action itself survives", () => {
const { bar, log } = onTable();
bar.commit("something that talks back", () => Toast.show("Bob is all in."));
assert.equal(Toast.onScreen, "Bob is all in.",
"commit clears what was there when it started, not what its own work puts up");
assert.deepEqual(log, ["dismiss", "begin something that talks back", "show Bob is all in.", "save", "rerender"]);
});
test("with no toast on screen it is still just one dismiss", () => {
const { bar, log } = onTable();
bar.commit("a fold", () => {});
assert.equal(log.filter(l => l === "dismiss").length, 1);
});
test("a page with no Toast at all does not throw", () => {
const { bar, state } = onTable();
delete globalThis.Toast;
assert.doesNotThrow(() => bar.commit("dealing the hand", () => Betting.beginHand(state)));
});
});
describe("every bar action really does go through that funnel", () => {
// The dismiss is worth nothing if some button reaches past `commit` to mutate the
// table itself. Actions are written as `this.commit(...)`; a `Betting.` call made
// straight from a click handler would be one that skips the clean-up — and the
// undo history with it, which is the older reason this funnel exists.
test("no click handler calls the betting engine directly", () => {
const strays = barSource
.split("\n")
.map((line, i) => [i + 1, line])
.filter(([, line]) => /=>\s*Betting\.(fold|check|call|allIn|raiseTo|beginHand|closeStreet)\(/.test(line))
.filter(([, line]) => !/this\.commit\(/.test(line))
.map(([n, line]) => `actionBar.js:${n}: ${line.trim()}`);
assert.deepEqual(strays, [], "these change the table without going through commit");
});
test("commit is what clears the toast, not each button", () => {
const dismissals = barSource.split("\n").filter(l => /Toast\.dismiss\(\)/.test(l)).length;
// Two: this one, and the raise pad — which opens without committing anything,
// and needs the strip clear because the pad makes the bar tall enough to push
// a toast up over the seats.
assert.equal(dismissals, 2,
"a third dismissal means a button is doing by hand what commit already does");
});
});
+166
View File
@@ -0,0 +1,166 @@
// The chips the felt plays with are the chips the box is checked against.
//
// "Starting stack" is offered in the setup panel as the ordinary way to open a table —
// "seats without their own stack start here" — and everything a dealer looks at reads
// it: the puck, the action bar, what a player is allowed to bet. The money side did
// not. It read `seat.stack` directly, which is null for exactly those seats, so a
// three-handed table playing for $600 reported no chips in play, a balanced bank and a
// standings list with nobody on it.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Money, HoldemState, Betting } = require("./load");
const openedWithStartingStack = (stack = 200, names = ["Ann", "Ben", "Cal"]) => {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 6);
state.defaultStack = stack;
names.forEach((name, i) => {
state.seats[i].name = name;
state.seats[i].inHand = true;
});
return state;
};
describe("what the table is playing for", () => {
test("is what the bank counts", () => {
const state = openedWithStartingStack();
// What the felt says each of them has.
assert.deepEqual(state.seats.slice(0, 3).map(p => Betting.stackOf(state, p)), [200, 200, 200]);
assert.equal(HoldemState.bankReconciliation(state).chipsInPlay, 600);
});
test("and the box being empty is a problem it now reports", () => {
const bank = HoldemState.bankReconciliation(openedWithStartingStack());
assert.equal(bank.cashIn, 0);
assert.equal(bank.difference, 600);
assert.equal(bank.balanced, false, "six hundred dollars of chips nobody paid for");
});
test("empty chairs are not people holding two hundred dollars", () => {
// The starting stack stands in for a seat that hasn't been given one, and every
// empty chair is such a seat. Counting them would invent $600 of chips at an
// empty table.
const state = openedWithStartingStack();
assert.equal(HoldemState.bankReconciliation(state).chipsInPlay, 600, "three players, not six chairs");
const empty = HoldemState.createDefault();
empty.defaultStack = 200;
assert.equal(HoldemState.bankReconciliation(empty).chipsInPlay, 0);
assert.equal(HoldemState.bankReconciliation(empty).balanced, true);
});
test("once the cash is written down it balances", () => {
const state = openedWithStartingStack();
state.seats.slice(0, 3).forEach(p => { p.buyIns = 200; });
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
test("a table where everyone has their own stack is unchanged", () => {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 4);
["Ann", "Ben"].forEach((name, i) => {
state.seats[i].name = name;
state.seats[i].stack = 150;
state.seats[i].buyIns = 150;
});
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.chipsInPlay, 300);
assert.equal(bank.balanced, true);
});
});
describe("who is on the settle-up list", () => {
test("everyone holding chips, including the ones holding the table's own stack", () => {
const rows = HoldemState.sessionStandings(openedWithStartingStack());
assert.deepEqual(rows.map(r => r.name), ["Ann", "Ben", "Cal"]);
assert.deepEqual(rows.map(r => r.chipsInFront), [200, 200, 200]);
});
test("with nothing bought in yet, which is the thing to notice", () => {
const rows = HoldemState.sessionStandings(openedWithStartingStack());
assert.deepEqual(rows.map(r => r.boughtIn), [0, 0, 0]);
assert.deepEqual(rows.map(r => r.cashPosition), [200, 200, 200]);
});
});
describe("naming the seats the cash is missing for", () => {
test("says who, and which kind of missing it is", () => {
const state = openedWithStartingStack();
state.seats[2].stack = 320; // Cal typed his own: an unrecorded rebuy
const owing = HoldemState.seatsOwingCash(state);
assert.deepEqual(owing.map(row => row.name), ["Ann", "Ben", "Cal"]);
assert.deepEqual(owing.map(row => row.fromStartingStack), [true, true, false]);
assert.deepEqual(owing.map(row => row.chips), [200, 200, 320]);
});
test("a seat whose buy-in is written down isn't on the list", () => {
const state = openedWithStartingStack();
state.seats[0].buyIns = 200;
assert.deepEqual(HoldemState.seatsOwingCash(state).map(row => row.name), ["Ben", "Cal"]);
});
test("and a table where nothing is owed has nobody on it", () => {
const state = openedWithStartingStack();
state.seats.slice(0, 3).forEach(p => { p.buyIns = 200; });
assert.deepEqual(HoldemState.seatsOwingCash(state), []);
});
});
describe("writing the starting stacks down", () => {
test("records exactly what those seats are holding", () => {
const state = openedWithStartingStack();
const done = HoldemState.recordStartingBuyIns(state);
assert.equal(done.seats, 3);
assert.equal(done.total, 600);
assert.deepEqual(state.seats.slice(0, 3).map(p => p.buyIns), [200, 200, 200]);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
test("and leaves somebody else's forgotten rebuy alone", () => {
// Only the dealer knows what that was. Guessing would be the tool inventing
// money, which is the fault this whole round is about.
const state = openedWithStartingStack();
state.seats[2].stack = 320;
HoldemState.recordStartingBuyIns(state);
assert.deepEqual(state.seats.slice(0, 3).map(p => p.buyIns), [200, 200, 0]);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, false);
assert.equal(bank.difference, 320, "still exactly Cal's chips, and still reported");
});
test("does nothing on a table that doesn't need it", () => {
const state = openedWithStartingStack();
state.seats.slice(0, 3).forEach(p => { p.buyIns = 200; });
const done = HoldemState.recordStartingBuyIns(state);
assert.equal(done.seats, 0);
assert.equal(done.total, 0);
assert.deepEqual(state.seats.slice(0, 3).map(p => p.buyIns), [200, 200, 200]);
});
});
describe("through a hand", () => {
test("the money adds up from the deal to the payout", () => {
const state = openedWithStartingStack(200, ["Ann", "Ben", "Cal", "Dee"]);
HoldemState.recordStartingBuyIns(state);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
Betting.beginHand(state);
assert.equal(HoldemState.bankReconciliation(state).balanced, true, "blinds are still on the table");
[3, 0, 1].forEach(() => { if (state.actingSeatIndex !== null) Betting.call(state, state.actingSeatIndex); });
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
const pot = Betting.potSoFar(state);
Betting.sweepToHandTotals(state);
Betting.creditWinnings(state, [{ id: state.seats[0].id, label: "Ann", amount: pot }]);
HoldemState.startNextHand(state);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, true);
assert.equal(bank.chipsInPlay, 800, "four buy-ins of two hundred, wherever they have moved to");
assert.ok(state.seats[0].stack > 200, "and the winner is holding more than they sat down with");
});
});
+394 -11
View File
@@ -93,6 +93,20 @@ const LayoutAudit = {
return false;
},
// The scrolling ancestor whose box this element has fallen outside of, if any.
// Wholly outside — an element straddling the edge is still half on show, and the
// half that is showing is worth hit-testing.
clippedOutBy(el, rect) {
for (let node = el.parentElement; node; node = node.parentElement) {
const style = getComputedStyle(node);
if (!/auto|scroll|hidden|overlay|clip/.test(style.overflowY + style.overflowX)) continue;
const box = node.getBoundingClientRect();
if (rect.top >= box.bottom - 0.5 || rect.bottom <= box.top + 0.5 ||
rect.left >= box.right - 0.5 || rect.right <= box.left + 0.5) return node;
}
return null;
},
// The modal that is currently on top, if any.
//
// Every check below asks "is this thing reachable", and while a sheet or dialog is
@@ -143,6 +157,22 @@ const LayoutAudit = {
return;
}
// Still on screen, but clipped away by a panel that scrolls. Hit-testing it
// is meaningless: the point lands on whatever the panel's own edge has next
// to it, and the answer comes back as a diagnosis of something that isn't
// happening. The pot wizard's third winner, below the fold in a list that
// scrolls, was reported for four viewports running as "fully covered by
// button Confirm Winner(s)" — the button is simply what is painted at that
// height. Whether it is a fault is the same question as for anything else
// out of view: can it be scrolled to.
const clip = this.clippedOutBy(el, rect);
if (clip) {
if (!this.reachableByScrolling(el)) {
offenders.push(`${this.describe(el)} :: clipped out of ${this.describe(clip)}, which cannot be scrolled to it`);
}
return;
}
const points = [
[rect.left + rect.width / 2, rect.top + rect.height / 2],
[rect.left + rect.width * 0.25, rect.top + rect.height * 0.3],
@@ -393,6 +423,37 @@ const LayoutAudit = {
}
},
// How much of this element actually reaches the screen, and what is behind the
// thing doing the fading.
//
// `opacity` on a box fades the whole box — its text and its own background together
// — onto whatever sits behind that box. So a dimmed seat is not "grey text on a
// dark puck"; it is a faded puck and faded text both landing on the felt. Both
// halves have to be composited the same way or the number means nothing.
fading(el) {
let alpha = 1;
let outermost = null;
for (let node = el; node; node = node.parentElement) {
const own = parseFloat(getComputedStyle(node).opacity);
if (own < 0.99) {
alpha *= own;
outermost = node;
}
}
if (!outermost) return { alpha: 1, behind: null };
return { alpha, behind: this.backgroundCandidates(outermost.parentElement || document.body)[0] || null };
},
// The two colours as the screen actually shows them, once the fading is applied.
asPainted(fgRaw, bg, fade) {
const solid = fgRaw.a === 1 ? fgRaw : this.over(fgRaw, bg);
if (fade.alpha >= 0.99 || !fade.behind) return { fg: solid, bg };
return {
fg: this.over({ ...solid, a: solid.a * fade.alpha }, fade.behind),
bg: this.over({ ...bg, a: bg.a * fade.alpha }, fade.behind),
};
},
contrast({ minimum = 4.5, largeMinimum = 3, selector = null } = {}) {
const offenders = [];
const unmeasured = [];
@@ -426,12 +487,17 @@ const LayoutAudit = {
// exempt — there's nothing to read at zero — but anything in between is
// reported as unmeasured rather than passed over in silence, because a
// number nobody checked is not the same as a number that's fine.
const opacity = parseFloat(style.opacity);
if (opacity <= 0.02) return;
const faded = opacity < 0.99 ||
[...this.ancestors(el)].some(a => parseFloat(getComputedStyle(a).opacity) < 0.99);
if (faded) {
unmeasured.push(`${this.describe(el)} :: faded (opacity ${opacity}), contrast not checked`);
const fade = this.fading(el);
if (fade.alpha <= 0.02) return;
// A control that is switched off is the one exemption WCAG itself grants —
// an inactive component has no contrast requirement, which is why every
// toolkit dims them. Said out loud rather than skipped in silence: this is
// the only exemption in here, and the moment a dimmed thing turns out to be
// live it stops applying.
const off = el.closest("[disabled], [aria-disabled='true']");
if (off) {
unmeasured.push(`${this.describe(el)} :: disabled control, exempt from AA`);
return;
}
// aria-hidden used to exempt text here, on the grounds that decoration
@@ -459,8 +525,8 @@ const LayoutAudit = {
// The kindest reading available: best contrast across every candidate.
let best = 0;
candidates.forEach(bg => {
const fg = fgRaw.a === 1 ? fgRaw : this.over(fgRaw, bg);
best = Math.max(best, this.contrastRatio(fg, bg));
const painted = this.asPainted(fgRaw, bg, fade);
best = Math.max(best, this.contrastRatio(painted.fg, painted.bg));
});
const sizePx = parseFloat(style.fontSize);
@@ -543,6 +609,17 @@ const LayoutAudit = {
.filter(el => el.type !== "color")
.filter(el => !(exempt && el.matches(exempt)))
.forEach(el => {
// A link inside a sentence is the one target WCAG itself carves out:
// its size is set by the line it sits in, and padding a word out to
// 44px would break the paragraph around it. The rule is about controls
// a thumb goes hunting for, not words in prose. Said out loud, and
// narrow — display:inline, and real text either side of it.
if (el.tagName === "A" && getComputedStyle(el).display === "inline" &&
el.parentElement &&
[...el.parentElement.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) {
unmeasured.push(`${this.describe(el)} :: link inside a sentence, sized by the line`);
return;
}
// A control inside a scrolling sheet can sit below its container's
// visible area while still having a viewport rect. elementFromPoint at
// its centre then returns the sheet, effectiveTarget gives up, and the
@@ -672,10 +749,306 @@ const LayoutAudit = {
return { name: "the felt shows one dealer button", offenders };
},
// Anything that says it is hidden and is drawn anyway.
//
// `hidden` gets its `display: none` from the browser's own stylesheet, the weakest
// rule in the cascade, so any class that sets a display beats it — and in this tool
// every button class does. The result is an element the code believes is gone,
// sitting on the screen: found as a 21x44 empty box under the bank check, and this
// file's own touch check had been calling it "could not be probed" rather than
// saying the plainer thing, which is that it should not be there at all.
hiddenButPainted() {
const offenders = [...document.querySelectorAll("[hidden]")]
.filter(el => {
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return false;
const style = getComputedStyle(el);
return style.display !== "none" && style.visibility !== "hidden";
})
.map(el => `${this.describe(el)} :: hidden, but drawn ${Math.round(el.getBoundingClientRect().width)}x${Math.round(el.getBoundingClientRect().height)}`);
return { name: "hidden means hidden", offenders };
},
// A seat's name, painted under the decoration on its own puck.
//
// The chip that marks the button sits in the puck's top-right corner on a layer
// above the text, and the name is centred across the whole width. A long one
// therefore ran underneath it and stopped — measured, "Christopher" on the button
// lost 20px of its 64px box and showed no ellipsis, because as far as the text was
// concerned it had all the room it needed. Nothing else here would have caught it:
// the occlusion check is about controls a thumb has to reach, and this is a label
// a dealer has to read.
seatLabelsClear() {
const offenders = [];
document.querySelectorAll(".seat").forEach(seat => {
const name = seat.querySelector(".seatPuckName");
if (!name || !name.textContent.trim()) return;
const box = name.getBoundingClientRect();
if (!box.width || !box.height) return;
// Padding is room the text has already been kept out of, so it is not
// somewhere the text can be covered.
const style = getComputedStyle(name);
const textLeft = box.left + parseFloat(style.paddingLeft || 0);
const textRight = box.right - parseFloat(style.paddingRight || 0);
seat.querySelectorAll(".dealerChip, .blindBadge").forEach(mark => {
const over = mark.getBoundingClientRect();
if (!over.width || !over.height) return;
const marked = getComputedStyle(mark);
if (marked.display === "none" || marked.visibility === "hidden" ||
parseFloat(marked.opacity) < 0.05) return;
const covered = Math.min(textRight, over.right) - Math.max(textLeft, over.left);
const vertical = Math.min(box.bottom, over.bottom) - Math.max(box.top, over.top);
if (covered > 1 && vertical > 1) {
offenders.push(`${this.describe(name)} :: ${Math.round(covered)}px under ${this.describe(mark)}`);
}
});
});
return { name: "seat names aren't painted under their own badges", offenders };
},
// A seat's writing, covered by something belonging to a different seat.
//
// seatLabelsClear() above asks whether a puck's own decoration sits on its own name.
// This asks the other half, and the other half was where the tool was actually
// failing: measured across nine viewports and six table sizes before this went in,
// seventeen of fifty-four tables had one seat's name or stack painted under a
// neighbour. On a Galaxy S8 at the most ordinary table there is — six players at a
// nine-handed table — seat 2's stack was under seat 3's puck, and five pairs of
// seats overlapped, the worst by 61px.
//
// Two ways in, and it takes both:
// - the pucks themselves overlapping, which the layout used to permit on the
// reasoning that rounded corners forgive a little; what they were forgiving was
// a four-figure stack.
// - a blind badge hanging off its puck onto the seat next door, which no amount
// of space between the pucks fixes on its own.
//
// Hit-tested against the glyph run rather than the element box. A name is centred,
// so its box is wider than its ink and testing the box would fail on empty air.
//
// The glyph run is then clipped back to what is actually painted, which is not the
// same thing and cost this check its first honest-looking failure. A puck's name is
// a `-webkit-box` with `line-clamp`, and getClientRects() hands back a rect for every
// line the text *would* have taken — including the two that the clamp throws away.
// Measured at 640x360 with twelve players: "Mike from work" reported a line 30px
// below its own puck, which duly hit-tested onto the seat underneath, and the seats
// were not touching at all. Nothing is painted there, so nothing can cover it.
seatsKeepTheirText() {
const name = "no seat covers another seat's writing";
if (this.modalScope()) {
return { name, offenders: [], skipped: "a sheet is open over the table" };
}
const seats = [...document.querySelectorAll(".seat")];
if (!seats.length) return { name, offenders: [], skipped: "no seats on this page" };
const offenders = [];
seats.forEach((seat, index) => {
seat.querySelectorAll(".seatPuckName, .seatPuckStack, .seatPuckTotal").forEach(label => {
const text = label.textContent.trim();
if (!text) return;
const painted = label.getBoundingClientRect();
if (!painted.width || !painted.height) return;
const range = document.createRange();
range.selectNodeContents(label);
[...range.getClientRects()].forEach(raw => {
const line = {
left: Math.max(raw.left, painted.left),
right: Math.min(raw.right, painted.right),
top: Math.max(raw.top, painted.top),
bottom: Math.min(raw.bottom, painted.bottom),
};
if (line.right - line.left <= 1 || line.bottom - line.top <= 1) return;
// Along the line rather than at its middle: a badge takes the start
// of it and a neighbouring puck the end, and a single centre probe
// walks past both.
for (let across = 0.08; across <= 0.92; across += 0.14) {
const x = line.left + (line.right - line.left) * across;
const y = (line.top + line.bottom) / 2;
const over = document.elementFromPoint(x, y);
if (!over || seat.contains(over) || over.contains(seat)) continue;
offenders.push(
`seat ${index + 1} "${text}" is under ${this.describe(over)}`);
return;
}
});
});
});
return { name, offenders };
},
// The other thing on the felt that carries a number.
//
// A chip says what a player has put in this street, which is what a call costs. Two
// of them on top of each other is two figures a dealer can't read, and one behind a
// puck is a figure that isn't there at all.
//
// Geometry rather than hit-testing, which is the opposite of how every other check
// here works and is forced: #betsLayer is `pointer-events: none`, so elementFromPoint
// never returns a chip — it returns whatever is behind it, for every chip, always.
// A first version of this probe hit-tested and duly reported all forty-five
// configurations as broken, including the ones that were fine. Paint order is known
// and fixed instead: #betsLayer comes before #seatsLayer in the document and a seat
// carries `z-index: 1`, so a puck a chip overlaps is a puck that chip is behind.
chipsKeepTheirAmounts() {
const name = "no bet chip is hidden behind a seat or another chip";
if (this.modalScope()) {
return { name, offenders: [], skipped: "a sheet is open over the table" };
}
const chips = [...document.querySelectorAll(".betChip")]
.filter(c => { const r = c.getBoundingClientRect(); return r.width > 0 && r.height > 0; });
if (!chips.length) return { name, offenders: [], skipped: "no bets on the felt" };
const overlap = (A, B) =>
Math.min(A.right, B.right) - Math.max(A.left, B.left) > 0.5 &&
Math.min(A.bottom, B.bottom) - Math.max(A.top, B.top) > 0.5;
const offenders = [];
const seats = [...document.querySelectorAll(".seat")];
chips.forEach(chip => {
const label = chip.textContent.trim() || "a chip";
const box = chip.getBoundingClientRect();
seats.forEach((seat, index) => {
// Its own puck is the one thing it is allowed to touch: on a narrow felt
// the chip clings to the seat rather than taking a ring of its own.
if (seat.contains(chip)) return;
if (overlap(box, seat.getBoundingClientRect())) {
offenders.push(`chip ${label} is behind seat ${index + 1}`);
}
});
// A chip wider than the puck it is clinging to is on its neighbours by
// construction, whatever the ring does.
const host = chip.closest(".seat");
if (host && chip.classList.contains("betChipAnchored")) {
const puck = host.getBoundingClientRect();
if (box.width > puck.width + 0.5) {
offenders.push(`chip ${label} is ${Math.round(box.width - puck.width)}px ` +
`wider than its own puck`);
}
}
});
for (let a = 0; a < chips.length; a++) {
for (let b = a + 1; b < chips.length; b++) {
if (overlap(chips[a].getBoundingClientRect(), chips[b].getBoundingClientRect())) {
offenders.push(`chip ${chips[a].textContent.trim()} and chip ` +
`${chips[b].textContent.trim()} are on top of each other`);
}
}
}
return { name, offenders: [...new Set(offenders)] };
},
// ---- Runner ----
// Every check this file knows how to make, every time.
//
// Two of them used not to be here. Contrast was simply missing from the list, and
// touch targets sat behind an opt-in flag nobody passed — so "the audit is clean"
// has meant nine checks rather than eleven, and the two left out are the two whose
// faults a dealer meets in a dim room with their thumb. Both were written, tested
// and then never run: the contrast checker was built across two rounds and every
// sweep since has been silent about colour.
//
// A check that decides it can't apply here says so out loud rather than reporting
// an empty offenders list, which reads as a pass. touchTargets stands itself down
// on a mouse-driven browser — that is right, a 24px control is fine with a cursor
// on it — but "not measured" and "measured and fine" are different answers and the
// runner now prints which one it got.
// The table has to be big enough for the game around it.
//
// The seat ring sat at a flat 44% by 42% of the seat layer at every size — two
// numbers picked against a phone. A fixed pair can only be right for one ratio of
// puck to felt, and measured on the running page it was wrong nearly everywhere:
// at 1280x900 nine-handed, five of nine pucks finished past the outer edge of the
// table, the worst by 49px; on a phone held sideways all six did. Seats floating
// off the felt onto the page read as the table being too small for the game rather
// than as players at a rail — and it was a different amount of wrong on every
// screen, which is what made it look like a mistake instead of a choice.
//
// Checked against the table's outer edge, border included: sitting *on* the rail is
// fine, hanging off the far side of it is not. The bet chips are held to the same
// rule — a chip is meant to be on the felt between its player and the pot.
seatsOnTheTable(slackPx = 1) {
const name = "seats and chips stay on the table";
if (this.modalScope()) {
return { name, offenders: [], skipped: "a sheet is open over the table" };
}
const table = document.getElementById("pokerTable");
if (!table) return { name, offenders: [], skipped: "no table on this page" };
const felt = table.getBoundingClientRect();
if (!felt.width || !felt.height) return { name, offenders: [], skipped: "table not laid out" };
const offenders = [];
const check = (el, what) => {
const r = el.getBoundingClientRect();
if (!r.width || !r.height) return;
const over = Math.max(
felt.left - r.left, r.right - felt.right,
felt.top - r.top, r.bottom - felt.bottom);
if (over > slackPx) offenders.push(`${what} hangs ${Math.round(over)}px past the rail`);
};
[...document.querySelectorAll(".seat")].forEach((seat, i) => check(seat, `seat ${i + 1}`));
[...document.querySelectorAll("#betsLayer > *")].forEach((chip, i) =>
check(chip, `bet chip ${i + 1}`));
return { name, offenders };
},
// An open dialog's buttons have to be on screen without hunting for them.
//
// The pot wizard — the one dialog in this tool that divides money — had its Confirm
// below a scroll at every size: measured with six players and a side pot, 244px off
// the bottom on an iPhone 14, 417 on a Galaxy S8, 583 on a phone held sideways, 172
// on a desktop. Nothing on screen said there was anything below the list of names,
// so the only control that finishes the hand was invisible with the table waiting.
//
// Checked by hit-testing rather than by geometry alone: a button can be inside the
// viewport and still be under something. Only dialogs that are actually open are
// considered, and only their buttons — a dialog with no buttons has nothing to find.
dialogActionsReachable() {
const name = "an open dialog's buttons are on screen";
const dialogs = [...document.querySelectorAll("[role='dialog'], [role='alertdialog']")]
.filter(d => {
const rect = d.getBoundingClientRect();
return rect.width > 0 && rect.height > 0 && getComputedStyle(d).visibility !== "hidden";
});
if (dialogs.length === 0) return { name, offenders: [], skipped: "no dialog is open" };
const offenders = [];
dialogs.forEach(dialog => {
const buttons = [...dialog.querySelectorAll("button")].filter(b => {
const r = b.getBoundingClientRect();
return r.width > 0 && r.height > 0;
});
buttons.forEach(button => {
const r = button.getBoundingClientRect();
const label = this.describe(button);
if (r.bottom > innerHeight || r.top < 0) {
const off = r.bottom > innerHeight
? Math.round(r.bottom - innerHeight) + "px below the fold"
: Math.round(-r.top) + "px above it";
offenders.push(`${label} is ${off}`);
return;
}
const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2);
if (hit && hit !== button && !button.contains(hit)) {
offenders.push(`${label} is covered by ${this.describe(hit)}`);
}
});
});
return { name, offenders };
},
runAll(options = {}) {
const checks = [
this.seatsOnTheTable(options.seatSlack),
this.dialogActionsReachable(),
this.touchAction(),
this.tapHighlight(),
this.textSelectable(),
@@ -686,8 +1059,13 @@ const LayoutAudit = {
this.fieldFontSize(),
this.seatOwnership(),
this.oneDealerButton(),
this.hiddenButPainted(),
this.seatLabelsClear(),
this.seatsKeepTheirText(),
this.chipsKeepTheirAmounts(),
this.contrast(options.contrast),
this.touchTargets(options.minimumTarget, options.touchTargets),
];
if (options.includeTouchTargets) checks.push(this.touchTargets(options.minimumTarget));
return {
viewport: `${innerWidth}x${innerHeight}`,
@@ -695,8 +1073,13 @@ const LayoutAudit = {
// Things worth knowing that aren't faults — see occlusion() on toasts.
// Controls a check couldn't probe go here too: not a fault, but not a pass
// either, and a silent skip is how faults hide.
warnings: checks.flatMap(c => [...(c.warnings || []), ...(c.unmeasured || [])]),
passed: checks.filter(c => c.offenders.length === 0).map(c => c.name),
warnings: checks.flatMap(c => [
...(c.warnings || []),
...(c.unmeasured || []),
...(c.skipped ? [`${c.name}: not run here — ${c.skipped}`] : []),
]),
passed: checks.filter(c => !c.skipped && c.offenders.length === 0).map(c => c.name),
skipped: checks.filter(c => c.skipped).map(c => c.name),
clean: checks.every(c => c.offenders.length === 0),
};
},
+167
View File
@@ -0,0 +1,167 @@
// The people standing behind the chairs.
//
// A full home game always has a couple of them, and the list lives on a napkin or in
// the dealer's head — which is where the argument comes from an hour later about who
// said they were next. Order of arrival, because it is the only ordering anybody has
// ever agreed to.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { HoldemState } = require("./load");
const table = (seated = 2, seats = 4) => {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, seats);
["Ann", "Ben", "Cal", "Dee"].slice(0, seated).forEach((name, i) => {
state.seats[i].name = name;
state.seats[i].stack = 200;
state.seats[i].buyIns = 200;
});
return state;
};
describe("keeping the list", () => {
test("names go on in the order they arrive", () => {
const state = table();
HoldemState.addToWaitingList(state, "Priya");
HoldemState.addToWaitingList(state, "Sam");
assert.deepEqual(state.waitingList.map(row => row.name), ["Priya", "Sam"]);
});
test("whitespace is trimmed and nothing empty gets on", () => {
const state = table();
assert.ok(HoldemState.addToWaitingList(state, " Priya "));
assert.equal(HoldemState.addToWaitingList(state, " "), null);
assert.equal(HoldemState.addToWaitingList(state, ""), null);
assert.deepEqual(state.waitingList.map(row => row.name), ["Priya"]);
});
test("two people with the same name are two people", () => {
// Home games have two Mikes. The list is keyed by id, not by name.
const state = table();
HoldemState.addToWaitingList(state, "Mike");
HoldemState.addToWaitingList(state, "Mike");
assert.equal(state.waitingList.length, 2);
assert.notEqual(state.waitingList[0].id, state.waitingList[1].id);
HoldemState.removeFromWaitingList(state, state.waitingList[0].id);
assert.equal(state.waitingList.length, 1, "only one of them leaves");
});
test("taking somebody off gives them back, so the toast can name them", () => {
const state = table();
HoldemState.addToWaitingList(state, "Priya");
const gone = HoldemState.removeFromWaitingList(state, state.waitingList[0].id);
assert.equal(gone.name, "Priya");
assert.deepEqual(state.waitingList, []);
assert.equal(HoldemState.removeFromWaitingList(state, "not-a-real-id"), null);
});
});
describe("which chairs are open", () => {
test("the ones with nobody in them, in seat order", () => {
assert.deepEqual(HoldemState.openSeats(table(2, 4)), [2, 3]);
assert.deepEqual(HoldemState.openSeats(table(4, 4)), []);
});
test("a chair with chips or a buy-in on it is not open", () => {
// Somebody who has stepped away from the table still owns their seat.
const state = table(2, 4);
state.seats[2].stack = 120;
state.seats[3].buyIns = 100;
assert.deepEqual(HoldemState.openSeats(state), []);
});
});
describe("sitting somebody down", () => {
test("their name goes on the chair and they come off the list", () => {
const state = table();
HoldemState.addToWaitingList(state, "Priya");
HoldemState.addToWaitingList(state, "Sam");
const result = HoldemState.seatFromWaitingList(state, state.waitingList[0].id, 2);
assert.equal(result.ok, true);
assert.equal(state.seats[2].name, "Priya");
assert.deepEqual(state.waitingList.map(row => row.name), ["Sam"]);
});
test("with nothing in front of them, because they haven't bought in yet", () => {
// Guessing a stack would put chips on the table nobody has paid for, which is
// the one thing the bank check exists to catch.
const state = table();
HoldemState.addToWaitingList(state, "Priya");
HoldemState.seatFromWaitingList(state, state.waitingList[0].id, 2);
assert.equal(state.seats[2].stack, null);
assert.equal(state.seats[2].buyIns, 0);
assert.equal(state.seats[2].inHand, false, "they're in the next hand, not this one");
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
test("never into a chair somebody is already in", () => {
const state = table();
HoldemState.addToWaitingList(state, "Priya");
const result = HoldemState.seatFromWaitingList(state, state.waitingList[0].id, 0);
assert.equal(result.ok, false);
assert.match(result.reason, /Ann is already/);
assert.equal(state.waitingList.length, 1, "and they keep their place in the queue");
});
test("nor from a name that has already been seated", () => {
const state = table();
HoldemState.addToWaitingList(state, "Priya");
const id = state.waitingList[0].id;
HoldemState.seatFromWaitingList(state, id, 2);
const again = HoldemState.seatFromWaitingList(state, id, 3);
assert.equal(again.ok, false);
assert.equal(state.seats[3].name, "", "the second chair is untouched");
});
test("a seat that doesn't exist is refused rather than invented", () => {
const state = table();
HoldemState.addToWaitingList(state, "Priya");
assert.equal(HoldemState.seatFromWaitingList(state, state.waitingList[0].id, 99).ok, false);
assert.equal(state.waitingList.length, 1);
});
});
describe("a seat opening up", () => {
test("cashing somebody out is what makes room for the next one", () => {
const state = table(4, 4);
HoldemState.addToWaitingList(state, "Priya");
assert.deepEqual(HoldemState.openSeats(state), [], "the table is full");
HoldemState.cashOut(state, 1);
assert.deepEqual(HoldemState.openSeats(state), [1]);
const seated = HoldemState.seatFromWaitingList(state, state.waitingList[0].id, 1);
assert.equal(seated.ok, true);
assert.equal(state.seats[1].name, "Priya");
// Ben's night is still on the record, and the money still adds up.
assert.equal(state.cashedOut.length, 1);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
});
describe("what a saved table remembers", () => {
test("the list survives a reload", () => {
const state = table();
HoldemState.addToWaitingList(state, "Priya");
const migrated = HoldemState.migrate(JSON.parse(JSON.stringify(state)));
assert.deepEqual(migrated.waitingList.map(row => row.name), ["Priya"]);
});
test("a table saved before the list existed has nobody waiting", () => {
const parsed = JSON.parse(JSON.stringify(table()));
delete parsed.waitingList;
assert.deepEqual(HoldemState.migrate(parsed).waitingList, []);
});
test("junk in a saved list is cleaned up rather than trusted", () => {
const parsed = JSON.parse(JSON.stringify(table()));
parsed.waitingList = [{ name: " Priya " }, { name: "" }, null, "Sam"];
const migrated = HoldemState.migrate(parsed);
assert.deepEqual(migrated.waitingList.map(row => row.name), ["Priya", "Sam"]);
assert.ok(migrated.waitingList.every(row => row.id), "and everybody gets an id");
});
});