Compare commits

..
Author SHA1 Message Date
Josh-Heaps 7f664e1b38 add deploy yml for gitea
.NET / build (pull_request) Successful in 53s
Playwright Tests / playwright-tests (pull_request) Canceled after 16s
2026-08-26 15:13:45 -06:00
Josh-HeapsandClaude Opus 5 5501c84e9b Test the ranging pipeline against a simulated room
The DSP tests drive the same files the page loads, so there is no second
implementation to drift. The room tests put two real browsers through a
real room with a synthetic microphone, which covers everything except the
acoustics: slot rotation, leave and rejoin, and the stalled-device case
where a chirp must be withheld rather than sent late.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-30 14:42:16 -06:00
Josh-HeapsandClaude Opus 5 d78251c928 Add the /echo page, capture and playback
Worklet capture into a ring buffer indexed by AudioContext frame, with
the chirp scheduled on the audio clock. Timers are avoided throughout:
a hidden tab has its timers throttled to roughly once a second, which is
long enough to put its chirp in another device's slot and misattribute
every arrival in the round. A device that cannot reach its slot in time
sits the round out rather than chirping late.

Echo cancellation, noise suppression and auto gain are all requested off
and warned about if the device refuses, since echo cancellation exists to
delete exactly the sound being measured.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-30 14:42:05 -06:00
Josh-HeapsandClaude Opus 5 94054c0f1b Add echo rooms, round scheduling and peak relay
In-memory rooms with a background service that opens a round per room,
rotates which device chirps first, and broadcasts the raw peak table once
everyone has reported or the deadline passes. Rounds are announced ahead
of time with a server timestamp so devices schedule against a shared
reference rather than against message arrival.

The server only ever holds sample indices; the geometry is solved on the
clients and no audio is uploaded.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-30 14:41:52 -06:00
Josh-HeapsandClaude Opus 5 183a53234f Add acoustic ranging maths and a room simulator
Chirp generation, FFT matched filter, first-arrival detection with
sub-sample peak fitting, the BeepBeep pair solve, triangle-inequality
outlier rejection and classical MDS, plus a virtual room that
synthesizes what each device would have recorded so the pipeline can be
exercised without microphones.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-30 14:41:39 -06:00
141 changed files with 2981 additions and 34283 deletions
-26
View File
@@ -1,26 +0,0 @@
# Unit tests for the Texas Hold'em dealer's money logic.
#
# The betting engine, the side-pot calculator and the table state are plain script-tag
# modules with no build step, so they run directly under Node's built-in test runner —
# no package.json, no install step, nothing to keep up to date.
name: Hold'em tests
on:
pull_request:
branches: [ "master" ]
push:
branches: [ "master" ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Run Hold'em unit tests
run: node --test tests/holdem/*.test.js
+1 -3
View File
@@ -366,6 +366,4 @@ MigrationBackup/
FodyWeavers.xsd
# Native chess engine CMake build output (the compiled .dll/.so are committed under Resources/)
native/**/build/
# Playwright MCP scratch output
.playwright-mcp/
native/**/build/
+296
View File
@@ -0,0 +1,296 @@
using Microsoft.Playwright;
using Microsoft.Playwright.NUnit;
using NUnit.Framework;
namespace JoshHeaps.Net.UiTests;
/// <summary>
/// Exercises the acoustic-ranging pipeline against a simulated room. The DSP runs in the browser
/// because that is where it runs in production; these tests drive the same files the page loads,
/// so there is no second implementation to drift.
/// </summary>
[TestFixture]
public class EchoDspTests : PageTest
{
private TestConfiguration Config => TestConfiguration.Instance;
public override BrowserNewContextOptions ContextOptions() => Config.GetBrowserContextOptions();
[SetUp]
public async Task LoadPipeline()
{
await Page.GotoAsync(Config.Test.BaseUrl);
await Page.AddScriptTagAsync(new() { Url = "/js/EchoScripts/EchoDsp.js" });
await Page.AddScriptTagAsync(new() { Url = "/js/EchoScripts/EchoSim.js" });
}
[Test]
public async Task Matched_Filter_Finds_The_Chirp_Within_One_Sample()
{
var error = await Page.EvaluateAsync<double>("""
() => {
const sampleRate = 48000;
const chirp = EchoDsp.makeChirp({ sampleRate, durationSeconds: 0.05, startHz: 2000, endHz: 8000 });
const recording = new Float32Array(sampleRate);
for (let i = 0; i < recording.length; i++) recording[i] = (Math.random() * 2 - 1) * 0.02;
const offset = 12345;
for (let i = 0; i < chirp.length; i++) recording[offset + i] += chirp[i] * 0.3;
const peak = EchoDsp.findFirstPeak(EchoDsp.matchedFilterEnvelope(recording, chirp));
return Math.abs(peak.index - offset);
}
""");
Assert.That(error, Is.LessThan(1.0), "arrival should be located to within a sample");
}
[Test]
public async Task A_Tone_Cannot_Be_Located_But_A_Chirp_Can()
{
var ratios = await Page.EvaluateAsync<double[]>("""
() => {
const sampleRate = 48000;
const sidelobeRatio = template => {
const recording = new Float32Array(sampleRate / 2);
const offset = 8000;
for (let i = 0; i < template.length; i++) recording[offset + i] += template[i];
const envelope = EchoDsp.matchedFilterEnvelope(recording, template);
const peak = EchoDsp.maxInRange(envelope, 0, envelope.length);
let highest = 0;
for (let i = 0; i < envelope.length; i++) {
if (Math.abs(i - peak.index) < 200) continue;
highest = Math.max(highest, envelope[i]);
}
return highest / peak.value;
};
const chirp = EchoDsp.makeChirp({ sampleRate, durationSeconds: 0.05, startHz: 2000, endHz: 8000 });
const tone = EchoDsp.makeChirp({ sampleRate, durationSeconds: 0.05, startHz: 5000, endHz: 5000 });
return [sidelobeRatio(chirp), sidelobeRatio(tone)];
}
""");
Assert.That(ratios[1], Is.GreaterThan(0.5), "a tone should correlate almost as well far from the true arrival");
Assert.That(ratios[0], Is.LessThan(0.25), "a chirp should give one unambiguous arrival");
}
[Test]
public async Task Clock_Offset_And_Pipeline_Latency_Cancel()
{
var distance = await Page.EvaluateAsync<double>("""
() => {
const sampleRate = 48000;
const speedOfSound = 343;
const flight = (4.2 / speedOfSound) * sampleRate;
const slot = 0.4 * sampleRate;
const offsetB = 987654;
const latencyA = 0.031 * sampleRate;
const latencyB = 0.128 * sampleRate;
return EchoDsp.pairDistance({
a1: latencyA,
a2: slot + latencyB + flight,
b1: offsetB + latencyA + flight,
b2: offsetB + slot + latencyB,
sampleRate,
speedOfSound
});
}
""");
Assert.That(distance, Is.EqualTo(4.2).Within(0.001));
}
[Test]
public async Task Collocated_Devices_Read_Zero_Before_Calibration()
{
var distance = await Page.EvaluateAsync<double>("""
() => {
const sampleRate = 48000;
const speedOfSound = 343;
const spacing = (0.19 / speedOfSound) * sampleRate;
const slot = 0.4 * sampleRate;
const latencyA = 0.04 * sampleRate;
const latencyB = 0.11 * sampleRate;
// Two tabs on one machine: one speaker, one microphone, so the self path and the
// cross path are the same physical distance.
return EchoDsp.pairDistance({
a1: latencyA + spacing,
a2: slot + latencyB + spacing,
b1: latencyA + spacing,
b2: slot + latencyB + spacing,
sampleRate,
speedOfSound
});
}
""");
Assert.That(distance, Is.EqualTo(0).Within(0.001));
}
[Test]
public async Task Speaker_To_Microphone_Spacing_Is_Added_Back()
{
var distances = await Page.EvaluateAsync<double[]>("""
() => {
const sampleRate = 48000;
const speedOfSound = 343;
const truth = 3.0;
const epsilonA = 0.18;
const epsilonB = 0.04;
const samples = metres => (metres / speedOfSound) * sampleRate;
const slot = 0.4 * sampleRate;
const peaks = {
a1: samples(epsilonA),
a2: slot + samples(truth),
b1: samples(truth),
b2: slot + samples(epsilonB),
sampleRate,
speedOfSound
};
return [
EchoDsp.pairDistance(peaks),
EchoDsp.pairDistance({ ...peaks, epsilonA, epsilonB })
];
}
""");
Assert.That(distances[0], Is.EqualTo(3.0 - 0.11).Within(0.005), "uncorrected range reads short");
Assert.That(distances[1], Is.EqualTo(3.0).Within(0.005), "correcting for spacing recovers the true range");
}
[Test]
public async Task Simulated_Room_Recovers_Distances_And_Layout()
{
var errors = await Page.EvaluateAsync<double[]>("""
() => {
const result = EchoSim.runRound({
positions: [[0, 0], [3.2, 0], [3.0, 2.6], [0.4, 2.9], [1.7, 1.4]]
});
return [EchoSim.worstDistanceError(result), EchoSim.worstPositionError(result), result.keep.length];
}
""");
Assert.That(errors[2], Is.EqualTo(5), "every device should survive a clean round");
Assert.That(errors[0], Is.LessThan(0.05), "worst pairwise range error");
Assert.That(errors[1], Is.LessThan(0.15), "worst recovered position error");
}
[Test]
public async Task A_Reflection_Louder_Than_The_Direct_Path_Does_Not_Win()
{
var errors = await Page.EvaluateAsync<double[]>("""
() => {
const measure = relativeThreshold => EchoSim.worstDistanceError(EchoSim.runRound({
positions: [[0, 0], [3.4, 0], [2.9, 2.7], [0.2, 2.5]],
reflections: [{ extraMetres: 1.8, gain: 5 }],
peakOptions: { relativeThreshold }
}));
return [measure(undefined), measure(0.5)];
}
""");
Assert.That(errors[0], Is.LessThan(0.05), "the first arrival is the distance, not the loudest one");
Assert.That(errors[1], Is.GreaterThan(1.5),
"a threshold high enough to miss the direct path must measure the reflection instead — this is what the default guards against");
}
[Test]
public async Task Echoes_Inside_The_Correlation_Lobe_Bound_The_Accuracy()
{
var errors = await Page.EvaluateAsync<double[]>("""
() => {
const positions = [[0, 0], [3.2, 0], [3.0, 2.6], [0.4, 2.9], [1.7, 1.4]];
const worst = reflectionExtraRange =>
EchoSim.worstDistanceError(EchoSim.runRound({ positions, reflectionExtraRange }));
return [worst([0.4, 4.0]), worst([0.08, 0.4])];
}
""");
Assert.That(errors[0], Is.LessThan(0.01), "echoes well clear of the direct arrival are rejected outright");
Assert.That(errors[1], Is.LessThan(0.15),
"echoes arriving inside the correlation lobe cannot be separated and bias the range — this bounds what a device resting on a hard surface can achieve");
}
[Test]
public async Task A_Bad_Measurement_Is_Rejected_And_The_Layout_Survives()
{
var outcome = await Page.EvaluateAsync<double[]>("""
() => {
const positions = [[0, 0], [3.2, 0], [3.0, 2.6], [0.4, 2.9], [1.6, 1.3]];
const config = EchoSim.buildConfiguration({ positions });
const reports = EchoSim.detectAll(EchoSim.synthesizeRound(config), config);
reports[3].peaks[0] += 9000;
const solved = EchoDsp.solveRound(reports, { speedOfSound: config.speedOfSound });
const truth = solved.keep.map(index => positions[index]);
const aligned = EchoDsp.alignToReference(solved.points, truth);
const worst = Math.max(...aligned.map((point, i) => EchoSim.separation(point, truth[i])));
const brokenPairSurvived = solved.keep.includes(0) && solved.keep.includes(3);
return [solved.keep.length, brokenPairSurvived ? 1 : 0, worst];
}
""");
Assert.That(outcome[0], Is.EqualTo(4), "exactly one endpoint of the bad pair should be dropped");
Assert.That(outcome[1], Is.EqualTo(0), "the impossible pair must not survive");
Assert.That(outcome[2], Is.LessThan(0.2), "the remaining layout should be unpoisoned");
}
[Test]
public async Task Alignment_Undoes_An_Arbitrary_Rotation_And_Mirror()
{
var errors = await Page.EvaluateAsync<double[]>("""
() => {
const reference = [[0, 0], [3.4, 0], [2.9, 2.7], [0.2, 2.5]];
const scramble = (points, angle, mirror) => points.map(([x, y]) => {
const mx = x * mirror;
return [mx * Math.cos(angle) - y * Math.sin(angle) + 11, mx * Math.sin(angle) + y * Math.cos(angle) - 4];
});
const worst = mirror => {
const aligned = EchoDsp.alignToReference(scramble(reference, 0.9, mirror), reference);
return Math.max(...aligned.map((point, i) => EchoSim.separation(point, reference[i])));
};
return [worst(1), worst(-1)];
}
""");
Assert.That(errors[0], Is.LessThan(1e-9), "rotation and translation should be recovered exactly");
Assert.That(errors[1], Is.LessThan(1e-9), "a mirrored solve should be un-mirrored onto the reference");
}
[Test]
public async Task Consecutive_Frames_Do_Not_Rotate_Or_Flip()
{
var drift = await Page.EvaluateAsync<double>("""
() => {
const positions = [[0, 0], [3.2, 0], [3.0, 2.6], [0.4, 2.9]];
const first = EchoSim.runRound({ positions, seed: 11 });
const previous = new Array(positions.length).fill(null);
first.keep.forEach((device, i) => { previous[device] = first.points[i]; });
const config = EchoSim.buildConfiguration({ positions, seed: 22 });
const reports = EchoSim.detectAll(EchoSim.synthesizeRound(config), config);
const second = EchoDsp.solveRound(reports, {
speedOfSound: config.speedOfSound,
previousPoints: previous
});
return Math.max(...second.keep.map((device, i) => EchoSim.separation(second.points[i], previous[device])));
}
""");
Assert.That(drift, Is.LessThan(0.3), "a stationary room should not move between frames");
}
}
+244
View File
@@ -0,0 +1,244 @@
using Microsoft.Playwright;
using Microsoft.Playwright.NUnit;
using NUnit.Framework;
namespace JoshHeaps.Net.UiTests;
/// <summary>
/// Drives two real browsers through a real room: the hub, the round scheduler, slot rotation,
/// detection and the solve all run unchanged. Only the microphone is synthetic, so the answer is
/// known in advance — this is everything except the acoustics.
/// </summary>
[TestFixture]
public class EchoRoomTests : PlaywrightTest
{
private const double TargetMetres = 2.5;
private IPlaywright? _playwright;
private IBrowser? _browser;
private readonly List<IBrowserContext> _contexts = [];
private TestConfiguration Config => TestConfiguration.Instance;
[OneTimeSetUp]
public async Task LaunchBrowser()
{
// Its own Playwright instance and browser: the fake-media launch flags have to be set at
// launch time, and the fixture-managed browser is already running by the time tests start.
_playwright = await Microsoft.Playwright.Playwright.CreateAsync();
_browser = await _playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = true,
Args =
[
"--use-fake-ui-for-media-stream",
"--use-fake-device-for-media-stream",
"--autoplay-policy=no-user-gesture-required"
]
});
}
[OneTimeTearDown]
public async Task CloseBrowser()
{
if (_browser is not null) await _browser.CloseAsync();
_playwright?.Dispose();
}
[TearDown]
public async Task CloseContexts()
{
foreach (var context in _contexts) await context.CloseAsync();
_contexts.Clear();
}
[Test]
public async Task Two_Devices_Measure_The_Distance_Between_Them()
{
var roomCode = $"T{Random.Shared.Next(1000, 9999)}";
var first = await NewDeviceAsync(roomCode, "laptop");
var second = await NewDeviceAsync(roomCode, "phone");
await Expect(first.Locator("#echoRoster li")).ToHaveCountAsync(2);
var measured = await WaitForMeasurementAsync(first);
var alsoMeasured = await WaitForMeasurementAsync(second);
Assert.That(measured, Is.EqualTo(TargetMetres).Within(0.05), "the first device's range");
Assert.That(alsoMeasured, Is.EqualTo(TargetMetres).Within(0.05), "both devices should agree");
}
[Test]
public async Task A_Device_Leaving_Stops_The_Rounds_And_Rejoining_Resumes_Them()
{
var roomCode = $"T{Random.Shared.Next(1000, 9999)}";
var first = await NewDeviceAsync(roomCode, "laptop");
var second = await NewDeviceAsync(roomCode, "phone");
await WaitForMeasurementAsync(first);
await second.ClickAsync("#echoLeave");
await Expect(first.Locator("#echoRoster li")).ToHaveCountAsync(1);
await Expect(first.Locator("#echoStatus")).ToContainTextAsync("Waiting for a second device");
await second.ClickAsync("#echoJoin");
await Expect(first.Locator("#echoRoster li")).ToHaveCountAsync(2);
Assert.That(await WaitForMeasurementAsync(first), Is.EqualTo(TargetMetres).Within(0.05));
}
/// <summary>
/// A stalled main thread is the two-tabs-on-one-machine failure: only one tab is visible, so the
/// other gets throttled and its round handling runs late. A late chirp attributed to the wrong
/// slot yields a plausible-looking but completely wrong range, so the requirement is not "always
/// measures" — it is "never reports a wrong answer". A round it cannot hit must be sat out.
/// </summary>
[Test]
public async Task A_Stalled_Device_Sits_Rounds_Out_Instead_Of_Reporting_Nonsense()
{
var roomCode = $"T{Random.Shared.Next(1000, 9999)}";
var first = await NewDeviceAsync(roomCode, "laptop");
var second = await NewDeviceAsync(roomCode, "phone", stallMilliseconds: 900);
await Expect(first.Locator("#echoRoster li")).ToHaveCountAsync(2);
await first.EvaluateAsync("() => { window.__seen = []; }");
await first.EvaluateAsync("""
() => {
const original = EchoPage.renderSolved.bind(EchoPage);
EchoPage.renderSolved = update => {
const range = update.solved?.matrix?.[0]?.[1];
if (range != null) window.__seen.push(range);
return original(update);
};
}
""");
await first.WaitForTimeoutAsync(20000);
var seen = await first.EvaluateAsync<double[]>("() => window.__seen");
var satOut = await second.EvaluateAsync<int>("() => EchoSession.skippedRounds");
TestContext.Out.WriteLine($"reported ranges: {string.Join(", ", seen.Select(r => r.ToString("0.000")))}, sat out: {satOut}");
Assert.That(satOut, Is.GreaterThan(0),
"the stall must actually have cost the device some slots, or this test proves nothing");
Assert.That(seen, Is.Not.Empty, "a stalled peer should still let some rounds through");
Assert.That(seen, Is.All.EqualTo(TargetMetres).Within(0.05),
"every range that gets reported must be right — a stalled device must sit the round out, not chirp late");
}
[Test]
public async Task The_Capture_Worklet_Keeps_A_Continuous_Readable_Stream()
{
var page = await NewDeviceAsync($"T{Random.Shared.Next(1000, 9999)}", "laptop", fakeMicrophone: false);
await page.WaitForFunctionAsync(
"() => EchoAudio.highestFrame > 48000",
null,
new PageWaitForFunctionOptions { Timeout = 15000, PollingInterval = 100 });
var capture = await page.EvaluateAsync<double[]>("""
() => [
EchoAudio.context.sampleRate,
EchoAudio.warnings.length,
EchoAudio.read(EchoAudio.highestFrame - 24000, 24000)?.length ?? 0,
EchoAudio.read(EchoAudio.highestFrame + 1000, 100) === null ? 1 : 0,
Math.abs(EchoAudio.frameAt(EchoAudio.context.currentTime) - EchoAudio.highestFrame)
]
""");
Assert.That(capture[0], Is.EqualTo(48000), "the pipeline assumes it got the rate it asked for");
Assert.That(capture[1], Is.EqualTo(0), "a clean fake device should raise no capture warnings");
Assert.That(capture[2], Is.EqualTo(24000), "recent audio must be readable out of the ring");
Assert.That(capture[3], Is.EqualTo(1), "reads past the captured end must fail rather than return silence");
Assert.That(capture[4], Is.LessThan(48000),
"the frame index and the context clock must stay in the same domain — a scheduled playback time is converted straight into a recording position");
}
/// <summary>
/// A page joined to the room with its microphone replaced by a synthesizer. Every slot's chirp
/// is placed where a room of this geometry would put it, including a different unknown output
/// latency per slot so the cancellation is actually exercised.
/// </summary>
private async Task<IPage> NewDeviceAsync(
string roomCode,
string name,
bool fakeMicrophone = true,
int stallMilliseconds = 0)
{
var context = await _browser!.NewContextAsync(new BrowserNewContextOptions
{
IgnoreHTTPSErrors = true,
Permissions = ["microphone"]
});
_contexts.Add(context);
var page = await context.NewPageAsync();
page.Console += (_, message) =>
{
if (message.Type == "error") TestContext.Out.WriteLine($"[{name} console] {message.Text}");
};
await page.GotoAsync($"{Config.Test.BaseUrl}/echo?room={roomCode}");
await page.FillAsync("#echoName", name);
if (fakeMicrophone) await page.EvaluateAsync(FakeMicrophoneScript, TargetMetres);
if (stallMilliseconds > 0) await page.EvaluateAsync(StallScript, stallMilliseconds);
await page.ClickAsync("#echoJoin");
return page;
}
/// <summary>Blocks the main thread on every round announcement, the way a throttled tab does.</summary>
private const string StallScript = """
stallMs => {
const original = EchoSession.handleRoundStarting.bind(EchoSession);
EchoSession.handleRoundStarting = schedule => {
const until = performance.now() + stallMs;
while (performance.now() < until) { /* hold the thread */ }
return original(schedule);
};
}
""";
private static async Task<double> WaitForMeasurementAsync(IPage page)
{
await page.WaitForFunctionAsync(
"() => EchoPage.lastSolved?.solved?.matrix?.[0]?.[1] != null",
null,
new PageWaitForFunctionOptions { Timeout = 30000, PollingInterval = 250 });
return await page.EvaluateAsync<double>("() => EchoPage.lastSolved.solved.matrix[0][1]");
}
/// <summary>
/// Synthesizes what the microphone would have heard for this round. The device's own chirp is
/// placed at the frame it was actually scheduled for rather than at its nominal slot position,
/// so any drift between "when the round said to play" and "when playback was really booked"
/// reaches the detector instead of being papered over by the harness.
/// </summary>
private const string FakeMicrophoneScript = """
targetMetres => {
const speedOfSound = 343;
const epsilonMetres = 0.08;
const latencyBySlot = [1400, 5200, 2600, 7100, 900, 4300, 3300, 6000];
EchoAudio.read = (startFrame, length) => {
const round = EchoSession.pending ?? EchoSession.lastRound;
if (!round) return null;
const chirp = EchoSession.chirp;
const toSamples = metres => Math.round((metres / speedOfSound) * round.sampleRate);
const recording = new Float32Array(length);
round.schedule.slotOrder.forEach((_, slot) => {
const own = slot === round.ownSlot;
const origin = own
? round.scheduledFrame - round.windowStart
: round.leadInSamples + slot * round.slotSamples;
const at = origin + latencyBySlot[slot] + toSamples(own ? epsilonMetres : targetMetres);
const amplitude = own ? 1.0 : 0.25;
for (let i = 0; i < chirp.length && at + i < length; i++) recording[at + i] += chirp[i] * amplitude;
});
for (let i = 0; i < length; i++) recording[i] += (Math.random() * 2 - 1) * 0.01;
return recording;
};
}
""";
}
@@ -1,4 +1,4 @@
# .gitea/workflows/deploy.yml
# .gitea/workflows/deploy.yml
name: Build and Deploy
on:
@@ -12,17 +12,13 @@ concurrency:
jobs:
build-deploy:
# Gitea's runner images are lean, so the toolchain is installed below rather
# than assumed. The glibc that libchess_engine.so links against comes from
# this image, not from the runner host — keep it matched to the prod server.
runs-on: ubuntu-latest
steps:
- name: Install toolchain
- name: Install deploy tools
run: |
apt-get update
apt-get install -y --no-install-recommends \
cmake build-essential rsync openssh-client
apt-get install -y --no-install-recommends rsync openssh-client
- name: Checkout
uses: actions/checkout@v4
@@ -33,26 +29,10 @@ jobs:
dotnet-version: '8.0.x'
- name: Restore
run: dotnet restore JoshHeaps.Net/JoshHeaps.Net.csproj
run: dotnet restore
- name: Build native chess engine (libchess_engine.so)
run: |
cmake -S native/chess_engine -B native/chess_engine/build -DCMAKE_BUILD_TYPE=Release
cmake --build native/chess_engine/build
cp native/chess_engine/build/libchess_engine.so JoshHeaps.Net/Resources/
# Publishing the project rather than the solution keeps chess_engine.vcxproj
# (Windows-only MSBuild C++ targets) and the UiTests assemblies out of it.
- name: Publish
run: dotnet publish JoshHeaps.Net/JoshHeaps.Net.csproj -c Release -o ./publish
- name: Verify payload
run: |
set -euo pipefail
test -f publish/Resources/libchess_engine.so \
|| { echo "libchess_engine.so missing from publish output"; exit 1; }
test -x publish/Resources/stockfish-ubuntu-x86-64-sse41-popcnt \
|| { echo "stockfish is not executable"; exit 1; }
run: dotnet publish -c Release -o ./publish
- name: Prepare SSH
env:
@@ -67,8 +47,6 @@ jobs:
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -p "$PORT" "$SSH_HOST" >> ~/.ssh/known_hosts 2>/dev/null
# --exclude chess-data: never let --delete remove the learned-engine training
# data, which lives in the deploy dir unless ChessEngine__WeightsPath is set.
- name: Rsync to server
env:
SSH_HOST: ${{ secrets.SSH_HOST }}
@@ -78,11 +56,11 @@ jobs:
run: |
set -euo pipefail
PORT="${SSH_PORT:-22}"
rsync -az --delete --exclude 'chess-data' \
rsync -az --delete \
-e "ssh -p $PORT -i ~/.ssh/deploy_key -o StrictHostKeyChecking=yes" \
publish/ "$SSH_USER@$SSH_HOST:$TARGET_DIR/"
- name: Reload and restart service
- name: Restart service
env:
SSH_HOST: ${{ secrets.SSH_HOST }}
SSH_PORT: ${{ secrets.SSH_PORT }}
+52
View File
@@ -0,0 +1,52 @@
using JoshHeaps.Net.Models;
using JoshHeaps.Net.Services.Interfaces;
using Microsoft.AspNetCore.SignalR;
namespace JoshHeaps.Net.Hubs;
/// <summary>
/// Membership and peak reporting for acoustic ranging rooms. Nothing that arrives here is audio:
/// a report is a handful of sample indices, and the geometry is solved on the clients.
/// </summary>
public class EchoHub(IEchoRoomStore rooms) : Hub
{
/// <summary>Join (or create) a room and receive an id plus the current roster.</summary>
public async Task<EchoJoinResult> JoinRoom(string roomCode, string displayName, int sampleRate)
{
var result = rooms.Join(roomCode, Context.ConnectionId, displayName, sampleRate);
await Groups.AddToGroupAsync(Context.ConnectionId, GroupFor(result.RoomCode));
await Clients.Group(GroupFor(result.RoomCode)).SendAsync("RoomChanged", result.Room);
return result;
}
/// <summary>File this device's arrival indices for the room's open round.</summary>
public bool ReportRound(EchoPeakReport report) => rooms.Report(Context.ConnectionId, report);
/// <summary>
/// Server clock, for estimating each device's offset from it. Only needs to be good to a few
/// tens of milliseconds: it decides which chirp is whose, never how far away anything is.
/// </summary>
public long ServerTime() => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public async Task<bool> LeaveRoom() => await RemoveFromRoom();
public override async Task OnDisconnectedAsync(Exception? exception)
{
await RemoveFromRoom();
await base.OnDisconnectedAsync(exception);
}
internal static string GroupFor(string roomCode) => $"echo:{roomCode.ToUpperInvariant()}";
private async Task<bool> RemoveFromRoom()
{
var (roomCode, room) = rooms.Leave(Context.ConnectionId);
if (roomCode is null) return false;
await Groups.RemoveFromGroupAsync(Context.ConnectionId, GroupFor(roomCode));
if (room is not null) await Clients.Group(GroupFor(roomCode)).SendAsync("RoomChanged", room);
return true;
}
}
+84
View File
@@ -0,0 +1,84 @@
namespace JoshHeaps.Net.Models;
/// <summary>A device taking part in a ranging room.</summary>
public sealed class EchoDevice
{
public required string DeviceId { get; init; }
public required string ConnectionId { get; init; }
public required string DisplayName { get; set; }
public int SampleRate { get; set; }
}
/// <summary>
/// One chirp cycle: every device plays in turn, and every device listens to the whole thing.
/// </summary>
public sealed class EchoRound
{
public required string RoundId { get; init; }
public required string[] SlotOrder { get; init; }
public int SlotMilliseconds { get; init; }
public DateTimeOffset Deadline { get; init; }
public Dictionary<string, EchoPeakReport> Reports { get; } = [];
}
/// <summary>
/// What one device heard. Peaks are fractional sample indices into that device's own continuous
/// recording, one per slot, null where a chirp was not detected. Nothing else is ever uploaded.
/// </summary>
public sealed class EchoPeakReport
{
public required string DeviceId { get; init; }
public required string RoundId { get; init; }
public int Slot { get; init; }
public int SampleRate { get; init; }
public double Epsilon { get; init; }
public double?[] Peaks { get; init; } = [];
}
public sealed class EchoJoinResult
{
public required string DeviceId { get; init; }
public required string RoomCode { get; init; }
public required EchoRoomSnapshot Room { get; init; }
}
public sealed class EchoRoomSnapshot
{
public required string RoomCode { get; init; }
public required EchoDeviceSnapshot[] Devices { get; init; }
}
public sealed class EchoDeviceSnapshot
{
public required string DeviceId { get; init; }
public required string DisplayName { get; init; }
public int SampleRate { get; init; }
}
/// <summary>Tells every device when to chirp: its own slot index and how long a slot lasts.</summary>
public sealed class EchoRoundSchedule
{
public required string RoundId { get; init; }
public required string[] SlotOrder { get; init; }
public int SlotMilliseconds { get; init; }
public int TailMilliseconds { get; init; }
/// <summary>
/// When slot zero should sound, in server time, set far enough ahead that every device can
/// receive the message and book the playback before it arrives. Devices schedule against this
/// rather than against message arrival, so one slow client cannot drag its chirp into another
/// device's slot and invalidate the round for everybody.
/// </summary>
public long StartsAtUnixMs { get; init; }
}
/// <summary>
/// Every device's peaks for one round, broadcast unchanged. Each client solves the geometry itself
/// so the server never needs the ranging maths.
/// </summary>
public sealed class EchoRoundResult
{
public required string RoundId { get; init; }
public required string[] SlotOrder { get; init; }
public required EchoPeakReport[] Reports { get; init; }
}
-58
View File
@@ -1,58 +0,0 @@
@page
@model JoshHeaps.Net.Pages.CasinoModel
@{
ViewData["Title"] = "Casino Games";
Layout = "_Layout";
}
<div class="casino-container">
<h1 class="casino-header">Casino Games</h1>
<p class="casino-subtitle">Tools for running table games without doing the math yourself</p>
<div class="games-grid">
<a href="/casino/texasholdem" class="game-card">
<div class="game-icon">🃏</div>
<div class="game-title">Texas Hold'em</div>
<div class="game-description">
A dealer's assistant: seat players around the table, track blinds, chips and
all-ins, then split main and side pots automatically.
</div>
</a>
<a href="/casino/texasholdem/quicksplit" class="game-card">
<div class="game-icon">➗</div>
<div class="game-title">Quick Split</div>
<div class="game-description">
Chop a pot in seconds on your phone — no table setup, just the amount,
how many players are splitting it, and the smallest chip in play.
</div>
</a>
<div class="game-card disabled">
<div class="game-icon">🎲</div>
<div class="game-title">Craps</div>
<div class="game-description">Payout calculator for the table.</div>
<div class="coming-soon">Coming soon...</div>
</div>
<div class="game-card disabled">
<div class="game-icon">🎡</div>
<div class="game-title">Roulette</div>
<div class="game-description">Bet tracking and payout reference.</div>
<div class="coming-soon">Coming soon...</div>
</div>
<div class="game-card disabled">
<div class="game-icon">🂡</div>
<div class="game-title">Blackjack</div>
<div class="game-description">Multi-hand dealer tracker.</div>
<div class="coming-soon">Coming soon...</div>
</div>
</div>
<a href="/" class="home-button">← Back to Home</a>
</div>
@section Styles {
<link href="/css/casino/page.css?v=@ViewData["cssVersion"]" rel="stylesheet" type="text/css" />
}
@@ -1,795 +0,0 @@
@page
@model JoshHeaps.Net.Pages.Casino.TexasHoldemModel
@{
ViewData["Title"] = "Texas Hold'em Dealer";
Layout = "_Layout";
}
<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 down to
the sidebar with the save/load pair — in a panel called Save & reset, so the
danger is on the label rather than at the end of a scroll — 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. *@
@* The word is its own element so a phone can drop it and keep the arrow, and the
aria-label is what a screen reader gets either way. It contains the visible
text on the sizes that still show it, which is what WCAG 2.5.3 asks of a name
that says more than the label does. *@
<div id="holdemHeaderLeft">
<a href="/casino" class="holdemBackLink" aria-label="Back to Casino">←<span class="backLinkWord"> Casino</span></a>
<h1>Texas Hold'em Dealer</h1>
</div>
<div id="holdemHeaderActions">
<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>
@* Not the accent any more. It is a shortcut to a sheet, available all night,
and it is never the next step — the bar always has that, and at showdown
the bar says so in as many words. See .actionAdvance in holdem.css. *@
<button id="resolvePotBtn" class="holdemBtn">Resolve Pot</button>
</div>
</header>
@* The seat sheet was the only one of the tool's seven overlays with nothing behind
it. On a phone it covers the felt from 250px down and the action bar with it, so
it is modal in everything but appearance — and what stayed lit above it was the
header, with Misdeal, Next Hand and Resolve Pot live under a thumb that was
reaching for a name field. NN/g and Material both say the same thing about this:
a modal sheet with an invisible scrim tells the user they can still touch what
they can still see, and they can't.
Not an `*Overlay` id, deliberately — Modal watches those and would take the
sidebar panel this becomes on a desktop for a dialog. It is driven entirely by
body.seatSheetOpen, and it is `display: none` above 700px where the panel is
just a panel. *@
<div id="seatSheetScrim"></div>
<div id="holdemLayout">
<section id="tableSection">
<div id="boardStrip" hidden></div>
<div id="pokerTableWrap">
<div id="pokerTable">
<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>
<div id="seatsLayer"></div>
</div>
<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>
<aside id="holdemSidebar">
<section id="seatEditorPanel" class="sidebarPanel seatEditorPanel">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="seatEditorHeader">
<h2 id="seatEditorTitle">Select a seat</h2>
<button id="closeSeatEditorBtn" class="seatSheetClose" aria-label="Done editing this seat">Done</button>
</div>
<div id="seatEditorBody">
<p class="fieldHint">Click a seat at the table to edit their name, cards, chips and anything else.</p>
</div>
</section>
@* 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><h2>Table Setup</h2> <span class="panelGlance" id="glanceTableSetup" hidden></span></summary>
<div class="panelBody">
<label class="fieldRow">
<span>Seats at table</span>
<input type="number" id="seatCountInput" min="2" max="24" value="10" />
</label>
<label class="fieldRow">
<span>Blinds move</span>
<select id="directionSelect">
<option value="clockwise" selected>Clockwise</option>
<option value="counterclockwise">Counterclockwise</option>
</select>
</label>
<label class="fieldRow">
<span>Dedicated dealer (not a seat)</span>
<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>Ask me for the cards as they come out</span>
<input type="checkbox" id="trackBoardToggle" />
</label>
@* The label used to lead with "Track the board", which is the feature's name
rather than what pressing it does to your evening. What it does is put a
card sheet in front of you at four moments: each street, and the showdown. *@
<p class="fieldHint">Every time you deal a street, a sheet asks which cards came off the deck, and puts them on the felt. At the showdown it asks for each hand that turns over &mdash; then Resolve Pot reads the winner and the amount instead of asking you. Close the sheet at any point to go back to picking the winner yourself.</p>
<label class="fieldRow">
<span>Keep the screen on during a hand</span>
<input type="checkbox" id="keepScreenAwakeToggle" />
</label>
@* On by default, and the only setting here that is. A dealer has to
opt in to the tool doing more than they asked; they should not have
to opt in to it staying readable. *@
<p class="fieldHint">Stops the phone dimming and locking between the flop and the turn. It only holds while betting is open, so the screen sleeps as usual during breaks &mdash; and the tool says so the first time it takes hold.</p>
<div class="blindsRow">
<label class="fieldRow">
<span>Small blind</span>
<input type="number" id="smallBlindInput" min="0" step="0.5" />
</label>
<label class="fieldRow">
<span>Big blind</span>
<input type="number" id="bigBlindInput" min="0" step="0.5" />
</label>
</div>
<label class="fieldRow">
<span>Starting stack ($)</span>
<input type="number" id="defaultStackInput" min="0" step="1" placeholder="e.g. 200" />
</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">
<label class="fieldRow">
<span>Base pot amount ($)</span>
<input type="number" id="basePotInput" min="0" step="1" placeholder="e.g. 500" />
</label>
<p class="fieldHint">For tracking a hand by hand instead of tapping the action: everyone is assumed to have put in this much, unless their seat says otherwise.</p>
</div>
</details>
</div>
</details>
@* These four were one panel called "Session", which is a container word rather
than a name: it held the standings, a waiting list, the hand log and the
save/load/reset buttons — a topic, a task, a log and three utilities, which
is four kinds of thing under one label. It measured at 1206px and 103
elements, and "The table itself" was 1052px down inside it, so reaching
Reset table meant opening a panel called Session and scrolling past the
money and the log to get there.
Each panel is named for the thing a dealer came looking for, and the
subheads that used to do that job are gone, because the summary says it
now. They are in the order of a night: set the table up, watch the money,
fill the seats, look back at a hand — and, last and apart from the rest,
the two buttons that end it. *@
<details class="sidebarPanel">
<summary><h2>Standings</h2> <span class="panelGlance" id="glanceStandings" hidden></span></summary>
<div class="panelBody">
<p id="storageWarning" class="storageWarning" hidden></p>
<div class="standingsTableWrap">
<div id="standingsTable">
<div class="standingsRow standingsHeader">
<span>Player</span>
<span class="standingsInHead">In</span>
<span class="standingsWonHead">Won</span>
<span class="standingsNetHead">Net</span>
<span class="standingsChipsHead" title="What they are holding — the cash to count out if they leave now">Chips</span>
<span title="Those chips, less the cash they handed over">Up/down</span>
</div>
<div id="standingsList"></div>
</div>
</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>
<div id="bankReconcile" class="bankReconcile" hidden>
<div class="bankReconcileRow">
<span>Cash taken</span>
<span id="bankCashIn"></span>
</div>
<div class="bankReconcileRow">
<span>Chips in play</span>
<span id="bankChipsInPlay"></span>
</div>
<div class="bankReconcileRow" id="bankDiscardedRow" hidden>
<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>
<h3 class="panelSubhead">Settle up</h3>
<ul id="settleUpList" class="settleUpList"></ul>
<p id="settleUpNote" class="fieldHint"></p>
</div>
</div>
</details>
<details class="sidebarPanel">
<summary><h2>Waiting list</h2> <span class="panelGlance" id="glanceWaiting" hidden></span></summary>
<div class="panelBody">
<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>
</details>
<details class="sidebarPanel">
<summary><h2>Hands</h2> <span class="panelGlance" id="glanceHands" hidden></span></summary>
<div class="panelBody">
<div class="handHistoryFilterRow">
<input id="handHistoryFilter" type="search" class="handHistoryFilter"
placeholder="Find a hand — name, amount or #" aria-label="Filter the hand log by player, amount or hand number" />
<span id="handHistoryCount" class="handHistoryCount" hidden></span>
</div>
<div id="handHistoryList"></div>
<p id="handHistoryNoMatch" class="fieldHint" hidden></p>
<p id="handHistoryEmptyHint" class="fieldHint">Resolved pots are logged here, in case a chip count is disputed later.</p>
<div class="handHistoryActions">
<button id="exportHistoryBtn" class="holdemBtn holdemBtnSmall">Export CSV</button>
<button id="clearHistoryBtn" class="holdemBtn holdemBtnSmall holdemBtnDanger">Clear history</button>
</div>
</div>
</details>
<details class="sidebarPanel">
<summary><h2>Chip Legend</h2> <span class="panelGlance" id="glanceChips" hidden></span></summary>
<div class="panelBody">
<div id="chipLegendList"></div>
<button id="addChipColorBtn" class="holdemBtn holdemBtnSmall">+ Add chip color</button>
<p class="fieldHint">Give each chip color a value, then count chips on a seat instead of typing a total.</p>
<div id="colourUp" hidden>
<h3 class="panelSubhead">Stacks in chips</h3>
<dl id="colourUpList" class="colourUpList"></dl>
<p class="fieldHint">The fewest chips that make each stack — for colouring up, or counting one out.</p>
</div>
</div>
</details>
<details class="sidebarPanel" id="keyboardPanel">
<summary><h2>Keyboard</h2></summary>
<div class="panelBody">
<dl id="shortcutLegend" class="shortcutLegend"></dl>
<p class="fieldHint">Nothing fires while you're typing in a field, or while a sheet is open over the table.</p>
</div>
</details>
<details class="sidebarPanel">
<summary><h2>Table Notes</h2> <span class="panelGlance" id="glanceNotes" hidden></span></summary>
<div class="panelBody">
<textarea id="tableNotes" rows="4" aria-label="Table notes" placeholder="Anything else worth tracking — side bets, IOUs, running totals..."></textarea>
</div>
</details>
@* Last, and on its own, because everything in it is about the night as a whole
rather than the hand in front of you — and because two of the three buttons
are the ones you cannot take back.
Reset table came down from the header a while ago, where it sat in the same
weight as Resolve Pot: the most-pressed control in a session beside the one
that throws the night away. It used to be buried at the bottom of Session,
1052px down, which hid it but also meant nobody could find it on purpose.
Naming the panel for both jobs puts the danger on the label, where it is
read before the panel is opened rather than met at the end of a scroll. *@
<details class="sidebarPanel">
<summary><h2>Save &amp; reset</h2></summary>
<div class="panelBody">
<p class="fieldHint">
The night lives in this browser and nowhere else. Save it to a file to carry it
to another device, or to have something to come back to if this one dies.
</p>
@* That sentence has always been true, and always been missing its
second half: a browser is allowed to throw site data away when the
device runs short, and Safari does it on a timer. So the panel now
says which of the two situations this device is actually in, and
offers the one thing that changes it. See requestDurable() in
state.js for why the ask is a button rather than a page-load call. *@
<p class="fieldHint" id="storageDurabilityHint" hidden></p>
<button id="keepStorageBtn" class="holdemBtn holdemBtnSmall" hidden>Ask this browser to keep it</button>
<div class="handHistoryActions">
<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 />
<button id="resetTableBtn" class="holdemBtn holdemBtnSmall holdemBtnDanger">Reset table</button>
</div>
</div>
</details>
</aside>
</div>
</div>
<template id="seatTemplate">
<div class="seat" draggable="true">
<div class="seatChairNumber"></div>
<button class="dealerChip" type="button" title="Make this seat the dealer button">D</button>
<span class="blindBadge sbBadge">SB</span>
<span class="blindBadge bbBadge">BB</span>
<span class="blindBadge strBadge" title="Straddled — the action comes back to this seat">STR</span>
<div class="seatPuckName"></div>
<div class="seatPuckCards"></div>
<div class="seatPuckTotal"></div>
<div class="seatPuckStack"></div>
</div>
</template>
@* Four things stacked flat used to be five: name, in/out, two hole-card slots, stack,
a five-box chip counter and a list of custom fields, every one of them at the same
weight, all of it open at once. Measured on a 390px phone the sheet came to 594px,
and the three controls a dealer touches on nearly every visit — the name, the two
status boxes, the stack — were 132px of it. The chip counter alone was 174px, the
tallest thing in the sheet, for a job most tables do once a night if at all; the two
card slots were 62px of dashed grey on every table that never asked to be shown a
card.
So the flat list is now three rows and three disclosures, and which of the three
stand open is a question about *this seat*, answered in renderSeatDisclosures: a
seat holding cards opens its cards, a seat with chips counted opens its count, a
seat with notes on it opens its notes. Anything with nothing in it stays a one-line
summary that says so. Nothing was removed and nothing moved to another screen. *@
<template id="seatEditorTemplate">
<div class="seatEditorForm">
<label class="fieldRow">
<span>Name</span>
<input type="text" class="seatNameInput" placeholder="Seat" maxlength="24" />
</label>
<div class="seatCardToggles">
<label class="inHandToggle" title="This seat is playing the current hand">
<input type="checkbox" class="inHandCheckbox" />
<span>In hand</span>
</label>
<label class="foldToggle" title="Folded">
<input type="checkbox" class="foldCheckbox" />
<span>Fold</span>
</label>
</div>
<label class="fieldRow stackRow">
<span>Stack</span>
<input type="number" class="stackInput" min="0" step="1" placeholder="table default" />
</label>
<div class="seatBuyIns" hidden></div>
<details class="subPanel seatSubPanel cardsPanel">
<summary><span class="seatSubPanelName">Hole cards</span> <span class="seatGlance cardsGlance"></span></summary>
<div class="subPanelBody">
<div class="seatCards">
<button type="button" class="cardSlot card1Slot" aria-label="Choose first card"></button>
<button type="button" class="cardSlot card2Slot" aria-label="Choose second card"></button>
</div>
</div>
</details>
@* Named for the question it answers rather than for the boxes it contains. The
counter, the typed override and the total are one calculation — what this
seat has put in the pot — and the answer now sits on the summary, so a shut
panel still says it. *@
<details class="subPanel seatSubPanel contributionPanel">
<summary><span class="seatSubPanelName">What they've put in</span> <span class="seatGlance contributionGlance"></span></summary>
<div class="subPanelBody seatContribution">
<div class="chipCounts"></div>
<label class="fieldRow amountOverrideRow">
<span>$ amount</span>
<input type="number" class="amountOverrideInput" min="0" step="1" placeholder="auto" />
</label>
<div class="seatTotal">Total: <span class="seatTotalAmount">$0</span></div>
</div>
</details>
<details class="subPanel seatSubPanel notesPanel">
<summary><span class="seatSubPanelName">Notes on this seat</span> <span class="seatGlance notesGlance"></span></summary>
<div class="subPanelBody">
<div class="customFields"></div>
<button class="holdemBtn holdemBtnSmall addFieldBtn">+ field</button>
</div>
</details>
</div>
</template>
<template id="chipLegendRowTemplate">
<div class="chipLegendRow">
<input type="color" class="chipColorInput" aria-label="Chip colour" />
<input type="number" class="chipValueInput" min="0" step="0.01" placeholder="value" aria-label="Chip value" />
<button class="holdemBtn holdemBtnSmall holdemBtnDanger removeChipColorBtn">×</button>
</div>
</template>
@* The value used to be a `title` attribute, which is a tooltip — and a tooltip is
nothing at all on the device this is used on. Five coloured dots with five number
boxes and no way to tell which one was the $25 without opening the Chip Legend and
matching colours by eye. It is text now. *@
<template id="chipCountTemplate">
<label class="chipCountRow">
<span class="chipSwatch"></span>
<span class="chipCountValue"></span>
<input type="number" class="chipCountInput" min="0" step="1" value="0" />
</label>
</template>
<template id="customFieldTemplate">
<div class="customFieldRow">
<input type="text" class="customFieldLabel" placeholder="Label" maxlength="20" />
<input type="text" class="customFieldValue" placeholder="Value" maxlength="40" />
<button class="holdemBtn holdemBtnSmall holdemBtnDanger removeFieldBtn">×</button>
</div>
</template>
<template id="standingsRowTemplate">
<div class="standingsRow">
<span class="standingsName"></span>
<span class="standingsIn"></span>
<span class="standingsWon"></span>
<span class="standingsNet"></span>
<span class="standingsChips"></span>
<span class="standingsCashOut"></span>
</div>
</template>
<template id="handHistoryRowTemplate">
<div class="handHistoryRow">
<div class="handHistoryRowHeader">
<span class="handHistoryHandNumber"></span>
<span class="handHistoryPot"></span>
<span class="handHistoryTime"></span>
</div>
<div class="handHistoryPayouts"></div>
</div>
</template>
<div id="addChipsOverlay" hidden>
<div id="addChipsSheet" role="dialog" aria-labelledby="addChipsTitle">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="addChipsHeader">
<h2 id="addChipsTitle"></h2>
<span id="addChipsSubtitle"></span>
</div>
<div id="addChipsQuick"></div>
<div class="addChipsEntry">
<span class="addChipsCurrency">$</span>
<input type="text" id="addChipsInput" inputmode="decimal" autocomplete="off" aria-label="Amount to add" />
</div>
<div class="addChipsActions">
<button id="addChipsConfirmBtn" class="holdemBtn holdemBtnAccent" type="button">Add to stack</button>
<button id="addChipsCancelBtn" data-modal-close class="holdemBtn holdemBtnGhost" type="button">Cancel</button>
</div>
</div>
</div>
<div id="rulingsOverlay" hidden>
<div id="rulingsSheet" role="dialog" aria-labelledby="rulingsTitle">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="rulingsHeader">
<h2 id="rulingsTitle">Common rulings</h2>
<button id="closeRulingsBtn" data-modal-close class="holdemBtn holdemBtnSmall holdemBtnGhost" type="button">Done</button>
</div>
<p class="rulingsIntro">
The conventions most rooms follow, for the calls that come up mid-hand.
Your house rules always win — and settle a dispute before the next hand,
not during it.
</p>
<nav id="rulingsIndex" class="rulingsIndex" aria-label="Jump to a ruling"></nav>
<section class="ruling" data-short="Misdeal">
<h3>Redeal it — misdeal</h3>
<ul>
<li>The first card goes to the wrong seat.</li>
<li>A seat entitled to a hand gets dealt out, or a seat that isn't entitled gets dealt in.</li>
<li>Two or more boxed cards turn up on the initial deal.</li>
<li>Either of the first two cards is exposed by dealer error.</li>
</ul>
</section>
<section class="ruling" data-short="Board card early">
<h3>A board card turned too early</h3>
<p>
If the fourth board card gets turned before the betting round is finished,
that card is out of play for the round. Finish the betting, then burn and
turn what would have been the fifth card in the fourth card's place.
</p>
</section>
<section class="ruling" data-short="Out of turn">
<h3>Acting out of turn</h3>
<p>
A one-off is usually just backed up if no one has acted behind them.
Doing it repeatedly is what earns a penalty.
</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>
The player left of the big blind may put out twice it before the cards,
without looking. It is a blind bet, not a raise made in turn, so it does
three things at once: everyone else acts first, the minimum raise becomes
twice the straddle, and the straddler still has the option when the
action comes back — they may raise even if nobody raised into them.
</p>
<p>
Re-straddles carry on to the left, each doubling again, and stop before
the small blind. Tap <em>Straddle</em> on the deal prompt and the tool
posts it, puts the right player on the clock and prices the raise;
the seat wears an <em>STR</em> badge for the hand.
</p>
</section>
<section class="ruling" data-short="Short all-in">
<h3>A short all-in doesn't reopen the betting</h3>
<p>
Somebody shoving in less than a full raise — say $3 more when the last
raise was $8 — does not give the players behind them another go. Anyone
who has already acted owes the difference or folds; they don't get to
raise again because a short stack happened to land between them.
</p>
<p>
A player who hadn't acted yet keeps full rights and may still raise, and
the minimum raise stays measured off the last <em>full</em> raise, not
off the short one. The action bar follows this for you.
</p>
</section>
<section class="ruling" data-short="Uncalled bet">
<h3>Chips nobody called come back</h3>
<p>
Bet more than anyone was able to call and the excess is returned to you
before the showdown — it was never contested, so it isn't part of the
pot. The pot breakdown shows it as "uncalled" rather than pretending it's
a side pot you could win.
</p>
</section>
<section class="ruling" data-short="Oversized chip">
<h3>One big chip, nothing said</h3>
<p>
The most common argument at a home table. A player facing a bet who
pushes out a single oversized chip without saying anything has
<em>called</em> — not raised, however big the chip is. To raise with one
chip you have to say "raise" before it lands; say it without an amount
and the raise is the most that chip allows.
</p>
<p>
Facing no bet, the same silent chip is a bet of the whole chip. And a
clear verbal declaration in turn is binding either way — if words and
chips disagree, whichever came first is the action.
</p>
</section>
<section class="ruling" data-short="Minimum raise">
<h3>A raise has to be a full raise</h3>
<p>
At least as much again as the last raise, or the big blind if there
hasn't been one. Anything between a call and that minimum isn't a raise
a player can make — it's a call, unless they're putting their last chips
in. The raise pad says so if you type one, and won't stop you: your
ruling beats the arithmetic.
</p>
</section>
<section class="ruling" data-short="Who shows first">
<h3>Who turns their hand over first</h3>
<p>
If there was a bet on the river, the last player to bet or raise shows
first. If the river was checked all the way round, it's the first live
player left of the button. Nobody has to be asked twice — a player may
always turn their hand over early if they want to.
</p>
<p>
When everyone is all-in before the river there was no final round to
lead, so it falls to whoever last put money in, on whichever street that
was. The action bar names the seat and the reason at every showdown, so
the call is already made before anyone asks.
</p>
</section>
<section class="ruling" data-short="Odd chip">
<h3>The odd chip in a split pot</h3>
<p>
When a chopped pot won't divide evenly, the odd chip goes to the first
player left of the button, not to whoever the dealer happened to tick
first. Pot payouts here order the winners that way, so the leftover lands
on the right seat every time.
</p>
</section>
<section class="ruling" data-short="String bet">
<h3>Betting in one motion — the string bet</h3>
<p>
A bet is whatever goes in on the first trip to the stack, unless the
amount was said out loud first. Reaching back for more chips without
having said "raise" is a string bet, and only the first motion stands.
Saying the number is always enough on its own: "raise to sixty" binds
whatever order the chips arrive in.
</p>
<p>
It's the rule home games invoke most and enforce least, and both are
fine — the point is that a player can't watch the table react and then
decide how much to bet. Say it, or push it all at once.
</p>
</section>
<p class="rulingsSource">
Follows the Tournament Directors Association rules, which most rooms and
home games take their lead from.
</p>
</div>
</div>
<div id="seatMenuOverlay" hidden>
<div id="seatMenuSheet" role="dialog" aria-labelledby="seatMenuTitle">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="seatMenuHeader">
<h2 id="seatMenuTitle"></h2>
<span id="seatMenuSubtitle"></span>
</div>
<div id="seatMenuActions"></div>
<button id="seatMenuCancelBtn" data-modal-close class="holdemBtn holdemBtnGhost" type="button">Cancel</button>
</div>
</div>
<div id="cardPickerOverlay" hidden>
<div id="cardPickerSheet" role="dialog" aria-labelledby="cardPickerTitle">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="cardPickerHeader">
<h2 id="cardPickerTitle"></h2>
<button id="cardPickerClearBtn" class="holdemBtn holdemBtnSmall" type="button">Clear</button>
<button id="cardPickerCloseBtn" data-modal-close class="holdemBtn holdemBtnSmall holdemBtnGhost" type="button">Done</button>
</div>
<div id="cardPickerSlots"></div>
<div id="cardPickerGrid"></div>
</div>
</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>
<div id="confirmOverlay" hidden>
<div id="confirmModal" role="alertdialog" aria-labelledby="confirmTitle" aria-describedby="confirmMessage" tabindex="-1">
<h2 id="confirmTitle"></h2>
<p id="confirmMessage"></p>
<div class="confirmActions">
<button id="confirmCancelBtn" data-modal-close class="holdemBtn holdemBtnGhost" type="button">Cancel</button>
<button id="confirmAcceptBtn" class="holdemBtn holdemBtnDanger" type="button">Confirm</button>
</div>
</div>
</div>
<div id="potWizardOverlay" hidden>
<div id="potWizardModal" role="dialog" aria-labelledby="potWizardTitle">
<div class="potWizardHeader">
<h2 id="potWizardTitle">Resolve the Pot</h2>
<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" />
@* The standard name first, then Apple's older one. Chrome has been printing
"<meta name="apple-mobile-web-app-capable"> is deprecated" into this page's
console on every load; the replacement is the unprefixed name, and Safari still
wants the prefixed one, so both are here. *@
<meta name="mobile-web-app-capable" content="yes" />
<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>
<script src="~/js/casino/holdem/potCalculator.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/state.js?v=@ViewData["cssVersion"]"></script>
@* After feedback.js, because the first lock it takes announces itself with a Toast. *@
<script src="~/js/casino/holdem/wakeLock.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>
<script src="~/js/casino/holdem/betting.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/actionBar.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/shortcuts.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/potWizard.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/handHistoryExport.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/modal.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/main.js?v=@ViewData["cssVersion"]"></script>
}
@@ -1,11 +0,0 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace JoshHeaps.Net.Pages.Casino
{
public class TexasHoldemModel : PageModel
{
public void OnGet()
{
}
}
}
@@ -1,95 +0,0 @@
@page
@model JoshHeaps.Net.Pages.Casino.TexasHoldem.QuickSplitModel
@{
ViewData["Title"] = "Quick Split";
Layout = "_Layout";
}
<div id="splitApp">
<header id="splitHeader">
<h1>Quick Split</h1>
<p class="splitSubtitle">Chop a pot without setting up a table.</p>
</header>
<div id="modeToggle" class="chipRow" role="group" aria-label="How the money went in">
<button type="button" id="modeEvenBtn" class="choiceChip selected">Everyone matched</button>
<button type="button" id="modeUnevenBtn" class="choiceChip">Someone's all-in</button>
</div>
<div id="splitResult" aria-live="polite">
<div id="splitResultLabel">Each player gets</div>
<div id="splitResultAmount">$0.00</div>
<div id="splitOddNote" hidden></div>
<div id="splitDustNote" hidden></div>
</div>
<div id="unevenResult" hidden aria-live="polite">
<div id="unevenPots"></div>
<p id="unevenEmpty" class="unevenEmpty">Enter what each player put in.</p>
</div>
<section class="splitField unevenOnly" hidden>
<span class="splitLabel">What each player put in</span>
<div id="unevenRows"></div>
<button type="button" id="addPlayerBtn" class="splitBtn splitBtnGhost">+ Add player</button>
</section>
<section class="splitField evenOnly">
<label for="potInput" class="splitLabel">Pot</label>
<div class="potInputWrap">
<span class="potCurrency">$</span>
<input type="text" id="potInput" inputmode="decimal" autocomplete="off"
placeholder="0" aria-label="Pot amount" />
<button type="button" id="clearPotBtn" class="clearPotBtn" aria-label="Clear pot amount" hidden>✕</button>
</div>
</section>
<section class="splitField evenOnly">
<span class="splitLabel" id="waysLabel">Split between</span>
<div id="waysChoices" class="chipRow" role="group" aria-labelledby="waysLabel"></div>
</section>
<section class="splitField evenOnly">
<span class="splitLabel" id="chipLabel">Smallest chip in play</span>
<div id="chipChoices" class="chipRow" role="group" aria-labelledby="chipLabel"></div>
</section>
<div id="splitActions">
<button type="button" id="resetSplitBtn" class="splitBtn splitBtnGhost">Clear</button>
<a href="/casino/texasholdem" class="splitBtn splitBtnGhost">Full dealer table →</a>
</div>
<p class="splitFootnote evenOnly">
If somebody was all-in for less than the others, switch to
<strong>Someone's all-in</strong> above.
</p>
<p class="splitFootnote unevenOnly" hidden>
Pots are listed with who can win each. Award them by hand strength, best hand
first. Nothing here is saved — the <a href="/casino/texasholdem">full table</a>
keeps a log.
</p>
</div>
<template id="unevenRowTemplate">
<div class="unevenRow">
<span class="unevenRowLabel"></span>
<div class="unevenAmountWrap">
<span class="unevenCurrency">$</span>
<input type="text" class="unevenAmount" inputmode="decimal" autocomplete="off" placeholder="0" />
</div>
<button type="button" class="unevenFoldBtn" aria-pressed="false">Folded</button>
<button type="button" class="unevenRemoveBtn" aria-label="Remove player">✕</button>
</div>
</template>
@section Styles {
<link href="/css/casino/quicksplit.css?v=@ViewData["cssVersion"]" rel="stylesheet" type="text/css" />
}
@section Scripts {
<script src="~/js/casino/holdem/money.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/splitCalculator.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/potCalculator.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/quickSplit.js?v=@ViewData["cssVersion"]"></script>
}
@@ -1,11 +0,0 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace JoshHeaps.Net.Pages.Casino.TexasHoldem
{
public class QuickSplitModel : PageModel
{
public void OnGet()
{
}
}
}
+70
View File
@@ -0,0 +1,70 @@
@page
@model JoshHeaps.Net.Pages.EchoModel
@{
Layout = "_Layout";
ViewData["Title"] = "Echo";
}
<div id="echoHeader">
<h1>Echo</h1>
<p class="echo-blurb">
Two devices measure the distance between them by chirping at each other and timing the answer.
Each one records continuously and only ever compares arrivals inside its own recording, so no
clock synchronisation is needed and the unknown audio latency cancels out.
</p>
<p class="echo-privacy">Only sample numbers leave your device. The recording never does.</p>
</div>
<div id="echoControls">
<label>Room <input id="echoRoom" type="text" maxlength="6" autocomplete="off" spellcheck="false" /></label>
<label>Name <input id="echoName" type="text" maxlength="16" placeholder="this device" autocomplete="off" /></label>
<label>
Speaker to mic (m)
<input id="echoEpsilon" type="number" min="0" max="0.5" step="0.01" />
</label>
<button id="echoJoin">Join and listen</button>
<button id="echoLeave" hidden>Leave</button>
</div>
<p id="echoStatus" class="echo-status">Pick a room, then open the same room on a second device.</p>
<p class="echo-share">Join link: <a id="echoShareLink" href="#"></a></p>
<div id="echoWarnings"></div>
<div id="echoReadout" class="echo-readout"><span class="echo-readout-idle">not measuring</span></div>
<div id="echoPanels">
<section class="echo-panel">
<h2>Devices</h2>
<ul id="echoRoster"></ul>
</section>
<section class="echo-panel">
<h2>Ranges</h2>
<div id="echoPairs"></div>
</section>
<section class="echo-panel">
<h2>Timing</h2>
<p class="echo-hint">How far each chirp landed from its slot. Steady means the arrivals are being matched to the right devices.</p>
<div id="echoDiagnostics"></div>
</section>
</div>
<section class="echo-panel echo-panel-wide">
<h2>Matched filter</h2>
<p class="echo-hint">Each spike is a chirp arriving. The bright one is this device hearing itself.</p>
<canvas id="echoTrace"></canvas>
</section>
<a class="echo-back" href="/">&larr; Back</a>
@section Scripts {
<script src="~/js/signalr/signalr.min.js"></script>
<script src="~/js/EchoScripts/EchoDsp.js"></script>
<script src="~/js/EchoScripts/EchoAudio.js"></script>
<script src="~/js/EchoScripts/EchoSession.js"></script>
<script src="~/js/EchoScripts/echoMain.js"></script>
}
@section Styles {
<link rel="stylesheet" href="~/css/variables.css?v=@ViewData["cssVersion"]" />
<link rel="stylesheet" href="~/css/echo/echo.css?v=@ViewData["cssVersion"]" />
}
@@ -2,7 +2,7 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
namespace JoshHeaps.Net.Pages
{
public class CasinoModel : PageModel
public class EchoModel : PageModel
{
public void OnGet()
{
-1
View File
@@ -64,7 +64,6 @@
<button class="demoButton" onclick="window.location.href='/watch'">Watch Live Chess</button>
<button class="demoButton" onclick="window.location.href='/particles'">Particle Simulator</button>
<button class="demoButton" onclick="window.location.href='/memorylane'">Memory Lane</button>
<button class="demoButton" onclick="window.location.href='/casino'">Casino Games</button>
<button class="demoButton" onclick="window.location.href='https://media.joshheaps.net'">Cloud Image Storage</button>
<button id="MoreFiller" class="demoButton">More coming soon...</button>
</div>
+1 -1
View File
@@ -1,6 +1,6 @@
@{
Layout = null;
ViewData["cssVersion"] = "1.0.8"; // <--- change this once to bust cache
ViewData["cssVersion"] = "1.0.7"; // <--- change this once to bust cache
}
<!DOCTYPE html>
+9 -42
View File
@@ -1,7 +1,7 @@
using JoshHeaps.Net.Hubs;
using JoshHeaps.Net.Services.Implementations;
using JoshHeaps.Net.Services.Interfaces;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
@@ -31,6 +31,12 @@ builder.Services.AddSingleton<IGameStore, GameStore>();
builder.Services.AddSingleton<ISelfPlayCoordinator, SelfPlayCoordinator>();
builder.Services.AddSingleton<AutoTrainingSettings>();
builder.Services.Configure<EchoRoundSettings>(configuration.GetSection(EchoRoundSettings.SectionName));
builder.Services.AddSingleton(provider =>
provider.GetRequiredService<IOptions<EchoRoundSettings>>().Value);
builder.Services.AddSingleton<IEchoRoomStore, EchoRoomStore>();
builder.Services.AddHostedService<EchoRoundService>();
if (!builder.Environment.IsDevelopment())
{
builder.Services.AddHostedService<AutoIpUpdateService>();
@@ -53,49 +59,8 @@ if (!app.Environment.IsDevelopment())
app.UseHttpsRedirection();
// One spelling of the casino URLs, because the Hold'em tool's offline support depends
// on it and nothing warns you when it breaks.
//
// Razor Pages routing is case-insensitive, so /Casino/TexasHoldem and
// /casino/texasholdem both serve the dealer tool and look identical. A service worker's
// scope is not: the spec matches it as a plain string prefix, so a worker scoped to
// "/casino/" does not control a page at "/Casino/TexasHoldem". Measured, that meant the
// capital-C spelling registered the worker, activated it, logged nothing — and then left
// the cache completely empty, because the page was never controlled and the precache
// handshake it waited on could not resolve. A dealer who bookmarked that URL had a tool
// that looked loaded and had nothing stored for the night the signal went.
//
// So one spelling wins and the other is redirected to it, permanently, before anything
// else in the pipeline gets a look.
//
// Deliberately scoped to /casino rather than applied site-wide. Every file under
// wwwroot/casino and wwwroot/images/casino is already lowercase, so lowercasing a path
// here can never miss a real file on a case-sensitive filesystem — a guarantee that does
// not hold for the rest of the site, and one that /chessHub in particular would break.
app.Use(async (context, next) =>
{
var path = context.Request.Path.Value;
if (path is not null
&& path.StartsWith("/casino", StringComparison.OrdinalIgnoreCase)
&& path.Any(char.IsUpper))
{
context.Response.Redirect(path.ToLowerInvariant() + context.Request.QueryString, permanent: true);
return;
}
await next();
});
// .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");
@@ -114,4 +79,6 @@ app.MapControllers();
app.MapHub<ChessHub>("/chessHub");
app.MapHub<EchoHub>("/echoHub");
app.Run();
@@ -1,4 +1,4 @@
using System.Collections.Concurrent;
using System.Collections.Concurrent;
using System.Text.Json;
using JoshHeaps.Net.Models;
using JoshHeaps.Net.Services.Interfaces;
@@ -10,7 +10,6 @@ public class BlogService : IBlogService
private readonly HttpClient _httpClient;
private readonly ILogger<BlogService> _logger;
private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes(5);
private readonly TimeSpan _staleGrace = TimeSpan.FromHours(1);
private readonly ConcurrentDictionary<string, CacheEntry> _cache = new();
@@ -66,9 +65,7 @@ public class BlogService : IBlogService
private async Task<T?> GetCachedAsync<T>(string key, Func<Task<T?>> factory) where T : class
{
_cache.TryGetValue(key, out var entry);
if (entry is not null && entry.ExpiresAt > DateTime.UtcNow)
if (_cache.TryGetValue(key, out var entry) && entry.ExpiresAt > DateTime.UtcNow)
return (T?)entry.Value;
var result = await factory();
@@ -76,26 +73,15 @@ public class BlogService : IBlogService
if (result is not null)
{
_cache[key] = new CacheEntry(result, DateTime.UtcNow.Add(_cacheTtl));
return result;
}
return entry is null ? null : ServeStale<T>(key, entry);
}
// Stale entries are dropped once the grace window closes so that a dead API fails the same
// way for every key. Serving them indefinitely let a cached post list render next to 404s on
// the posts themselves, which reads as a site bug rather than an outage.
private T? ServeStale<T>(string key, CacheEntry entry) where T : class
{
if (entry.ExpiresAt.Add(_staleGrace) > DateTime.UtcNow)
else if (entry is not null)
{
_logger.LogWarning("Blog API unreachable, serving stale cache for key {Key}", key);
// API unreachable — serve stale cache
_logger.LogWarning("Serving stale cache for key {Key}", key);
return (T?)entry.Value;
}
_cache.TryRemove(key, out _);
_logger.LogError("Blog API unreachable for over {StaleGrace}, dropping stale cache for key {Key}", _staleGrace, key);
return null;
return result;
}
public void ClearCache()
@@ -0,0 +1,189 @@
using System.Collections.Concurrent;
using JoshHeaps.Net.Models;
using JoshHeaps.Net.Services.Interfaces;
namespace JoshHeaps.Net.Services.Implementations;
/// <summary>
/// In-memory ranging rooms. Singleton: rooms are process-wide and short-lived, and the site runs
/// as a single instance, so there is nothing to persist and no backplane to coordinate.
/// </summary>
public sealed class EchoRoomStore : IEchoRoomStore
{
private sealed class Room
{
public required string Code { get; init; }
public List<EchoDevice> Devices { get; } = [];
public EchoRound? Round { get; set; }
public int RoundCounter { get; set; }
public DateTimeOffset LastActivity { get; set; } = DateTimeOffset.UtcNow;
}
private readonly ConcurrentDictionary<string, Room> _rooms = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, string> _roomsByConnection = [];
public EchoJoinResult Join(string roomCode, string connectionId, string displayName, int sampleRate)
{
var room = _rooms.GetOrAdd(roomCode, code => new Room { Code = code });
var device = new EchoDevice
{
DeviceId = Guid.NewGuid().ToString("N")[..8],
ConnectionId = connectionId,
DisplayName = displayName,
SampleRate = sampleRate
};
lock (room)
{
room.Devices.RemoveAll(existing => existing.ConnectionId == connectionId);
room.Devices.Add(device);
room.LastActivity = DateTimeOffset.UtcNow;
_roomsByConnection[connectionId] = room.Code;
return new EchoJoinResult { DeviceId = device.DeviceId, RoomCode = room.Code, Room = SnapshotLocked(room) };
}
}
public (string? roomCode, EchoRoomSnapshot? room) Leave(string connectionId)
{
if (!_roomsByConnection.TryRemove(connectionId, out var roomCode)) return (null, null);
if (!_rooms.TryGetValue(roomCode, out var room)) return (roomCode, null);
lock (room)
{
room.Devices.RemoveAll(device => device.ConnectionId == connectionId);
room.Round = null;
room.LastActivity = DateTimeOffset.UtcNow;
if (room.Devices.Count == 0) _rooms.TryRemove(roomCode, out _);
return (roomCode, SnapshotLocked(room));
}
}
public EchoRoomSnapshot? Snapshot(string roomCode)
{
if (!_rooms.TryGetValue(roomCode, out var room)) return null;
lock (room) return SnapshotLocked(room);
}
public IReadOnlyCollection<string> MeasurableRooms =>
[.. _rooms.Values.Where(room => room.Devices.Count >= 2).Select(room => room.Code)];
public EchoRoundSchedule? StartRound(
string roomCode,
int slotMilliseconds,
int tailMilliseconds,
TimeSpan lead,
TimeSpan grace)
{
if (!_rooms.TryGetValue(roomCode, out var room)) return null;
lock (room)
{
if (room.Round is not null || room.Devices.Count < 2) return null;
var slotOrder = RotatedSlotOrder(room);
var startsAt = DateTimeOffset.UtcNow + lead;
var duration = TimeSpan.FromMilliseconds(slotOrder.Length * slotMilliseconds + tailMilliseconds);
room.Round = new EchoRound
{
RoundId = Guid.NewGuid().ToString("N")[..12],
SlotOrder = slotOrder,
SlotMilliseconds = slotMilliseconds,
Deadline = startsAt + duration + grace
};
room.LastActivity = DateTimeOffset.UtcNow;
return new EchoRoundSchedule
{
RoundId = room.Round.RoundId,
SlotOrder = slotOrder,
SlotMilliseconds = slotMilliseconds,
TailMilliseconds = tailMilliseconds,
StartsAtUnixMs = startsAt.ToUnixTimeMilliseconds()
};
}
}
public bool Report(string connectionId, EchoPeakReport report)
{
var device = FindDevice(connectionId, out var room);
if (device is null || room is null) return false;
lock (room)
{
if (room.Round?.RoundId != report.RoundId) return false;
if (!room.Round.SlotOrder.Contains(device.DeviceId)) return false;
room.Round.Reports[device.DeviceId] = report;
room.LastActivity = DateTimeOffset.UtcNow;
return true;
}
}
public EchoRoundResult? TryCloseRound(string roomCode)
{
if (!_rooms.TryGetValue(roomCode, out var room)) return null;
lock (room)
{
var round = room.Round;
if (round is null) return null;
var everyoneReported = round.SlotOrder.All(round.Reports.ContainsKey);
if (!everyoneReported && DateTimeOffset.UtcNow < round.Deadline) return null;
room.Round = null;
return new EchoRoundResult
{
RoundId = round.RoundId,
SlotOrder = round.SlotOrder,
Reports = [.. round.SlotOrder.Where(round.Reports.ContainsKey).Select(id => round.Reports[id])]
};
}
}
public int PruneIdle(TimeSpan idleFor)
{
var cutoff = DateTimeOffset.UtcNow - idleFor;
var stale = _rooms.Values.Where(room => room.LastActivity < cutoff).Select(room => room.Code).ToList();
foreach (var code in stale) _rooms.TryRemove(code, out _);
return stale.Count;
}
private static EchoRoomSnapshot SnapshotLocked(Room room) =>
new()
{
RoomCode = room.Code,
Devices =
[
.. room.Devices.Select(device => new EchoDeviceSnapshot
{
DeviceId = device.DeviceId,
DisplayName = device.DisplayName,
SampleRate = device.SampleRate
})
]
};
private static string[] RotatedSlotOrder(Room room)
{
var offset = room.RoundCounter++ % room.Devices.Count;
return [.. room.Devices.Skip(offset).Concat(room.Devices.Take(offset)).Select(device => device.DeviceId)];
}
private EchoDevice? FindDevice(string connectionId, out Room? room)
{
room = null;
if (!_roomsByConnection.TryGetValue(connectionId, out var roomCode)) return null;
if (!_rooms.TryGetValue(roomCode, out room)) return null;
lock (room) return room.Devices.FirstOrDefault(device => device.ConnectionId == connectionId);
}
}
@@ -0,0 +1,107 @@
using JoshHeaps.Net.Hubs;
using JoshHeaps.Net.Services.Interfaces;
using Microsoft.AspNetCore.SignalR;
namespace JoshHeaps.Net.Services.Implementations;
public sealed class EchoRoundSettings
{
public const string SectionName = "Echo";
/// <summary>
/// Slot length. Wide enough that no device's chirp can land in another's search window once
/// unknown output latency (tens of milliseconds, different per device) and message jitter are
/// accounted for.
/// </summary>
public int SlotMilliseconds { get; set; } = 500;
/// <summary>Time after the last chirp for propagation, detection and reporting.</summary>
public int TailMilliseconds { get; set; } = 700;
public int GraceMilliseconds { get; set; } = 1500;
public int GapMilliseconds { get; set; } = 250;
public int IdleRoomMinutes { get; set; } = 10;
/// <summary>
/// How far ahead a round is announced. Must exceed the worst message delivery plus client
/// stall, or a device will find its slot already gone and sit the round out.
/// </summary>
public int LeadMilliseconds { get; set; } = 600;
}
/// <summary>
/// Drives continuous ranging: opens a round for every room that has two or more devices, closes it
/// once everyone has reported or the deadline passes, and broadcasts the raw peak table.
/// </summary>
public sealed class EchoRoundService(
IEchoRoomStore rooms,
IHubContext<EchoHub> hub,
EchoRoundSettings settings,
ILogger<EchoRoundService> logger) : BackgroundService
{
private readonly Dictionary<string, DateTimeOffset> _nextRoundAllowedAt = [];
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var lastPrune = DateTimeOffset.UtcNow;
while (!stoppingToken.IsCancellationRequested)
{
try
{
await TickAsync();
lastPrune = PruneIfDue(lastPrune);
}
catch (Exception error)
{
logger.LogError(error, "Echo round tick failed");
}
await Task.Delay(50, stoppingToken);
}
}
private async Task TickAsync()
{
foreach (var roomCode in rooms.MeasurableRooms)
{
await CloseFinishedRoundAsync(roomCode);
await OpenRoundIfDueAsync(roomCode);
}
}
private async Task CloseFinishedRoundAsync(string roomCode)
{
var result = rooms.TryCloseRound(roomCode);
if (result is null) return;
_nextRoundAllowedAt[roomCode] = DateTimeOffset.UtcNow.AddMilliseconds(settings.GapMilliseconds);
await hub.Clients.Group(EchoHub.GroupFor(roomCode)).SendAsync("RoundComplete", result);
}
private async Task OpenRoundIfDueAsync(string roomCode)
{
if (_nextRoundAllowedAt.TryGetValue(roomCode, out var earliest) && DateTimeOffset.UtcNow < earliest) return;
var schedule = rooms.StartRound(
roomCode,
settings.SlotMilliseconds,
settings.TailMilliseconds,
TimeSpan.FromMilliseconds(settings.LeadMilliseconds),
TimeSpan.FromMilliseconds(settings.GraceMilliseconds));
if (schedule is null) return;
await hub.Clients.Group(EchoHub.GroupFor(roomCode)).SendAsync("RoundStarting", schedule);
}
private DateTimeOffset PruneIfDue(DateTimeOffset lastPrune)
{
if (DateTimeOffset.UtcNow - lastPrune < TimeSpan.FromMinutes(1)) return lastPrune;
var pruned = rooms.PruneIdle(TimeSpan.FromMinutes(settings.IdleRoomMinutes));
if (pruned > 0) logger.LogInformation("Pruned {Count} idle echo room(s)", pruned);
return DateTimeOffset.UtcNow;
}
}
@@ -100,26 +100,11 @@ public sealed class Stockfish : IChessEngine
if (line == token) break;
}
// If Stockfish doesn't exit on "quit" (crashed, zombie, ignores stdin close), don't hang
// here forever — that would block GameStore's removal task and leave the finished game
// stuck in the store, cluttering the watch page indefinitely.
private static readonly TimeSpan _exitTimeout = TimeSpan.FromSeconds(5);
public async ValueTask DisposeAsync()
{
Send("quit");
_stdin.Close();
try
{
await _p.WaitForExitAsync().WaitAsync(_exitTimeout);
}
catch (TimeoutException)
{
if (!_p.HasExited)
_p.Kill(entireProcessTree: true);
}
await _p.WaitForExitAsync();
_p.Dispose();
}
}
@@ -0,0 +1,45 @@
using JoshHeaps.Net.Models;
namespace JoshHeaps.Net.Services.Interfaces;
/// <summary>
/// Process-wide registry of ranging rooms. Holds only device identity and the sample indices each
/// device reported, so the server is a scheduler and a relay — it never sees audio.
/// </summary>
public interface IEchoRoomStore
{
/// <summary>Add a device to a room, creating the room if this is the first arrival.</summary>
EchoJoinResult Join(string roomCode, string connectionId, string displayName, int sampleRate);
/// <summary>Remove whichever device owns this connection, returning the room it left.</summary>
(string? roomCode, EchoRoomSnapshot? room) Leave(string connectionId);
/// <summary>Snapshot of a room's roster, or null if the room is gone.</summary>
EchoRoomSnapshot? Snapshot(string roomCode);
/// <summary>Room codes with at least two devices, which is the minimum for a measurement.</summary>
IReadOnlyCollection<string> MeasurableRooms { get; }
/// <summary>
/// Open a new round for a room, rotating which device chirps first so no single device is
/// permanently the slot-order anchor.
/// </summary>
EchoRoundSchedule? StartRound(
string roomCode,
int slotMilliseconds,
int tailMilliseconds,
TimeSpan lead,
TimeSpan grace);
/// <summary>File a device's peaks against the room's open round.</summary>
bool Report(string connectionId, EchoPeakReport report);
/// <summary>
/// Close the open round if every device has reported or its deadline has passed, returning the
/// reports to broadcast.
/// </summary>
EchoRoundResult? TryCloseRound(string roomCode);
/// <summary>Drop rooms that have had no activity for longer than <paramref name="idleFor"/>.</summary>
int PruneIdle(TimeSpan idleFor);
}
@@ -1,32 +0,0 @@
{
"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
@@ -1,125 +0,0 @@
// 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
-126
View File
@@ -1,126 +0,0 @@
body {
background: #1a1a1a;
min-height: 100vh;
margin: 0;
padding: 0;
}
.casino-container {
max-width: 1000px;
margin: 0 auto;
padding: 4rem 2rem;
text-align: center;
}
.casino-header {
color: #f5f5f5;
font-size: 2.5rem;
margin-bottom: 0.5rem;
font-weight: 300;
letter-spacing: 0.1em;
}
.casino-subtitle {
color: #a0a0a0;
font-size: 1rem;
margin-bottom: 4rem;
font-weight: 300;
}
.games-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
margin: 3rem auto;
max-width: 900px;
padding: 0 1rem;
}
.game-card {
background: #2a2a2a;
border: 1px solid #3a3a3a;
border-radius: 4px;
padding: 2rem 1.5rem;
transition: all 0.3s ease;
cursor: pointer;
text-decoration: none;
color: inherit;
display: flex;
flex-direction: column;
align-items: center;
}
.game-card:hover {
background: #2f2f2f;
border-color: #4a4a4a;
transform: translateY(-2px);
}
.game-card.disabled {
opacity: 0.4;
cursor: not-allowed;
}
.game-card.disabled:hover {
background: #2a2a2a;
border-color: #3a3a3a;
transform: none;
}
.game-icon {
font-size: 2.5rem;
margin-bottom: 1rem;
opacity: 0.9;
}
.game-title {
font-size: 1.2rem;
font-weight: 400;
color: #f5f5f5;
margin-bottom: 0.75rem;
letter-spacing: 0.05em;
}
.game-description {
font-size: 0.9rem;
color: #999;
line-height: 1.6;
font-weight: 300;
}
.coming-soon {
color: #666;
font-style: italic;
margin-top: 0.5rem;
font-size: 0.85rem;
}
.home-button {
margin-top: 4rem;
padding: 0.75rem 1.5rem;
font-size: 0.9rem;
background: transparent;
color: #f5f5f5;
border: 1px solid #3a3a3a;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
text-decoration: none;
display: inline-block;
letter-spacing: 0.05em;
}
.home-button:hover {
background: #2a2a2a;
border-color: #4a4a4a;
}
@media (max-width: 768px) {
.casino-header {
font-size: 2rem;
}
.games-grid {
grid-template-columns: 1fr;
}
}
@@ -1,628 +0,0 @@
/* Quick Split is phone-first: sized for one thumb at the table, then allowed to
breathe on a laptop. Palette matches the dealer table so the two read as one tool. */
body {
background: radial-gradient(ellipse at 50% -10%, #1c1c1c 0%, #101010 55%, #0a0a0a 100%);
min-height: 100vh;
margin: 0;
color: #e6e6e6;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
/* Same touch handling as the dealer table — see the note there. This page is the one
a dealer opens mid-hand to chop a pot, so the ~300ms the browser spends deciding
whether a tap was a double-tap-to-zoom is the last thing it needs. */
button,
[role="button"],
input,
select,
textarea,
a {
touch-action: manipulation;
}
button,
[role="button"],
input,
select,
textarea,
a {
-webkit-tap-highlight-color: transparent;
}
/* Not on the fields — a dealer typing a pot amount still needs to select it. */
button,
[role="button"] {
-webkit-user-select: none;
user-select: none;
}
.clearPotBtn:active:not(:disabled),
.choiceChip:active:not(:disabled),
.stepBtn:active:not(:disabled),
.splitBtn:active:not(:disabled),
.splitBtnGhost:active:not(:disabled),
.unevenFoldBtn:active:not(:disabled),
.unevenRemoveBtn:active:not(:disabled) {
transform: translateY(1px);
filter: brightness(1.25);
transition-duration: 0.04s;
}
@media (prefers-reduced-motion: reduce) {
.clearPotBtn:active:not(:disabled),
.choiceChip:active:not(:disabled),
.stepBtn:active:not(:disabled),
.splitBtn:active:not(:disabled),
.splitBtnGhost:active:not(:disabled),
.unevenFoldBtn:active:not(:disabled),
.unevenRemoveBtn:active:not(:disabled) {
transform: none;
}
}
#splitApp {
max-width: 480px;
margin: 0 auto;
padding: 1.25rem 1rem 3rem;
}
/* ---------- Header ---------- */
#splitHeader h1 {
margin: 0;
font-size: 1.5rem;
font-weight: 300;
letter-spacing: 0.04em;
color: #f5f5f5;
position: relative;
display: inline-block;
padding-bottom: 0.35rem;
}
#splitHeader h1::after {
content: "";
position: absolute;
left: 0;
bottom: 0;
width: 36px;
height: 3px;
border-radius: 2px;
background: linear-gradient(90deg, #d8b46a, #a9782f);
}
.splitSubtitle {
margin: 0.35rem 0 1.25rem;
color: #8f8f8f;
font-size: 0.85rem;
}
/* ---------- Mode toggle ---------- */
#modeToggle {
margin-bottom: 1.1rem;
}
/* ---------- Uneven amounts ---------- */
#unevenRows {
display: flex;
flex-direction: column;
gap: 0.45rem;
margin-bottom: 0.6rem;
}
.unevenRow {
display: flex;
align-items: center;
gap: 0.45rem;
}
.unevenRowLabel {
flex: none;
width: 2rem;
color: #8f8f8f;
font-size: 0.8rem;
font-weight: 600;
}
.unevenAmountWrap {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 0.3rem;
background: #141414;
border: 1px solid #3a3a3a;
border-radius: 10px;
padding: 0 0.6rem;
}
.unevenAmountWrap:focus-within {
border-color: #d8b46a;
}
.unevenCurrency {
/* Was #777 — 4.11:1 on this background, under the 4.5:1 small text needs. It sits
against every amount a dealer types, so it is read constantly. */
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;
color: #f2f2f2;
font-family: inherit;
font-size: 16px;
font-variant-numeric: tabular-nums;
padding: 0.6rem 0;
}
.unevenFoldBtn {
flex: none;
min-height: 44px;
padding: 0 0.6rem;
border-radius: 9px;
border: 1px solid #3a3a3a;
background: #232323;
color: #8f8f8f;
font-family: inherit;
font-size: 0.72rem;
cursor: pointer;
}
.unevenFoldBtn.selected {
background: linear-gradient(180deg, #3d1f1f, #2c1515);
border-color: #5b2626;
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: 46px;
height: 46px;
border: none;
background: none;
/* Was #6a6a6a — 3.66:1, the worst on the page, on a control that deletes a
player's entry. A destructive action should not be the faintest thing in view. */
color: #9a9a9a;
font-size: 0.85rem;
cursor: pointer;
}
.unevenRemoveBtn:disabled {
opacity: 0.3;
cursor: not-allowed;
}
#unevenResult {
background: linear-gradient(160deg, #1f2a21, #161c17);
border: 1px solid #2c3a2f;
border-radius: 14px;
padding: 0.9rem 1rem;
margin-bottom: 1.5rem;
}
#unevenResult[hidden] {
display: none;
}
.unevenPot {
display: flex;
align-items: baseline;
/* Wraps so a chop opens underneath its own pot rather than squeezing in beside the
eligible-players list and pushing it off the row. */
flex-wrap: wrap;
gap: 0.6rem;
padding: 0.3rem 0;
font-size: 0.85rem;
}
.unevenChopToggle {
flex: none;
order: 3;
/* 44px on touch: it moves money, like everything else that does. */
min-height: 32px;
padding: 0.2rem 0.6rem;
border: 1px solid rgba(216, 180, 106, 0.45);
border-radius: 999px;
background: rgba(216, 180, 106, 0.1);
color: #e3c887;
font: inherit;
font-size: 0.74rem;
cursor: pointer;
}
.unevenChopToggle:hover {
background: rgba(216, 180, 106, 0.18);
}
.unevenChopToggle:focus-visible {
outline: 2px solid #d8b46a;
outline-offset: 2px;
}
.unevenChopDetail {
order: 4;
flex: 0 0 100%;
/* Or the padding is added on top of the 100% basis and the panel sits wider than
the row it belongs to — measured 328px inside a 309px row on a phone. */
box-sizing: border-box;
margin: 0.15rem 0 0.2rem;
padding: 0.45rem 0.6rem;
border-radius: 8px;
background: rgba(255, 255, 255, 0.04);
}
.unevenChopWays {
display: flex;
align-items: center;
gap: 0.45rem;
margin-bottom: 0.3rem;
}
.unevenChopWaysLabel {
color: #cfcfcf;
font-size: 0.78rem;
font-variant-numeric: tabular-nums;
}
.unevenChopEach {
margin: 0;
color: #f2f2f2;
font-weight: 600;
}
.unevenChopNote {
margin: 0.2rem 0 0;
color: #9a9a9a;
font-size: 0.76rem;
}
.unevenChopDust {
color: #e0b169;
}
@media (max-width: 700px), (pointer: coarse) {
.unevenChopToggle {
min-height: 44px;
padding: 0.4rem 0.9rem;
}
}
.unevenPot + .unevenPot {
border-top: 1px solid rgba(255, 255, 255, 0.06);
}
.unevenPotLabel {
flex: none;
color: #d8b46a;
font-weight: 600;
}
.unevenPotAmount {
flex: none;
color: #f2f2f2;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.unevenPotWho {
flex: 1;
min-width: 0;
text-align: right;
color: #9a9a9a;
font-size: 0.78rem;
}
.unevenPotReturn .unevenPotLabel,
.unevenPotReturn .unevenPotAmount {
color: #9a9a9a;
font-weight: 500;
}
.unevenPotTotal {
margin-top: 0.15rem;
border-top: 1px solid rgba(255, 255, 255, 0.14) !important;
}
.unevenPotTotal .unevenPotLabel {
color: #8f9d92;
font-weight: 500;
}
.unevenEmpty {
margin: 0;
color: #8f9d92;
font-size: 0.82rem;
line-height: 1.45;
}
/* ---------- The answer ---------- */
#splitResult {
background: linear-gradient(160deg, #1f2a21, #161c17);
border: 1px solid #2c3a2f;
border-radius: 14px;
padding: 1.4rem 1.1rem;
text-align: center;
margin-bottom: 1.5rem;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
#splitResult.hasAmount {
border-color: #3c6b46;
box-shadow: 0 0 0 1px rgba(78, 201, 122, 0.08), 0 6px 20px rgba(0, 0, 0, 0.35);
}
#splitResultLabel {
color: #8f9d92;
font-size: 0.78rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
#splitResultAmount {
margin-top: 0.35rem;
font-size: clamp(2.6rem, 14vw, 3.4rem);
font-weight: 600;
line-height: 1.05;
color: #f2f2f2;
font-variant-numeric: tabular-nums;
letter-spacing: -0.01em;
}
#splitResult.hasAmount #splitResultAmount {
color: #7ee2a0;
}
#splitOddNote {
margin-top: 0.7rem;
color: #d8b46a;
font-size: 0.85rem;
line-height: 1.45;
}
#splitDustNote {
margin-top: 0.5rem;
color: #e0a1a1;
font-size: 0.8rem;
line-height: 1.4;
}
/* ---------- Inputs ---------- */
.splitField {
display: block;
margin-bottom: 1.35rem;
}
/* A `display` declaration outranks the browser's own [hidden] rule, so anything
given one has to opt back out explicitly or toggling `hidden` does nothing. */
[hidden] {
display: none !important;
}
.splitLabel {
display: block;
margin-bottom: 0.5rem;
color: #9a9a9a;
font-size: 0.75rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.potInputWrap {
display: flex;
align-items: center;
gap: 0.4rem;
background: #141414;
border: 1px solid #3a3a3a;
border-radius: 12px;
padding: 0.2rem 0.75rem;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
.potInputWrap:focus-within {
border-color: #d8b46a;
box-shadow: 0 0 0 3px rgba(216, 180, 106, 0.12);
}
.potCurrency {
color: #777;
font-size: 1.6rem;
font-weight: 300;
}
#potInput {
flex: 1;
min-width: 0;
background: none;
border: none;
outline: none;
color: #f2f2f2;
font-size: 2rem;
font-weight: 500;
font-variant-numeric: tabular-nums;
padding: 0.55rem 0;
font-family: inherit;
}
#potInput::placeholder {
color: #4a4a4a;
}
.clearPotBtn {
flex: none;
width: 34px;
height: 34px;
border-radius: 50%;
border: none;
background: #262626;
color: #999;
font-size: 0.85rem;
cursor: pointer;
}
@media (hover: hover) {
.clearPotBtn:hover {
background: #333;
color: #ddd;
}
}
/* ---------- Tap targets ---------- */
.chipRow {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.choiceChip {
flex: 1 1 auto;
min-width: 58px;
min-height: 52px;
padding: 0.5rem 0.7rem;
background: linear-gradient(180deg, #2e2e2e, #232323);
border: 1px solid #3a3a3a;
border-radius: 11px;
color: #ddd;
font-size: 1rem;
font-family: inherit;
cursor: pointer;
transition: all 0.15s ease;
}
@media (hover: hover) {
.choiceChip:hover {
border-color: #4a4a4a;
background: linear-gradient(180deg, #383838, #2a2a2a);
}
}
.choiceChip.selected {
background: linear-gradient(180deg, #3a2f18, #241d0f);
border-color: #d8b46a;
color: #f0d9a8;
font-weight: 600;
}
.waysStepper {
display: flex;
align-items: center;
gap: 0.35rem;
flex: 1 1 auto;
min-width: 150px;
background: #191919;
border: 1px solid #333;
border-radius: 11px;
padding: 0.2rem 0.4rem;
}
.stepBtn {
width: 40px;
height: 44px;
border: none;
border-radius: 8px;
background: #262626;
color: #ddd;
font-size: 1.25rem;
line-height: 1;
font-family: inherit;
cursor: pointer;
}
@media (hover: hover) {
.stepBtn:hover {
background: #333;
}
}
.waysReadout {
flex: 1;
text-align: center;
color: #999;
font-size: 0.8rem;
font-variant-numeric: tabular-nums;
}
/* ---------- Footer actions ---------- */
#splitActions {
display: flex;
gap: 0.6rem;
margin-top: 1.75rem;
}
.splitBtn {
flex: 1;
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 48px;
padding: 0.6rem 0.9rem;
border-radius: 10px;
border: 1px solid #3a3a3a;
background: linear-gradient(180deg, #2e2e2e, #232323);
color: #ddd;
font-size: 0.9rem;
font-family: inherit;
text-decoration: none;
cursor: pointer;
transition: all 0.15s ease;
}
@media (hover: hover) {
.splitBtn:hover {
border-color: #4a4a4a;
background: linear-gradient(180deg, #383838, #2a2a2a);
}
}
.splitBtnGhost {
background: transparent;
}
.splitFootnote {
margin-top: 1.5rem;
/* Was #6f6f6f — 3.94:1. It carries the instruction for what to do with the pot
list, which is not a decorative line. */
color: #8d8d8d;
font-size: 0.78rem;
line-height: 1.5;
text-align: center;
}
/* This footnote names a control the dealer is being told to reach for, so the name
itself has to be readable — it was 3.39:1 at its worst, inheriting the muted grey
the surrounding sentence is deliberately set in. Emphasised text carrying the
instruction gets its own colour rather than the aside's. */
.splitFootnote strong {
color: #a8a8a8;
font-weight: 600;
}
.splitFootnote a {
color: #a9782f;
}
/* Roomier once there's a real screen to work with. */
@media (min-width: 700px) {
#splitApp {
padding-top: 2.5rem;
}
#splitHeader h1 {
font-size: 1.8rem;
}
}
+287
View File
@@ -0,0 +1,287 @@
body {
background: var(--color-bg);
color: var(--color-text);
font-family: var(--font-body);
margin: 0;
padding: 2rem 1.25rem 4rem;
}
#echoHeader {
max-width: 46rem;
margin: 0 auto 1.5rem;
}
#echoHeader h1 {
color: var(--color-heading);
font-size: 2.4rem;
letter-spacing: -0.02em;
margin: 0 0 0.6rem;
}
.echo-blurb {
line-height: 1.6;
margin: 0 0 0.5rem;
}
.echo-privacy {
color: var(--color-text-subtle);
font-family: var(--font-mono);
font-size: 0.8rem;
margin: 0;
}
#echoControls {
align-items: flex-end;
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
margin: 0 auto 1rem;
max-width: 46rem;
}
#echoControls label {
color: var(--color-text-muted);
display: flex;
flex-direction: column;
font-family: var(--font-mono);
font-size: 0.75rem;
gap: 0.3rem;
text-transform: lowercase;
}
#echoControls input {
background: var(--color-surface-raised);
border: 1px solid var(--color-border);
border-radius: 6px;
color: var(--color-heading);
font-family: var(--font-mono);
font-size: 1rem;
padding: 0.5rem 0.6rem;
width: 7rem;
}
#echoControls input:focus {
border-color: var(--color-accent-border);
outline: none;
}
#echoControls button {
background: transparent;
border: 1px solid var(--color-accent-border);
border-radius: 6px;
color: var(--color-accent);
cursor: pointer;
font-family: var(--font-mono);
font-size: 0.9rem;
padding: 0.6rem 1.1rem;
transition: background 0.15s ease, color 0.15s ease;
}
#echoControls button:hover:not(:disabled) {
background: var(--color-accent);
color: var(--color-bg);
}
#echoControls button:disabled {
border-color: var(--color-border);
color: var(--color-text-subtle);
cursor: default;
}
.echo-status,
.echo-share {
font-family: var(--font-mono);
font-size: 0.8rem;
margin: 0 auto 0.4rem;
max-width: 46rem;
}
.echo-share a {
color: var(--color-accent);
text-decoration: none;
word-break: break-all;
}
#echoWarnings {
margin: 0 auto;
max-width: 46rem;
}
.echo-warning {
background: rgba(255, 170, 0, 0.08);
border: 1px solid rgba(255, 170, 0, 0.35);
border-radius: 6px;
color: #ffcc66;
font-size: 0.85rem;
line-height: 1.5;
margin: 0.5rem 0;
padding: 0.7rem 0.9rem;
}
.echo-readout {
align-items: baseline;
display: flex;
flex-direction: column;
gap: 0.4rem;
margin: 2rem auto;
max-width: 46rem;
min-height: 6rem;
}
.echo-metres {
color: var(--color-accent);
font-family: var(--font-mono);
font-size: clamp(3.5rem, 14vw, 7rem);
font-variant-numeric: tabular-nums;
line-height: 1;
}
.echo-metres small {
color: var(--color-text-subtle);
font-size: 0.28em;
margin-left: 0.2em;
}
.echo-readout-detail,
.echo-readout-idle {
color: var(--color-text-subtle);
font-family: var(--font-mono);
font-size: 0.8rem;
}
#echoPanels {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
margin: 0 auto;
max-width: 46rem;
}
.echo-panel {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 8px;
padding: 1rem 1.1rem;
}
.echo-panel-wide {
margin: 1rem auto 0;
max-width: 46rem;
}
.echo-panel h2 {
color: var(--color-heading-secondary);
font-family: var(--font-mono);
font-size: 0.8rem;
font-weight: 500;
letter-spacing: 0.08em;
margin: 0 0 0.75rem;
text-transform: uppercase;
}
.echo-hint {
color: var(--color-text-subtle);
font-size: 0.8rem;
margin: -0.4rem 0 0.75rem;
}
#echoRoster {
list-style: none;
margin: 0;
padding: 0;
}
.echo-device {
border-bottom: 1px solid var(--color-border);
font-family: var(--font-mono);
font-size: 0.85rem;
padding: 0.45rem 0;
}
.echo-device:last-child {
border-bottom: none;
}
.echo-device-self {
color: var(--color-accent);
}
#echoPairs {
overflow-x: auto;
}
#echoPairs table {
border-collapse: collapse;
font-family: var(--font-mono);
font-size: 0.85rem;
width: 100%;
}
#echoPairs th {
color: var(--color-text-subtle);
font-weight: 500;
padding: 0 0.6rem 0.4rem 0;
text-align: left;
}
#echoPairs td {
border-top: 1px solid var(--color-border);
color: var(--color-heading-secondary);
font-variant-numeric: tabular-nums;
padding: 0.4rem 0.6rem 0.4rem 0;
}
.echo-dropped td {
color: var(--color-text-subtle);
text-decoration: line-through;
}
.echo-slots {
list-style: none;
margin: 0 0 0.6rem;
padding: 0;
}
.echo-slots li {
color: var(--color-heading-secondary);
font-family: var(--font-mono);
font-size: 0.85rem;
font-variant-numeric: tabular-nums;
padding: 0.2rem 0;
}
.echo-slots .echo-missed {
color: #ff7676;
}
.echo-diag-line {
color: var(--color-text-subtle);
font-family: var(--font-mono);
font-size: 0.75rem;
line-height: 1.5;
margin: 0;
}
.echo-diag-line strong {
color: #ff7676;
}
#echoTrace {
display: block;
height: 160px;
width: 100%;
}
.echo-back {
color: var(--color-text-subtle);
display: block;
font-family: var(--font-mono);
font-size: 0.8rem;
margin: 2rem auto 0;
max-width: 46rem;
text-decoration: none;
}
.echo-back:hover {
color: var(--color-accent);
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

@@ -0,0 +1,160 @@
/*
* Microphone capture and chirp playback, both indexed by AudioContext frame.
*
* Frames, not wall-clock: currentTime * sampleRate is exactly the frame number, so a playback
* scheduled at an audio-clock time converts directly into a position in the recording. Nothing here
* depends on a timer firing on schedule, which matters because a hidden tab's timers are throttled
* to about once a second and its chirp would land in another device's slot.
*/
const EchoAudio = {
TARGET_SAMPLE_RATE: 48000,
RING_SECONDS: 20,
BLUETOOTH_HINTS: /bluetooth|airpod|hands-?free|headset|\bbt\b|wireless/i,
context: null,
stream: null,
capture: null,
ring: null,
highestFrame: 0,
peakAmplitude: 0,
warnings: [],
onSamples: null,
async start() {
if (this.context) return this.describe();
this.stream = await navigator.mediaDevices.getUserMedia({
// Echo cancellation exists to delete sounds this device just played, which is exactly
// the measurement. Gain control and noise suppression distort the chirp's envelope.
audio: {
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
channelCount: 1
}
});
this.context = new AudioContext({ sampleRate: this.TARGET_SAMPLE_RATE, latencyHint: "interactive" });
await this.context.audioWorklet.addModule("/js/EchoScripts/EchoCaptureProcessor.js");
await this.context.resume();
this.ring = new Float32Array(Math.ceil(this.context.sampleRate * this.RING_SECONDS));
this.attachCapture();
this.warnings = this.inspectDevice();
return this.describe();
},
attachCapture() {
const source = this.context.createMediaStreamSource(this.stream);
this.capture = new AudioWorkletNode(this.context, "echo-capture", { numberOfOutputs: 0 });
this.capture.port.onmessage = ({ data }) => this.write(data.frame, data.samples);
source.connect(this.capture);
return this.capture;
},
write(frame, samples) {
const capacity = this.ring.length;
let loudest = 0;
for (let i = 0; i < samples.length; i++) {
this.ring[(frame + i) % capacity] = samples[i];
loudest = Math.max(loudest, Math.abs(samples[i]));
}
this.peakAmplitude = Math.max(this.peakAmplitude * 0.95, loudest);
this.highestFrame = Math.max(this.highestFrame, frame + samples.length);
this.onSamples?.(this.highestFrame);
return this.highestFrame;
},
/** The recording position for an AudioContext time. Exact: currentTime * sampleRate is a frame. */
frameAt(contextTime) {
return Math.round(contextTime * this.context.sampleRate);
},
/** Copy an absolute frame range out of the ring, or null if it is not (or no longer) held. */
read(startFrame, length) {
if (length <= 0) return null;
if (startFrame + length > this.highestFrame) return null;
if (startFrame < this.highestFrame - this.ring.length) return null;
const capacity = this.ring.length;
const window = new Float32Array(length);
for (let i = 0; i < length; i++) window[i] = this.ring[((startFrame + i) % capacity + capacity) % capacity];
return window;
},
/**
* Schedule a chirp on the audio clock and return the frame it was scheduled for. When it
* actually leaves the speaker is later by an unknown output latency and does not need to be
* known — it is recovered from the recording of it.
*/
play(chirp, atContextTime, gain = 0.5) {
const when = Math.max(atContextTime, this.context.currentTime);
const buffer = this.context.createBuffer(1, chirp.length, this.context.sampleRate);
buffer.copyToChannel(chirp, 0);
const source = this.context.createBufferSource();
const volume = this.context.createGain();
volume.gain.value = gain;
source.buffer = buffer;
source.connect(volume).connect(this.context.destination);
source.start(when);
return this.frameAt(when);
},
/** How far behind the audio clock the main thread's view of the recording is running. */
captureLagSeconds() {
return this.context.currentTime - this.highestFrame / this.context.sampleRate;
},
/** Reported output latency, which bounds how late a scheduled chirp can reach the microphone. */
outputLatencySeconds() {
return (this.context.outputLatency || 0) + (this.context.baseLatency || 0);
},
inspectDevice() {
const warnings = [];
const track = this.stream.getAudioTracks()[0];
const settings = track?.getSettings() ?? {};
if (this.context.sampleRate !== this.TARGET_SAMPLE_RATE)
warnings.push(`Running at ${this.context.sampleRate}Hz instead of 48000Hz — ranges stay correct but resolution drops.`);
if (this.BLUETOOTH_HINTS.test(track?.label ?? ""))
warnings.push("This looks like a Bluetooth microphone. Bluetooth resamples and re-times the stream, which breaks the measurement — switch to the built-in speaker and microphone.");
for (const [name, label] of [["echoCancellation", "Echo cancellation"], ["autoGainControl", "Auto gain"], ["noiseSuppression", "Noise suppression"]])
if (settings[name] === true) warnings.push(`${label} could not be turned off on this device — the measurement will be unreliable.`);
return warnings;
},
describe() {
const track = this.stream.getAudioTracks()[0];
return {
sampleRate: this.context.sampleRate,
label: track?.label ?? "microphone",
outputLatencyMs: Math.round(this.outputLatencySeconds() * 1000),
warnings: this.warnings
};
},
async stop() {
this.stream?.getTracks().forEach(track => track.stop());
await this.context?.close();
this.context = null;
this.stream = null;
this.capture = null;
this.ring = null;
this.highestFrame = 0;
this.onSamples = null;
return true;
}
};
if (typeof window !== "undefined") window.EchoAudio = EchoAudio;
@@ -0,0 +1,39 @@
/*
* Capture worklet. Every block is tagged with the AudioContext frame it started at, which makes the
* context's own clock the index for all captured audio: a scheduled playback time converts to a
* recording position exactly, with no dependence on when the main thread got round to noticing.
*
* A worklet rather than ScriptProcessorNode because a dropped buffer would break the continuity
* that the sample count depends on.
*/
const BLOCK_SAMPLES = 2048;
class EchoCaptureProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.block = new Float32Array(BLOCK_SAMPLES);
this.filled = 0;
this.blockStartFrame = 0;
}
process(inputs) {
const channel = inputs[0]?.[0];
if (!channel) return true;
for (let i = 0; i < channel.length; i++) {
if (this.filled === 0) this.blockStartFrame = currentFrame + i;
this.block[this.filled++] = channel[i];
if (this.filled === BLOCK_SAMPLES) this.flush();
}
return true;
}
flush() {
const samples = this.block.slice(0, this.filled);
this.port.postMessage({ frame: this.blockStartFrame, samples }, [samples.buffer]);
this.filled = 0;
}
}
registerProcessor("echo-capture", EchoCaptureProcessor);
@@ -0,0 +1,585 @@
/*
* Pure signal-processing and geometry for acoustic ranging. No DOM, no Web Audio, no network:
* everything here is a function of its arguments so the simulator and the tests can drive the
* exact code the page runs.
*/
const EchoDsp = {
speedOfSound(temperatureCelsius = 20) {
return 331.3 + 0.606 * temperatureCelsius;
},
nextPowerOfTwo(value) {
let size = 1;
while (size < value) size <<= 1;
return size;
},
/**
* Linear frequency sweep, tapered at both ends. A sweep is used rather than a tone because a
* tone's autocorrelation peaks once per period, leaving no unambiguous arrival to measure.
*/
makeChirp({ sampleRate, durationSeconds, startHz, endHz, taperFraction = 0.15 }) {
const length = Math.round(sampleRate * durationSeconds);
const sweepRate = (endHz - startHz) / durationSeconds;
const chirp = new Float32Array(length);
for (let i = 0; i < length; i++) {
const t = i / sampleRate;
chirp[i] = Math.sin(2 * Math.PI * (startHz * t + 0.5 * sweepRate * t * t));
}
return this.applyTaper(chirp, taperFraction);
},
applyTaper(signal, fraction) {
const edge = Math.max(1, Math.floor(signal.length * fraction));
for (let i = 0; i < edge; i++) {
const window = 0.5 - 0.5 * Math.cos((Math.PI * i) / edge);
signal[i] *= window;
signal[signal.length - 1 - i] *= window;
}
return signal;
},
twiddles(size) {
this._twiddleCache ??= new Map();
const cached = this._twiddleCache.get(size);
if (cached) return cached;
const half = size >> 1;
const table = { cos: new Float64Array(half), sin: new Float64Array(half) };
for (let i = 0; i < half; i++) {
const angle = (-2 * Math.PI * i) / size;
table.cos[i] = Math.cos(angle);
table.sin[i] = Math.sin(angle);
}
this._twiddleCache.set(size, table);
return table;
},
fft(real, imaginary, inverse = false) {
const size = real.length;
this.reverseBits(real, imaginary);
const { cos, sin } = this.twiddles(size);
for (let span = 2; span <= size; span <<= 1) {
const half = span >> 1;
const stride = size / span;
for (let base = 0; base < size; base += span) {
for (let k = 0; k < half; k++) {
const twiddle = k * stride;
const wReal = cos[twiddle];
const wImaginary = inverse ? -sin[twiddle] : sin[twiddle];
const lower = base + k;
const upper = lower + half;
const productReal = real[upper] * wReal - imaginary[upper] * wImaginary;
const productImaginary = real[upper] * wImaginary + imaginary[upper] * wReal;
real[upper] = real[lower] - productReal;
imaginary[upper] = imaginary[lower] - productImaginary;
real[lower] += productReal;
imaginary[lower] += productImaginary;
}
}
}
if (!inverse) return { real, imaginary };
for (let i = 0; i < size; i++) {
real[i] /= size;
imaginary[i] /= size;
}
return { real, imaginary };
},
reverseBits(real, imaginary) {
const size = real.length;
for (let i = 1, j = 0; i < size; i++) {
let bit = size >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i >= j) continue;
[real[i], real[j]] = [real[j], real[i]];
[imaginary[i], imaginary[j]] = [imaginary[j], imaginary[i]];
}
return { real, imaginary };
},
/**
* Matched-filter envelope of a recording against a template, via FFT cross-correlation.
* Negative frequencies are dropped so the result is the analytic envelope rather than a burst
* oscillating at the sweep frequency — an oscillating peak defeats sub-sample interpolation
* and makes first-arrival detection jitter by half a carrier period.
*/
matchedFilterEnvelope(recording, template) {
const size = this.nextPowerOfTwo(recording.length + template.length);
const recordingReal = new Float64Array(size);
const recordingImaginary = new Float64Array(size);
const templateReal = new Float64Array(size);
const templateImaginary = new Float64Array(size);
recordingReal.set(recording);
templateReal.set(template);
this.fft(recordingReal, recordingImaginary);
this.fft(templateReal, templateImaginary);
const analyticReal = new Float64Array(size);
const analyticImaginary = new Float64Array(size);
const half = size >> 1;
for (let i = 0; i <= half; i++) {
const gain = i === 0 || i === half ? 1 : 2;
analyticReal[i] = gain * (recordingReal[i] * templateReal[i] + recordingImaginary[i] * templateImaginary[i]);
analyticImaginary[i] = gain * (recordingImaginary[i] * templateReal[i] - recordingReal[i] * templateImaginary[i]);
}
this.fft(analyticReal, analyticImaginary, true);
const envelope = new Float32Array(recording.length);
for (let i = 0; i < envelope.length; i++)
envelope[i] = Math.sqrt(analyticReal[i] * analyticReal[i] + analyticImaginary[i] * analyticImaginary[i]);
return envelope;
},
maxInRange(values, start, end) {
let index = start;
let value = -Infinity;
for (let i = start; i < end; i++) {
if (values[i] <= value) continue;
value = values[i];
index = i;
}
return { index, value };
},
medianInRange(values, start, end, sampleLimit = 2048) {
const span = end - start;
if (span <= 0) return 0;
const stride = Math.max(1, Math.floor(span / sampleLimit));
const sampled = [];
for (let i = start; i < end; i += stride) sampled.push(values[i]);
sampled.sort((left, right) => left - right);
return sampled[sampled.length >> 1];
},
/**
* Sub-sample peak position by fitting a parabola through the peak and its neighbours. One
* tenth of a sample is 0.7mm of range at 48kHz, so this is most of the accuracy for free.
*/
refinePeakIndex(envelope, index) {
if (index <= 0 || index >= envelope.length - 1) return index;
const before = envelope[index - 1];
const peak = envelope[index];
const after = envelope[index + 1];
const curvature = before - 2 * peak + after;
if (curvature === 0) return index;
const offset = (0.5 * (before - after)) / curvature;
return index + Math.max(-1, Math.min(1, offset));
},
/**
* First arrival in a window, not the loudest one. A reflection off a wall or table often
* comes back louder than the direct path, and only the direct path is the distance.
*/
findFirstPeak(envelope, options = {}) {
const start = Math.max(0, Math.floor(options.start ?? 0));
const end = Math.min(envelope.length, Math.ceil(options.end ?? envelope.length));
if (end - start < 8) return null;
const loudest = this.maxInRange(envelope, start, end);
const noiseFloor = this.medianInRange(envelope, start, end);
const snr = noiseFloor > 0 ? loudest.value / noiseFloor : Infinity;
if (snr < (options.minSnr ?? 4)) return null;
// Held above the noise floor so sidelobes cannot trigger it, but well below the loudest
// arrival so that a reflection several times louder than the direct path cannot mask it.
const threshold = Math.max(
noiseFloor * (options.noiseMultiple ?? 6),
loudest.value * (options.relativeThreshold ?? 0.15)
);
let crossing = start;
while (crossing < end && envelope[crossing] < threshold) crossing++;
if (crossing >= end) return null;
const lobeEnd = Math.min(end, crossing + (options.lobeSamples ?? 64));
const arrival = this.maxInRange(envelope, crossing, lobeEnd);
return { index: this.refinePeakIndex(envelope, arrival.index), amplitude: arrival.value, snr };
},
/**
* Locate every chirp of one round in a single device's recording.
*
* The device's own chirp is the anchor: it is always present and always the loudest thing in
* the recording, and its position absorbs this device's own output and input latency. Every
* other slot is then searched relative to that anchor, so no clock agreement between devices
* is required — only that the chirps stay in their slots.
*/
detectSlotPeaks({
envelope,
slotCount,
slotSamples,
ownSlot,
ownSearchStart,
ownSearchSamples,
slotHints = null,
peakOptions = {}
}) {
const own = this.findFirstPeak(envelope, {
...peakOptions,
start: ownSearchStart,
end: ownSearchStart + ownSearchSamples
});
if (!own) return null;
const anchor = own.index - ownSlot * slotSamples;
const pad = Math.floor(slotSamples * 0.45);
const peaks = new Array(slotCount).fill(null);
peaks[ownSlot] = own;
for (let slot = 0; slot < slotCount; slot++) {
if (slot === ownSlot) continue;
const centre = anchor + slot * slotSamples + (slotHints?.[slot] ?? 0);
peaks[slot] = this.findFirstPeak(envelope, {
...peakOptions,
start: centre - pad,
end: centre + pad
});
}
return { anchor, peaks };
},
/**
* Distance between two devices from four arrival indices, each measured inside the recording
* of the device that made it. Clock offset and audio-pipeline latency appear once with each
* sign and cancel; the devices' own speaker-to-microphone spacing does not, and is added back.
*/
pairDistance({ a1, a2, b1, b2, sampleRate, sampleRateA, sampleRateB, speedOfSound, epsilonA = 0, epsilonB = 0 }) {
// Each interval is converted to seconds in its own device's sample rate before the two are
// subtracted: a device that hands back 44100 instead of 48000 would otherwise contribute
// its interval in the wrong unit.
const intervalA = (a2 - a1) / (sampleRateA ?? sampleRate);
const intervalB = (b2 - b1) / (sampleRateB ?? sampleRate);
return ((intervalA - intervalB) / 2) * speedOfSound + (epsilonA + epsilonB) / 2;
},
/**
* Symmetric distance matrix from one round of reports. Entries stay null where either device
* failed to hear one of the four chirps the pair needs.
*/
buildDistanceMatrix(reports, { speedOfSound = 343, maxDistance = 40 } = {}) {
const count = reports.length;
const matrix = Array.from({ length: count }, () => new Array(count).fill(null));
for (let i = 0; i < count; i++) {
matrix[i][i] = 0;
for (let j = i + 1; j < count; j++) {
const distance = this.distanceBetween(reports[i], reports[j], speedOfSound);
if (distance === null || distance < -1 || distance > maxDistance) continue;
matrix[i][j] = Math.max(0, distance);
matrix[j][i] = matrix[i][j];
}
}
return matrix;
},
distanceBetween(deviceA, deviceB, speedOfSound) {
const a1 = deviceA.peaks[deviceA.slot];
const a2 = deviceA.peaks[deviceB.slot];
const b1 = deviceB.peaks[deviceA.slot];
const b2 = deviceB.peaks[deviceB.slot];
if (a1 === null || a2 === null || b1 === null || b2 === null) return null;
return this.pairDistance({
a1,
a2,
b1,
b2,
sampleRateA: deviceA.sampleRate,
sampleRateB: deviceB.sampleRate,
speedOfSound,
epsilonA: deviceA.epsilon ?? 0,
epsilonB: deviceB.epsilon ?? 0
});
},
/**
* Largest set of devices linked by measured distances. Anything outside it cannot be placed
* relative to the others, and leaving it in makes the completed matrix infinite.
*/
largestConnectedComponent(matrix) {
const unvisited = new Set(matrix.map((_, index) => index));
let largest = [];
while (unvisited.size > 0) {
const component = [];
const queue = [unvisited.values().next().value];
unvisited.delete(queue[0]);
while (queue.length > 0) {
const current = queue.pop();
component.push(current);
for (const next of unvisited)
if (matrix[current][next] !== null) {
unvisited.delete(next);
queue.push(next);
}
}
if (component.length > largest.length) largest = component;
}
return largest.sort((left, right) => left - right);
},
/**
* Drop devices whose distances are geometrically impossible. One device reporting a bad peak
* distorts the whole layout, so the worst triangle-inequality offender is removed and the
* check repeated. Below four devices there is no redundancy left and nothing can be checked.
*/
rejectOutliers(matrix, candidates, tolerance = 0.5) {
const keep = [...candidates];
while (keep.length > 3) {
const violations = this.countTriangleViolations(matrix, keep, tolerance);
const worst = violations.reduce((best, count, index) => (count > violations[best] ? index : best), 0);
if (violations[worst] === 0) break;
keep.splice(worst, 1);
}
return keep;
},
submatrix(matrix, indices) {
return indices.map(row => indices.map(column => matrix[row][column]));
},
countTriangleViolations(matrix, keep, tolerance) {
const violations = new Array(keep.length).fill(0);
for (let i = 0; i < keep.length; i++) {
for (let j = i + 1; j < keep.length; j++) {
for (let k = j + 1; k < keep.length; k++) {
const sides = [matrix[keep[i]][keep[j]], matrix[keep[j]][keep[k]], matrix[keep[i]][keep[k]]];
if (sides.some(side => side === null)) continue;
const longest = Math.max(...sides);
const perimeter = sides.reduce((sum, side) => sum + side, 0);
if (longest <= perimeter - longest + tolerance) continue;
violations[i]++;
violations[j]++;
violations[k]++;
}
}
}
return violations;
},
/** Fill gaps with the shortest known path between the two devices so MDS gets a full matrix. */
completeMatrix(matrix) {
const count = matrix.length;
const filled = matrix.map(row => row.map(value => (value === null ? Infinity : value)));
for (let via = 0; via < count; via++)
for (let i = 0; i < count; i++)
for (let j = 0; j < count; j++)
filled[i][j] = Math.min(filled[i][j], filled[i][via] + filled[via][j]);
return filled;
},
/** Jacobi eigendecomposition of a symmetric matrix. Returns eigenvalues and column vectors. */
symmetricEigen(matrix, maxSweeps = 100, tolerance = 1e-14) {
const count = matrix.length;
const working = matrix.map(row => Float64Array.from(row));
const vectors = Array.from({ length: count }, (_, i) => {
const column = new Float64Array(count);
column[i] = 1;
return column;
});
for (let sweep = 0; sweep < maxSweeps; sweep++) {
if (this.offDiagonalMagnitude(working) < tolerance) break;
for (let p = 0; p < count - 1; p++)
for (let q = p + 1; q < count; q++)
this.rotateOut(working, vectors, p, q);
}
return {
values: working.map((row, i) => row[i]),
vectors
};
},
offDiagonalMagnitude(matrix) {
let total = 0;
for (let i = 0; i < matrix.length; i++)
for (let j = i + 1; j < matrix.length; j++) total += matrix[i][j] * matrix[i][j];
return total;
},
rotateOut(matrix, vectors, p, q) {
if (Math.abs(matrix[p][q]) < 1e-300) return matrix;
const theta = (matrix[q][q] - matrix[p][p]) / (2 * matrix[p][q]);
const sign = theta >= 0 ? 1 : -1;
const tangent = sign / (Math.abs(theta) + Math.sqrt(theta * theta + 1));
const cosine = 1 / Math.sqrt(tangent * tangent + 1);
const sine = tangent * cosine;
const count = matrix.length;
for (let k = 0; k < count; k++) {
const left = matrix[k][p];
const right = matrix[k][q];
matrix[k][p] = cosine * left - sine * right;
matrix[k][q] = sine * left + cosine * right;
}
for (let k = 0; k < count; k++) {
const left = matrix[p][k];
const right = matrix[q][k];
matrix[p][k] = cosine * left - sine * right;
matrix[q][k] = sine * left + cosine * right;
}
for (let k = 0; k < count; k++) {
const left = vectors[k][p];
const right = vectors[k][q];
vectors[k][p] = cosine * left - sine * right;
vectors[k][q] = sine * left + cosine * right;
}
return matrix;
},
/**
* Classical multidimensional scaling: coordinates whose pairwise distances best reproduce the
* matrix. The result is only defined up to rotation, translation and mirroring.
*/
classicalMds(distances, dimensions = 2) {
const count = distances.length;
const squared = distances.map(row => row.map(value => value * value));
const rowMeans = squared.map(row => row.reduce((sum, value) => sum + value, 0) / count);
const grandMean = rowMeans.reduce((sum, value) => sum + value, 0) / count;
const centred = squared.map((row, i) => row.map((value, j) => -0.5 * (value - rowMeans[i] - rowMeans[j] + grandMean)));
const { values, vectors } = this.symmetricEigen(centred);
const order = values
.map((value, index) => ({ value, index }))
.sort((left, right) => right.value - left.value)
.slice(0, dimensions);
return Array.from({ length: count }, (_, i) =>
order.map(({ value, index }) => vectors[i][index] * Math.sqrt(Math.max(0, value)))
);
},
/**
* Rotate, mirror and translate a constellation onto a reference layout. Without this, every
* solve returns an arbitrary orientation and the display spins and flips between updates.
*/
alignToReference(points, reference) {
if (!reference || reference.length !== points.length || points.length === 0) return points;
const pointCentre = this.centroid(points);
const referenceCentre = this.centroid(reference);
let best = null;
for (const mirror of [1, -1]) {
const candidate = this.rotateOnto(points, reference, pointCentre, referenceCentre, mirror);
if (!best || candidate.residual < best.residual) best = candidate;
}
return best.points;
},
centroid(points) {
const sum = points.reduce((total, [x, y]) => [total[0] + x, total[1] + y], [0, 0]);
return [sum[0] / points.length, sum[1] / points.length];
},
rotateOnto(points, reference, pointCentre, referenceCentre, mirror) {
let sineTerm = 0;
let cosineTerm = 0;
for (let i = 0; i < points.length; i++) {
const px = (points[i][0] - pointCentre[0]) * mirror;
const py = points[i][1] - pointCentre[1];
const qx = reference[i][0] - referenceCentre[0];
const qy = reference[i][1] - referenceCentre[1];
sineTerm += px * qy - py * qx;
cosineTerm += px * qx + py * qy;
}
const angle = Math.atan2(sineTerm, cosineTerm);
const cosine = Math.cos(angle);
const sine = Math.sin(angle);
let residual = 0;
const aligned = points.map((point, i) => {
const px = (point[0] - pointCentre[0]) * mirror;
const py = point[1] - pointCentre[1];
const x = px * cosine - py * sine + referenceCentre[0];
const y = px * sine + py * cosine + referenceCentre[1];
residual += (x - reference[i][0]) ** 2 + (y - reference[i][1]) ** 2;
return [x, y];
});
return { points: aligned, residual };
},
/**
* Full solve for one round: distances, connectivity, outlier rejection, then a constellation
* aligned onto the previous frame.
*
* <c>previousPoints</c> is indexed by report position, with null for devices that were dropped
* last round, so alignment survives devices coming and going.
*/
solveRound(reports, { speedOfSound = 343, previousPoints = null, tolerance = 0.5 } = {}) {
const matrix = this.buildDistanceMatrix(reports, { speedOfSound });
const connected = this.largestConnectedComponent(matrix);
const keep = this.rejectOutliers(matrix, connected, tolerance);
const points = keep.length >= 2 ? this.classicalMds(this.completeMatrix(this.submatrix(matrix, keep))) : [];
const reference = previousPoints ? keep.map(index => previousPoints[index]) : null;
const alignable = reference?.length === points.length && reference.every(Boolean);
return {
matrix,
keep,
points: alignable ? this.alignToReference(points, reference) : points
};
}
};
if (typeof window !== "undefined") window.EchoDsp = EchoDsp;
@@ -0,0 +1,269 @@
/*
* Round lifecycle: join a room, chirp when told to, measure every chirp in our own recording, and
* report the frame indices. Peaks are reported relative to the analysis window rather than to an
* absolute frame — every measurement is a difference within one device's own recording, so a
* constant per-device origin cancels.
*
* Both the chirp and the analysis are driven by the audio clock rather than by timers: a hidden tab
* has its timers throttled to roughly once a second, which is long enough to put its chirp in
* another device's slot and turn the whole round into nonsense.
*/
const EchoSession = {
LEAD_IN_SECONDS: 0.25,
TEMPERATURE_CELSIUS: 20,
MAX_OUTPUT_LATENCY_SECONDS: 0.35,
CHIRP: { durationSeconds: 0.05, startHz: 2000, endHz: 8000 },
CLOCK_SAMPLES: 5,
LATE_TOLERANCE_SECONDS: 0.05,
connection: null,
deviceId: null,
roomCode: null,
serverOffsetMs: 0,
skippedRounds: 0,
devices: [],
chirp: null,
pending: null,
lastRound: null,
hintsByDevice: {},
previousPoints: null,
epsilon: 0.08,
onUpdate: () => {},
async join(roomCode, displayName, { onUpdate }) {
this.onUpdate = onUpdate ?? this.onUpdate;
const audio = await EchoAudio.start();
this.chirp = EchoDsp.makeChirp({ sampleRate: audio.sampleRate, ...this.CHIRP });
EchoAudio.onSamples = frame => this.analyseIfCaptured(frame);
this.connection = new signalR.HubConnectionBuilder().withUrl("/echoHub").withAutomaticReconnect().build();
this.connection.on("RoomChanged", room => this.handleRoomChanged(room));
this.connection.on("RoundStarting", schedule => this.handleRoundStarting(schedule));
this.connection.on("RoundComplete", result => this.handleRoundComplete(result));
await this.connection.start();
const joined = await this.connection.invoke("JoinRoom", roomCode, displayName, audio.sampleRate);
this.deviceId = joined.deviceId;
this.roomCode = joined.roomCode;
this.devices = joined.room.devices;
this.serverOffsetMs = await this.estimateServerOffset();
return { ...joined, audio, serverOffsetMs: this.serverOffsetMs };
},
/**
* Offset from the server clock, by the usual round-trip midpoint. Only needs to be good enough
* to identify which chirp belongs to which slot, which is tens of milliseconds — the ranging
* itself never uses a shared clock.
*/
async estimateServerOffset() {
const offsets = [];
for (let attempt = 0; attempt < this.CLOCK_SAMPLES; attempt++) {
const sent = Date.now();
const serverNow = await this.connection.invoke("ServerTime");
const received = Date.now();
offsets.push(serverNow - (sent + received) / 2);
}
offsets.sort((left, right) => left - right);
return offsets[offsets.length >> 1];
},
serverNowMs() {
return Date.now() + this.serverOffsetMs;
},
handleRoomChanged(room) {
this.devices = room.devices;
this.previousPoints = null;
this.hintsByDevice = {};
this.onUpdate({ kind: "room", room });
return room;
},
/**
* Schedule our chirp for our slot on the audio clock, and record which frames this round will
* occupy so the analysis can start the moment that audio has actually been captured.
*/
handleRoundStarting(schedule) {
const ownSlot = schedule.slotOrder.indexOf(this.deviceId);
if (ownSlot < 0 || !EchoAudio.context) return null;
const sampleRate = EchoAudio.context.sampleRate;
const slotSeconds = schedule.slotMilliseconds / 1000;
const secondsUntilStart = (schedule.startsAtUnixMs - this.serverNowMs()) / 1000;
const roundStartTime = EchoAudio.context.currentTime + secondsUntilStart;
const playAtTime = roundStartTime + ownSlot * slotSeconds;
// Sitting a round out is far better than chirping late: a chirp in the wrong slot is
// attributed to the wrong device and ruins the round for everyone, whereas a missing chirp
// costs only this pair, this round.
if (playAtTime < EchoAudio.context.currentTime - this.LATE_TOLERANCE_SECONDS) {
this.skippedRounds++;
this.onUpdate({ kind: "skipped", schedule, lateBySeconds: EchoAudio.context.currentTime - playAtTime });
return null;
}
const scheduledFrame = EchoAudio.play(this.chirp, playAtTime);
const round = {
schedule,
ownSlot,
sampleRate,
scheduledFrame,
slotSamples: Math.round(slotSeconds * sampleRate),
leadInSamples: Math.round(this.LEAD_IN_SECONDS * sampleRate),
startFrame: EchoAudio.frameAt(roundStartTime),
outputLatencyMs: Math.round(EchoAudio.outputLatencySeconds() * 1000),
captureLagMs: Math.round(EchoAudio.captureLagSeconds() * 1000)
};
round.windowStart = round.startFrame - round.leadInSamples;
round.windowLength =
round.leadInSamples +
schedule.slotOrder.length * round.slotSamples +
Math.round((schedule.tailMilliseconds / 1000) * sampleRate);
this.pending = round;
this.onUpdate({ kind: "roundStarting", round });
return round;
},
/**
* Run as soon as the round's audio exists in the ring. Driven by captured audio rather than a
* timer so a throttled tab still analyses on time.
*/
analyseIfCaptured(highestFrame) {
const round = this.pending;
if (!round) return null;
if (highestFrame < round.windowStart + round.windowLength) return null;
this.pending = null;
return this.analyse(round);
},
analyse(round) {
this.lastRound = round;
const recording = EchoAudio.read(round.windowStart, round.windowLength);
if (!recording) return null;
const envelope = EchoDsp.matchedFilterEnvelope(recording, this.chirp);
const detected = EchoDsp.detectSlotPeaks({
envelope,
slotCount: round.schedule.slotOrder.length,
slotSamples: round.slotSamples,
ownSlot: round.ownSlot,
// Anchored on the frame the chirp was scheduled for, so the only unknown left is how
// long the speaker takes to actually emit it.
ownSearchStart: round.scheduledFrame - round.windowStart,
ownSearchSamples: Math.round((this.MAX_OUTPUT_LATENCY_SECONDS + this.CHIRP.durationSeconds) * round.sampleRate),
slotHints: this.hintsFor(round.schedule)
});
const diagnostics = this.describeRound(round, detected);
this.onUpdate({ kind: "envelope", envelope, detected, round, diagnostics });
if (!detected) return null;
this.rememberHints(round.schedule, detected, round.slotSamples);
return this.report(round, detected);
},
describeRound(round, detected) {
const millisecondsPer = 1000 / round.sampleRate;
return {
captureLagMs: round.captureLagMs,
outputLatencyMs: round.outputLatencyMs,
serverOffsetMs: Math.round(this.serverOffsetMs),
skippedRounds: this.skippedRounds,
clipping: EchoAudio.peakAmplitude >= 0.99,
inputPeak: Number(EchoAudio.peakAmplitude.toFixed(3)),
ownFound: Boolean(detected?.peaks[round.ownSlot]),
slots: round.schedule.slotOrder.map((deviceId, slot) => ({
deviceId,
own: slot === round.ownSlot,
residualMs: detected?.peaks[slot]
? Math.round((detected.peaks[slot].index - (detected.anchor + slot * round.slotSamples)) * millisecondsPer)
: null,
snr: detected?.peaks[slot] ? Math.round(detected.peaks[slot].snr) : null
}))
};
},
report(round, detected) {
return this.connection.invoke("ReportRound", {
deviceId: this.deviceId,
roundId: round.schedule.roundId,
slot: round.ownSlot,
sampleRate: round.sampleRate,
epsilon: this.epsilon,
peaks: detected.peaks.map(peak => peak?.index ?? null)
});
},
/**
* Where each device's chirp actually landed last round, relative to where the slot said it
* would. Output latency differs by tens of milliseconds per device and is stable, so carrying
* the residual forward keeps the search windows centred instead of merely wide.
*/
rememberHints(schedule, detected, slotSamples) {
schedule.slotOrder.forEach((deviceId, slot) => {
const peak = detected.peaks[slot];
if (!peak) return;
this.hintsByDevice[deviceId] = peak.index - (detected.anchor + slot * slotSamples);
});
return this.hintsByDevice;
},
hintsFor(schedule) {
return schedule.slotOrder.map(deviceId => this.hintsByDevice[deviceId] ?? 0);
},
handleRoundComplete(result) {
const reports = result.reports.map(report => ({ ...report, peaks: report.peaks ?? [] }));
const solved = EchoDsp.solveRound(reports, {
speedOfSound: EchoDsp.speedOfSound(this.TEMPERATURE_CELSIUS),
previousPoints: this.previousPoints
});
this.previousPoints = this.pointsByReportIndex(reports, solved);
this.onUpdate({ kind: "solved", result, reports, solved, deviceId: this.deviceId });
return solved;
},
pointsByReportIndex(reports, solved) {
const points = new Array(reports.length).fill(null);
solved.keep.forEach((reportIndex, i) => {
points[reportIndex] = solved.points[i];
});
return points;
},
setEpsilon(metres) {
this.epsilon = metres;
localStorage.setItem("echo.epsilon", String(metres));
return this.epsilon;
},
loadEpsilon() {
const stored = Number(localStorage.getItem("echo.epsilon"));
this.epsilon = Number.isFinite(stored) && stored > 0 ? stored : 0.08;
return this.epsilon;
},
async leave() {
await this.connection?.invoke("LeaveRoom").catch(() => {});
await this.connection?.stop();
await EchoAudio.stop();
this.connection = null;
this.pending = null;
this.previousPoints = null;
this.hintsByDevice = {};
return true;
}
};
if (typeof window !== "undefined") window.EchoSession = EchoSession;
@@ -0,0 +1,213 @@
/*
* Virtual room for exercising the real ranging pipeline without microphones. Synthesizes what
* each device would have recorded — propagation delay, reflections, noise, per-device clock offset
* and unknown output latency — then runs the same EchoDsp code the page runs.
*/
const EchoSim = {
DEFAULTS: {
sampleRate: 48000,
slotSeconds: 0.4,
tailSeconds: 0.5,
speedOfSound: 343,
noiseAmplitude: 0.01,
referenceGain: 0.5,
minimumPathMetres: 0.25,
maximumOutputLatencySeconds: 0.2,
chirp: { durationSeconds: 0.05, startHz: 2000, endHz: 8000 },
reflectionsPerPath: 2,
reflectionExtraRange: [0.4, 4.0],
reflectionGainRange: [0.2, 0.8],
seed: 20260730
},
randomGenerator(seed) {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let mixed = Math.imul(state ^ (state >>> 15), 1 | state);
mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;
return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;
};
},
separation(first, second) {
return Math.hypot(first[0] - second[0], first[1] - second[1]);
},
buildConfiguration(overrides = {}) {
const config = { ...this.DEFAULTS, ...overrides };
const count = config.positions.length;
config.chirp = { ...this.DEFAULTS.chirp, ...(overrides.chirp ?? {}) };
config.epsilon ??= new Array(count).fill(0.05);
config.clockOffsets ??= config.positions.map((_, i) => i * 7919);
config.outputLatencies ??= config.positions.map((_, i) => 0.02 + 0.03 * i);
config.scheduleJitter ??= config.positions.map((_, i) => 0.004 * i);
config.reflections ??= this.buildReflectionTable(config);
return config;
},
/**
* Multipath for every source-to-listener path independently. Giving every path the same echo
* would be worthless as a test: an identical bias on all four arrivals cancels out of the
* range formula, so a uniform echo model hides exactly the error it is supposed to expose.
*/
buildReflectionTable(config) {
const random = this.randomGenerator(config.seed ^ 0x5f3759df);
const spread = (range, value) => range[0] + value * (range[1] - range[0]);
return config.positions.map(() =>
config.positions.map(() =>
Array.from({ length: config.reflectionsPerPath }, () => ({
extraMetres: spread(config.reflectionExtraRange, random()),
gain: spread(config.reflectionGainRange, random())
}))
)
);
},
reflectionsFor(config, source, listener) {
return Array.isArray(config.reflections[0]) ? config.reflections[source][listener] : config.reflections;
},
/** One recording per device, plus the index each device believes it started playing at. */
synthesizeRound(config) {
const { positions, sampleRate, slotSeconds, tailSeconds } = config;
const random = this.randomGenerator(config.seed);
const template = EchoDsp.makeChirp({ sampleRate, ...config.chirp });
const maximumOffset = Math.max(...config.clockOffsets);
const length = Math.ceil((positions.length * slotSeconds + tailSeconds) * sampleRate) + maximumOffset;
const devices = positions.map((_, index) => ({
recording: this.noiseBuffer(length, config.noiseAmplitude, random),
ownSearchStart: Math.round((index * slotSeconds + config.scheduleJitter[index]) * sampleRate) + config.clockOffsets[index]
}));
for (let source = 0; source < positions.length; source++)
for (let listener = 0; listener < positions.length; listener++)
this.mixArrivals(devices[listener].recording, template, config, source, listener);
return { devices, template };
},
noiseBuffer(length, amplitude, random) {
const buffer = new Float32Array(length);
for (let i = 0; i < length; i++) buffer[i] = (random() * 2 - 1) * amplitude;
return buffer;
},
mixArrivals(recording, template, config, source, listener) {
const emissionSeconds =
source * config.slotSeconds + config.scheduleJitter[source] + config.outputLatencies[source];
const directMetres =
source === listener ? config.epsilon[source] : this.separation(config.positions[source], config.positions[listener]);
const paths = [
{ metres: directMetres, gain: 1 },
...this.reflectionsFor(config, source, listener).map(({ extraMetres, gain }) => ({
metres: directMetres + extraMetres,
gain
}))
];
for (const path of paths) {
const arrival = emissionSeconds + path.metres / config.speedOfSound;
const amplitude =
(config.referenceGain / Math.max(path.metres, config.minimumPathMetres)) * path.gain;
this.addAt(recording, template, Math.round(arrival * config.sampleRate) + config.clockOffsets[listener], amplitude);
}
return recording;
},
addAt(recording, template, offset, amplitude) {
const start = Math.max(0, offset);
const end = Math.min(recording.length, offset + template.length);
for (let i = start; i < end; i++) recording[i] += template[i - offset] * amplitude;
return recording;
},
/** Run every device's recording through detection and return one report per device. */
detectAll({ devices, template }, config) {
const slotSamples = Math.round(config.slotSeconds * config.sampleRate);
const searchSamples = Math.round(
(config.maximumOutputLatencySeconds + config.chirp.durationSeconds + 0.05) * config.sampleRate
);
return devices.map((device, slot) => {
const envelope = EchoDsp.matchedFilterEnvelope(device.recording, template);
const detected = EchoDsp.detectSlotPeaks({
envelope,
slotCount: devices.length,
slotSamples,
ownSlot: slot,
ownSearchStart: device.ownSearchStart,
ownSearchSamples: searchSamples,
peakOptions: config.peakOptions ?? {}
});
return {
deviceId: `sim-${slot}`,
slot,
sampleRate: config.sampleRate,
epsilon: config.epsilon[slot],
peaks: (detected?.peaks ?? new Array(devices.length).fill(null)).map(peak => peak?.index ?? null)
};
});
},
/** Synthesize, detect and solve, reporting recovered geometry against the ground truth. */
runRound(overrides = {}) {
const config = this.buildConfiguration(overrides);
const round = this.synthesizeRound(config);
const reports = this.detectAll(round, config);
const solved = EchoDsp.solveRound(reports, { speedOfSound: config.speedOfSound });
return {
config,
reports,
...solved,
distanceErrors: this.distanceErrors(solved.matrix, config),
positionErrors: this.positionErrors(solved, config)
};
},
distanceErrors(matrix, config) {
const errors = [];
for (let i = 0; i < matrix.length; i++)
for (let j = i + 1; j < matrix.length; j++) {
const truth = this.separation(config.positions[i], config.positions[j]);
errors.push({
pair: [i, j],
truth,
measured: matrix[i][j],
error: matrix[i][j] === null ? null : matrix[i][j] - truth
});
}
return errors;
},
positionErrors({ keep, points }, config) {
if (points.length !== keep.length || points.length < 2) return [];
const truth = keep.map(index => config.positions[index]);
const aligned = EchoDsp.alignToReference(points, truth);
return aligned.map((point, i) => this.separation(point, truth[i]));
},
worstDistanceError(result) {
const magnitudes = result.distanceErrors.map(({ error }) => (error === null ? Infinity : Math.abs(error)));
return magnitudes.length === 0 ? 0 : Math.max(...magnitudes);
},
worstPositionError(result) {
return result.positionErrors.length === 0 ? Infinity : Math.max(...result.positionErrors);
}
};
if (typeof window !== "undefined") window.EchoSim = EchoSim;
@@ -0,0 +1,282 @@
/*
* Page wiring for /echo. Renders what the session measures: the matched-filter trace with the
* arrivals it picked, the pairwise ranges, and — while only two devices are present — one large
* number, because that number is the whole measurement.
*/
const EchoPage = {
HISTORY_LENGTH: 12,
elements: {},
lastSolved: null,
lastDiagnostics: null,
history: [],
roundsSeen: 0,
start() {
this.elements = {
room: document.getElementById("echoRoom"),
name: document.getElementById("echoName"),
join: document.getElementById("echoJoin"),
leave: document.getElementById("echoLeave"),
status: document.getElementById("echoStatus"),
warnings: document.getElementById("echoWarnings"),
readout: document.getElementById("echoReadout"),
pairs: document.getElementById("echoPairs"),
roster: document.getElementById("echoRoster"),
trace: document.getElementById("echoTrace"),
epsilon: document.getElementById("echoEpsilon"),
shareLink: document.getElementById("echoShareLink"),
diagnostics: document.getElementById("echoDiagnostics")
};
this.elements.room.value = new URLSearchParams(location.search).get("room") ?? this.randomCode();
this.elements.epsilon.value = EchoSession.loadEpsilon();
this.elements.epsilon.addEventListener("change", () => this.applyEpsilon());
this.elements.join.addEventListener("click", () => this.join());
this.elements.leave.addEventListener("click", () => this.leave());
return this;
},
randomCode() {
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
return Array.from({ length: 4 }, () => alphabet[Math.floor(Math.random() * alphabet.length)]).join("");
},
applyEpsilon() {
const metres = Number(this.elements.epsilon.value);
if (!Number.isFinite(metres) || metres < 0) return null;
EchoSession.setEpsilon(metres);
return metres;
},
async join() {
const roomCode = this.elements.room.value.trim().toUpperCase();
if (!roomCode) return null;
this.setStatus("Requesting the microphone…");
this.elements.join.disabled = true;
try {
const joined = await EchoSession.join(roomCode, this.deviceName(), { onUpdate: update => this.handle(update) });
this.showJoined(joined);
return joined;
} catch (error) {
this.setStatus(`Could not start: ${error.message}`);
this.elements.join.disabled = false;
return null;
}
},
deviceName() {
const typed = this.elements.name.value.trim();
if (typed) return typed;
return /android|iphone|ipad|mobile/i.test(navigator.userAgent) ? "phone" : "laptop";
},
showJoined(joined) {
this.elements.leave.hidden = false;
this.elements.room.disabled = true;
this.elements.name.disabled = true;
this.elements.shareLink.textContent = `${location.origin}/echo?room=${joined.roomCode}`;
this.elements.shareLink.href = `/echo?room=${joined.roomCode}`;
this.renderWarnings(joined.audio);
this.renderRoster(joined.room.devices);
this.setStatus(`Listening at ${joined.audio.sampleRate}Hz. Open the same room on another device.`);
return joined;
},
async leave() {
await EchoSession.leave();
this.elements.leave.hidden = true;
this.elements.join.disabled = false;
this.elements.room.disabled = false;
this.elements.name.disabled = false;
this.setStatus("Left the room.");
return true;
},
handle(update) {
if (update.kind === "room") return this.renderRoster(update.room.devices);
if (update.kind === "envelope") {
this.renderDiagnostics(update.diagnostics);
return this.renderTrace(update);
}
if (update.kind === "solved") return this.renderSolved(update);
return null;
},
/**
* Per-slot residual is the diagnostic that matters: it is how far each chirp landed from where
* its slot said it would. Steady residuals mean the arrivals are being attributed correctly;
* residuals jumping by more than a slot mean they are not, and every range is then meaningless.
*/
renderDiagnostics(diagnostics) {
if (!diagnostics) return null;
this.lastDiagnostics = diagnostics;
const slots = diagnostics.slots
.map(slot => {
const label = slot.own ? "self" : slot.deviceId;
const residual = slot.residualMs === null ? "missed" : `${slot.residualMs > 0 ? "+" : ""}${slot.residualMs}ms`;
return `<li class="${slot.residualMs === null ? "echo-missed" : ""}">${label} · ${residual}${slot.snr === null ? "" : ` · snr ${slot.snr}`}</li>`;
})
.join("");
this.elements.diagnostics.innerHTML = `
<ul class="echo-slots">${slots}</ul>
<p class="echo-diag-line">
capture lag ${diagnostics.captureLagMs}ms · output latency ${diagnostics.outputLatencyMs}ms ·
clock offset ${diagnostics.serverOffsetMs}ms · rounds sat out ${diagnostics.skippedRounds} ·
input peak ${diagnostics.inputPeak}${diagnostics.clipping ? " <strong>CLIPPING</strong>" : ""}
</p>`;
return diagnostics;
},
recordHistory(metres) {
this.history.push(metres);
if (this.history.length > this.HISTORY_LENGTH) this.history.shift();
const spread = Math.max(...this.history) - Math.min(...this.history);
return { spread, count: this.history.length };
},
setStatus(message) {
this.elements.status.textContent = message;
return message;
},
renderWarnings(audio) {
this.elements.warnings.innerHTML = "";
for (const warning of audio.warnings) {
const item = document.createElement("p");
item.className = "echo-warning";
item.textContent = warning;
this.elements.warnings.appendChild(item);
}
return audio.warnings.length;
},
renderRoster(devices) {
this.elements.roster.innerHTML = "";
for (const device of devices) {
const row = document.createElement("li");
row.className = device.deviceId === EchoSession.deviceId ? "echo-device echo-device-self" : "echo-device";
row.textContent = `${device.displayName} · ${device.sampleRate}Hz`;
this.elements.roster.appendChild(row);
}
if (devices.length < 2) this.setStatus("Waiting for a second device to join this room.");
return devices.length;
},
renderSolved({ result, reports, solved }) {
this.roundsSeen++;
const raw = EchoDsp.buildDistanceMatrix(
reports.map(report => ({ ...report, epsilon: 0 })),
{ speedOfSound: EchoDsp.speedOfSound(EchoSession.TEMPERATURE_CELSIUS) }
);
this.lastSolved = { result, reports, solved, raw };
this.renderReadout(reports, solved, raw);
this.renderPairs(reports, solved, raw);
this.setStatus(`Round ${this.roundsSeen} · ${reports.length} of ${EchoSession.devices.length} devices reported`);
return solved;
},
renderReadout(reports, solved, raw) {
const readout = this.elements.readout;
if (reports.length !== 2 || solved.matrix[0][1] === null) {
readout.innerHTML = `<span class="echo-readout-idle">${reports.length < 2 ? "waiting for a pair" : "measuring…"}</span>`;
return null;
}
const corrected = solved.matrix[0][1];
const { spread, count } = this.recordHistory(corrected);
readout.innerHTML = `
<span class="echo-metres">${corrected.toFixed(2)}<small>m</small></span>
<span class="echo-readout-detail">
raw ${raw[0][1].toFixed(3)}m · calibration +${(corrected - raw[0][1]).toFixed(3)}m ·
spread over last ${count} ${spread.toFixed(2)}m
</span>`;
return corrected;
},
renderPairs(reports, solved, raw) {
const rows = [];
for (let i = 0; i < reports.length; i++)
for (let j = i + 1; j < reports.length; j++) {
const dropped = !solved.keep.includes(i) || !solved.keep.includes(j);
const measured = solved.matrix[i][j];
rows.push(`<tr class="${dropped ? "echo-dropped" : ""}">
<td>${reports[i].deviceId} ↔ ${reports[j].deviceId}</td>
<td>${measured === null ? "—" : measured.toFixed(3) + " m"}</td>
<td>${raw[i][j] === null ? "—" : raw[i][j].toFixed(3) + " m"}</td>
</tr>`);
}
this.elements.pairs.innerHTML = rows.length
? `<table><thead><tr><th>pair</th><th>range</th><th>raw</th></tr></thead><tbody>${rows.join("")}</tbody></table>`
: "";
return rows.length;
},
/** The matched-filter trace, with a marker on each arrival the detector accepted. */
renderTrace({ envelope, detected, round }) {
const canvas = this.elements.trace;
const context = canvas.getContext("2d");
const width = (canvas.width = canvas.clientWidth);
const height = (canvas.height = 160);
const peak = EchoDsp.maxInRange(envelope, 0, envelope.length).value || 1;
context.clearRect(0, 0, width, height);
context.strokeStyle = "rgba(9, 255, 0, 0.75)";
context.beginPath();
const bucket = envelope.length / width;
for (let x = 0; x < width; x++) {
const start = Math.floor(x * bucket);
const highest = EchoDsp.maxInRange(envelope, start, Math.min(envelope.length, Math.floor(start + bucket))).value;
const y = height - (highest / peak) * (height - 8) - 4;
x === 0 ? context.moveTo(x, y) : context.lineTo(x, y);
}
context.stroke();
this.drawMarkers(context, detected, round, envelope.length, width, height);
return canvas;
},
drawMarkers(context, detected, round, envelopeLength, width, height) {
if (!detected) return null;
context.font = "11px 'Cascadia Code', monospace";
detected.peaks.forEach((peak, slot) => {
if (!peak) return;
const x = (peak.index / envelopeLength) * width;
const own = slot === round.ownSlot;
context.strokeStyle = own ? "#5fff5f" : "rgba(255, 255, 255, 0.55)";
context.fillStyle = context.strokeStyle;
context.beginPath();
context.moveTo(x, 0);
context.lineTo(x, height);
context.stroke();
context.fillText(own ? `self (${slot})` : `slot ${slot}`, x + 4, 14 + slot * 13);
});
return detected.peaks.length;
}
};
document.addEventListener("DOMContentLoaded", () => EchoPage.start());
File diff suppressed because it is too large Load Diff
@@ -1,92 +0,0 @@
// "Add chips" — a rebuy, a top-up, or the first buy-in of the night.
//
// Quick amounts come off the table's starting stack, because a rebuy is almost
// always one buy-in, sometimes half or two. The keypad is there for the times it
// isn't. Recorded as cash in as well as chips, so at the end of the night the
// dealer can say what each player actually handed over.
const AddChips = {
state: null,
onConfirm: null,
seatIndex: null,
draft: "",
open(state, seatIndex, onConfirm) {
this.state = state;
this.seatIndex = seatIndex;
this.onConfirm = onConfirm;
this.draft = String(this.baseAmount());
this.render();
document.getElementById("addChipsOverlay").hidden = false;
},
close() {
document.getElementById("addChipsOverlay").hidden = true;
},
// The table's starting stack if there is one, otherwise something sane to nudge
// rather than an empty box.
baseAmount() {
const configured = Number(this.state.defaultStack);
if (!Number.isNaN(configured) && configured > 0) return configured;
const bb = Number(this.state.bigBlind) || 0;
return bb > 0 ? bb * 100 : 100;
},
quickAmounts() {
const base = this.baseAmount();
return [
{ label: "½ buy-in", value: Money.round(base / 2) },
{ label: "Buy-in", value: base },
{ label: "2 buy-ins", value: base * 2 },
];
},
render() {
const player = this.state.seats[this.seatIndex];
document.getElementById("addChipsTitle").textContent =
`Add chips — ${HoldemState.displayName(player, this.seatIndex)}`;
const stack = Betting.stackOf(this.state, player);
const boughtIn = Number(player.buyIns) || 0;
document.getElementById("addChipsSubtitle").textContent = boughtIn > 0
? `${Money.format(stack)} in front · ${Money.format(boughtIn)} in so far`
: `${Money.format(stack)} in front`;
const quick = document.getElementById("addChipsQuick");
quick.innerHTML = "";
this.quickAmounts().forEach(option => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "addChipsQuickBtn";
btn.classList.toggle("selected", Number(this.draft) === option.value);
const label = document.createElement("span");
label.className = "addChipsQuickLabel";
label.textContent = option.label;
const amount = document.createElement("span");
amount.className = "addChipsQuickAmount";
amount.textContent = Money.format(option.value);
btn.appendChild(label);
btn.appendChild(amount);
btn.addEventListener("click", () => {
this.draft = String(option.value);
this.render();
});
quick.appendChild(btn);
});
const input = document.getElementById("addChipsInput");
input.value = this.draft;
},
confirm() {
const amount = Math.max(0, Number(document.getElementById("addChipsInput").value) || 0);
this.close();
if (amount > 0) this.onConfirm(this.seatIndex, Money.round(amount));
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = AddChips;
}
@@ -1,801 +0,0 @@
// Live betting: who's to act, what it costs them, and where the money goes.
//
// This is bookkeeping, not a game — the dealer taps what the humans at the table
// actually did, and the tool keeps the arithmetic straight. It deliberately never
// blocks an action it thinks is "illegal"; a dealer overruling the maths is right
// more often than the maths is.
//
// Money model: `player.committed` is what a seat has put in on the current street.
// When a street closes it sweeps into `player.amountOverride`, which is the seat's
// total for the hand — the same field the pot badge, the pot wizard, the standings
// and the CSV already read. So the betting bar is a fast way to fill in a field
// that already existed, and nothing downstream had to change.
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";
},
round(amount) {
return Money.round(amount);
},
// ---- Reading the table ----
liveSeats(state) {
return state.seats
.map((player, index) => ({ player, index }))
.filter(s => s.player.inHand && !s.player.folded);
},
// Who would post if the hand were dealt right now. Used to preview the blinds
// while the table is still being set, so a dealer can see where they'll land
// before any money moves.
// A seat that is dealt in, has nothing in the pot, and has no chips behind.
//
// Not the same as all-in: an all-in player has money riding on the hand. This is
// somebody who busted and hasn't bought back in yet, which a home game produces
// about once an hour. A seat with no stack *recorded* isn't broke either —
// stackOf falls back to the table's starting stack for those — only an explicit
// zero counts.
brokeSeats(state) {
const broke = [];
state.seats.forEach((player, index) => {
if (!player.inHand) return;
if (this.handTotal(player) > this.EPSILON_CHIPS) return;
if (this.stackOf(state, player) > this.EPSILON_CHIPS) return;
broke.push(index);
});
return broke;
},
// The table as it will be once the seats that can't post are dealt around. A view,
// not a change: the preview has to ask the same question the deal will answer, and
// asking it of a different shape of table is how the two came apart last time.
tableAsDealt(state) {
const broke = this.brokeSeats(state);
if (broke.length === 0) return state;
const skip = new Set(broke);
return {
...state,
seats: state.seats.map((player, index) =>
skip.has(index) ? { ...player, inHand: false, folded: false } : player),
};
},
blindPreview(state) {
// Dealing relocates a button parked on an empty chair before it works out who
// posts, so the preview has to answer for the button where it *will* be. Asking
// from where it currently sits gave a different pair of blinds than the deal
// produced — the preview promising one thing and doing another is exactly the
// guessing this whole step exists to remove. Same reason the broke seats come
// out first: the preview once promised a small blind from a seat with no chips.
const dealt = this.tableAsDealt(state);
const buttonIndex = HoldemState.buttonSeatForDeal(dealt);
const asDealt = buttonIndex === dealt.dealerSeatIndex
? dealt
: { ...dealt, dealerSeatIndex: buttonIndex };
const satOut = this.brokeSeats(state);
const { sbIndex, bbIndex, headsUp, manual, deadSmallBlind } = HoldemState.getBlindSeats(asDealt);
if (bbIndex === null) return null;
return {
sbIndex, bbIndex, headsUp, manual: !!manual, deadSmallBlind: !!deadSmallBlind,
deadButton: !!asDealt.deadButton && !asDealt.seats[buttonIndex].inHand,
// Asked of the table as it will be dealt, for the same reason the blinds
// are: someone sitting out for having no chips isn't owed a blind, and the
// big blind of the hand about to go out isn't either.
debtors: HoldemState.blindDebtors(asDealt, bbIndex),
posting: (state.postingIn || []).slice(),
buttonIndex,
buttonMoves: buttonIndex !== state.dealerSeatIndex,
satOut,
smallBlind: this.round(state.smallBlind || 0),
bigBlind: this.round(state.bigBlind || 0),
// What the straddles will be if the hand is dealt as it stands, and how
// many more this table could take.
straddles: this.straddleSeats(state),
maxStraddles: this.maxStraddles(state),
};
},
// ---- Straddles ----
//
// A straddle is a blind raise put out before the cards, by the player left of the
// big blind, for twice it. It buys the last word before the flop: everyone else
// acts first, and the straddler still has the option when it comes back round even
// if nobody raised. Re-straddles carry on left, each doubling again.
//
// Home games run them constantly and a dealer has to get three things right at
// once — the amount, who is first to act, and what the minimum raise becomes. The
// tool used to do none of them, so a dealer's only way through was to deal, have
// the straddler "raise" to $4, and hand the action to the wrong player.
// How many straddles this table could take. Everyone but the two blinds can put
// one out; heads-up that is nobody, which is the right answer — the button is
// already the small blind and there is no seat left of the big blind to straddle
// from.
maxStraddles(state) {
return Math.max(0, this.liveSeats(this.tableAsDealt(state)).length - 2);
},
// Who straddles and for how much, walking left from the big blind and doubling.
// Asked of the table as it will be dealt, so a seat about to be sat out for having
// no chips is never handed a straddle it can't post.
straddleSeats(state, count = state.straddleCount) {
const wanted = Math.min(Math.max(0, Number(count) || 0), this.maxStraddles(state));
if (wanted <= 0) return [];
const dealt = this.tableAsDealt(state);
const buttonIndex = HoldemState.buttonSeatForDeal(dealt);
const asDealt = buttonIndex === dealt.dealerSeatIndex
? dealt
: { ...dealt, dealerSeatIndex: buttonIndex };
const { bbIndex } = HoldemState.getBlindSeats(asDealt);
if (bbIndex === null) return [];
const straddles = [];
let index = bbIndex;
let amount = this.round((Number(state.bigBlind) || 0) * 2);
for (let n = 0; n < wanted; n++) {
index = this.nextToAct(asDealt, index);
if (index === null || index === bbIndex) break;
straddles.push({ index, amount });
amount = this.round(amount * 2);
}
return straddles;
},
// Does handing this seat chips also put them back in the game?
//
// At a real table those are one event, and here they were two: a busted player got
// their chips and stayed sat out, silently skipped hand after hand until somebody
// noticed and found "Deal in" in the seat menu. Nothing said so — the toast just
// read "Ben added $100".
//
// Not for a seat that was sat out while *holding* chips. That's a dealer who sat
// somebody out on purpose and is topping them up, and dealing them back in would be
// the tool guessing at something it wasn't told. Only a seat with no stack of its
// own: busted at zero, or a chair being bought into for the first time.
//
// Deliberately reads player.stack rather than stackOf(), which substitutes the
// table's starting stack for a seat that has none — the question here is what this
// seat was actually recorded as holding.
buyInDealsThemIn(player) {
if (!player || player.inHand) return false;
const own = player.stack;
const recorded = own !== null && own !== undefined && String(own).trim() !== "";
return !recorded || Number(own) <= this.EPSILON_CHIPS;
},
// "bet" or "raise" — what putting more in is actually called right now.
//
// A wager into a pot nobody has wagered into is a bet; everything after that is a
// raise. The bar decided this from what the acting player still owes, which gets
// the big blind's option backwards: they owe nothing, so it offered "Bet", but
// their own blind is a live bet and putting more in is a raise. It gets the other
// half wrong too — the raise pad said "Raise to" for an opening bet on the flop,
// and wrote "Ann's raise to $10" into the undo control for it.
//
// The arithmetic was always right (minRaiseTo returns two big blinds for the big
// blind's option and one for an opening bet). This is only what it's called, which
// for a tool a dealer announces the action from is not a small thing.
wagerVerb(state) {
return (state.currentBet || 0) > this.EPSILON_CHIPS ? "raise" : "bet";
},
committed(player) {
return this.round(player.committed || 0);
},
// Everything this seat has put in across the whole hand, including the street
// still in progress.
handTotal(player) {
return this.round((Number(player.amountOverride) || 0) + this.committed(player));
},
// Never below zero. A seat can't have negative chips in front of it, and a typo in
// the stack field used to come back as-is — which then flowed into putIn(), where
// `Math.min(amount, -50)` moves a negative amount and *adds* chips to the table.
stackOf(state, player) {
const own = player.stack;
if (own !== null && own !== undefined && String(own).trim() !== "") {
return Math.max(0, this.round(own));
}
const fallback = Number(state.defaultStack);
return Number.isNaN(fallback) ? 0 : Math.max(0, this.round(fallback));
},
toCall(state, player) {
return Math.max(0, this.round((state.currentBet || 0) - this.committed(player)));
},
// A raise has to at least match the last one; before any raise, the big blind
// is the yardstick.
minRaiseTo(state) {
const increment = this.round(state.lastRaiseSize || state.bigBlind || 0);
return this.round((state.currentBet || 0) + (increment || 1));
},
potSoFar(state) {
return this.round(
state.seats.reduce((sum, p) => sum + this.handTotal(p), 0)
);
},
// ---- Moving the action ----
nextLiveIndex(state, fromIndex) {
const count = state.seatCount;
for (let step = 1; step <= count; step++) {
const index = this.seatAt(state, fromIndex, step);
const player = state.seats[index];
if (player.inHand && !player.folded) return index;
}
return null;
},
// Who the dealer asks next. A player who is all-in is still in the hand and still
// wins pots, but has no decision left, so the action passes over them.
nextToAct(state, fromIndex) {
const count = state.seatCount;
for (let step = 1; step <= count; step++) {
const index = this.seatAt(state, fromIndex, step);
const player = state.seats[index];
if (player.inHand && !player.folded && this.stackOf(state, player) > this.EPSILON_CHIPS) return index;
}
return null;
},
// A player still in the hand with chips in the pot and nothing left behind. This is
// the same stack test nextToAct uses to pass over them, which is the point: the
// seat the felt marks all-in is exactly the seat the dealer will never be asked to
// act on again.
//
// The "chips in the pot" half matters. A seat with an empty stack who hasn't put
// anything in is a busted player who shouldn't have been dealt in, not a player
// who moved all-in, and calling them all-in on the felt would be a lie.
isAllIn(state, player) {
if (!player || !player.inHand || player.folded) return false;
return this.handTotal(player) > this.EPSILON_CHIPS &&
this.stackOf(state, player) <= this.EPSILON_CHIPS;
},
// Which chair sits `step` places along in the direction of play. The table owns
// this — walking the seats is exactly where the button, the blinds and the action
// used to drift apart from each other, so there is one implementation of it.
seatAt(state, fromIndex, step) {
return HoldemState.nextSeatIndex(state, fromIndex, step);
},
// A street is done when everyone still live has either matched the bet or has
// no chips left to argue with, and everyone has had a turn since the last raise.
isStreetComplete(state) {
const live = this.liveSeats(state);
if (live.length <= 1) return true;
const unsettled = live.filter(s => {
const allIn = this.stackOf(state, s.player) <= 0;
const matched = this.toCall(state, s.player) <= 0;
return !allIn && (!matched || !s.player.hasActed);
});
return unsettled.length === 0;
},
// ---- Actions ----
// Moves `amount` from a seat's stack into the middle for this street. Returns
// what actually moved, which is less than asked for if it puts them all-in.
putIn(state, index, amount) {
const player = state.seats[index];
const stack = this.stackOf(state, player);
const moved = this.round(Math.min(Math.max(0, amount), stack));
player.stack = this.round(stack - moved);
player.committed = this.round(this.committed(player) + moved);
return moved;
},
fold(state, index) {
state.seats[index].folded = true;
state.seats[index].hasActed = true;
this.passAction(state, index);
},
check(state, index) {
state.seats[index].hasActed = true;
this.passAction(state, index);
},
call(state, index) {
const player = state.seats[index];
this.putIn(state, index, this.toCall(state, player));
player.hasActed = true;
this.passAction(state, index);
},
// `total` is what the seat's street commitment becomes — "raise to", the way a
// dealer says it out loud, not "raise by".
raiseTo(state, index, total) {
const player = state.seats[index];
const target = this.round(total);
const delta = this.round(target - this.committed(player));
const moved = this.putIn(state, index, delta);
const newBet = this.committed(player);
const previousBet = state.currentBet || 0;
if (newBet > previousBet) {
const increase = this.round(newBet - previousBet);
// Aggression, whether or not it was a full raise — a short all-in doesn't
// reopen the betting, but the player who made it is still the last one who
// put money in, and at the showdown they are still the one who shows first.
state.streetAggressorIndex = index;
state.handAggressorIndex = index;
// What a full raise would have had to be: at least as much again as the
// last one, or the big blind if there hasn't been a raise yet.
const fullRaise = this.round(state.lastRaiseSize || state.bigBlind || 0);
const isFullRaise = increase >= fullRaise - this.EPSILON_CHIPS;
state.currentBet = newBet;
if (isFullRaise) {
state.lastRaiseSize = increase;
// A real raise reopens the action: everyone else owes a response again.
state.seats.forEach((p, i) => {
if (i !== index && p.inHand && !p.folded) p.hasActed = false;
});
}
// Otherwise this is a short all-in — somebody with less than a full raise
// left shoving it in. The most misread rule in poker: it does *not* reopen
// the betting to anyone who has already acted. They owe the difference or
// they fold; they don't get to raise again because a short stack happened
// to be between them. Players yet to act keep their full rights, which
// they do here because their hasActed is already false.
//
// lastRaiseSize deliberately isn't lowered either, or the next legal raise
// would be computed off the short amount and come out too small.
}
player.hasActed = true;
this.passAction(state, index);
return moved;
},
allIn(state, index) {
const player = state.seats[index];
return this.raiseTo(state, index, this.round(this.committed(player) + this.stackOf(state, player)));
},
passAction(state, index) {
state.actingSeatIndex = this.isStreetComplete(state) ? null : this.nextToAct(state, index);
},
// ---- Street and hand boundaries ----
// Pulls whatever is in front of the players into their hand totals. Anything that
// reads a seat's contribution — the pot wizard above all — has to run after this,
// or it will price the pot without the chips sitting on the current street.
sweepToHandTotals(state) {
state.seats.forEach(player => {
const moved = this.committed(player);
if (moved > 0) {
player.amountOverride = this.round((Number(player.amountOverride) || 0) + moved);
}
player.committed = 0;
player.hasActed = false;
});
},
// Sweeps the street's chips into each seat's hand total and opens the next one.
closeStreet(state) {
this.sweepToHandTotals(state);
state.currentBet = 0;
state.lastRaiseSize = 0;
// Whoever led this street stops being the answer the moment the next one opens.
// The hand's aggressor is deliberately left alone: it's the fallback for a
// river nobody could bet on.
state.streetAggressorIndex = null;
const nextStreetIndex = this.STREETS.indexOf(state.street || "preflop") + 1;
state.street = this.STREETS[nextStreetIndex] || "river";
// It takes two players with chips to have a bet. Once everyone left is all-in
// the rest of the board is just dealt out.
if (!this.canStillBet(state)) {
state.actingSeatIndex = null;
return;
}
// After the flop the first live player left of the button acts — which heads-up
// is the big blind, since the button is the small blind. Naming the big blind
// directly also covers a button parked on a seat nobody is sitting in, and it
// still has to be someone with chips left to bet.
const { bbIndex, headsUp } = HoldemState.getBlindSeats(state);
const bigBlindCanAct =
headsUp &&
bbIndex !== null &&
!state.seats[bbIndex].folded &&
this.stackOf(state, state.seats[bbIndex]) > this.EPSILON_CHIPS;
state.actingSeatIndex = bigBlindCanAct
? bbIndex
: this.nextToAct(state, state.dealerSeatIndex);
},
isHandOver(state) {
return this.liveSeats(state).length <= 1;
},
// Players still in the hand who have chips left to put in. Fewer than two of them
// means the betting is finished even though the hand isn't.
seatsWithChips(state) {
return this.liveSeats(state).filter(s => this.stackOf(state, s.player) > this.EPSILON_CHIPS);
},
EPSILON_CHIPS: Money.EPSILON,
canStillBet(state) {
return this.liveSeats(state).length > 1 && this.seatsWithChips(state).length > 1;
},
// True when the hand is still live but nobody can bet again — the dealer is just
// running the board out.
isRunningOut(state) {
// Only while a hand is actually being played. Before the deal, a table of
// busted players who haven't rebought looks exactly like a table of all-ins to
// this test, and the bar was announcing a run-out over a felt with no cards and
// no chips on it.
if (!state.bettingOpen) return false;
return this.liveSeats(state).length > 1 && !this.canStillBet(state);
},
// True while nothing has happened in this hand except the blinds going in. Up to
// that point the dealer can still move the button or rename the blinds and have
// it cost nothing — which is the state a home game spends a lot of time in,
// arguing about whose turn it is before the cards come out.
onlyBlindsIn(state) {
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
// times before anybody is happy with it.
repostBlinds(state) {
state.seats.forEach(player => {
const back = this.committed(player);
if (back > 0) player.stack = this.round(this.stackOf(state, player) + back);
player.committed = 0;
player.hasActed = false;
});
this.beginHand(state);
},
// Deals a fresh betting round: blinds posted, action to the seat after the big
// blind, which is where a dealer expects to be looking when the cards go out.
//
// Called when the dealer says the table is ready, not automatically when the
// previous hand ends — everything before this point is setup, where seats and the
// button can move freely because no money has been committed.
beginHand(state) {
state.bettingOpen = true;
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.
state.streetAggressorIndex = null;
state.handAggressorIndex = null;
// Deal around anyone with no chips, before anything else reads the table.
//
// A busted player who hasn't rebought used to be dealt in anyway, and the
// result was a hand nobody could finish: the table promised a small blind from
// a seat with nothing to post it with, took it from nobody, put the action on
// the big blind with only their own money in front of them, and announced
// "3 players — all-in, running out the board" before a card was dealt.
//
// Sitting them out is what a dealer does. Seat, name and buy-in record are
// untouched, so dealing them back in is one tap when they buy chips.
this.brokeSeats(state).forEach(index => {
state.seats[index].inHand = false;
state.seats[index].folded = false;
});
// Position is read off the button all through the hand, so it has to be on
// somebody before the blinds are worked out — not on the empty seat 1 a
// brand-new table starts on.
HoldemState.ensureButtonOnPlayer(state);
state.seats.forEach(player => {
player.committed = 0;
player.hasActed = false;
});
const sb = Number(state.smallBlind) || 0;
const bb = Number(state.bigBlind) || 0;
const { sbIndex, bbIndex, headsUp } = HoldemState.getBlindSeats(state);
// A null big blind means there aren't enough players to post at all. A null
// small blind with a big blind behind it is the dead small blind, which is a
// hand that gets dealt like any other — it just has one blind in it.
if (bbIndex === null) {
state.currentBet = 0;
state.actingSeatIndex = null;
state.postedBlinds = null;
state.postedStraddles = [];
return;
}
if (sb > 0 && sbIndex !== null) this.putIn(state, sbIndex, sb);
if (bb > 0) this.putIn(state, bbIndex, bb);
// Anyone the dealer said would post to come in past the blinds. It's a big
// blind like any other — it buys them a hand they'd otherwise have to wait for
// — so it goes in the middle the same way, before the count below reads it.
const posting = Array.isArray(state.postingIn) ? state.postingIn : [];
if (bb > 0) {
state.seats.forEach((player, index) => {
if (index === sbIndex || index === bbIndex) return;
if (player.inHand && posting.includes(player.id)) this.putIn(state, index, bb);
});
}
// Deliberately not cleared here. repostBlinds takes every posted chip back and
// deals again through this same function, so a post that cleared itself on the
// way in would be refunded and never retaken — the dealer moves the button and
// somebody's post quietly vanishes. startNextHand is what ends it.
// What the next hand's rotation is worked out from. Recorded here, where the
// blinds are actually posted, because by the time it's needed the seats have
// moved on and the answer can no longer be read off the table.
state.postedBlinds = { sbIndex, bbIndex };
// Who got cards. Read next hand to tell a player who has been here all along
// from one who has just walked up and had the blinds go past them.
state.dealtLastHand = state.seats.filter(p => p.inHand).map(p => p.id);
// Straddles go out after the blinds and before the cards, each one left of the
// last. Posted here rather than left to the dealer to fake as a raise, because
// a raise from that seat would hand the action to the wrong player.
const straddles = this.straddleSeats(state);
straddles.forEach(({ index, amount }) => this.putIn(state, index, amount));
state.postedStraddles = straddles.map(({ index }) => index);
state.currentBet = this.round(state.seats.reduce(
(most, player) => Math.max(most, this.committed(player)), 0));
// A straddle is a blind raise, so what has to be matched to raise again is the
// straddle itself, not the big blind underneath it: $2 blinds with a $4
// straddle make the next raise $8, the same way the $2 blind makes it $4.
// Left alone, the minimum would come out at $6 and the dealer would be talked
// out of it by every player at the table.
state.lastRaiseSize = straddles.length > 0 ? state.currentBet : (bb || 0);
// Heads-up the button is the small blind and acts first before the flop; with
// three or more it's the seat after the big blind. Either way, a blind big
// enough to put that player all-in leaves them nothing to decide.
//
// A straddle moves that seat along: first to act is left of the last straddler,
// and the straddler keeps the option, which falls out of nobody having acted
// yet.
const lastPosted = straddles.length > 0
? straddles[straddles.length - 1].index
: bbIndex;
state.actingSeatIndex = headsUp
? (this.stackOf(state, state.seats[sbIndex]) > this.EPSILON_CHIPS ? sbIndex : this.nextToAct(state, sbIndex))
: this.nextToAct(state, lastPosted);
},
// What a pot-sized raise actually is, as a "raise to" total.
//
// Not "the bet plus the pot as it stands". The raiser calls first, and their call
// is in the pot before the raise is measured off it, so the pot being matched is
// the one that exists after the call:
//
// raise to = the current bet + (pot + what they owe) × fraction
//
// Pre-flop at 1/2 that gives $7, not $5: call the $2, which makes the pot $5, then
// raise $5. Leaving the call out understates every one of these, and players say
// "pot" out loud meaning a definite number.
//
// Facing no bet this is a plain pot-sized bet — toCall is zero and currentBet is
// zero, so it comes out as the pot, which is the right answer there too.
// Rounded up to something the table's chips can actually build. Half the pot is
// constantly a half-chip amount — pre-flop at 1/2 it is $4.50, and the smallest
// chip in the default legend is a dollar, so the button offered a number the
// dealer would have to round themselves every single time.
//
// Only when the legend describes this game. A smallest chip *larger* than the big
// blind means the denominations were never set for these stakes, and rounding a
// 5c/10c table up to whole dollars would be the tool doing real damage on the
// strength of a field somebody forgot to fill in. Left exact there, and the wrong
// legend stays visible rather than being quietly applied.
potRaiseTo(state, index, fraction = 1) {
const player = state.seats[index];
if (!player) return 0;
const potAfterCall = this.round(this.potSoFar(state) + this.toCall(state, player));
const exact = this.round((state.currentBet || 0) + potAfterCall * fraction);
const step = Money.fromCents(Money.chipStepCents(state.chipLegend));
const bigBlind = Number(state.bigBlind) || 0;
if (step <= 0 || (bigBlind > 0 && step > bigBlind)) return exact;
return Money.upToChip(exact, state.chipLegend);
},
// Who turns their hand over first.
//
// A call the dealer makes at every showdown that isn't a fold, and one nobody at
// the table volunteers for — everyone would rather see a hand than show one. The
// tool knew who last raised and who sits left of the button and said neither, so
// the dealer was working it out from memory while five people waited.
//
// Three cases, in the order the rule asks them:
// * somebody bet or raised on the final round — they show first;
// * the round was checked through — first live player left of the button;
// * nobody could bet, because the chips were already in — the last player who
// did put money in, on whichever round that was.
//
// Returns null when there's nothing to call: one player left, or none.
showdownOrder(state) {
const live = this.liveSeats(state);
if (live.length < 2) return null;
const seatOf = index =>
Number.isInteger(index) && live.some(s => s.index === index) ? index : null;
const streetAggressor = seatOf(state.streetAggressorIndex);
if (streetAggressor !== null) {
return { index: streetAggressor, reason: "aggressor" };
}
// Nobody could have bet this round, so "no bet on the final round" isn't a
// choice anybody made and the seat left of the button hasn't earned the
// obligation. It falls to whoever last put money in.
if (!this.canStillBet(state)) {
const handAggressor = seatOf(state.handAggressorIndex);
if (handAggressor !== null) return { index: handAggressor, reason: "allInAggressor" };
}
const order = HoldemState.liveOrderFromButton(state)
.filter(index => live.some(s => s.index === index));
return order.length > 0 ? { index: order[0], reason: "leftOfButton" } : null;
},
// Winners get their share put back in front of them.
creditWinnings(state, payouts) {
payouts.forEach(payout => {
const player = state.seats.find(p => p.id === payout.id);
if (!player) return;
player.stack = this.round(this.stackOf(state, player) + payout.amount);
});
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = Betting;
}
@@ -1,207 +0,0 @@
// Tap a card instead of typing it.
//
// Typing "AH" into a two-character box is fine at a desk and miserable at a table:
// it needs a keyboard, it accepts nonsense like "ZZ", and it happily lets the same
// card land in two players' hands. The picker is one tap per card, greys out cards
// already dealt somewhere else at the table, and stores exactly the same two-character
// string the rest of the tool has always read.
const CardPicker = {
RANKS: ["A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"],
SUITS: [
{ code: "S", symbol: "♠", red: false },
{ code: "H", symbol: "♥", red: true },
{ code: "D", symbol: "♦", red: true },
{ code: "C", symbol: "♣", red: false },
],
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;
},
// Why the sheet is closing, because one caller needs to tell the difference.
//
// "filled" is the sheet finishing its own job — the last empty slot it was offering
// got a card. "dismissed" is the dealer leaving: Done, Escape, or a tap on the scrim.
// A single seat's cards don't care which. A showdown does: it walks the players one
// at a time, and the two answers are "next player" and "stop asking".
//
// The hooks are dropped before the callback runs, so a caller that opens the sheet
// again from inside `onDone` installs its own and this close can't fire twice.
close(reason = "dismissed") {
document.getElementById("cardPickerOverlay").hidden = true;
const done = this.hooks && this.hooks.onDone;
this.hooks = null;
if (done) done(reason);
},
// 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 (!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) {
this.write(this.cardIndex, card);
this.hooks.onPick(this.seatIndex, this.cardIndex, card);
// 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;
}
this.close("filled");
},
clearSlot() {
this.write(this.cardIndex, "");
this.hooks.onPick(this.seatIndex, this.cardIndex, "");
this.render();
},
// 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}`;
},
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 = "";
values.forEach((_, slot) => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pickerSlot";
btn.classList.toggle("active", slot === this.cardIndex);
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;
this.render();
});
slots.appendChild(btn);
});
const grid = document.getElementById("cardPickerGrid");
grid.innerHTML = "";
this.RANKS.forEach(rank => {
this.SUITS.forEach(suit => {
const card = `${rank}${suit.code}`;
const takenBy = used.get(card);
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pickerCard";
btn.classList.toggle("cardRed", suit.red);
btn.disabled = !!takenBy;
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");
}
const rankEl = document.createElement("span");
rankEl.className = "pickerRank";
rankEl.textContent = rank;
const suitEl = document.createElement("span");
suitEl.className = "pickerSuit";
suitEl.textContent = suit.symbol;
btn.appendChild(rankEl);
btn.appendChild(suitEl);
btn.addEventListener("click", () => this.assign(card));
grid.appendChild(btn);
});
});
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = CardPicker;
}
@@ -1,136 +0,0 @@
// Toasts and confirmation dialogs, so the table never has to fall back on the
// browser's own alert boxes. A system confirm() steals focus, looks nothing like
// the rest of the page, and on a phone it's a full-screen interruption — all of
// which is a bad trade for a dealer trying to keep a game moving.
// A short-lived message at the bottom of the screen, optionally with one action
// (in practice: Undo). Only one is ever on screen; a second replaces the first.
const Toast = {
DEFAULT_DURATION_MS: 8000,
timer: null,
show(message, options = {}) {
const host = document.getElementById("toastHost");
if (!host) return;
this.dismiss();
const toast = document.createElement("div");
toast.className = "toast";
toast.setAttribute("role", "status");
const text = document.createElement("span");
text.className = "toastText";
text.textContent = message;
toast.appendChild(text);
if (options.actionLabel && options.onAction) {
const action = document.createElement("button");
action.type = "button";
action.className = "toastAction";
action.textContent = options.actionLabel;
action.addEventListener("click", () => {
this.dismiss();
options.onAction();
});
toast.appendChild(action);
}
const close = document.createElement("button");
close.type = "button";
close.className = "toastClose";
close.setAttribute("aria-label", "Dismiss");
close.textContent = "✕";
close.addEventListener("click", () => this.dismiss());
toast.appendChild(close);
host.appendChild(toast);
// Next frame, so the entrance transition actually runs.
requestAnimationFrame(() => {
toast.classList.add("toastVisible");
this.publishHeight();
});
this.timer = setTimeout(
() => this.dismiss(),
options.duration || this.DEFAULT_DURATION_MS
);
},
dismiss() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
const host = document.getElementById("toastHost");
if (host) host.innerHTML = "";
this.publishHeight();
},
// How much of the bottom of the window this is standing on.
//
// The toast is fixed, so it is not in the flow and nothing scrolling a control into
// view knows it is there — measured on the desktop sweep, tabbing to Common rulings
// while a toast was up left the focus ring entirely behind it. The stylesheet adds
// this to the bar's own height to work out where a focused control has to stop, so
// it is published rather than guessed: the toast is one line or two depending on the
// message, and on a narrow screen the same message is taller again.
publishHeight() {
if (typeof document === "undefined" || !document.documentElement) return;
const host = document.getElementById("toastHost");
const height = host && host.firstElementChild
? Math.round(host.getBoundingClientRect().height)
: 0;
document.documentElement.style.setProperty("--toastHeight", `${height}px`);
},
};
// Styled stand-in for confirm(). Resolves true if the dealer goes through with it.
const Dialog = {
confirm({ title, message, confirmLabel = "Confirm", cancelLabel = "Cancel", danger = false }) {
return new Promise(resolve => {
const overlay = document.getElementById("confirmOverlay");
const modal = overlay.querySelector("#confirmModal");
overlay.querySelector("#confirmTitle").textContent = title;
overlay.querySelector("#confirmMessage").textContent = message;
const confirmBtn = overlay.querySelector("#confirmAcceptBtn");
const cancelBtn = overlay.querySelector("#confirmCancelBtn");
confirmBtn.textContent = confirmLabel;
cancelBtn.textContent = cancelLabel;
confirmBtn.classList.toggle("holdemBtnDanger", danger);
confirmBtn.classList.toggle("holdemBtnAccent", !danger);
const finish = result => {
overlay.hidden = true;
confirmBtn.removeEventListener("click", onAccept);
cancelBtn.removeEventListener("click", onCancel);
overlay.removeEventListener("click", onBackdrop);
document.removeEventListener("keydown", onKey);
resolve(result);
};
const onAccept = () => finish(true);
const onCancel = () => finish(false);
const onBackdrop = e => {
if (e.target === overlay) finish(false);
};
const onKey = e => {
if (e.key === "Escape") finish(false);
if (e.key === "Enter") finish(true);
};
confirmBtn.addEventListener("click", onAccept);
cancelBtn.addEventListener("click", onCancel);
overlay.addEventListener("click", onBackdrop);
document.addEventListener("keydown", onKey);
overlay.hidden = false;
modal.focus();
confirmBtn.focus();
});
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = { Toast, Dialog };
}
@@ -1,130 +0,0 @@
// Turns the in-memory hand history into a CSV file the dealer can download for a
// paper trail — a house manager or a disputed chip count needs something that
// outlives the browser tab, not just a scrollable panel in the sidebar.
const HandHistoryExport = {
csvField(value) {
const str = String(value ?? "");
return /[",\n]/.test(str) ? `"${str.replace(/"/g, '""')}"` : str;
},
formatTimestamp(timestamp) {
try {
return new Date(timestamp).toLocaleString();
} catch {
return "";
}
},
// Money columns go in as bare numbers. Written as "$1,250,000.00" they import as
// text, so the one thing anybody opens this file to do — total a column and see
// 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 = "" } = {}) {
// 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 || [])
.map(p => `${p.label}: ${Money.format(p.amount)}`)
.join("; ");
rows.push([
entry.handNumber,
this.formatTimestamp(entry.timestamp),
Money.forSheet(entry.pot),
Money.forSheet(entry.rake || 0),
payouts,
]);
});
// The settle-up numbers go in the same file as the hands they came from, so a
// dealer handing over one export isn't asked for a second one at cash-out.
if (standings.length > 0) {
rows.push([]);
rows.push(["Session Standings"]);
// Bought in and chips now are what a cash-out is settled from; paid in and
// won describe the hands. Both belong in the file the dealer hands over.
//
// Notes go last so the money columns keep the shape a spreadsheet expects.
// "IOU: $20 to Ann" is exactly the kind of thing that has to be in the file
// somebody settles up from, and it was only ever visible inside that seat's
// own editor.
rows.push(["Player", "Paid In", "Won", "Net", "Bought In", "Chips Now", "Up/Down", "Notes"]);
standings.forEach(row => {
rows.push([
// 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),
Money.forSheet(row.boughtIn || 0),
Money.forSheet(row.chipsNow || 0),
Money.forSheet(row.cashPosition || 0),
row.notes || "",
]);
});
// And the answer the standings are read to get to. Whoever opens this file
// wants the payment list, not to redo the arithmetic in a spreadsheet.
const plan = SettleUp.plan(standings);
if (plan.payments.length > 0) {
rows.push([]);
rows.push(["Settle Up"]);
rows.push(["Pays", "Receives", "Amount"]);
plan.payments.forEach(payment => {
rows.push([payment.from, payment.to, Money.forSheet(payment.amount)]);
});
if (!plan.balanced) {
// The file is the paper trail, so the caveat travels with it rather
// than living only in a sidebar nobody exported.
rows.push([
plan.shortBy > 0
? `Unpaid: ${Money.forSheet(plan.shortBy)} — more chips in play than cash taken`
: `Unclaimed: ${Money.forSheet(plan.overBy)} — more cash taken than chips in play`,
]);
}
}
}
// The table's own notes — side bets, IOUs, the promo running until midnight.
// The dealer typed them because they matter to the night, and the export is the
// thing that outlives the browser tab; leaving them behind meant the one place
// the context was written down was the one place it couldn't be handed over.
// csvField quotes the line breaks, so a multi-line note survives as one cell.
if (notes && notes.trim()) {
rows.push([]);
rows.push(["Table Notes"]);
rows.push([notes.trim()]);
}
return rows.map(row => row.map(f => this.csvField(f)).join(",")).join("\r\n");
},
fileName() {
const now = new Date();
const pad = n => String(n).padStart(2, "0");
const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
return `holdem-hand-history-${stamp}.csv`;
},
download(handHistory, standings = [], options = {}) {
const csv = this.toCsv(handHistory, standings, options);
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = this.fileName();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = HandHistoryExport;
}
@@ -1,285 +0,0 @@
// 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;
}
File diff suppressed because it is too large Load Diff
@@ -1,147 +0,0 @@
// Keyboard and screen-reader behaviour for every overlay in the tool, in one place.
//
// There are six of them — seat menu, card picker, add chips, rulings, pot wizard,
// confirm — opened and closed by five different modules, and each one was missing
// the same three things: focus never moved into the dialog, Tab walked straight out
// of it into the page behind the scrim, and Escape did nothing (only the rulings
// sheet handled it). Measured before this: 0 of 5 moved focus in, 5 of 5 leaked Tab,
// 1 of 5 closed on Escape.
//
// Rather than patch that into five modules, this watches the `hidden` attribute every
// overlay already toggles. Nothing else had to change, and an overlay added later
// gets the same behaviour without anyone remembering to wire it up — which is the
// failure this is fixing in the first place.
const Modal = {
// `:not([hidden])` matters — a sheet that is itself hidden inside an open overlay
// must not be a Tab stop.
FOCUSABLE: [
"a[href]",
"button:not([disabled])",
'input:not([disabled]):not([type="hidden"])',
"select:not([disabled])",
"textarea:not([disabled])",
'[tabindex]:not([tabindex="-1"])',
].join(","),
open: [],
mount() {
document.querySelectorAll('[id$="Overlay"]').forEach(overlay => this.watch(overlay));
// Capture phase: the dialog gets first refusal on Escape and Tab, before any
// table-level shortcut sees them.
document.addEventListener("keydown", e => this.onKeyDown(e), true);
},
watch(overlay) {
const sync = () => {
const isOpen = !overlay.hidden;
const known = this.open.some(entry => entry.overlay === overlay);
if (isOpen && !known) this.onOpened(overlay);
else if (!isOpen && known) this.onClosed(overlay);
};
new MutationObserver(sync).observe(overlay, { attributes: true, attributeFilter: ["hidden"] });
sync();
},
sheetOf(overlay) {
return overlay.querySelector('[role="dialog"], [role="alertdialog"]') || overlay.firstElementChild || overlay;
},
focusableIn(overlay) {
return [...overlay.querySelectorAll(this.FOCUSABLE)].filter(el => {
if (el.closest("[hidden]")) return false;
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
});
},
onOpened(overlay) {
const sheet = this.sheetOf(overlay);
// aria-modal is only true while the thing is actually open, so it's set here
// rather than baked into the markup.
if (sheet) sheet.setAttribute("aria-modal", "true");
this.open.push({ overlay, returnFocus: document.activeElement });
// Focus the first real control. A dialog that leaves focus on the button
// behind it reads, to a screen reader, as though nothing happened at all.
// Content-only sheets get focus on the sheet so the title is announced.
const focusable = this.focusableIn(overlay);
const target = focusable[0];
if (target) {
target.focus({ preventScroll: true });
} else if (sheet) {
if (!sheet.hasAttribute("tabindex")) sheet.setAttribute("tabindex", "-1");
sheet.focus({ preventScroll: true });
}
},
onClosed(overlay) {
const index = this.open.findIndex(entry => entry.overlay === overlay);
if (index === -1) return;
const [entry] = this.open.splice(index, 1);
const sheet = this.sheetOf(overlay);
if (sheet) sheet.removeAttribute("aria-modal");
// Put the dealer back where they were. Without this, closing the pot wizard
// drops focus to the top of the document and the next Tab starts from the
// page header.
const back = entry.returnFocus;
if (back && back.isConnected && typeof back.focus === "function") {
back.focus({ preventScroll: true });
}
},
topmost() {
return this.open.length ? this.open[this.open.length - 1] : null;
},
// Escape presses the dialog's own cancel/close button rather than just hiding the
// overlay, so whatever that button does — resolving the confirm promise, clearing
// the add-chips draft — still happens. Only if there isn't one does it hide the
// overlay directly.
dismiss(overlay) {
const closer = overlay.querySelector("[data-modal-close]");
if (closer) closer.click();
else overlay.hidden = true;
},
onKeyDown(event) {
const top = this.topmost();
if (!top) return;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
this.dismiss(top.overlay);
return;
}
if (event.key !== "Tab") return;
// Keep Tab inside the dialog. Everything behind the scrim is unreachable by
// mouse, so letting the keyboard wander back there is a trap with no way out.
const focusable = this.focusableIn(top.overlay);
if (focusable.length === 0) {
event.preventDefault();
return;
}
const first = focusable[0];
const last = focusable[focusable.length - 1];
const active = document.activeElement;
if (event.shiftKey && (active === first || !top.overlay.contains(active))) {
event.preventDefault();
last.focus({ preventScroll: true });
} else if (!event.shiftKey && (active === last || !top.overlay.contains(active))) {
event.preventDefault();
first.focus({ preventScroll: true });
}
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = Modal;
}
@@ -1,194 +0,0 @@
// Shared money handling for every casino surface. Kept apart from the table's
// rendering so the quick-split calculator can pull it in without dragging the whole
// seat/chip UI along with it.
//
// Everything the dealer touches is money, and money is decimal, so every module used
// to carry its own `Math.round(x * 100) / 100`. That's one rounding rule written out
// sixteen times in six files, which is sixteen chances for one of them to drift.
// It lives here now, and the modules that do arithmetic call these instead.
const Money = {
// Half a cent. Chip comparisons need a tolerance: a stack that lands on
// 0.0000000001 after a split is empty as far as a dealer is concerned, and an
// exact `> 0` would treat that player as still having chips to bet.
EPSILON: 0.004,
// All money maths goes through cents, so 0.1 + 0.2 never reaches a payout.
toCents(amount) {
return Math.round((Number(amount) || 0) * 100);
},
fromCents(cents) {
return cents / 100;
},
round(amount) {
return this.toCents(amount) / 100;
},
// Cents only when there are cents.
//
// A chip game deals in whole numbers nearly all the time, and a trailing ".00"
// is two characters that say nothing — measured at ~22px, against the 64px a
// seat puck has to show a stack in. "$1,250,000.00" doesn't fit and wraps;
// "$1,250,000" does. Amounts that genuinely carry cents still show them, so a
// 25c-blind game reads exactly as it did.
format(amount) {
const value = Number(amount) || 0;
const hasCents = this.toCents(value) % 100 !== 0;
return `$${value.toLocaleString(undefined, {
minimumFractionDigits: hasCents ? 2 : 0,
maximumFractionDigits: 2,
})}`;
},
// The same amount for a spreadsheet rather than for a person: no currency symbol
// and no thousands separators, because those are what make a column of money
// import as text and refuse to add up.
forSheet(amount) {
return (this.toCents(amount) / 100).toFixed(2);
},
// The chips to actually push, for an amount.
//
// A payout figure is the answer to the arithmetic, not to the dealer's job: they
// still have to work out that $132 is two blacks, a green, a red and two whites
// while six people watch. The chip legend already knows the denominations.
//
// Largest first, which is greedy and therefore not optimal for an arbitrary set of
// values — but poker chips are not arbitrary. Every real set is canonical (each
// denomination divides the next: 1, 5, 25, 100, 500), and greedy is exactly optimal
// on those. A dealer who invents a 3-and-7 chip set gets a valid answer that might
// use one chip more than it had to.
//
// Anything the smallest chip can't make comes back as `remainder` rather than being
// rounded away: a 50c share in a game whose smallest chip is a dollar is a real
// problem for the dealer to solve, not a rounding error to hide.
// The smallest chip the table has said it plays with, in cents. Zero when no
// denominations are set, which means the tool has been told nothing about what
// chips exist and shouldn't pretend otherwise.
chipStepCents(legend) {
const values = (legend || [])
.map(chip => this.toCents(chip.value))
.filter(cents => cents > 0);
return values.length > 0 ? Math.min(...values) : 0;
},
// Rounds an amount up to something the table can actually build out of its chips.
//
// Up rather than down or nearest: these are bet sizes, and a pot-sized bet that
// has been shaved is no longer a pot-sized bet. Rounding up also can't drop an
// amount below a legal minimum, which rounding the other way can.
upToChip(amount, legend) {
const step = this.chipStepCents(legend);
if (step <= 0) return this.round(amount);
const cents = this.toCents(amount);
if (cents <= 0) return this.round(amount);
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 };
const values = (legend || [])
.map(chip => ({ chip, cents: this.toCents(chip.value) }))
.filter(entry => entry.cents > 0)
.sort((a, b) => b.cents - a.cents);
const chips = [];
values.forEach(entry => {
const count = Math.floor(cents / entry.cents);
if (count <= 0) return;
cents -= count * entry.cents;
chips.push({ value: this.fromCents(entry.cents), count, color: entry.chip.color });
});
return { chips, remainder: this.fromCents(cents) };
},
// "2×$50, 1×$25, 2×$1" — the breakdown as a dealer would say it out loud.
//
// A table with no chip legend gets nothing rather than "$132 no chip covers": it
// hasn't told us its denominations, so there is no advice to give and the amount
// stands on its own. A legend that exists but can't reach the amount is different,
// and does say so.
formatChipBreakdown(amount, legend) {
const hasDenominations = (legend || []).some(chip => this.toCents(chip.value) > 0);
if (!hasDenominations) return "";
const { chips, remainder } = this.chipBreakdown(amount, legend);
if (chips.length === 0 && remainder === 0) return "";
const parts = chips.map(chip => `${chip.count}×${this.format(chip.value)}`);
if (remainder > 0) parts.push(`${this.format(remainder)} no chip covers`);
return parts.join(", ");
},
// Should focusing this field select what's already in it?
//
// Every amount box in this tool opens pre-filled with a suggestion: the raise pad
// offers the minimum, Add chips offers a buy-in, the seat editor offers the stack
// it already has. A dealer taps the box because they want a *different* number,
// and a tap puts the caret after the suggestion instead of over it. Measured on a
// phone: the raise pad showing 4, tap, type "60" — the field reads 460. Add chips
// showing 200, tap, type "50" — 20050.
//
// Only number boxes. A name or a note is a thing you edit, and selecting all of
// it on focus would be the same mistake pointing the other way.
selectsOnFocus(field) {
if (!field || field.tagName !== "INPUT") return false;
const type = String(field.type || "").toLowerCase();
if (type === "number") return true;
return type === "text" && String(field.inputMode || "").toLowerCase() === "decimal";
},
// Would a wheel over this field change what it says?
//
// True only for a focused `<input type="number">`, which a browser treats as a
// spinbutton and lets the wheel drive. Every other way of driving one is deliberate
// — the arrow keys, the stepper arrows, typing — and all of them are left alone.
// Scrolling is the one nobody means: the dealer is reaching for another panel and
// the cursor happens to still be over a field they touched a moment ago.
//
// A predicate rather than a listener so the rule can be tested without a browser,
// the same way selectsOnFocus is. main.js does the blurring.
wheelWouldEdit(field, activeElement) {
// The tag check is belt and braces and known to be so: nothing but an <input>
// carries type="number", so the line below already excludes every textarea,
// select and button on the page. Deleting it passes every test in this file,
// which was checked rather than assumed. It stays for symmetry with
// selectsOnFocus above, not because it is load-bearing.
if (!field || field.tagName !== "INPUT") return false;
if (String(field.type || "").toLowerCase() !== "number") return false;
// An unfocused spinbutton ignores the wheel, so there is nothing to defend and
// blurring something that isn't focused would be a no-op with a side effect.
return activeElement === field;
},
// "+$40.00" / "-$40.00" rather than "$-40.00" — a standings column is read at a
// glance, and the sign belongs out front where the eye lands first.
formatSigned(amount) {
const value = Number(amount) || 0;
if (value > 0) return `+${this.format(value)}`;
if (value < 0) return `-${this.format(Math.abs(value))}`;
return this.format(0);
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = Money;
}
@@ -1,173 +0,0 @@
// Pure side-pot math. No DOM, no globals besides the PotCalculator namespace, so the
// dealer's payout logic can be reasoned about (and unit tested) on its own.
//
// A "contribution entry" is { id, remaining, folded }. `remaining` starts as the amount
// that player put in the pot and is whittled down round by round as money gets paid out.
const PotCalculator = {
EPSILON: Money.EPSILON,
// Builds the initial entry list from raw contributions, keeping folded players in
// (their chips are still "dead money" owed to whoever wins) while excluding anyone
// who put in nothing at all.
buildEntries(players) {
return players
.filter(p => p.contribution > this.EPSILON)
.map(p => ({ id: p.id, remaining: p.contribution, folded: !!p.folded }));
},
totalPot(entries) {
return entries.reduce((sum, e) => sum + e.remaining, 0);
},
// Players still eligible to be picked as a winner for the money that's left.
getContenders(entries) {
return entries.filter(e => !e.folded && e.remaining > this.EPSILON);
},
// Splits the money on the table into the main pot and any side pots, with who can
// win each. Read-only — this is what a dealer says out loud before the showdown
// ("main pot four-eighty, side pot ninety between seats 3 and 5"), which is the
// announcement that goes missing far more often than the arithmetic goes wrong.
//
// Every distinct all-in amount opens a new layer: each player pays into a layer up
// to their own contribution, and only players who reached that height can win it.
// Folded money stays in — it's dead money owed to whoever wins the layer it fell in.
layers(players) {
// Uncalled chips were never played for, so they come off the top before any
// pot is built. Deriving the pots from what's left is what keeps this function
// and uncalledReturns() from disagreeing about the same money — they used to
// decide "uncontested" separately, and an overbet that its own bettor was
// still live for got announced as a side pot only they could win.
const returned = new Map(this.uncalledReturns(players).map(r => [r.id, Money.toCents(r.amount)]));
const live = players
.map(p => ({ ...p, cents: Money.toCents(p.contribution) - (returned.get(p.id) || 0) }))
.filter(p => p.cents > 0);
if (live.length === 0) return [];
const heights = [...new Set(live.map(p => p.cents))].sort((a, b) => a - b);
const layers = [];
let floor = 0;
heights.forEach(height => {
const band = height - floor;
const payers = live.filter(p => p.cents >= height);
const amount = band * payers.length;
const eligible = payers.filter(p => !p.folded).map(p => p.id);
if (amount > 0) {
if (eligible.length > 0) {
layers.push({ amount: Money.fromCents(amount), eligible });
} else if (layers.length > 0) {
// Everyone who reached this height folded, so it isn't a pot of its
// own — it's dead money owed to whoever wins the layer underneath.
// Dropping it would quietly shrink the announced pot.
const below = layers[layers.length - 1];
below.amount = Money.round(below.amount + Money.fromCents(amount));
}
// With no layer underneath either, nobody in the hand is live at all.
// That's a fold flag the dealer needs to fix, not a payout to guess at.
}
floor = height;
});
// Consecutive layers with the same set of eligible players are one pot to a
// dealer — nobody announces two side pots between the same two people.
const merged = [];
layers.forEach(layer => {
const previous = merged[merged.length - 1];
const sameEligibility =
previous &&
previous.eligible.length === layer.eligible.length &&
previous.eligible.every(id => layer.eligible.includes(id));
if (sameEligibility) {
previous.amount = Money.round(previous.amount + layer.amount);
} else {
merged.push({ ...layer });
}
});
return merged.map((layer, index) => ({
...layer,
label: index === 0 ? "Main pot" : `Side pot ${index}`,
}));
},
// Chips nobody could call, which the dealer pushes back rather than into the pot.
//
// A bet is only called up to what somebody *else* was willing to put in, so the
// ceiling for each player is the largest contribution among everyone but them.
// Measuring against the whole table instead — including the bettor's own chips —
// makes the biggest bet its own yardstick, so the one case this exists for (you
// shove, a short stack calls for less) comes back empty.
uncalledReturns(players) {
const contributing = players.filter(p => p.contribution > this.EPSILON);
// Nobody live at all means the fold flags are wrong, not that every chip on
// the table was uncalled. That's a correction for the dealer to make, so say
// nothing here and let the wizard ask them to fix it.
if (contributing.filter(p => !p.folded).length === 0) return [];
const cents = contributing.map(p => Money.toCents(p.contribution));
return contributing
.map((p, index) => {
const others = cents.filter((_, i) => i !== index);
const cap = others.length > 0 ? Math.max(...others) : 0;
return { id: p.id, amount: Money.fromCents(cents[index] - cap) };
})
.filter(r => r.amount > this.EPSILON);
},
// Awards the current pot layer to `winnerIds` (one id, or several for a split/tie).
// The payout is capped at the smallest remaining contribution among the winners —
// that's the classic side-pot rule: an all-in player can only win what everyone at
// the table matched, and the excess rolls forward to the next round.
resolveRound(entries, winnerIds) {
const winners = entries.filter(e => winnerIds.includes(e.id) && e.remaining > this.EPSILON);
if (winners.length === 0) {
throw new Error("No valid winners selected for this round.");
}
const cap = Math.min(...winners.map(w => w.remaining));
let payoutPool = 0;
const updatedEntries = entries.map(e => {
if (e.remaining <= this.EPSILON) return e;
const used = Math.min(e.remaining, cap);
payoutPool += used;
return { ...e, remaining: Money.round(e.remaining - used) };
});
payoutPool = Money.round(payoutPool);
const baseShareCents = Math.floor(Money.toCents(payoutPool) / winners.length);
let leftoverCents = Money.toCents(payoutPool) - baseShareCents * winners.length;
const perWinner = winnerIds
.filter(id => winners.some(w => w.id === id))
.map(id => ({ id, amountCents: baseShareCents }));
// Odd cents (can't split evenly) go one at a time to the winners, in the order
// they were selected, so nothing is ever lost to rounding.
let i = 0;
while (leftoverCents > 0 && perWinner.length > 0) {
perWinner[i % perWinner.length].amountCents += 1;
leftoverCents--;
i++;
}
const result = perWinner.map(w => ({ id: w.id, amount: Money.fromCents(w.amountCents) }));
const remainingContenders = this.getContenders(updatedEntries);
return {
payoutPool,
capApplied: cap,
perWinner: result,
updatedEntries,
remainingContenders,
};
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = PotCalculator;
}
@@ -1,498 +0,0 @@
// Walks the dealer through awarding the pot: "who won?", and if that player was
// all-in for less than everyone else, "who's next?" — repeating until every dollar
// in the pot has been assigned. Built on PotCalculator's pure round-resolution math.
const PotWizard = {
state: null,
onFinished: null,
entries: [],
playerLabelById: new Map(),
log: [],
open(state, onFinished) {
this.state = state;
this.onFinished = onFinished;
const players = state.seats.filter(
p => HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount) > 0
);
this.playerLabelById = new Map(
players.map(p => [p.id, this.labelFor(p, state.seats.indexOf(p))])
);
this.seatIndexById = new Map(players.map(p => [p.id, state.seats.indexOf(p)]));
// The label carries name and cards together for the log and the payout lines;
// the choice rows want them separately so each can be styled and read on its own.
this.nameById = new Map(
players.map(p => [p.id, HoldemState.displayName(p, state.seats.indexOf(p))])
);
this.cardsById = new Map(
players.map(p => [p.id, (p.cards || []).filter(Boolean)])
);
const contributions = players.map(p => ({
id: p.id,
contribution: HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount),
// A seat switched off mid-hand still has its chips in the pot, but it
// can no more win them than a folded one can — same dead money, and the
// wizard must not offer it as a winner.
folded: p.folded || HoldemState.isDeadMoney(p),
}));
this.entries = PotCalculator.buildEntries(contributions);
// Kept so the wizard can show the whole breakdown up front, not just the layer
// it happens to be asking about.
this.layers = PotCalculator.layers(contributions);
this.returns = PotCalculator.uncalledReturns(contributions);
this.log = [];
this.totals = new Map();
document.getElementById("potWizardOverlay").hidden = false;
this.renderStep();
},
close() {
document.getElementById("potWizardOverlay").hidden = true;
},
labelFor(player, seatIndex) {
const name = HoldemState.displayName(player, seatIndex);
const cards = (player.cards || []).filter(Boolean).map(c => Render.formatCard(c)).join(" ");
return cards ? `${name} (${cards})` : name;
},
addToTotal(id, amount) {
this.totals.set(id, (this.totals.get(id) || 0) + amount);
},
// A chopped pot rarely divides exactly, and the odd chip goes to the first player
// left of the button — not to whoever the dealer happened to tick first. The
// calculator hands leftovers out in the order it's given the winners, so ordering
// them here is what makes the payout match the rule.
orderFromButton(ids) {
const distance = new Map();
for (let step = 1; step <= this.state.seatCount; step++) {
distance.set(HoldemState.nextSeatIndex(this.state, this.state.dealerSeatIndex, step), step);
}
return [...ids].sort((a, b) =>
(distance.get(this.seatIndexById.get(a)) ?? 0) - (distance.get(this.seatIndexById.get(b)) ?? 0)
);
},
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) {
const result = PotCalculator.resolveRound(this.entries, [contenders[0].id]);
this.recordRound(result);
this.entries = result.updatedEntries;
contenders = PotCalculator.getContenders(this.entries);
}
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());
const remaining = PotCalculator.totalPot(this.entries.filter(e => e.remaining > PotCalculator.EPSILON));
if (contenders.length === 0 && remaining > PotCalculator.EPSILON) {
const warning = document.createElement("p");
warning.className = "potWizardPrompt";
// Money left over because nobody could call it isn't a pot anyone won —
// it goes back to whoever put it in. Telling the dealer to un-fold someone
// to "win" it would be wrong.
const returned = (this.returns || []).reduce((sum, r) => sum + r.amount, 0);
if (Math.abs(returned - remaining) <= PotCalculator.EPSILON && returned > 0) {
const who = this.returns.map(r => this.playerLabelById.get(r.id)).join(", ");
warning.textContent = `${Money.format(remaining)} was never called — push it back to ${who} rather than paying it out.`;
} else {
warning.textContent = `${Money.format(remaining)} is still unassigned, but every remaining player is marked Folded. Uncheck Fold on whoever should win it.`;
}
body.appendChild(warning);
body.appendChild(this.renderSummary());
return;
}
if (contenders.length === 0 || remaining <= PotCalculator.EPSILON) {
body.appendChild(this.renderSummary());
return;
}
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 = 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 => {
const label = document.createElement("label");
label.className = "potWizardChoice";
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);
});
label.appendChild(checkbox);
const text = document.createElement("span");
text.className = "potWizardChoiceText";
const name = document.createElement("span");
name.className = "potWizardChoiceName";
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)}`;
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.
const cards = this.cardsById.get(c.id) || [];
if (cards.length > 0) {
const cardsEl = document.createElement("span");
cardsEl.className = "potWizardChoiceCards";
cards.forEach((card, i) => {
if (i > 0) cardsEl.appendChild(document.createTextNode(" "));
const span = document.createElement("span");
if (/[HD]$/i.test(card)) span.className = "cardRed";
span.textContent = Render.formatCard(card);
cardsEl.appendChild(span);
});
label.appendChild(cardsEl);
}
choices.appendChild(label);
});
round.appendChild(choices);
const hint = document.createElement("p");
hint.className = "fieldHint";
hint.textContent = "Check more than one to split the pot on a tie.";
round.appendChild(hint);
const confirmBtn = document.createElement("button");
confirmBtn.className = "holdemBtn holdemBtnAccent";
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;
const result = PotCalculator.resolveRound(this.entries, this.orderFromButton(selected));
this.recordRound(result);
this.entries = result.updatedEntries;
this.renderStep();
});
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) {
result.perWinner.forEach(w => this.addToTotal(w.id, w.amount));
this.log.push({
amount: result.payoutPool,
winners: result.perWinner.map(w => `${this.playerLabelById.get(w.id)} (${Money.format(w.amount)})`),
});
},
// The announcement, spelled out before anyone is asked to pick a winner: what the
// main pot is worth, what each side pot is worth, and who can win each.
renderBreakdown() {
const node = Render.buildPotBreakdown(
this.layers || [],
this.returns || [],
id => this.playerLabelById.get(id),
"Announce before the showdown"
);
if (!node) return document.createDocumentFragment();
node.classList.add("potBreakdownWizard");
return node;
},
renderLog() {
const wrap = document.createElement("div");
wrap.className = "potWizardLog";
if (this.log.length === 0) return wrap;
this.log.forEach((entry, idx) => {
const line = document.createElement("p");
line.className = "potWizardLogLine";
line.textContent = `Pot ${idx + 1}: ${Money.format(entry.amount)} → ${entry.winners.join(", ")}`;
wrap.appendChild(line);
});
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";
const heading = document.createElement("h3");
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";
empty.textContent = "Nobody has money in this pot yet — mark seats \"In hand\" and set contributions first.";
wrap.appendChild(empty);
} else {
const legend = (this.state && this.state.chipLegend) || [];
const list = document.createElement("ul");
for (const { id, amount } of split.payouts) {
const li = document.createElement("li");
li.textContent = `${this.playerLabelById.get(id)} — ${Money.format(amount)}`;
// The amount is the answer to the arithmetic; the chips are the answer
// to the dealer's job. Only when the legend has been filled in — a
// table that never set up chip colours gets the number on its own,
// which is what it had before.
const chips = Money.formatChipBreakdown(amount, legend);
if (chips) {
const note = document.createElement("span");
note.className = "payoutChips";
note.textContent = chips;
li.appendChild(note);
}
list.appendChild(li);
}
wrap.appendChild(list);
}
const actions = document.createElement("div");
actions.className = "potWizardActions";
const applyBtn = document.createElement("button");
applyBtn.className = "holdemBtn holdemBtnAccent";
applyBtn.textContent = "Start Next Hand";
applyBtn.addEventListener("click", () => {
// 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(paid.payouts, { rake: paid.rake, pot: paid.pot });
});
actions.appendChild(applyBtn);
// This button cancels — it does not pay anybody. Under a heading reading
// "Final Payouts" with an amount beside a name, "Close" reads like dismissing
// something already done, and a dealer who taps it walks away believing the
// pot has been pushed. It hasn't: the chips are still in the middle and the
// hand isn't logged. So it says what it does.
const cancelBtn = document.createElement("button");
cancelBtn.className = "holdemBtn holdemBtnGhost";
cancelBtn.textContent = "Cancel — don't pay yet";
cancelBtn.addEventListener("click", () => this.close());
actions.appendChild(cancelBtn);
if (this.totals.size > 0) {
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(note);
}
this.footer().appendChild(actions);
return wrap;
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = PotWizard;
}
@@ -1,371 +0,0 @@
// The quick-split screen: pot in, payout out, nothing to set up and nothing saved.
// A dealer opens this one-handed with players waiting, so every control is a tap and
// the answer updates as they type rather than behind a "calculate" button.
const QuickSplit = {
WAY_CHOICES: [2, 3, 4, 5],
CHIP_CHOICES: [
{ value: 0.01, label: "1¢" },
{ value: 0.25, label: "25¢" },
{ value: 1, label: "$1" },
{ value: 5, label: "$5" },
{ value: 25, label: "$25" },
],
MAX_WAYS: 12,
ways: 2,
chip: 1,
// "even" is the common case — one pot, everyone matched. "uneven" is the one this
// screen used to send people back to the full table for: somebody all-in for less,
// so the money splits into a main pot and side pots.
mode: "even",
entries: [],
mount() {
this.potInput = document.getElementById("potInput");
this.clearPotBtn = document.getElementById("clearPotBtn");
this.entries = [{ amount: "", folded: false }, { amount: "", folded: false }, { amount: "", folded: false }];
this.renderWayChoices();
this.renderChipChoices();
this.renderUnevenRows();
document.getElementById("modeEvenBtn").addEventListener("click", () => this.setMode("even"));
document.getElementById("modeUnevenBtn").addEventListener("click", () => this.setMode("uneven"));
document.getElementById("addPlayerBtn").addEventListener("click", () => {
this.entries.push({ amount: "", folded: false });
this.renderUnevenRows();
this.update();
});
this.potInput.addEventListener("input", () => {
this.sanitizePotInput();
this.update();
});
this.clearPotBtn.addEventListener("click", () => {
this.potInput.value = "";
this.potInput.focus();
this.update();
});
document.getElementById("resetSplitBtn").addEventListener("click", () => {
this.potInput.value = "";
this.ways = 2;
this.chip = 1;
this.renderWayChoices();
this.renderChipChoices();
this.potInput.focus();
this.update();
});
this.update();
},
// Keeps the field to something parseable without fighting the typist: digits and a
// single decimal point, at most two places.
sanitizePotInput() {
const cleaned = this.potInput.value
.replace(/[^0-9.]/g, "")
.replace(/(\..*)\./g, "$1")
.replace(/(\.\d\d)\d+/, "$1");
if (cleaned !== this.potInput.value) this.potInput.value = cleaned;
},
makeChoiceButton(label, isSelected, onPick) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "choiceChip";
btn.textContent = label;
btn.setAttribute("aria-pressed", String(isSelected));
btn.classList.toggle("selected", isSelected);
btn.addEventListener("click", onPick);
return btn;
},
renderWayChoices() {
const row = document.getElementById("waysChoices");
row.innerHTML = "";
this.WAY_CHOICES.forEach(count => {
row.appendChild(
this.makeChoiceButton(String(count), this.ways === count, () => {
this.ways = count;
this.renderWayChoices();
this.update();
})
);
});
// Beyond a five-way chop it's rare enough to hide behind a stepper rather than
// spend a row of buttons on it.
const more = document.createElement("div");
more.className = "waysStepper";
const minus = this.makeStepButton("−", () => this.stepWays(-1));
const plus = this.makeStepButton("+", () => this.stepWays(1));
const readout = document.createElement("span");
readout.className = "waysReadout";
readout.textContent = `${this.ways} ways`;
more.appendChild(minus);
more.appendChild(readout);
more.appendChild(plus);
row.appendChild(more);
},
makeStepButton(label, onPick) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "stepBtn";
btn.textContent = label;
btn.addEventListener("click", onPick);
return btn;
},
stepWays(delta) {
this.ways = Math.max(2, Math.min(this.MAX_WAYS, this.ways + delta));
this.renderWayChoices();
this.update();
},
renderChipChoices() {
const row = document.getElementById("chipChoices");
row.innerHTML = "";
this.CHIP_CHOICES.forEach(choice => {
row.appendChild(
this.makeChoiceButton(choice.label, this.chip === choice.value, () => {
this.chip = choice.value;
this.renderChipChoices();
this.update();
})
);
});
},
setMode(mode) {
this.mode = mode;
document.getElementById("modeEvenBtn").classList.toggle("selected", mode === "even");
document.getElementById("modeUnevenBtn").classList.toggle("selected", mode === "uneven");
document.querySelectorAll(".evenOnly").forEach(el => { el.hidden = mode !== "even"; });
document.querySelectorAll(".unevenOnly").forEach(el => { el.hidden = mode !== "uneven"; });
document.getElementById("splitResult").hidden = mode !== "even";
document.getElementById("unevenResult").hidden = mode !== "uneven";
this.update();
},
renderUnevenRows() {
const host = document.getElementById("unevenRows");
const template = document.getElementById("unevenRowTemplate");
host.innerHTML = "";
this.entries.forEach((entry, index) => {
const row = template.content.firstElementChild.cloneNode(true);
row.querySelector(".unevenRowLabel").textContent = `P${index + 1}`;
const amount = row.querySelector(".unevenAmount");
amount.value = entry.amount;
amount.setAttribute("aria-label", `Player ${index + 1} amount`);
amount.addEventListener("input", () => {
entry.amount = amount.value.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
if (entry.amount !== amount.value) amount.value = entry.amount;
this.update();
});
// Folded money stays in the pot as dead money, but its owner can't win any
// of it — which is exactly the distinction that makes side pots tricky.
const fold = row.querySelector(".unevenFoldBtn");
fold.classList.toggle("selected", entry.folded);
fold.setAttribute("aria-pressed", String(entry.folded));
fold.addEventListener("click", () => {
entry.folded = !entry.folded;
this.renderUnevenRows();
this.update();
});
const remove = row.querySelector(".unevenRemoveBtn");
remove.disabled = this.entries.length <= 2;
remove.addEventListener("click", () => {
this.entries.splice(index, 1);
this.renderUnevenRows();
this.update();
});
host.appendChild(row);
});
},
// Chopping one of the pots listed above, without leaving the screen that worked it
// out. Starts closed and at as many ways as there are players who can win the pot,
// which is the common case; the stepper covers a chop between fewer of them, which
// is the other one.
//
// The per-pot ways live on the row rather than in `this.ways`, so opening a chop on
// the main pot doesn't change what the side pot below it is saying.
addChopControl(row, amount, contenderCount) {
let ways = contenderCount;
let open = false;
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "unevenChopToggle";
const detail = document.createElement("div");
detail.className = "unevenChopDetail";
detail.hidden = true;
const draw = () => {
toggle.textContent = open ? "Hide chop" : "Chop";
toggle.setAttribute("aria-expanded", String(open));
detail.hidden = !open;
if (!open) return;
const result = SplitCalculator.split(amount, ways, this.chip);
detail.innerHTML = "";
const stepper = document.createElement("div");
stepper.className = "unevenChopWays";
stepper.appendChild(this.makeStepButton("−", () => {
if (ways > 2) { ways -= 1; draw(); }
}));
const label = document.createElement("span");
label.className = "unevenChopWaysLabel";
label.textContent = `${ways} ways`;
stepper.appendChild(label);
stepper.appendChild(this.makeStepButton("+", () => {
if (ways < Math.max(contenderCount, this.MAX_WAYS)) { ways += 1; draw(); }
}));
detail.appendChild(stepper);
const each = document.createElement("p");
each.className = "unevenChopEach";
each.textContent = `${Money.format(result.each)} each`;
detail.appendChild(each);
// Same wording as the main split, because it is the same rule and a dealer
// shouldn't have to notice they're reading a different screen.
if (result.valid && result.oddChips > 0) {
const odd = document.createElement("p");
odd.className = "unevenChopNote";
odd.textContent = result.oddChips === 1
? `plus one odd ${Money.format(result.chip)} chip to the first player left of the button`
: `plus ${result.oddChips} odd ${Money.format(result.chip)} chips — one each to the ` +
`first ${result.oddChips} players left of the button`;
detail.appendChild(odd);
}
if (result.valid && result.dust > 0) {
const dust = document.createElement("p");
dust.className = "unevenChopNote unevenChopDust";
dust.textContent =
`${Money.format(result.dust)} doesn't divide into ${Money.format(result.chip)} chips — ` +
`pick a smaller denomination.`;
detail.appendChild(dust);
}
};
toggle.addEventListener("click", () => { open = !open; draw(); });
draw();
row.appendChild(toggle);
row.appendChild(detail);
},
updateUneven() {
const players = this.entries
.map((entry, index) => ({ id: `P${index + 1}`, contribution: Number(entry.amount) || 0, folded: entry.folded }))
.filter(p => p.contribution > 0);
const pots = PotCalculator.layers(players);
const returns = PotCalculator.uncalledReturns(players);
const host = document.getElementById("unevenPots");
const empty = document.getElementById("unevenEmpty");
host.innerHTML = "";
if (pots.length === 0 && returns.length === 0) {
empty.hidden = false;
empty.textContent = players.length === 0
? "Enter what each player put in."
: "Nobody left who can win — un-fold whoever should take it.";
return;
}
empty.hidden = true;
const addRow = (label, amount, who, className, chopWays) => {
const row = document.createElement("div");
row.className = `unevenPot ${className || ""}`;
const name = document.createElement("span");
name.className = "unevenPotLabel";
name.textContent = label;
const value = document.createElement("span");
value.className = "unevenPotAmount";
value.textContent = Money.format(amount);
const eligible = document.createElement("span");
eligible.className = "unevenPotWho";
eligible.textContent = who;
row.appendChild(name);
row.appendChild(value);
row.appendChild(eligible);
host.appendChild(row);
// Two players tying for a side pot is ordinary, and working out each one's
// share meant copying the amount into the other mode by hand — retyping a
// number the screen had just worked out, which is a transcription error
// waiting to happen with money on it. The chop happens here instead.
//
// Only offered where it means something: a pot with at least two people
// who can win it. Not the uncalled row, which goes back to one player, and
// not the total.
if (chopWays >= 2) this.addChopControl(row, amount, chopWays);
};
pots.forEach(pot => addRow(pot.label, pot.amount, pot.eligible.join(", "), "", pot.eligible.length));
returns.forEach(ret => addRow("Uncalled", ret.amount, `back to ${ret.id}`, "unevenPotReturn"));
const total = players.reduce((sum, p) => sum + p.contribution, 0);
addRow("On the table", Money.round(total), "", "unevenPotTotal");
},
update() {
if (this.mode === "uneven") {
this.updateUneven();
return;
}
const potValue = Number(this.potInput.value);
const pot = Number.isNaN(potValue) ? 0 : potValue;
this.clearPotBtn.hidden = this.potInput.value === "";
const result = SplitCalculator.split(pot, this.ways, this.chip);
document.getElementById("splitResultLabel").textContent =
`Each of ${result.players} players gets`;
document.getElementById("splitResultAmount").textContent = Money.format(result.each);
const oddNote = document.getElementById("splitOddNote");
if (result.valid && result.oddChips > 0) {
oddNote.textContent = result.oddChips === 1
? `plus one odd ${Money.format(result.chip)} chip to the first player left of the button`
: `plus ${result.oddChips} odd ${Money.format(result.chip)} chips — one each to the ` +
`first ${result.oddChips} players left of the button`;
oddNote.hidden = false;
} else {
oddNote.hidden = true;
}
const dustNote = document.getElementById("splitDustNote");
if (result.valid && result.dust > 0) {
dustNote.textContent =
`${Money.format(result.dust)} doesn't divide into ${Money.format(result.chip)} chips — ` +
`pick a smaller denomination.`;
dustNote.hidden = false;
} else {
dustNote.hidden = true;
}
document.getElementById("splitResult").classList.toggle("hasAmount", result.valid && result.each > 0);
},
};
document.addEventListener("DOMContentLoaded", () => QuickSplit.mount());
File diff suppressed because it is too large Load Diff
@@ -1,178 +0,0 @@
// The long-press menu on a seat. Everything a dealer does to one player mid-hand,
// one press and one tap away, without opening the full editor and without hunting
// for whose turn it is in the action bar.
const SeatMenu = {
state: null,
hooks: null,
seatIndex: null,
mode: null,
open(state, hooks, seatIndex) {
this.state = state;
this.hooks = hooks;
this.seatIndex = seatIndex;
// Always the action list, never whatever the sheet was showing when it last
// closed — a seat menu that opens on a list of chairs is a menu that lost the
// dealer's place.
this.mode = null;
this.render();
document.getElementById("seatMenuOverlay").hidden = false;
},
close() {
document.getElementById("seatMenuOverlay").hidden = true;
},
// Only the actions that make sense for this seat right now — a folded player has
// nothing to go all-in with, and an empty chair has nothing to fold.
actionsFor(player, index) {
const actions = [];
const dealtIn = player.inHand;
const live = dealtIn && !player.folded;
if (live) {
actions.push({ label: "Fold", className: "menuDanger", run: () => this.hooks.fold(index) });
actions.push({ label: "All-in", className: "menuAccent", run: () => this.hooks.allIn(index) });
} else if (dealtIn && player.folded) {
actions.push({ label: "Un-fold", run: () => this.hooks.unfold(index) });
}
// The most common interruption in a cash game, and until now it meant opening
// the editor and retyping a stack from memory.
actions.push({ label: "Add chips…", run: () => this.hooks.addChips(index) });
actions.push({
label: dealtIn ? "Sit out" : "Deal in",
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) });
}
// Naming a blind by hand. Only offered while nothing but the blinds are in —
// once somebody has called, moving a blind would mean unpicking a bet that
// has already been answered, and that's a decision for the dealer's mouth,
// not a menu item. Which blind a seat already has is shown rather than
// offered again.
if (dealtIn && Betting.onlyBlindsIn(this.state)) {
const blinds = HoldemState.getBlindSeats(this.state);
if (blinds.sbIndex !== index) {
actions.push({ label: "Make small blind", run: () => this.hooks.assignBlind(index, "sb") });
}
if (blinds.bbIndex !== index) {
actions.push({ label: "Make big blind", run: () => this.hooks.assignBlind(index, "bb") });
}
if (this.state.blindOverride) {
actions.push({ label: "Blinds follow the button again", run: () => this.hooks.clearBlindOverride() });
}
}
// Changing chairs was drag-and-drop only, and HTML5 drag events are never
// generated from a touch screen — so on the device this tool is mostly used on,
// the "drag to swap seats" the hint advertised did nothing at all. This is the
// same move, by the route a thumb can actually take.
if (this.state.seats.length > 1) {
actions.push({ label: "Move to…", run: () => this.openMovePicker() });
}
actions.push({ label: "Edit seat…", run: () => this.hooks.editSeat(index) });
return actions;
},
// The chairs this player could move to. Every other chair: swapping into an empty
// one is how a player moves, and swapping with an occupied one is two players
// changing places, which is the other half of the same job.
destinationsFor(index) {
return this.state.seats
.map((player, seat) => ({ player, seat }))
.filter(entry => entry.seat !== index);
},
openMovePicker() {
this.mode = "move";
this.render();
},
render() {
const player = this.state.seats[this.seatIndex];
const title = document.getElementById("seatMenuTitle");
const subtitle = document.getElementById("seatMenuSubtitle");
const list = document.getElementById("seatMenuActions");
list.innerHTML = "";
if (this.mode === "move") {
title.textContent = `Move ${HoldemState.displayName(player, this.seatIndex)} to…`;
subtitle.textContent = "Their chips, cards and bet go with them. The button and the blinds stay on the chair.";
this.destinationsFor(this.seatIndex).forEach(({ player: other, seat }) => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "seatMenuBtn";
// displayName falls back to "Seat 5" for a chair with nobody in it,
// which reads as "Seat 5 — Seat 5". An empty chair says it's empty.
const named = (other.name || "").trim();
btn.textContent = named ? `Seat ${seat + 1} — ${named}` : `Seat ${seat + 1} — empty`;
btn.addEventListener("click", () => {
const from = this.seatIndex;
this.close();
this.hooks.swapSeats(from, seat);
});
list.appendChild(btn);
});
return;
}
title.textContent = HoldemState.displayName(player, this.seatIndex);
const stack = Betting.stackOf(this.state, player);
const owed = Betting.toCall(this.state, player);
const bits = [];
if (stack > 0) bits.push(`${Money.format(stack)} behind`);
if (owed > 0) bits.push(`${Money.format(owed)} to call`);
subtitle.textContent = bits.join(" · ");
this.actionsFor(player, this.seatIndex).forEach(action => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = `seatMenuBtn ${action.className || ""}`;
btn.textContent = action.label;
btn.addEventListener("click", () => {
// "Move to…" stays on the sheet and swaps it for the seat list; every
// other action is the end of the interaction.
if (action.label === "Move to…") {
action.run();
return;
}
this.close();
action.run();
});
list.appendChild(btn);
});
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = SeatMenu;
}
@@ -1,66 +0,0 @@
// Who hands cash to whom at the end of the night.
//
// The standings panel already works out what everyone is up or down. It then stopped,
// which leaves the dealer with six signed numbers at 2am and the actual job still to
// do: turning them into payments. That's the step people get wrong — not the poker.
//
// Everything is done in cents. A settlement that has to come out exactly right is the
// last place to let a float land on 41.99999999.
const SettleUp = {
// Largest debt against largest win, repeatedly. It's greedy rather than optimal,
// and for this problem that's the right trade: finding the true minimum number of
// transfers is NP-hard, while this is guaranteed to need at most one payment fewer
// than there are people, and each payment it does emit clears somebody out of the
// list entirely. A dealer wants a short list they can read down, not a proof.
//
// Payers are the outer loop so that everything one person owes is printed together
// — the list is read out loud, one player at a time.
plan(standings) {
const owed = [];
const owing = [];
(standings || []).forEach(row => {
const cents = Money.toCents(row.cashPosition);
if (cents > 0) owed.push({ name: row.name, cents });
else if (cents < 0) owing.push({ name: row.name, cents: -cents });
});
owed.sort((a, b) => b.cents - a.cents || a.name.localeCompare(b.name));
owing.sort((a, b) => b.cents - a.cents || a.name.localeCompare(b.name));
const payments = [];
let creditor = 0;
owing.forEach(payer => {
while (payer.cents > 0 && creditor < owed.length) {
const taker = owed[creditor];
const amount = Math.min(payer.cents, taker.cents);
payments.push({ from: payer.name, to: taker.name, amount: Money.fromCents(amount) });
payer.cents -= amount;
taker.cents -= amount;
if (taker.cents === 0) creditor++;
}
});
// What's left over when the chips on the table don't match the cash that came
// in. It is never a rounding artifact — the arithmetic is integer cents — so it
// is always the thing the bank check is already warning about: a rebuy nobody
// wrote down, or a miscount. Reported rather than quietly spread across the
// payments, because inventing a transfer to make the columns agree is how a
// real person ends up short.
const unpaid = Money.fromCents(owed.reduce((sum, row) => sum + row.cents, 0));
const unspent = Money.fromCents(owing.reduce((sum, row) => sum + row.cents, 0));
return {
payments,
// Only one of these can be non-zero: either there are more chips than cash
// or less, never both.
shortBy: unpaid,
overBy: unspent,
balanced: unpaid === 0 && unspent === 0,
};
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = SettleUp;
}
@@ -1,97 +0,0 @@
// Keyboard control for a dealer running this on a laptop.
//
// The phone has gestures; the desktop had a mouse and nothing else. These are the
// same actions the bar already offers, reachable without moving a hand to the
// trackpad between every decision — which is the whole point when the bar is being
// tapped thirty times a hand.
const Shortcuts = {
// Deliberately single letters with no modifier: a dealer's spare hand rests on
// the keyboard, and a chord is slower than reaching for the button would be.
KEYS: {
f: "fold",
c: "checkOrCall",
r: "raise",
a: "allIn",
" ": "advance",
enter: "advance",
u: "undo",
escape: "cancel",
},
// What each one does, in a dealer's words, for the legend in the sidebar.
//
// Lives beside KEYS because the two must not drift: F, C and R are printed on the
// buttons they drive, but A and U were on nothing at all — a dealer who learned
// the first three from the bar had no way to find out the other two existed. A
// shortcut with no line here is a shortcut nobody can find, and there's a test
// that says so.
LEGEND: [
{ keys: ["F"], action: "fold", what: "Fold" },
{ keys: ["C"], action: "checkOrCall", what: "Check, or call the bet" },
{ keys: ["R"], action: "raise", what: "Open the amount pad to bet or raise" },
{ keys: ["A"], action: "allIn", what: "Put this player all-in" },
{ keys: ["U"], action: "undo", what: "Take back the last action" },
{ keys: ["Space", "Enter"], action: "advance", what: "Deal, or move to the next street" },
{ keys: ["Esc"], action: "cancel", what: "Close the amount pad without betting" },
],
mount(handlers) {
this.handlers = handlers;
document.addEventListener("keydown", e => this.onKey(e));
},
// Nothing fires while the dealer is typing a name, an amount, or a note — the
// "c" in "Cass" must not fold the table.
isTyping() {
const el = document.activeElement;
if (!el) return false;
const tag = el.tagName;
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || el.isContentEditable;
},
// An overlay owns the keyboard while it's up. Asking the document which overlays
// are open, rather than listing them, means a sheet added later can't quietly
// start letting "f" fold the table behind it — the same reason Modal watches for
// them instead of being told about each one.
overlayOpen() {
return [...document.querySelectorAll('[id$="Overlay"]')].some(el => !el.hidden);
},
// Enter and Space are how a keyboard presses the control it is already sitting on.
// Claiming them for "advance" didn't just block that press — it ran a different
// action instead. Measured: Tab to Resolve Pot, press Enter, and the table dealt
// the next hand. Space on the same button worked, because "advance" happened to
// decline that time and the browser's own activation got through. A control that
// does something else every other press is worse than one that does nothing.
//
// Only these two keys are handed back. The letter shortcuts stay live with a
// button focused, because a button does nothing with "f" and the dealer's hand
// shouldn't have to leave them.
focusedControlOwnsKey(key) {
if (key !== "enter" && key !== " ") return false;
const el = document.activeElement;
return !!(el && el.matches && el.matches('button, [role="button"], a[href], summary'));
},
onKey(e) {
if (e.metaKey || e.ctrlKey || e.altKey) return;
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key.toLowerCase();
const action = this.KEYS[key];
if (!action) return;
if (this.focusedControlOwnsKey(key)) return;
// Escape is the exception: it should still close the raise pad even if focus
// happens to be sitting in its amount field.
if (this.isTyping() && !(action === "cancel")) return;
if (this.overlayOpen()) return;
const handled = this.handlers[action] && this.handlers[action]();
if (handled) e.preventDefault();
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = Shortcuts;
}
@@ -1,53 +0,0 @@
// Pure math for chopping one pot between tied players. No DOM.
//
// A dealer can't push half a chip across the felt, so this works in whole chips of
// whatever the smallest denomination in play is: everyone gets the same stack, and
// whatever won't divide is called out separately as odd chips. House rule for those
// is that they go to the first player left of the button, one at a time.
const SplitCalculator = {
// Everything is done in cents to keep 0.1 + 0.2 out of a payout.
toCents(amount) {
return Money.toCents(amount);
},
split(potAmount, ways, chipAmount) {
const potCents = this.toCents(potAmount);
const chipCents = Math.max(1, this.toCents(chipAmount));
const players = Math.max(1, Math.floor(Number(ways) || 0));
if (potCents <= 0) {
return { valid: false, each: 0, oddChips: 0, chip: chipCents / 100, dust: 0, players };
}
const wholeChips = Math.floor(potCents / chipCents);
// Left over when the pot itself isn't a whole number of the smallest chip —
// usually means the dealer picked the wrong denomination, so it's surfaced
// rather than silently rolled into someone's stack.
const dustCents = potCents - wholeChips * chipCents;
const chipsEach = Math.floor(wholeChips / players);
const oddChips = wholeChips - chipsEach * players;
return {
valid: true,
players,
each: (chipsEach * chipCents) / 100,
oddChips,
chip: chipCents / 100,
dust: dustCents / 100,
};
},
// Sanity check for the UI: what the split actually hands out has to equal the pot.
accountedFor(result) {
return Money.fromCents(
Money.toCents(result.each) * result.players +
Money.toCents(result.chip) * result.oddChips +
Money.toCents(result.dust)
);
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = SplitCalculator;
}
File diff suppressed because it is too large Load Diff
@@ -1,126 +0,0 @@
// Keeps the screen on while a hand is live.
//
// The dealer's phone spends the night face-up on the felt with nine people round it,
// and the one thing it reliably does between the flop and the turn is dim, then lock.
// Every hand, all night. A dozen rounds of work have gone into making the next step
// readable at a glance, and none of it survives a black screen and a passcode with
// four people waiting to know whether the bet is called.
//
// Held only while betting is actually open. A phone left on the table through a break,
// a re-buy, or the twenty minutes where everyone is arguing about pizza sleeps exactly
// like any other phone — which is the difference between a tool that respects a battery
// and one a dealer stops trusting with their evening.
const WakeLock = {
// The browser's promise to stay awake. Null whenever we aren't holding one, which
// includes every moment the browser has taken it back on us — see `start()`.
sentinel: null,
// What the last sync decided we want. Kept separate from `sentinel` because
// requesting one is asynchronous: a hand can be dealt and folded out inside the
// await, and the answer to "should we still be holding this" has to be the current
// one rather than the one that was true when the request went out.
wanted: false,
// One request at a time. `sync()` runs off renderAll, which fires many times a
// second during a busy street; without this, two overlapping requests both get
// past the "already holding one?" check and the second sentinel leaks — the screen
// then stays awake after the hand ends, with nothing left holding a reference to
// turn it off.
pending: false,
// Whether the dealer has been told this is happening. Once per page load, not once
// per hand: the same toast at the top of all forty hands of a session would be the
// single most annoying thing the tool does.
told: false,
// Set by main.js so the toast's "Turn off" can actually turn it off.
hooks: null,
supported() {
return typeof navigator !== "undefined" && "wakeLock" in navigator;
},
// The whole decision, with no browser in it, so it can be tested as what it is:
// a rule about when a poker table needs the screen.
shouldHold(state) {
if (!state) return false;
if (state.keepScreenAwake === false) return false;
return state.bettingOpen === true;
},
// Called after anything that could start or end a hand. Safe to call constantly.
sync(state) {
this.wanted = this.supported() && this.shouldHold(state);
if (this.wanted) this.acquire();
else this.release();
},
async acquire() {
if (this.sentinel || this.pending) return;
this.pending = true;
try {
const sentinel = await navigator.wakeLock.request("screen");
// The hand can have ended while that was in flight. Letting this one go
// immediately is the only correct answer; holding it "just until the next
// sync" is how a phone stays lit on an empty table.
if (!this.wanted) {
try { await sentinel.release(); } catch { /* already gone */ }
return;
}
this.sentinel = sentinel;
// The browser releases this itself when the tab is hidden, and tells us so.
// Without this listener our `sentinel` would be a stale object and the
// re-acquire in `start()` would decline to do anything.
sentinel.addEventListener("release", () => {
if (this.sentinel === sentinel) this.sentinel = null;
});
this.tell();
} catch {
// Battery saver, a hidden tab, a browser that simply says no. All of these
// are the browser doing its job, and none of them is worth an error at a
// poker table — the tool works exactly as it did before, the screen just
// dims the way the phone's own settings say it should.
} finally {
this.pending = false;
}
},
async release() {
const sentinel = this.sentinel;
this.sentinel = null;
if (!sentinel) return;
try { await sentinel.release(); } catch { /* already released */ }
},
// Said once, at the moment it first becomes true, with the way out attached.
//
// The alternative was a permanent indicator in the header, and the header is the
// one part of this page that has been fought over for crowding more than any other.
// A dealer needs to know their phone is behaving unusually exactly once; after that
// it is a setting, and settings live in the sidebar.
tell() {
if (this.told) return;
this.told = true;
if (typeof Toast === "undefined") return;
Toast.show("Keeping the screen on while a hand is live.", {
actionLabel: "Turn off",
onAction: () => { if (this.hooks && this.hooks.turnOff) this.hooks.turnOff(); },
});
},
// A screen wake lock is not something you take once. The browser drops it whenever
// the document stops being visible — switching apps to check a rule, the phone
// locking on its own before the first hand was dealt, a notification pulled down —
// and it never comes back on its own. A tool that requests it at the start of the
// hand and assumes it still has it is a tool that works until the first interruption.
start(getState) {
if (!this.supported()) return;
document.addEventListener("visibilitychange", () => {
if (document.visibilityState !== "visible") return;
this.sync(getState());
});
},
};
if (typeof module !== "undefined" && module.exports) module.exports = WakeLock;
+3 -7
View File
@@ -103,13 +103,9 @@ CHESS_API void CHESS_CALL trainer_destroy(TrainerHandle trainer);
/* Record one played position (post-move FEN) into the accumulator. */
CHESS_API void CHESS_CALL trainer_record(TrainerHandle trainer, const char* fen);
/* Apply a finished game's outcome to the global weights and save. Each touched cell (a piece
* on a square, or a feature) tracks a presence-weighted running average of the game's
* "advantage" — the game's outcome (scaled by `weight`, e.g. 0.5 for a material-imbalance
* draw) minus how much of that outcome the winner's average material edge already explains —
* so mg/eg/featW end up as a fractional win-rate (percent of games won with that piece there,
* minus percent lost), not an unbounded plus/minus tally, and a piece doesn't get credit
* merely for existing on the winning side of a material blowout. winner: 0 = white, 1 = black. */
/* Apply a finished game's outcome to the global weights and save: rewards the winner's
* occupied squares / features and punishes the loser's, scaled by `weight` (e.g. 0.5 for a
* material-imbalance draw). winner: 0 = white, 1 = black. */
CHESS_API void CHESS_CALL trainer_apply(TrainerHandle trainer, int winner, double weight);
#ifdef __cplusplus
+30 -122
View File
@@ -26,7 +26,6 @@
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <mutex>
#include <new>
#include <string>
@@ -116,25 +115,11 @@ struct ChessEngine {
/* The process-global learned weights: the single source of truth, loaded from disk once and
* updated in place by training. Engine handles snapshot it at creation; the visualization
* snapshots it on demand. Guarded by g_weightsMutex for updates/saves (eval reads its own
* per-handle copy, so it never touches this concurrently).
*
* mg/eg/featW are DERIVED, not accumulated: each is always exactly OUT_SCALE * (score/visits)
* for its cell (see trainer_apply), recomputed whenever that cell's stats change. visits is
* the presence-weighted count of games that touched the cell (how much to trust the average);
* score is the presence-weighted sum of each game's material-adjusted advantage (see
* trainer_apply) — so score/visits is literally "fraction of (presence-weighted) games won
* with this piece here, minus fraction lost," bounded to [-1,1] by construction. */
* per-handle copy, so it never touches this concurrently). */
struct LearnedWeights {
int mg[chess::PIECE_TYPE_NB][64] = {};
int eg[chess::PIECE_TYPE_NB][64] = {};
int featW[FEATURE_NB] = {};
double mgVisits[chess::PIECE_TYPE_NB][64] = {};
double mgScore [chess::PIECE_TYPE_NB][64] = {};
double egVisits[chess::PIECE_TYPE_NB][64] = {};
double egScore [chess::PIECE_TYPE_NB][64] = {};
double featVisits[FEATURE_NB] = {};
double featScore [FEATURE_NB] = {};
};
static LearnedWeights g_weights;
@@ -142,15 +127,13 @@ static std::mutex g_weightsMutex;
static std::string g_weightsPath;
/* Per-game training accumulator (one per learned CPU-vs-CPU game). Records, per ply, where
* each side's pieces sat (split into midgame/endgame by phase), each side's feature
* activations, and the white-minus-black material balance; trainer_apply turns the totals
* into a presence-weighted update to the running per-cell averages. Squares are white-relative
* each side's pieces sat (split into midgame/endgame by phase) and each side's feature
* activations; trainer_apply turns the totals into weight nudges. Squares are white-relative
* (black indexes sq ^ 56), so a side's tally lines up with the shared white-relative table. */
struct Trainer {
double mgOcc[chess::COLOR_NB][chess::PIECE_TYPE_NB][64] = {};
double egOcc[chess::COLOR_NB][chess::PIECE_TYPE_NB][64] = {};
double featAcc[chess::COLOR_NB][FEATURE_NB] = {};
double matDiffAcc = 0.0; /* sum over plies of (white material - black material), cp */
int plies = 0;
};
@@ -189,12 +172,9 @@ static int parse_variant(const char* options) {
}
/* On-disk format: 6*64 mg ints (PAWN..KING, squares 0..63), then 6*64 eg ints, then
* FEATURE_NB feature ints, then the backing visits/score doubles for each (mgVisits, mgScore,
* egVisits, egScore, featVisits, featScore) in the same shapes, all whitespace-separated. A
* missing file or short read leaves the rest neutral (0), so an absent weights file just means
* "train from a blank slate" — and a file written by the pre-fractional-learning format (which
* ends after the feature ints) loads its mg/eg/featW fine and simply starts every cell's
* visits/score history fresh from the next game that touches it. Caller holds g_weightsMutex. */
* FEATURE_NB feature ints, whitespace-separated. A missing file or short read leaves the
* rest neutral (0), so an absent weights file just means "train from a blank slate".
* Caller holds g_weightsMutex. */
static void load_global_weights(const char* path) {
g_weights = LearnedWeights{}; /* reset to neutral before loading */
@@ -210,29 +190,9 @@ static void load_global_weights(const char* path) {
if (!(f >> g_weights.eg[pt][sq])) return;
for (int i = 0; i < FEATURE_NB; ++i)
if (!(f >> g_weights.featW[i])) return;
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq)
if (!(f >> g_weights.mgVisits[pt][sq])) return;
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq)
if (!(f >> g_weights.mgScore[pt][sq])) return;
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq)
if (!(f >> g_weights.egVisits[pt][sq])) return;
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq)
if (!(f >> g_weights.egScore[pt][sq])) return;
for (int i = 0; i < FEATURE_NB; ++i)
if (!(f >> g_weights.featVisits[i])) return;
for (int i = 0; i < FEATURE_NB; ++i)
if (!(f >> g_weights.featScore[i])) return;
}
/* Persist g_weights to g_weightsPath in the format load_global_weights reads. Full round-trip
* precision on the doubles (visits/score are running sums that keep accumulating across many
* games, so truncating them would drift the derived mg/eg/featW over time). Caller holds the
* lock. */
/* Persist g_weights to g_weightsPath in the format load_global_weights reads. Caller holds the lock. */
static void save_global_weights() {
if (g_weightsPath.empty()) return;
std::ofstream f(g_weightsPath);
@@ -243,18 +203,6 @@ static void save_global_weights() {
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq) f << g_weights.eg[pt][sq] << (sq == 63 ? '\n' : ' ');
for (int i = 0; i < FEATURE_NB; ++i) f << g_weights.featW[i] << (i == FEATURE_NB - 1 ? '\n' : ' ');
f << std::setprecision(17);
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq) f << g_weights.mgVisits[pt][sq] << (sq == 63 ? '\n' : ' ');
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq) f << g_weights.mgScore[pt][sq] << (sq == 63 ? '\n' : ' ');
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq) f << g_weights.egVisits[pt][sq] << (sq == 63 ? '\n' : ' ');
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq) f << g_weights.egScore[pt][sq] << (sq == 63 ? '\n' : ' ');
for (int i = 0; i < FEATURE_NB; ++i) f << g_weights.featVisits[i] << (i == FEATURE_NB - 1 ? '\n' : ' ');
for (int i = 0; i < FEATURE_NB; ++i) f << g_weights.featScore[i] << (i == FEATURE_NB - 1 ? '\n' : ' ');
}
/* Maps the 1..20 difficulty to a search depth. Kept modest: the search has no
@@ -434,18 +382,13 @@ static int evaluate(const chess::Position& pos) {
* compute_features() is the single source of feature activations, used by BOTH the eval here
* and the trainer, so the two can never disagree. Constants below are the only tunables. */
/* Per-game-outcome learning constants. Squares and features both learn a presence/activation-
* weighted AVERAGE advantage in [-1,1] (see trainer_apply) — OUT_SCALE just converts that
* average into a centipawn-ish int for the eval/table to add directly. FEAT_SCALE normalizes
* each feature's raw per-ply activation to a comparable magnitude before it's used as a weight
* (so high-count mobility doesn't dwarf the small pawn-structure terms), same as before.
* MATERIAL_ELO_SCALE is the classic centipawn-to-win-probability curve
* (expected = 1/(1+10^(-cp/400))) used to compute how much of a result material already
* explains, so training credits placement/features only for the part of the result that
* material didn't already predict. */
static constexpr int SQ_OUT_SCALE = 250;
static constexpr int FEAT_OUT_SCALE = 500;
static constexpr double MATERIAL_ELO_SCALE = 400.0;
/* Per-game-outcome learning rates and clamps. Squares accumulate occupancy (plies on a
* square, summed); features accumulate normalized per-ply activation (averaged, divided by a
* nominal scale so high-magnitude mobility doesn't dwarf the small pawn-structure terms). */
static constexpr double SQUARE_LR = 0.5;
static constexpr int SQ_CLAMP = 250;
static constexpr double FEAT_LR = 2.0;
static constexpr int FEAT_CLAMP = 500;
static constexpr double FEAT_SCALE[FEATURE_NB] = { 4, 6, 8, 14, 2, 1, 1, 2 };
/* Game phase in [0,1] from remaining non-pawn material (PeSTO weights N=B=1, R=2, Q=4; max
@@ -880,9 +823,7 @@ CHESS_API void CHESS_CALL trainer_record(TrainerHandle t, const char* fen) {
chess::Position pos = chess::Position::from_fen(fen);
double phase = game_phase(pos);
/* Per-square occupancy, split into midgame/endgame by phase, white-relative; and the
* white-minus-black material balance at this ply, used at trainer_apply time to strip
* "material already explains this" out of the training signal. */
/* Per-square occupancy, split into midgame/endgame by phase, white-relative. */
chess::Bitboard occ = pos.pieces();
while (occ) {
chess::Square s = chess::pop_lsb(occ);
@@ -892,7 +833,6 @@ CHESS_API void CHESS_CALL trainer_record(TrainerHandle t, const char* fen) {
int relSq = (c == chess::WHITE) ? int(s) : (int(s) ^ 56);
t->mgOcc[c][pt][relSq] += (1.0 - phase);
t->egOcc[c][pt][relSq] += phase;
t->matDiffAcc += (c == chess::WHITE ? 1 : -1) * piece_value(pt);
}
/* Per-side feature activations. */
@@ -907,66 +847,34 @@ CHESS_API void CHESS_CALL trainer_record(TrainerHandle t, const char* fen) {
t->plies++;
}
/* Applies a finished game's outcome as a presence-weighted running average per cell, instead
* of an unbounded incremental nudge:
*
* score[cell] / visits[cell] == "fraction of (presence-weighted) games won with this piece
* on this square, minus fraction lost"
*
* `weight` is the caller's confidence in the result (1.0 for a checkmate, 0.5 for a
* material-imbalance draw, as before). On top of that, the update is scaled by how much of the
* result ISN'T already explained by material: `expected` is the win probability the winner's
* average material edge over the game implies (the same centipawn->win-probability curve
* engines use for Elo estimates); `1 - expected` is the "surprise" left over once material is
* accounted for. A win where the winner was already up a rook the whole game is unsurprising
* (expected ~= 1, ~no update) — the eval already knows material matters via piece_value(), so
* square/feature tables shouldn't get credit for "a piece existed"; a win pulled off (or a draw
* held) while materially behind is highly informative and gets a correspondingly large update.
* This same magnitude applies to BOTH the winner's reward and the loser's punishment: by the
* symmetry of win probabilities (P(loser wins) = 1 - P(winner wins)), the loser's own advantage
* — actual(0) minus their expected win probability — has exactly the same magnitude, `1 -
* expected`, just negative. */
CHESS_API void CHESS_CALL trainer_apply(TrainerHandle t, int winner, double weight) {
if (!t || t->plies <= 0) return;
double avgMaterialDiff = t->matDiffAcc / t->plies; /* white - black, cp */
double winnerMaterialDiff = (winner == chess::WHITE) ? avgMaterialDiff : -avgMaterialDiff;
double expected = 1.0 / (1.0 + std::pow(10.0, -winnerMaterialDiff / MATERIAL_ELO_SCALE));
double advantageMag = weight * (1.0 - expected);
if (!t) return;
std::lock_guard<std::mutex> lock(g_weightsMutex);
/* pass 0 = winner (positive advantage); pass 1 = loser (negative advantage). */
/* pass 0 = winner (reward, +1); pass 1 = loser (punish, -1). */
for (int pass = 0; pass < 2; ++pass) {
chess::Color side = chess::Color((pass == 0 ? winner : (winner ^ 1)) & 1);
double advantage = pass == 0 ? advantageMag : -advantageMag;
int sign = pass == 0 ? 1 : -1;
for (int pt = chess::PAWN; pt <= chess::KING; ++pt)
for (int sq = 0; sq < 64; ++sq) {
double mgFrac = t->mgOcc[side][pt][sq] / t->plies; /* fraction of the game spent here, [0,1] */
if (mgFrac != 0.0) {
g_weights.mgVisits[pt][sq] += mgFrac;
g_weights.mgScore [pt][sq] += mgFrac * advantage;
g_weights.mg[pt][sq] = int(std::lround(
SQ_OUT_SCALE * g_weights.mgScore[pt][sq] / g_weights.mgVisits[pt][sq]));
if (t->mgOcc[side][pt][sq] != 0.0) {
int d = sign * int(std::lround(SQUARE_LR * t->mgOcc[side][pt][sq] * weight));
g_weights.mg[pt][sq] = std::clamp(g_weights.mg[pt][sq] + d, -SQ_CLAMP, SQ_CLAMP);
}
double egFrac = t->egOcc[side][pt][sq] / t->plies;
if (egFrac != 0.0) {
g_weights.egVisits[pt][sq] += egFrac;
g_weights.egScore [pt][sq] += egFrac * advantage;
g_weights.eg[pt][sq] = int(std::lround(
SQ_OUT_SCALE * g_weights.egScore[pt][sq] / g_weights.egVisits[pt][sq]));
if (t->egOcc[side][pt][sq] != 0.0) {
int d = sign * int(std::lround(SQUARE_LR * t->egOcc[side][pt][sq] * weight));
g_weights.eg[pt][sq] = std::clamp(g_weights.eg[pt][sq] + d, -SQ_CLAMP, SQ_CLAMP);
}
}
for (int i = 0; i < FEATURE_NB; ++i) {
double activation = (t->featAcc[side][i] / t->plies) / FEAT_SCALE[i]; /* per-ply average, normalized */
if (activation == 0.0) continue;
g_weights.featVisits[i] += std::abs(activation);
g_weights.featScore [i] += activation * advantage;
g_weights.featW[i] = int(std::lround(
FEAT_OUT_SCALE * g_weights.featScore[i] / g_weights.featVisits[i]));
}
if (t->plies > 0)
for (int i = 0; i < FEATURE_NB; ++i) {
double avg = t->featAcc[side][i] / t->plies; /* per-ply average, normalized */
int d = sign * int(std::lround(FEAT_LR * (avg / FEAT_SCALE[i]) * weight));
g_weights.featW[i] = std::clamp(g_weights.featW[i] + d, -FEAT_CLAMP, FEAT_CLAMP);
}
}
save_global_weights();
File diff suppressed because it is too large Load Diff
-128
View File
@@ -1,128 +0,0 @@
// 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);
});
});
-173
View File
@@ -1,173 +0,0 @@
// Who the felt marks "ALL IN".
//
// The mark's whole value is that a dealer can scan the ring and see who can still be
// bet at, so the test that matters most is the last one: the seats it marks are
// exactly the seats the betting round refuses to ask for another chip.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
const path = require("path");
const { Betting, HoldemState, makeTable, chipsOnTable } = require("./load");
const CSS = fs.readFileSync(
path.join(__dirname, "..", "..", "JoshHeaps.Net", "wwwroot", "css", "casino", "holdem.css"), "utf8");
// The declarations inside one rule, by its exact selector.
const ruleBody = selector => {
const at = CSS.indexOf(`\n${selector} {`);
if (at < 0) return null;
const open = CSS.indexOf("{", at);
return CSS.slice(open + 1, CSS.indexOf("}", open));
};
test("a player who moved all-in is marked", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100 });
state.seats[3].stack = 12;
Betting.beginHand(state);
Betting.allIn(state, state.actingSeatIndex);
assert.equal(Betting.isAllIn(state, state.seats[3]), true);
assert.equal(state.seats[3].stack, 0);
});
test("a player with chips behind is not", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
Betting.beginHand(state);
assert.equal(Betting.isAllIn(state, state.seats[0]), false);
assert.equal(Betting.isAllIn(state, state.seats[1]), false);
});
test("a busted player who was dealt in but has put nothing in is not", () => {
// An empty stack alone isn't all-in — it's someone who shouldn't have been dealt
// in. Calling that "ALL IN" on the felt would be a lie about a live pot.
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 100 });
state.seats[2].stack = 0;
assert.equal(Betting.isAllIn(state, state.seats[2]), false);
});
test("a folded player with an empty stack is not", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 100 });
state.seats[1].committed = 5;
state.seats[1].stack = 0;
state.seats[1].folded = true;
assert.equal(Betting.isAllIn(state, state.seats[1]), false);
});
test("an empty chair is not", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1], stack: 100 });
assert.equal(Betting.isAllIn(state, state.seats[4]), false);
});
test("a seat with no stack of its own falls back to the table's and isn't marked", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 100 });
state.defaultStack = 200;
state.seats[2].stack = null;
state.seats[2].committed = 10;
assert.equal(Betting.isAllIn(state, state.seats[2]), false);
});
test("the seats marked are exactly the ones the action passes over", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100 });
state.seats[1].stack = 8;
state.seats[3].stack = 30;
Betting.beginHand(state);
// Everyone in, two of them for less than the others can cover.
for (let step = 0; step < 4; step++) Betting.allIn(state, state.actingSeatIndex);
const marked = state.seats
.map((player, index) => (Betting.isAllIn(state, player) ? index : null))
.filter(index => index !== null);
const skipped = state.seats
.map((player, index) =>
player.inHand && !player.folded && Betting.nextToAct(state, index - 1) !== index ? index : null)
.filter(index => index !== null);
assert.deepEqual(marked, skipped);
assert.ok(marked.length > 0, "the scenario should actually produce all-in players");
});
test("nobody is marked once the next hand starts", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 100 });
state.seats[2].stack = 5;
Betting.beginHand(state);
Betting.allIn(state, state.actingSeatIndex);
assert.ok(state.seats.some(player => Betting.isAllIn(state, player)));
// The short stack got there by winning nothing; give them chips back the way a
// dealer would before the next deal.
HoldemState.startNextHand(state);
state.seats[2].stack = 50;
assert.equal(state.seats.filter(player => Betting.isAllIn(state, player)).length, 0);
});
test("marking nobody doesn't move a chip", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100 });
state.seats[3].stack = 12;
Betting.beginHand(state);
const before = chipsOnTable(state);
state.seats.forEach(player => Betting.isAllIn(state, player));
assert.equal(chipsOnTable(state), before);
});
// ---- And the shape of the mark, which is the felt's problem ------------------
//
// "ALL IN" is the only thing that ever lands on the stack line with a space in it, and
// a space is somewhere to break. Measured at 360x640 with twelve players all-in, it
// wanted 36px and had 34: it broke onto a second line, and an 11px line became 22.
//
// That is not a typography complaint. The puck went from 55px tall to 66, and puck
// height is what the seat ring is short of — at the ends of an ellipse the seats are
// separated vertically, so 11px taller is 11px further into the seat next door. The
// layout search then tried every width it has, found none that cleared, and fell back
// to the narrowest, which is also the one that wraps hardest.
//
// So the rule every design system gives a badge applies here too: one line, always.
describe("the mark is one line, because the ring cannot afford two", () => {
test("a stack line can never wrap", () => {
const body = ruleBody(".seatPuckStack");
assert.ok(body, "the .seatPuckStack rule should exist");
assert.match(body, /white-space:\s*nowrap/,
"the stack line must not be allowed to wrap — a second line is 11px the ring hasn't got");
});
test("and on the tightest pucks it gives up its letter-spacing to fit", () => {
// Not wrapping alone only converts a wrap into a spill: a line that cannot wrap
// and still doesn't fit paints over the seat beside it instead. The spacing is
// 3.6px of the 36 it wanted, and it is the one of the mark's three signals that
// can go — the warm colour and the bold weight stay.
const base = ruleBody(".seatPuckStack.seatPuckAllIn");
const tight = ruleBody(".seatsTight .seatPuckStack.seatPuckAllIn");
assert.ok(base, "the base all-in rule should exist");
assert.ok(tight, "the tight-tier all-in rule should exist");
const spacingOf = body => {
const match = body.match(/letter-spacing:\s*([\d.]+)em/);
return match ? Number(match[1]) : null;
};
const wide = spacingOf(base);
const narrow = spacingOf(tight);
assert.ok(wide !== null && narrow !== null, "both rules should set letter-spacing in em");
assert.ok(narrow < wide,
`the tight tier should space the mark more tightly than the ordinary one (${narrow} vs ${wide})`);
// The arithmetic that has to hold for it to fit at all: six characters at 10px
// with 4px of padding either side and a 1px border, inside a 44px puck.
const CONTENT_PX = 44 - 2 * 4 - 2 * 1;
const inkAt = spacing => 32.4 + spacing * 10 * "ALL IN".length;
assert.ok(inkAt(narrow) <= CONTENT_PX,
`"ALL IN" must fit the narrowest puck: ${inkAt(narrow).toFixed(1)}px into ${CONTENT_PX}px`);
assert.ok(inkAt(wide) > CONTENT_PX,
"the ordinary spacing is what didn't fit — if it does now, this test is measuring the wrong thing");
});
test("the two signals that survive are the ones doing the work", () => {
// The spacing exists so "ALL IN" doesn't read as money at a glance. Dropping it
// on the narrow pucks is only safe while the colour and the weight remain, so
// they are pinned here rather than left to be tidied away later.
const base = ruleBody(".seatPuckStack.seatPuckAllIn");
assert.match(base, /color:\s*#ffcf6b/i, "the warm colour separates it from a grey stack");
assert.match(base, /font-weight:\s*700/, "and the weight does the rest");
});
});
-135
View File
@@ -1,135 +0,0 @@
// 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;
});
});
-98
View File
@@ -1,98 +0,0 @@
// Perceptual contrast (APCA), and how much of it each piece of text needs.
//
// The audit already had a contrast check and it passed, which is why this exists. That
// check measures WCAG 2 contrast ratio, and WCAG 2's own authors say it is the wrong
// instrument for this page: the ratio is a luminance gap, and a luminance gap
// systematically *overstates* readability once one of the two colours is near black.
// This table's page is #141414 and its panels are darker still, so every reading it
// takes is on the side of the algorithm where it is least reliable. Text can clear
// 4.5:1 and still read as a smudge.
//
// APCA asks the other question — can text of *this size and weight* be read on this
// background — and answers it on a scale where a given number means the same
// readability at either polarity. It replaces nothing: the WCAG check stays, because
// that is the number an accessibility audit will ask for. This is the one that says
// whether a dealer can read it in a dim room.
//
// Constants are 0.98G-4g, and the implementation is checked against the eight
// published reference pairs in apcaMath.test.js. An unverified contrast checker is
// worse than none, because it launders a guess into a number.
const MAIN_TRC = 2.4;
const R_CO = 0.2126729, G_CO = 0.7151522, B_CO = 0.0721750;
const NORM_BG = 0.56, NORM_TXT = 0.57, REV_TXT = 0.62, REV_BG = 0.65;
const BLK_THRS = 0.022, BLK_CLMP = 1.414;
const SCALE_BOW = 1.14, SCALE_WOB = 1.14;
const LO_BOW_OFFSET = 0.027, LO_WOB_OFFSET = 0.027;
const DELTA_Y_MIN = 0.0005, LO_CLIP = 0.001;
// Screen luminance. Note this is a straight exponent, not the sRGB piecewise curve —
// APCA specifies the simple 2.4 power and the two are not interchangeable here.
function sRGBtoY(rgb) {
const s = c => Math.pow(c / 255.0, MAIN_TRC);
return R_CO * s(rgb[0]) + G_CO * s(rgb[1]) + B_CO * s(rgb[2]);
}
// Signed: positive is dark text on light, negative is light text on dark. The sign
// carries the polarity, and polarity is not cosmetic — the same luminance pair reads
// differently each way round, which is the whole reason this exists.
function contrast(txtY, bgY) {
txtY = txtY > BLK_THRS ? txtY : txtY + Math.pow(BLK_THRS - txtY, BLK_CLMP);
bgY = bgY > BLK_THRS ? bgY : bgY + Math.pow(BLK_THRS - bgY, BLK_CLMP);
if (Math.abs(bgY - txtY) < DELTA_Y_MIN) return 0.0;
let sapc, out;
if (bgY > txtY) {
sapc = (Math.pow(bgY, NORM_BG) - Math.pow(txtY, NORM_TXT)) * SCALE_BOW;
out = sapc < LO_CLIP ? 0.0 : sapc - LO_BOW_OFFSET;
} else {
sapc = (Math.pow(bgY, REV_BG) - Math.pow(txtY, REV_TXT)) * SCALE_WOB;
out = sapc > -LO_CLIP ? 0.0 : sapc + LO_WOB_OFFSET;
}
return out * 100;
}
function lc(textRgb, bgRgb) {
return contrast(sRGBtoY(textRgb), sRGBtoY(bgRgb));
}
// How much contrast this text needs, from the published APCA levels:
//
// Lc 90 fluent body text; and the floor for anything at 14px/400 or 12px/400
// Lc 75 the minimum for a column of body text (18px/400, 16px/500, 14px/700)
// Lc 60 the minimum for content text that isn't a column or block
// Lc 45 larger, heavier text — headlines at 36px/400 or 24px/700
// Lc 30 the absolute floor, and only for genuinely spot-read text
//
// Interpolating between those anchors rather than inventing a curve. Weight is folded
// in as an effective size because that is how the published table behaves: bolder
// strokes buy roughly the same readability as bigger ones, and 14px/700 sitting at the
// same Lc 75 as 18px/400 is the anchor that fixes the exchange rate.
function requiredLc(px, weight = 400) {
const heavier = Math.max(0, (Number(weight) || 400) - 400) / 300; // 400..700 -> 0..1
const effective = px * (1 + 0.28 * heavier); // 14px/700 ~= 18px/400
const anchors = [
[12, 90],
[14, 90],
[15, 82],
[18, 75],
[24, 60],
[36, 45],
];
if (effective <= anchors[0][0]) return anchors[0][1];
const last = anchors[anchors.length - 1];
if (effective >= last[0]) return last[1];
for (let i = 1; i < anchors.length; i++) {
const [x0, y0] = anchors[i - 1];
const [x1, y1] = anchors[i];
if (effective <= x1) {
const t = (effective - x0) / (x1 - x0);
return y0 + t * (y1 - y0);
}
}
return last[1];
}
module.exports = { sRGBtoY, contrast, lc, requiredLc };
-141
View File
@@ -1,141 +0,0 @@
// The contrast arithmetic, checked against the numbers its authors publish.
//
// A contrast checker that is wrong is worse than not having one, because it launders a
// guess into a number and then a stylesheet gets tuned to it. The eight pairs below are
// the reference values published with APCA 0.98G-4g; if the implementation drifts from
// them by so much as a rounding change, these fail and nothing downstream is believed.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { lc, contrast, sRGBtoY, requiredLc } = require("./apca");
const hex = h => {
h = h.replace("#", "");
if (h.length === 3) h = h.split("").map(c => c + c).join("");
return [0, 2, 4].map(i => parseInt(h.slice(i, i + 2), 16));
};
describe("the published reference pairs", () => {
// Text first, background second, exactly as the reference table lists them.
const CASES = [
["#888", "#fff", 63.056469930209424],
["#fff", "#888", -68.54146436644962],
["#000", "#aaa", 58.146262578561334],
["#aaa", "#000", -56.24113336839742],
["#123", "#def", 91.66830811481631],
["#def", "#123", -93.06770049484275],
["#123", "#444", 8.32326136957393],
["#444", "#123", -7.526878460278154],
];
CASES.forEach(([text, bg, expected]) => {
test(`${text} on ${bg} is Lc ${expected.toFixed(2)}`, () => {
assert.ok(Math.abs(lc(hex(text), hex(bg)) - expected) < 1e-9,
`got ${lc(hex(text), hex(bg))}, want ${expected}`);
});
});
});
describe("polarity", () => {
test("is signed, and the sign is not decoration", () => {
// Dark text on light is positive, light text on dark negative. The two are not
// mirror images — swapping them changes the magnitude as well as the sign,
// which is the entire reason this is used instead of a ratio.
const dark = lc(hex("#888"), hex("#fff"));
const light = lc(hex("#fff"), hex("#888"));
assert.ok(dark > 0 && light < 0);
assert.ok(Math.abs(Math.abs(dark) - Math.abs(light)) > 5,
"the same pair reads differently each way round");
});
test("a colour on itself is nothing at all", () => {
assert.equal(lc(hex("#2c2c2c"), hex("#2c2c2c")), 0);
});
test("and so is a difference too small to see", () => {
// Below deltaYmin the answer is zero rather than a tiny number, so a rounding
// artefact can never be reported as contrast.
assert.equal(lc([44, 44, 44], [44, 44, 45]), 0);
});
});
describe("luminance", () => {
test("is the straight 2.4 power, not the sRGB piecewise curve", () => {
// Worth pinning: the two are close enough to look right and different enough to
// move a borderline reading. Mid grey under the piecewise curve is ~0.2159.
assert.ok(Math.abs(sRGBtoY([128, 128, 128]) - Math.pow(128 / 255, 2.4)) < 1e-6);
});
test("white is as close to 1 as the published coefficients get", () => {
// 1.0000001, not 1. The three coefficients are given to seven places and sum to
// a hair over one, and that is the specification rather than a mistake to
// correct — the reference pairs above only come out exact with these values.
// Asserted loosely on purpose: tightening this to 1e-12 fails on correct code.
assert.ok(Math.abs(sRGBtoY([255, 255, 255]) - 1) < 1e-6);
assert.equal(sRGBtoY([0, 0, 0]), 0);
});
test("green carries most of it", () => {
// Not arbitrary: it's why gold on green was the worst pairing on the felt.
assert.ok(sRGBtoY([0, 255, 0]) > sRGBtoY([255, 0, 0]) + sRGBtoY([0, 0, 255]));
});
test("contrast() takes luminances, lc() takes colours", () => {
assert.equal(contrast(sRGBtoY(hex("#888")), sRGBtoY(hex("#fff"))), lc(hex("#888"), hex("#fff")));
});
});
describe("how much contrast a given piece of text needs", () => {
test("the published anchors land where they should", () => {
assert.equal(Math.round(requiredLc(12, 400)), 90);
assert.equal(Math.round(requiredLc(14, 400)), 90);
assert.equal(Math.round(requiredLc(18, 400)), 75);
assert.equal(Math.round(requiredLc(24, 400)), 60);
assert.equal(Math.round(requiredLc(36, 400)), 45);
});
test("smaller text asks for more, never less", () => {
for (let px = 9; px < 40; px++) {
assert.ok(requiredLc(px, 400) >= requiredLc(px + 1, 400),
`${px}px should ask for at least as much as ${px + 1}px`);
}
});
test("weight buys size, at the rate the published table sets", () => {
// 14px/700 and 18px/400 sit at the same Lc 75 in the table, and that pair is
// what fixes the exchange rate between weight and size here.
assert.ok(Math.abs(requiredLc(14, 700) - requiredLc(18, 400)) < 3);
assert.ok(requiredLc(14, 700) < requiredLc(14, 400), "bold asks for less than regular");
});
test("it never runs off either end", () => {
assert.equal(requiredLc(4, 400), 90);
assert.equal(requiredLc(200, 900), 45);
});
});
describe("what the page's own colours measure", () => {
// These are the readings the round was built on. Pinned so that a future change to
// the tokens has to look at them rather than move them by accident.
const PANEL = hex("#1a1a1a");
test("the greys these tokens replaced were below the floor", () => {
assert.ok(Math.abs(lc(hex("#9a9a9a"), PANEL)) < 50, "the old muted grey");
assert.ok(Math.abs(lc(hex("#8a8a8a"), PANEL)) < 40, "the old dim grey");
});
test("and the ones that replaced them clear it", () => {
assert.ok(Math.abs(lc(hex("#c8c8c8"), PANEL)) >= 60, "muted");
assert.ok(Math.abs(lc(hex("#b4b4b4"), PANEL)) >= 58, "dim");
});
test("the three tiers are still three tiers", () => {
// The worry with lifting muted and dim is that they collapse into --text and the
// page flattens. They don't: the spread is wider than it was.
const text = Math.abs(lc(hex("#eeeeee"), PANEL));
const muted = Math.abs(lc(hex("#c8c8c8"), PANEL));
const dim = Math.abs(lc(hex("#b4b4b4"), PANEL));
assert.ok(text > muted && muted > dim, "still ordered");
assert.ok(text - dim > 30, "and still a real spread");
});
});
-175
View File
@@ -1,175 +0,0 @@
// 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
@@ -1,108 +0,0 @@
// 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"), []);
});
});
-224
View File
@@ -1,224 +0,0 @@
// The banker's job, which is a different job from the dealer's: every chip on the
// table is a promise to pay cash for it later, and somebody has to be able to check
// that the promise can be kept before the last two players try to cash out.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, HoldemState, Money, makeTable } = require("./load");
const seat = (state, index, name, cash, chips) => {
const p = state.seats[index];
p.name = name; p.inHand = true; p.buyIns = cash; p.stack = chips;
return p;
};
describe("everyone with money in the game is accounted for", () => {
test("a player who has bought in but played no logged hand still appears", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 0 });
seat(state, 0, "Ann", 100, 100);
seat(state, 1, "Ben", 100, 100);
seat(state, 2, "Cal", 200, 200); // just sat down
state.seats[0].amountOverride = 10;
state.seats[1].amountOverride = 10;
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 20 }]);
state.seats[0].amountOverride = null;
state.seats[1].amountOverride = null;
const names = HoldemState.sessionStandings(state).map(r => r.name);
assert.ok(names.includes("Cal"), `Cal handed over $200 and is missing: ${names.join(", ")}`);
});
test("their row reads as no hands played, not as a loss", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 100, 100);
seat(state, 1, "Ben", 200, 200);
const cal = HoldemState.sessionStandings(state).find(r => r.name === "Ben");
assert.equal(cal.in, 0);
assert.equal(cal.won, 0);
assert.equal(cal.net, 0);
assert.equal(cal.boughtIn, 200);
assert.equal(cal.cashPosition, 0, "level: they've bought chips and still hold them");
});
test("an empty chair is not dragged into the settle-up", () => {
const state = makeTable({ seatCount: 9, seated: [0], stack: 0 });
seat(state, 0, "Ann", 100, 100);
const rows = HoldemState.sessionStandings(state);
assert.equal(rows.length, 1);
});
test("somebody who has cashed out completely still shows what they took", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 100, 0); // handed every chip back
seat(state, 1, "Ben", 100, 200);
const ann = HoldemState.sessionStandings(state).find(r => r.name === "Ann");
assert.equal(ann.cashPosition, -100, "down the whole buy-in");
});
});
describe("does the cash box cover the chips on the table", () => {
test("a straight game balances", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 0 });
seat(state, 0, "Ann", 100, 60);
seat(state, 1, "Ben", 100, 140);
seat(state, 2, "Cal", 100, 100);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.cashIn, 300);
assert.equal(bank.chipsInPlay, 300);
assert.equal(bank.difference, 0);
assert.equal(bank.balanced, true);
});
test("chips outrunning the cash box is caught before cash-out", () => {
// The 2am failure: the last players out can't be paid.
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 0 });
seat(state, 0, "Ann", 100, 100);
seat(state, 1, "Ben", 100, 100);
seat(state, 2, "Cal", 100, 260); // took chips for a rebuy nobody wrote down
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.cashIn, 300);
assert.equal(bank.chipsInPlay, 460);
assert.equal(bank.difference, 160);
assert.equal(bank.balanced, false);
});
test("cash taken for chips never handed over is caught too", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 200, 100); // paid 200, only got 100 in chips
seat(state, 1, "Ben", 100, 100);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.difference, -100);
assert.equal(bank.balanced, false);
});
test("chips in the middle still count as chips in play", () => {
// Money in the pot is somebody's; it just hasn't been won yet. Leaving it out
// would report a shortfall every time a hand was open — which is nearly always.
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.seats.forEach(p => { if (p.inHand) p.buyIns = 100; });
const before = HoldemState.bankReconciliation(state);
assert.equal(before.balanced, true);
Betting.beginHand(state); // blinds go in
Betting.raiseTo(state, 0, 25); // and a raise
Betting.sweepToHandTotals(state); // banked into the pot
const during = HoldemState.bankReconciliation(state);
assert.equal(during.balanced, true, "an open pot is not a discrepancy");
assert.equal(during.chipsInPlay, before.chipsInPlay);
});
test("a whole session of play never knocks the books out", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
state.seats.forEach(p => { if (p.inHand) p.buyIns = 100; });
for (let hand = 0; hand < 6; hand++) {
Betting.beginHand(state);
Betting.liveSeats(state).forEach(s => {
if (Betting.toCall(state, s.player) > 0) Betting.call(state, s.index);
});
Betting.sweepToHandTotals(state);
const pot = HoldemState.totalPot(state);
const winner = Betting.liveSeats(state)[0];
const payouts = [{ id: winner.player.id, label: "w", amount: pot }];
HoldemState.recordHand(state, payouts);
Betting.creditWinnings(state, payouts);
HoldemState.startNextHand(state);
assert.equal(HoldemState.bankReconciliation(state).balanced, true, `books off after hand ${hand + 1}`);
}
});
test("a rebuy keeps the books straight, a chip grab doesn't", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 100, 100);
seat(state, 1, "Ben", 100, 100);
// A proper rebuy: cash to the banker, chips to the player.
state.seats[0].buyIns += 100;
state.seats[0].stack += 100;
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
// Chips taken without paying.
state.seats[1].stack += 50;
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, false);
assert.equal(bank.difference, 50);
});
test("nothing to reconcile before anybody has bought in", () => {
const state = makeTable({ seatCount: 6, seated: [], stack: 0 });
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.cashIn, 0);
assert.equal(bank.chipsInPlay, 0);
assert.equal(bank.balanced, true);
});
test("float dust is not a discrepancy", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 0.1 + 0.2, 0.3);
seat(state, 1, "Ben", 10, 10);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
});
describe("the number the banker counts out", () => {
// The standings had two signed columns and neither was an amount to pay. A player
// up $140 on a $340 stack read "$140" under a heading saying "Cash out", at the
// exact moment somebody was counting money onto the table.
test("chips in front is what they are holding, not what they are up", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1], stack: 340 });
state.seats[0].name = "Ann";
state.seats[0].buyIns = 200;
state.seats[1].buyIns = 200;
state.seats[1].stack = 60;
const rows = HoldemState.sessionStandings(state);
const ann = rows.find(r => r.name === "Ann");
assert.equal(ann.chipsInFront, 340, "the cash to count out");
assert.equal(ann.cashPosition, 140, "and separately, that they are up $140");
});
test("a player who is down still has chips to be handed", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1], stack: 60 });
state.seats[0].name = "Cal";
state.seats.forEach(p => { p.buyIns = 200; });
const cal = HoldemState.sessionStandings(state).find(r => r.name === "Cal");
assert.equal(cal.chipsInFront, 60, "they leave with $60 of chips");
assert.equal(cal.cashPosition, -140, "having lost $140 of the $200 they brought");
});
test("chips still out in the middle are counted as theirs", () => {
// Cashing out mid-hand isn't a thing, but the panel is read mid-hand constantly
// and a stack that drops by the size of a bet looks like money going missing.
const state = makeTable({ seatCount: 6, seated: [0, 1], stack: 200 });
state.seats[0].name = "Dee";
state.seats.forEach(p => { p.buyIns = 200; });
Betting.beginHand(state);
Betting.raiseTo(state, 0, 50);
const dee = HoldemState.sessionStandings(state).find(r => r.name === "Dee");
assert.equal(dee.chipsInFront, 200, "stack plus what's in the middle for them");
assert.equal(dee.cashPosition, 0, "so they are still level");
});
test("chips and up/down always differ by exactly the buy-in", () => {
const state = makeTable({ seatCount: 9, seated: [0, 1, 2, 3], stack: 100 });
[340, 150, 60, 250].forEach((chips, i) => {
state.seats[i].stack = chips;
state.seats[i].buyIns = 200 + i * 50;
});
HoldemState.sessionStandings(state).forEach(row => {
assert.equal(Money.round(row.chipsInFront - row.boughtIn), row.cashPosition,
`${row.name}'s two columns should tell one story`);
});
});
});
-473
View File
@@ -1,473 +0,0 @@
// 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");
});
});
-198
View File
@@ -1,198 +0,0 @@
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, makeTable, chipsOnTable } = require("./load");
describe("Betting.beginHand", () => {
test("blinds are posted and the seat after the big blind acts first", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0, smallBlind: 1, bigBlind: 2 });
Betting.beginHand(state);
assert.equal(state.seats[1].committed, 1, "small blind");
assert.equal(state.seats[2].committed, 2, "big blind");
assert.equal(state.currentBet, 2);
assert.equal(state.actingSeatIndex, 3, "under the gun");
});
test("heads-up, the button posts the small blind and acts first pre-flop", () => {
const state = makeTable({ seatCount: 6, seated: [2, 5], dealerSeatIndex: 2 });
Betting.beginHand(state);
assert.equal(state.seats[2].committed, 1, "the button is the small blind");
assert.equal(state.seats[5].committed, 2);
assert.equal(state.actingSeatIndex, 2, "the small blind acts first pre-flop heads-up");
});
test("heads-up, the big blind acts first once the flop is out", () => {
const state = makeTable({ seatCount: 6, seated: [2, 5], dealerSeatIndex: 2 });
Betting.beginHand(state);
Betting.call(state, 2);
Betting.check(state, 5);
Betting.closeStreet(state);
assert.equal(state.street, "flop");
assert.equal(state.actingSeatIndex, 5, "the big blind is first to act after the flop");
});
test("a blind bigger than a stack puts that player all-in without stalling the action", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1], dealerSeatIndex: 0, smallBlind: 50, bigBlind: 100 });
state.seats[0].stack = 10; // can't cover the small blind
Betting.beginHand(state);
assert.equal(state.seats[0].stack, 0, "all-in for what they had");
assert.equal(state.seats[0].committed, 10);
assert.notEqual(state.actingSeatIndex, 0, "a player with no chips has nothing to decide");
});
test("posting blinds never invents or destroys chips", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100 });
const before = chipsOnTable(state);
Betting.beginHand(state);
assert.equal(chipsOnTable(state), before);
});
});
describe("Betting street completion", () => {
test("a street ends once everyone has matched the bet and had a turn", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3);
Betting.call(state, 0);
Betting.call(state, 1);
assert.equal(Betting.isStreetComplete(state), false, "the big blind still has an option");
Betting.check(state, 2);
assert.equal(Betting.isStreetComplete(state), true);
assert.equal(state.actingSeatIndex, null);
});
test("a raise reopens the action for everyone who had already called", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3);
Betting.call(state, 0);
assert.equal(state.seats[3].hasActed, true);
Betting.raiseTo(state, 1, 10);
assert.equal(state.seats[3].hasActed, false, "seat 3 owes a response again");
assert.equal(state.seats[0].hasActed, false);
assert.equal(state.currentBet, 10);
assert.equal(Betting.isStreetComplete(state), false);
});
test("the action skips a player who is all-in but still in the hand", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
state.seats[3].stack = 5;
Betting.beginHand(state);
Betting.allIn(state, 3);
assert.equal(state.seats[3].stack, 0);
assert.notEqual(state.actingSeatIndex, 3);
// They are still live and can still win the pot.
assert.ok(Betting.liveSeats(state).some(s => s.index === 3));
});
test("closing a street sweeps chips into hand totals and resets the bet", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3);
Betting.call(state, 0);
Betting.call(state, 1);
Betting.check(state, 2);
const before = chipsOnTable(state);
Betting.closeStreet(state);
assert.equal(state.currentBet, 0);
assert.equal(state.street, "flop");
assert.equal(chipsOnTable(state), before, "sweeping moves chips, it doesn't change the total");
state.seats.forEach(p => assert.equal(p.committed, 0));
assert.equal(Betting.handTotal(state.seats[2]), 2);
});
});
describe("Betting all-in run-outs", () => {
test("with everyone all-in there is nobody left to ask", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], stack: 20, dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.allIn(state, 2);
Betting.allIn(state, 0);
Betting.allIn(state, 1);
assert.equal(Betting.canStillBet(state), false);
assert.equal(Betting.isRunningOut(state), true, "the board just gets dealt out");
Betting.closeStreet(state);
assert.equal(state.actingSeatIndex, null, "no phantom action on the flop");
});
test("one player with chips against an all-in cannot bet alone", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.seats[1].stack = 5;
Betting.beginHand(state);
Betting.fold(state, 2);
Betting.allIn(state, 0);
Betting.allIn(state, 1);
assert.equal(Betting.canStillBet(state), false);
assert.equal(Betting.isHandOver(state), false, "two players are still live for the showdown");
});
test("everyone folding to one player ends the hand", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.fold(state, 3);
Betting.fold(state, 0);
Betting.fold(state, 1);
assert.equal(Betting.isHandOver(state), true);
});
});
describe("Betting money handling", () => {
test("a player can never put in more than they have", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], stack: 30, dealerSeatIndex: 0 });
Betting.beginHand(state);
const moved = Betting.putIn(state, 0, 500);
assert.equal(moved, 30);
assert.equal(state.seats[0].stack, 0);
});
test("raise-to is what a dealer says out loud, not raise-by", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.raiseTo(state, 3, 10);
assert.equal(state.seats[3].committed, 10, "their street total is 10, not 10 on top");
assert.equal(state.seats[3].stack, 90);
});
test("the minimum raise has to match the last one", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
assert.equal(Betting.minRaiseTo(state), 4, "a big blind of 2 makes the first raise 4");
Betting.raiseTo(state, 3, 10);
assert.equal(Betting.minRaiseTo(state), 18, "an 8-chip raise means the next one is to 18");
});
test("winnings land back in front of the player", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.creditWinnings(state, [{ id: state.seats[0].id, amount: 42.5 }]);
assert.equal(state.seats[0].stack, 142.5, "the button posts nothing three-handed");
});
test("fractional blinds don't drift into floating-point dust", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], stack: 10, smallBlind: 0.1, bigBlind: 0.2 });
Betting.beginHand(state);
Betting.call(state, 0); // button limps
Betting.call(state, 1); // small blind completes
Betting.check(state, 2); // big blind is happy
Betting.closeStreet(state);
assert.equal(chipsOnTable(state), 30, "0.1 + 0.2 arithmetic didn't lose a chip");
assert.equal(Betting.potSoFar(state), 0.6);
state.seats.forEach(p => assert.equal(p.stack, 9.8));
});
});
-118
View File
@@ -1,118 +0,0 @@
// 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");
});
});
-148
View File
@@ -1,148 +0,0 @@
// Dealing around a player who busted and hasn't bought back in.
//
// A home game produces one of these about once an hour. The table used to deal them
// in anyway, promise a blind from a seat with nothing to post it with, take it from
// nobody, and then sit on a hand that could never finish.
const test = require("node:test");
const assert = require("node:assert");
const { Betting, HoldemState, makeTable, chipsOnTable } = require("./load");
const postedBy = state =>
state.seats
.map((player, index) => (player.committed > 0 ? { seat: index + 1, amount: player.committed } : null))
.filter(Boolean);
test("a seat with no chips and nothing in the pot is broke", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[2].stack = 0;
assert.deepEqual(Betting.brokeSeats(state), [2]);
});
test("an all-in player is not broke — they have money riding on the hand", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[2].stack = 12;
Betting.beginHand(state);
Betting.allIn(state, 2);
assert.equal(Betting.stackOf(state, state.seats[2]), 0);
assert.equal(Betting.isAllIn(state, state.seats[2]), true);
assert.deepEqual(Betting.brokeSeats(state), []);
});
test("a seat with no stack recorded falls back to the table's and isn't broke", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.defaultStack = 200;
state.seats[2].stack = null;
assert.deepEqual(Betting.brokeSeats(state), []);
});
test("a chair nobody is sitting in isn't broke, it's empty", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
assert.deepEqual(Betting.brokeSeats(state), []);
});
test("dealing sits the broke seat out and leaves everything else about it alone", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100 });
state.seats[2].stack = 0;
state.seats[2].name = "Cal";
state.seats[2].buyIns = 100;
Betting.beginHand(state);
assert.equal(state.seats[2].inHand, false);
assert.equal(state.seats[2].folded, false, "sat out, not folded — they didn't muck anything");
assert.equal(state.seats[2].name, "Cal");
assert.equal(state.seats[2].buyIns, 100);
});
test("the blinds skip the broke seat and land on players who can post", () => {
// Button on seat 1, so the blinds would be seats 2 and 3. Seat 2 is busted.
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
state.seats[1].stack = 0;
Betting.beginHand(state);
assert.deepEqual(postedBy(state), [
{ seat: 3, amount: state.smallBlind },
{ seat: 4, amount: state.bigBlind },
]);
});
test("the preview promises what the deal produces", () => {
// The fault this whole step exists to prevent: the preview once read a table the
// deal was about to change underneath it.
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
state.seats[1].stack = 0;
state.bettingOpen = false;
const preview = Betting.blindPreview(state);
assert.deepEqual(preview.satOut, [1]);
Betting.beginHand(state);
const posted = postedBy(state);
assert.equal(posted.find(p => p.amount === state.smallBlind).seat, preview.sbIndex + 1);
assert.equal(posted.find(p => p.amount === state.bigBlind).seat, preview.bbIndex + 1);
});
test("asking for the preview doesn't sit anybody out on its own", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[1].stack = 0;
Betting.blindPreview(state);
assert.equal(state.seats[1].inHand, true, "the preview is a view, not a change");
});
test("with only one player left holding chips there is nothing to preview", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[1].stack = 0;
state.seats[2].stack = 0;
assert.equal(Betting.blindPreview(state), null);
});
test("no chips move when the broke seats are dealt around", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100 });
state.seats[2].stack = 0;
const before = chipsOnTable(state);
Betting.beginHand(state);
assert.equal(chipsOnTable(state), before);
});
test("the board isn't running out before the hand is dealt", () => {
// Two busted players and one with chips looks exactly like a table of all-ins to
// the run-out test, and the bar was announcing one over an empty felt.
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[1].stack = 0;
state.seats[2].stack = 0;
state.bettingOpen = false;
assert.equal(Betting.isRunningOut(state), false);
});
test("buying back in puts them in the next hand", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[2].stack = 0;
Betting.beginHand(state);
assert.equal(state.seats[2].inHand, false);
// What the dealer does when they hand over cash: chips, and back in.
state.seats[2].stack = 100;
state.seats[2].inHand = true;
HoldemState.startNextHand(state);
Betting.beginHand(state);
assert.equal(state.seats[2].inHand, true);
assert.equal(Betting.liveSeats(state).length, 3);
});
test("the table dealt around them counts the right number of players", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100 });
state.seats[3].stack = 0;
assert.equal(Betting.liveSeats(state).length, 4);
assert.equal(Betting.liveSeats(Betting.tableAsDealt(state)).length, 3);
assert.equal(state.seats[3].inHand, true, "the view didn't touch the table");
});
-76
View File
@@ -1,76 +0,0 @@
// Whether handing a seat chips also puts them back in the game.
const test = require("node:test");
const assert = require("node:assert");
const { Betting, makeTable } = require("./load");
test("a busted player who has been sat out comes back in", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[1].stack = 0;
Betting.beginHand(state); // the deal sits them out
assert.equal(state.seats[1].inHand, false);
assert.equal(Betting.buyInDealsThemIn(state.seats[1]), true);
});
test("a chair being bought into for the first time comes in", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1], stack: 100 });
state.seats[4].name = "Eve";
state.seats[4].stack = null;
assert.equal(Betting.buyInDealsThemIn(state.seats[4]), true);
});
test("a seat sat out while holding chips stays out", () => {
// A dealer sat them out on purpose and is topping them up. Dealing them back in
// would be the tool guessing at something it wasn't told.
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[2].inHand = false;
assert.equal(Betting.buyInDealsThemIn(state.seats[2]), false);
});
test("somebody already in the hand is left exactly where they are", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
assert.equal(Betting.buyInDealsThemIn(state.seats[0]), false);
// Including a player who is in but out of chips — they're all-in, not sat out.
state.seats[2].stack = 0;
assert.equal(state.seats[2].inHand, true);
assert.equal(Betting.buyInDealsThemIn(state.seats[2]), false);
});
test("a blank stack field reads as nothing recorded, not as a number", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1], stack: 100 });
state.seats[3].name = "Dee";
state.seats[3].stack = "";
assert.equal(Betting.buyInDealsThemIn(state.seats[3]), true);
});
test("it doesn't ask the table what a missing stack would have been", () => {
// stackOf substitutes the table's starting stack for a seat that has none, which
// would make a seat with nothing recorded look like it was holding chips.
const state = makeTable({ seatCount: 6, seated: [0, 1], stack: 100 });
state.defaultStack = 500;
state.seats[4].name = "Eve";
state.seats[4].stack = null;
assert.equal(Betting.stackOf(state, state.seats[4]), 500);
assert.equal(Betting.buyInDealsThemIn(state.seats[4]), true);
});
test("asking doesn't change anything", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 100 });
state.seats[2].stack = 0;
state.seats[2].inHand = false;
const before = JSON.stringify(state);
Betting.buyInDealsThemIn(state.seats[2]);
assert.equal(JSON.stringify(state), before);
});
test("nothing to decide about a seat that isn't there", () => {
assert.equal(Betting.buyInDealsThemIn(null), false);
assert.equal(Betting.buyInDealsThemIn(undefined), false);
});
-129
View File
@@ -1,129 +0,0 @@
// 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
@@ -1,229 +0,0 @@
// 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);
});
});
-82
View File
@@ -1,82 +0,0 @@
// The chips to actually push, for an amount.
const test = require("node:test");
const assert = require("node:assert");
const { Money } = require("./load");
// A standard house set.
const LEGEND = [
{ value: 1, color: "#fff" },
{ value: 5, color: "#c0392b" },
{ value: 25, color: "#27ae60" },
{ value: 100, color: "#2c3e50" },
{ value: 500, color: "#8e44ad" },
];
const say = (amount, legend = LEGEND) => Money.formatChipBreakdown(amount, legend);
test("a payout comes back as chips, largest first", () => {
assert.equal(say(132), "1×$100, 1×$25, 1×$5, 2×$1");
});
test("it uses the fewest chips on a normal set", () => {
const { chips } = Money.chipBreakdown(500, LEGEND);
assert.deepEqual(chips.map(c => `${c.count}×${c.value}`), ["1×500"]);
});
test("a denomination that doesn't fit is skipped rather than listed as none", () => {
assert.equal(say(7), "1×$5, 2×$1");
});
test("nothing to pay is nothing to say", () => {
assert.equal(say(0), "");
assert.equal(say(-5), "");
});
test("no legend means no advice, not a wrong answer", () => {
// A table that never set chip colours up gets the amount on its own.
assert.equal(say(132, []), "");
assert.equal(say(132, null), "");
});
test("a legend with no values in it yet is the same as none", () => {
assert.equal(say(132, [{ value: "", color: "#fff" }, { value: 0, color: "#000" }]), "");
});
test("what the smallest chip can't make is reported, not rounded away", () => {
// 50c in a game whose smallest chip is a dollar is the dealer's problem to solve,
// and they can only solve it if they're told.
const { chips, remainder } = Money.chipBreakdown(10.5, LEGEND);
assert.deepEqual(chips.map(c => `${c.count}×${c.value}`), ["2×5"]);
assert.equal(remainder, 0.5);
assert.equal(say(10.5), "2×$5, $0.50 no chip covers");
});
test("cent chips make cent amounts exactly", () => {
const cents = [{ value: 0.25 }, { value: 0.05 }, { value: 0.01 }];
assert.equal(say(0.41, cents), "1×$0.25, 3×$0.05, 1×$0.01");
assert.equal(Money.chipBreakdown(0.41, cents).remainder, 0);
});
test("the chips add up to the amount", () => {
for (const amount of [1, 7, 33, 132, 499, 500, 1234, 9999]) {
const { chips, remainder } = Money.chipBreakdown(amount, LEGEND);
const total = chips.reduce((sum, c) => sum + c.count * c.value, 0) + remainder;
assert.equal(Money.round(total), amount, `${amount} should be accounted for`);
}
});
test("a legend in any order still pays largest first", () => {
const jumbled = [{ value: 25 }, { value: 1 }, { value: 500 }, { value: 5 }, { value: 100 }];
assert.equal(say(631, jumbled), "1×$500, 1×$100, 1×$25, 1×$5, 1×$1");
});
test("the colour comes along, so the felt can say it in chips", () => {
const { chips } = Money.chipBreakdown(25, LEGEND);
assert.equal(chips[0].color, "#27ae60");
});
test("a legend that exists but can't reach the amount does say so", () => {
// Different from having no legend at all: this table has told us its chips, and
// the answer is that they don't go that low.
assert.equal(say(3, [{ value: 5 }, { value: 25 }]), "$3 no chip covers");
});
-183
View File
@@ -1,183 +0,0 @@
// Taking a chip colour out of the legend.
//
// This was one click of an unlabelled 24px button, and it was not a change to a legend.
// computeContribution() prices a seat by running the legend over that seat's chip
// counts, so a colour that leaves takes every chip counted in it off the table.
// Measured in a browser on a three-handed table: deleting the $500 row took $22,500 of
// $26,874 with it, with no confirmation, nothing said afterwards, and no way back —
// a colour added again is a new colour with a new id, while the counts stay keyed to
// the one that left. The counts were left behind too, so the saved file carried money
// that nothing could price and nothing could show.
//
// What is tested here is mostly the number in the warning, because a warning that
// overstates is worse than none: it is the one thing a dealer would have to trust at
// the exact moment they are about to lose track of the box.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { HoldemState, Money } = require("./load");
const tableWith = ({ counts = [], overrides = [], basePot = null } = {}) => {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 9);
state.basePotAmount = basePot;
["Christopher", "Mike from work", "Alexandra"].forEach((name, i) => {
state.seats[i].name = name;
state.seats[i].inHand = true;
state.seats[i].buyIns = 500;
state.seats[i].chipCounts = {};
});
counts.forEach(([seat, chipIndex, n]) => {
state.seats[seat].chipCounts[state.chipLegend[chipIndex].id] = n;
});
overrides.forEach(([seat, amount]) => { state.seats[seat].amountOverride = amount; });
return state;
};
const onTable = state => state.seats.reduce(
(sum, p) => sum + HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount), 0);
// ---------------------------------------------------------------------------
describe("what a chip colour is holding up", () => {
test("is the money, named seat by seat", () => {
const state = tableWith({ counts: [[0, 2, 4], [1, 2, 10]] }); // the $25 chip
const usage = HoldemState.chipColorUsage(state, state.chipLegend[2].id);
assert.equal(usage.total, 350);
assert.equal(usage.chips, 14);
assert.deepEqual(usage.seats.map(s => [s.name, s.count, s.amount]), [
["Christopher", 4, 100],
["Mike from work", 10, 250],
]);
});
test("is nothing at all for a colour nobody counted", () => {
const state = tableWith({ counts: [[0, 2, 4]] });
const usage = HoldemState.chipColorUsage(state, state.chipLegend[4].id);
assert.equal(usage.total, 0);
assert.deepEqual(usage.seats, []);
assert.ok(usage.chip, "the colour itself is still found, so it can be named");
});
test("and nothing for a colour that isn't there", () => {
const state = tableWith();
assert.deepEqual(HoldemState.chipColorUsage(state, "no-such-chip"),
{ chip: null, total: 0, chips: 0, seats: [] });
});
});
describe("the number in the warning is the number the table loses", () => {
// The whole point. Multiplying the chips by their value would have been the obvious
// way to work this out and it is wrong in both directions — the two tests below are
// the two ways it is wrong.
const dropFromRemoving = (state, chipId) => {
const before = onTable(state);
HoldemState.removeChipColor(state, chipId);
return Money.round(before - onTable(state));
};
test("a seat with a typed amount ignores its chips, so its colour is worth nothing", () => {
// computeContribution() reads amountOverride first and never reaches the counts.
// Christopher is holding ten $25 chips on paper and priced at a flat $90.
const state = tableWith({ counts: [[0, 2, 10]], overrides: [[0, 90]] });
const chipId = state.chipLegend[2].id;
const usage = HoldemState.chipColorUsage(state, chipId);
assert.equal(usage.total, 0, "$250 of chips, but the seat is not priced from them");
assert.equal(dropFromRemoving(state, chipId), 0);
});
test("a seat whose chips all leave falls back to the base pot, not to zero", () => {
// The $25s are everything Christopher has counted, so taking them away drops him
// to the table's standing ante — a loss of 50, not of 250.
const state = tableWith({ counts: [[0, 2, 10]], basePot: 200 });
const chipId = state.chipLegend[2].id;
const usage = HoldemState.chipColorUsage(state, chipId);
assert.equal(usage.total, 50, "250 of chips, but only 50 of it actually leaves");
assert.equal(dropFromRemoving(state, chipId), 50);
});
test("and across a spread of tables the two always agree", () => {
function rng(seed) {
let s = seed >>> 0;
return () => {
s = (s * 1664525 + 1013904223) >>> 0;
return s / 4294967296;
};
}
const random = rng(20260906);
let withMoney = 0;
for (let table = 0; table < 2000; table++) {
const counts = [];
for (let seat = 0; seat < 3; seat++) {
for (let chip = 0; chip < 5; chip++) {
if (random() < 0.5) counts.push([seat, chip, 1 + Math.floor(random() * 20)]);
}
}
const overrides = [];
for (let seat = 0; seat < 3; seat++) {
if (random() < 0.25) overrides.push([seat, Math.floor(random() * 400)]);
}
const basePot = random() < 0.5 ? 200 : null;
const chipIndex = Math.floor(random() * 5);
const stated = tableWith({ counts, overrides, basePot });
const chipId = stated.chipLegend[chipIndex].id;
const claimed = HoldemState.chipColorUsage(stated, chipId).total;
const actual = dropFromRemoving(tableWith({ counts, overrides, basePot }), chipId);
if (claimed !== 0) withMoney++;
assert.equal(claimed, actual,
`table ${table}: warned ${claimed}, table moved ${actual}\n` +
JSON.stringify({ counts, overrides, basePot, chipIndex }));
}
// Guards the generator: shapes that never put money on a colour would make every
// assertion above compare zero with zero.
assert.ok(withMoney > 500, `only ${withMoney} of 2000 tables had money on the colour`);
});
test("and it can be a gain, which is said as one", () => {
// Fourteen $1 chips against a $200 standing ante: once the colour goes, the seat
// stops being priced from its chips and falls through to the ante, so the table
// goes *up* by 186. Found by the randomised check above, not by hand.
const state = tableWith({ counts: [[1, 0, 14]], basePot: 200 });
const usage = HoldemState.chipColorUsage(state, state.chipLegend[0].id);
assert.equal(usage.total, -186);
assert.equal(dropFromRemoving(state, state.chipLegend[0].id), -186);
});
});
describe("removing it", () => {
test("takes the counts with it, so nothing is left priced by a colour that is gone", () => {
const state = tableWith({ counts: [[0, 2, 4], [1, 2, 10], [1, 0, 3]] });
const chipId = state.chipLegend[2].id;
HoldemState.removeChipColor(state, chipId);
assert.equal(state.chipLegend.filter(c => c.id === chipId).length, 0);
state.seats.forEach(player => assert.ok(!(chipId in (player.chipCounts || {})),
"a count against a colour no legend entry answers to is money nothing can show"));
// The other colour on that seat is untouched.
assert.equal(state.seats[1].chipCounts[state.chipLegend[0].id], 3);
});
test("reports what it cost, measured before anything moved", () => {
const state = tableWith({ counts: [[0, 2, 4]] });
const usage = HoldemState.removeChipColor(state, state.chipLegend[2].id);
assert.equal(usage.total, 100);
assert.equal(usage.seats.length, 1);
});
test("and a colour that isn't there changes nothing", () => {
const state = tableWith({ counts: [[0, 2, 4]] });
const before = onTable(state);
const usage = HoldemState.removeChipColor(state, "no-such-chip");
assert.equal(usage.chip, null);
assert.equal(state.chipLegend.length, 5);
assert.equal(onTable(state), before);
});
});
-268
View File
@@ -1,268 +0,0 @@
// The button when somebody gets up out of the blinds.
//
// Passing the button to the next *player* is right until a chair between the button
// and the blinds empties. Then it pulls the whole blind order forward a place: the
// player after the empty chair is never asked for a big blind, and the one after them
// is asked an orbit early. The dead button rule holds the rotation to the seats for
// one hand so the big blind still advances exactly one player.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { HoldemState, Betting, makeTable } = require("./load");
// Four players in six chairs: Ann 0, Ben 1, Cal 2, Dee 3.
const NAMES = ["Ann", "Ben", "Cal", "Dee"];
const table = (dealerSeatIndex = 0) => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 200, dealerSeatIndex });
NAMES.forEach((name, i) => { state.seats[i].name = name; });
return state;
};
const nameOf = (state, index) =>
index === null || index === undefined ? null : (state.seats[index].name || `empty seat ${index + 1}`);
const blinds = state => {
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
return { sb: nameOf(state, sbIndex), bb: nameOf(state, bbIndex) };
};
const leave = (state, index) => {
state.seats[index].name = "";
state.seats[index].inHand = false;
state.seats[index].stack = 0;
state.seats[index].buyIns = 0;
};
describe("somebody gets up out of the blinds", () => {
test("the small blind leaves: dead button, and the big blind still moves one player", () => {
const state = table(1); // button Ben, small Cal, big Dee
Betting.beginHand(state);
assert.deepEqual(blinds(state), { sb: "Cal", bb: "Dee" });
leave(state, 2); // Cal takes their chips and goes
HoldemState.startNextHand(state);
Betting.beginHand(state);
assert.equal(state.dealerSeatIndex, 2, "the button holds Cal's empty chair");
assert.equal(state.seats[2].inHand, false, "which is the point — it's on nobody");
assert.deepEqual(blinds(state), { sb: "Dee", bb: "Ann" },
"Dee moves from big to small and Ann posts the big blind, one player along");
});
test("and Ann is not skipped, which is the money in it", () => {
// The old rotation passed the button to the next player, which made the blinds
// Ann/Ben — Ann never posting a big blind at all, and Ben posting one an orbit
// early. That is a real big blind out of a real player's stack.
const state = table(1);
Betting.beginHand(state);
leave(state, 2);
HoldemState.startNextHand(state);
assert.equal(blinds(state).bb, "Ann", "Ann owes the big blind and still owes it");
});
test("the big blind leaves: no small blind is posted this hand", () => {
const state = table(1); // button Ben, small Cal, big Dee
Betting.beginHand(state);
leave(state, 3); // Dee goes
HoldemState.startNextHand(state);
Betting.beginHand(state);
const { sbIndex, bbIndex, deadSmallBlind } = HoldemState.getBlindSeats(state);
assert.equal(state.dealerSeatIndex, 2, "the button reaches Cal as it was always going to");
assert.equal(sbIndex, null, "the small blind is dead");
assert.equal(deadSmallBlind, true, "and says so, rather than looking like a table with no blinds");
assert.equal(nameOf(state, bbIndex), "Ann", "the big blind still moves on one player");
});
test("a dead small blind still deals a hand, with one blind in the middle", () => {
const state = table(1);
Betting.beginHand(state);
leave(state, 3);
HoldemState.startNextHand(state);
Betting.beginHand(state);
assert.equal(state.bettingOpen, true, "the hand goes ahead");
const posted = state.seats.reduce((sum, p) => sum + Betting.committed(p), 0);
assert.equal(posted, state.bigBlind, "just the big blind, and nothing conjured to stand in for the small");
assert.equal(state.currentBet, state.bigBlind);
assert.ok(state.actingSeatIndex !== null, "and somebody is on the clock");
});
test("somebody leaving from anywhere else changes nothing", () => {
const state = table(1); // button Ben, small Cal, big Dee
Betting.beginHand(state);
leave(state, 0); // Ann, who was under the gun
HoldemState.startNextHand(state);
assert.equal(state.dealerSeatIndex, 2, "the button passes to Cal exactly as before");
assert.equal(state.deadButton, false);
assert.equal(state.deadSmallBlind, false);
assert.deepEqual(blinds(state), { sb: "Dee", bb: "Ben" });
});
});
describe("the ordinary rotation is untouched", () => {
test("a full table passes the button one player at a time", () => {
const state = table(0);
const seen = [];
for (let hand = 0; hand < 8; hand++) {
Betting.beginHand(state);
seen.push(blinds(state).bb);
HoldemState.startNextHand(state);
}
assert.deepEqual(seen, ["Cal", "Dee", "Ann", "Ben", "Cal", "Dee", "Ann", "Ben"],
"two clean orbits, everybody paying one big blind per orbit");
assert.equal(state.deadButton, false);
assert.equal(state.deadSmallBlind, false);
});
test("players spread thinly around a big table don't create dead positions", () => {
// Three players in nine chairs. The chairs between them were never in the
// rotation, so holding to seats there would post blinds to nobody hand after
// hand — which is why the button follows players, not chairs, by default.
const state = makeTable({ seatCount: 9, seated: [0, 4, 7], stack: 200, dealerSeatIndex: 0 });
["Ann", "", "", "", "Ben", "", "", "Cal"].forEach((n, i) => { state.seats[i].name = n; });
const seen = [];
for (let hand = 0; hand < 6; hand++) {
Betting.beginHand(state);
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
assert.ok(state.seats[sbIndex].inHand, "a real player posts the small blind");
assert.ok(state.seats[bbIndex].inHand, "and a real player the big");
seen.push(nameOf(state, bbIndex));
HoldemState.startNextHand(state);
}
assert.deepEqual(seen, ["Cal", "Ann", "Ben", "Cal", "Ann", "Ben"], "one big blind each per orbit");
});
test("pressing next hand twice without dealing just passes the button along", () => {
const state = table(0);
Betting.beginHand(state);
HoldemState.startNextHand(state);
assert.equal(state.dealerSeatIndex, 1);
HoldemState.startNextHand(state);
assert.equal(state.dealerSeatIndex, 2, "and doesn't rotate off the same hand twice");
});
});
describe("the rule knows where it stops", () => {
test("down to two players, heads-up takes over and nothing is left dead", () => {
const state = table(1);
Betting.beginHand(state);
leave(state, 2);
leave(state, 3); // both blinds walk at once
HoldemState.startNextHand(state);
Betting.beginHand(state);
const { sbIndex, headsUp } = HoldemState.getBlindSeats(state);
assert.equal(headsUp, true);
assert.equal(sbIndex, state.dealerSeatIndex, "heads-up the button posts the small blind");
assert.ok(state.seats[state.dealerSeatIndex].inHand, "and the button is on a player again");
});
test("a button stranded by accident is still rescued", () => {
// Not the dead button: nobody left out of the blinds, the chair the button is
// on just emptied. That one does want putting back on a player.
const state = table(3);
state.seats[3].inHand = false;
HoldemState.ensureButtonOnPlayer(state);
assert.ok(state.seats[state.dealerSeatIndex].inHand);
});
test("moving the button by hand clears the dead positions", () => {
const state = table(1);
Betting.beginHand(state);
leave(state, 2);
HoldemState.startNextHand(state);
assert.equal(state.deadButton, true);
// What the seat menu's "Give the button" does.
state.dealerSeatIndex = 0;
state.deadButton = false;
state.deadSmallBlind = false;
Betting.beginHand(state);
const { sbIndex } = HoldemState.getBlindSeats(state);
assert.ok(state.seats[sbIndex].inHand, "a real small blind again, where the dealer put it");
});
test("naming a blind by hand overrules a dead one", () => {
const state = table(1);
Betting.beginHand(state);
leave(state, 3);
HoldemState.startNextHand(state);
assert.equal(state.deadSmallBlind, true);
state.blindOverride = { sbIndex: 1, bbIndex: 0 };
const { sbIndex, bbIndex, manual } = HoldemState.getBlindSeats(state);
assert.equal(manual, true);
assert.equal(sbIndex, 1, "the dealer's word beats the rule");
assert.equal(bbIndex, 0);
});
test("a table saved before any of this reads as nothing dead", () => {
const state = table(0);
const parsed = JSON.parse(JSON.stringify(state));
delete parsed.deadButton;
delete parsed.deadSmallBlind;
delete parsed.postedBlinds;
const store = new Map([[HoldemState.STORAGE_KEY, JSON.stringify(parsed)]]);
globalThis.localStorage = {
getItem: key => (store.has(key) ? store.get(key) : null),
setItem: (key, value) => store.set(key, value),
removeItem: key => store.delete(key),
};
const loaded = HoldemState.load();
assert.equal(loaded.deadButton, false);
assert.equal(loaded.deadSmallBlind, false);
assert.equal(loaded.postedBlinds, null);
HoldemState.startNextHand(loaded);
assert.ok(loaded.seats[loaded.dealerSeatIndex].inHand, "and rotates the ordinary way");
delete globalThis.localStorage;
});
});
describe("chips are not invented or lost by any of it", () => {
test("posting one blind instead of two moves chips and doesn't make them", () => {
// Measured across the deal, which is the step that touches stacks. A hand with
// a dead small blind has one blind in the middle instead of two — the danger is
// a null small blind being treated as a zero-cost posting somewhere, or the big
// blind quietly covering for it.
const state = table(1);
const chips = s => s.seats.reduce(
(sum, p) => sum + Betting.stackOf(s, p) + Betting.handTotal(p), 0);
Betting.beginHand(state);
leave(state, 3); // the big blind goes, small blind dies
for (let hand = 0; hand < 4; hand++) {
HoldemState.startNextHand(state);
const before = chips(state);
Betting.beginHand(state);
assert.equal(chips(state), before, `the deal drifted the count on hand ${hand + 1}`);
}
});
test("a dead small blind takes exactly one blind out of one stack", () => {
const state = table(1);
Betting.beginHand(state);
leave(state, 3);
HoldemState.startNextHand(state);
const stacks = () => state.seats.map(p => Betting.stackOf(state, p));
const before = stacks();
Betting.beginHand(state);
const after = stacks();
const paid = before.map((v, i) => v - after[i]).filter(d => d !== 0);
assert.deepEqual(paid, [state.bigBlind], "one player, one big blind, nobody else touched");
});
});
-205
View File
@@ -1,205 +0,0 @@
// Dealing and betting are two decisions, and fusing them meant the table guessed.
//
// The moment between hands is when people sit down, stand up and argue about whose
// turn it is. With blinds posted the instant the previous hand ended, the blind
// badges recomputed off `inHand` while the committed chips stayed frozen — so seating
// somebody produced a big blind who had posted nothing.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, HoldemState, makeTable, chipsOnTable } = require("./load");
const postedBy = state => state.seats
.map((p, i) => (Betting.committed(p) > 0 ? i : null))
.filter(i => i !== null);
describe("the table waits to be dealt", () => {
test("finishing a hand leaves the next one un-dealt", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
assert.equal(state.bettingOpen, true);
HoldemState.startNextHand(state);
assert.equal(state.bettingOpen, false, "the next hand hasn't been dealt");
assert.equal(state.actingSeatIndex, null, "nobody is on the clock");
assert.deepEqual(postedBy(state), [], "and no blind has been committed");
});
test("no money moves until the dealer deals", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
const start = chipsOnTable(state);
HoldemState.startNextHand(state);
assert.equal(chipsOnTable(state), start);
assert.equal(HoldemState.totalPot(state), 0);
Betting.beginHand(state);
assert.equal(state.bettingOpen, true);
assert.equal(postedBy(state).length, 2, "now the blinds are in");
assert.equal(chipsOnTable(state), start, "and nothing was created doing it");
});
});
describe("setting the table costs nothing", () => {
test("seating a player before the deal changes who posts", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
HoldemState.startNextHand(state);
const before = Betting.blindPreview(state);
state.seats[3].inHand = true;
state.seats[3].stack = 100;
const after = Betting.blindPreview(state);
assert.notDeepEqual(
[before.sbIndex, before.bbIndex],
[after.sbIndex, after.bbIndex],
"the preview follows the new table"
);
assert.deepEqual(postedBy(state), [], "and still nothing is committed");
Betting.beginHand(state);
assert.deepEqual(postedBy(state).sort(), [after.sbIndex, after.bbIndex].sort(),
"the money lands where the preview said it would");
});
test("removing a player before the deal can't strand their blind", () => {
// The old failure: take out the big blind after the hand had begun and their
// chips stayed in the pot while the badge moved to somebody who'd posted
// nothing. Before the deal there is nothing to strand.
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
HoldemState.startNextHand(state);
const doomed = Betting.blindPreview(state).bbIndex;
state.seats[doomed].inHand = false;
assert.deepEqual(postedBy(state), [], "nobody has posted, so nothing is stranded");
Betting.beginHand(state);
const posted = postedBy(state);
assert.ok(!posted.includes(doomed), "the player who left posts nothing");
posted.forEach(i => assert.ok(state.seats[i].inHand, "only players in the hand post"));
});
test("moving the button before the deal just moves it", () => {
const state = makeTable({ seatCount: 8, seated: [0, 2, 4, 6], dealerSeatIndex: 0 });
const start = chipsOnTable(state);
HoldemState.startNextHand(state);
[2, 4, 6, 0].forEach(seat => {
state.dealerSeatIndex = seat;
assert.deepEqual(postedBy(state), [], `passing the button to seat ${seat + 1} posted something`);
assert.equal(chipsOnTable(state), start);
});
Betting.beginHand(state);
assert.equal(chipsOnTable(state), start, "dealing moves chips between stacks, not into thin air");
});
test("what the preview promises is what gets posted", () => {
const state = makeTable({ seatCount: 9, seated: [1, 3, 6, 8], dealerSeatIndex: 1 });
HoldemState.startNextHand(state);
const preview = Betting.blindPreview(state);
Betting.beginHand(state);
assert.equal(Betting.committed(state.seats[preview.sbIndex]), preview.smallBlind);
assert.equal(Betting.committed(state.seats[preview.bbIndex]), preview.bigBlind);
});
test("there's nothing to preview without two players", () => {
const alone = makeTable({ seatCount: 6, seated: [2] });
HoldemState.startNextHand(alone);
assert.equal(Betting.blindPreview(alone), null);
const empty = makeTable({ seatCount: 6, seated: [] });
HoldemState.startNextHand(empty);
assert.equal(Betting.blindPreview(empty), null);
});
test("a hand-picked blind shows up in the preview", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
HoldemState.startNextHand(state);
state.blindOverride = { sbIndex: 3, bbIndex: 0 };
const preview = Betting.blindPreview(state);
assert.equal(preview.manual, true);
assert.equal(preview.sbIndex, 3);
assert.equal(preview.bbIndex, 0);
});
});
describe("a table saved mid-hand comes back mid-hand", () => {
const loadWith = saved => {
const original = globalThis.localStorage;
globalThis.localStorage = { getItem: () => JSON.stringify(saved), setItem: () => {}, removeItem: () => {} };
const state = HoldemState.load();
globalThis.localStorage = original;
return state;
};
test("chips already committed mean the betting was open", () => {
const state = loadWith({
seats: [{ id: "a", name: "Ann", inHand: true, committed: 2 }, { id: "b", name: "Ben", inHand: true, committed: 0 }],
handNumber: 3,
});
assert.equal(state.bettingOpen, true, "otherwise it would offer to deal over a live hand");
});
test("somebody on the clock means the betting was open", () => {
const state = loadWith({
seats: [{ id: "a", inHand: true }, { id: "b", inHand: true }],
actingSeatIndex: 1, handNumber: 2,
});
assert.equal(state.bettingOpen, true);
});
test("a quiet table comes back waiting to be dealt", () => {
const state = loadWith({
seats: [{ id: "a", inHand: true }, { id: "b", inHand: true }],
actingSeatIndex: null, handNumber: 5,
});
assert.equal(state.bettingOpen, false);
});
});
describe("the preview tells the truth about the button", () => {
test("a button parked on an empty chair is answered for where it will be", () => {
// The preview used to read the button where it sat, while dealing relocated it
// first — so it promised one pair of blinds and produced another.
const state = makeTable({ seatCount: 6, seated: [1, 2, 3], dealerSeatIndex: 0 });
state.bettingOpen = false;
assert.equal(state.seats[0].inHand, false, "the button is on an empty chair");
const preview = Betting.blindPreview(state);
assert.equal(preview.buttonMoves, true, "and the preview knows it will move");
Betting.beginHand(state);
assert.equal(Betting.committed(state.seats[preview.sbIndex]), preview.smallBlind);
assert.equal(Betting.committed(state.seats[preview.bbIndex]), preview.bigBlind);
assert.equal(state.dealerSeatIndex, preview.buttonIndex, "and it moved where it said");
});
test("asking where the button will be doesn't move it", () => {
const state = makeTable({ seatCount: 6, seated: [1, 2, 3], dealerSeatIndex: 0 });
state.bettingOpen = false;
Betting.blindPreview(state);
Betting.blindPreview(state);
assert.equal(state.dealerSeatIndex, 0, "the preview is a question, not an action");
});
test("a button already on a player is left alone", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.bettingOpen = false;
const preview = Betting.blindPreview(state);
assert.equal(preview.buttonMoves, false);
assert.equal(preview.buttonIndex, 0);
});
test("buttonSeatForDeal copes with a table nobody is sitting at", () => {
const state = makeTable({ seatCount: 6, seated: [] });
assert.equal(HoldemState.buttonSeatForDeal(state), state.dealerSeatIndex);
});
});
-164
View File
@@ -1,164 +0,0 @@
// 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, and feedback.js for the
// toast's height, which is one line or two depending on what is being said.
// The seat sheet's height is the same idea as the action bar's, and for the same
// reason: two things fixed to the bottom of a phone, and the toast has to clear
// whichever is taller. It changes when a section of the sheet is unfolded, so it
// is measured rather than written down — see Render.watchSeatSheetHeight.
const fromScript = new Set([
"--actionBarHeight", "--feltRoomPx", "--seatPuckW", "--betChipColour",
"--toastHeight", "--seatSheetHeight",
]);
// 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/);
});
});
-94
View File
@@ -1,94 +0,0 @@
// Chips the dealer took off the table on purpose.
//
// Starting the next hand with money still in the middle destroys it — the tool asks
// first and says so afterwards. What it didn't do was remember, so the bank check saw
// only that chips were gone and reported them as missing.
const test = require("node:test");
const assert = require("node:assert");
const { HoldemState, Money, makeTable } = require("./load");
const table = () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 200 });
state.seats.slice(0, 4).forEach(player => { player.buyIns = 200; });
return state;
};
test("a table with nothing thrown away balances as before", () => {
const bank = HoldemState.bankReconciliation(table());
assert.equal(bank.balanced, true);
assert.equal(bank.discarded, 0);
});
test("chips that went missing are still reported", () => {
// The check exists for this: cash in the box with no chips to match it.
const state = table();
state.seats[0].stack = 150;
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, false);
assert.equal(bank.difference, -50);
});
test("an abandoned pot is accounted for rather than counted as missing", () => {
const state = table();
state.seats[1].stack = 199;
state.seats[2].stack = 198;
state.seats[3].stack = 198;
state.discarded = 5;
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.chipsInPlay, 795);
assert.equal(bank.discarded, 5);
assert.equal(bank.balanced, true, "the box knows exactly where that $5 went");
});
test("throwing a pot away doesn't hide a real shortfall underneath it", () => {
const state = table();
state.seats[1].stack = 199;
state.seats[2].stack = 198;
state.seats[3].stack = 148; // $50 genuinely unaccounted for as well
state.discarded = 5;
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, false);
assert.equal(bank.difference, -50);
});
test("a nonsense discarded value can't move the answer", () => {
const state = table();
state.discarded = -100;
assert.equal(HoldemState.bankReconciliation(state).discarded, 0);
state.discarded = "not a number";
assert.equal(HoldemState.bankReconciliation(state).discarded, 0);
});
test("a table saved before this existed reads as nothing thrown away", () => {
const saved = JSON.stringify(table());
const parsed = JSON.parse(saved);
delete parsed.discarded;
const store = new Map([[HoldemState.STORAGE_KEY, JSON.stringify(parsed)]]);
globalThis.localStorage = {
getItem: key => (store.has(key) ? store.get(key) : null),
setItem: (key, value) => store.set(key, value),
removeItem: key => store.delete(key),
};
const loaded = HoldemState.load();
assert.equal(loaded.discarded, 0);
assert.equal(HoldemState.bankReconciliation(loaded).balanced, true);
delete globalThis.localStorage;
});
test("the amounts still add up the way the panel shows them", () => {
const state = table();
state.seats[1].stack = 199;
state.seats[2].stack = 198;
state.seats[3].stack = 198;
state.discarded = 5;
const bank = HoldemState.bankReconciliation(state);
assert.equal(Money.round(bank.chipsInPlay + bank.discarded), bank.cashIn);
});
-97
View File
@@ -1,97 +0,0 @@
// The things the dealer wrote down, in the file they hand over.
//
// The export already carried the hands, the standings and the settle-up. It didn't
// carry either of the two places a dealer types context — the per-seat fields and the
// table's own notes — so the one place an IOU was written down was the one place it
// couldn't leave.
const test = require("node:test");
const assert = require("node:assert");
const { HandHistoryExport, HoldemState, makeTable } = require("./load");
const tableWithNotes = () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 200 });
["Ann", "Ben", "Cal"].forEach((name, i) => {
state.seats[i].name = name;
state.seats[i].buyIns = 200;
});
state.seats[0].customFields = [
{ label: "Seat rent", value: "paid to 2am" },
{ label: "Venmo", value: "@ann" },
];
state.seats[1].customFields = [{ label: "IOU", value: "$20 to Ann" }];
return state;
};
test("a seat's own fields ride along with its standings row", () => {
const state = tableWithNotes();
const csv = HandHistoryExport.toCsv([], HoldemState.sessionStandings(state));
assert.match(csv, /Seat rent: paid to 2am; Venmo: @ann/);
assert.match(csv, /IOU: \$20 to Ann/);
});
test("the money columns keep their order, with notes on the end", () => {
const state = tableWithNotes();
const csv = HandHistoryExport.toCsv([], HoldemState.sessionStandings(state));
assert.match(csv, /Player,Paid In,Won,Net,Bought In,Chips Now,Up\/Down,Notes/);
});
test("a seat with nothing written against it gets an empty cell, not the word undefined", () => {
const state = tableWithNotes();
const csv = HandHistoryExport.toCsv([], HoldemState.sessionStandings(state));
const calRow = csv.split("\r\n").find(line => line.startsWith("Cal,"));
assert.ok(calRow, "Cal should have a row");
assert.ok(calRow.endsWith(","), `expected an empty last cell, got ${calRow}`);
assert.ok(!/undefined|null/.test(calRow));
});
test("a blank label or value doesn't produce a stray colon", () => {
const state = tableWithNotes();
state.seats[2].customFields = [{ label: "Note", value: "" }, { label: "", value: "" }];
const csv = HandHistoryExport.toCsv([], HoldemState.sessionStandings(state));
const calRow = csv.split("\r\n").find(line => line.startsWith("Cal,"));
assert.match(calRow, /Note/);
assert.ok(!/;\s*;/.test(calRow), "an entirely blank field shouldn't take a slot");
});
test("the table's notes are in the file", () => {
const state = tableWithNotes();
state.notes = "High-hand promo until midnight.";
const csv = HandHistoryExport.toCsv([], HoldemState.sessionStandings(state), { notes: state.notes });
assert.match(csv, /Table Notes/);
assert.match(csv, /High-hand promo until midnight\./);
});
test("a multi-line note survives as one cell", () => {
// csvField quotes anything with a line break in it, so the note doesn't turn into
// rows a spreadsheet reads as more players.
const state = tableWithNotes();
const notes = "Line one\nLine two, with a comma\nLine \"three\"";
const csv = HandHistoryExport.toCsv([], HoldemState.sessionStandings(state), { notes });
assert.match(csv, /"Line one\nLine two, with a comma\nLine ""three"""/);
});
test("no notes means no section, not an empty heading", () => {
const state = tableWithNotes();
const csv = HandHistoryExport.toCsv([], HoldemState.sessionStandings(state), { notes: " " });
assert.ok(!/Table Notes/.test(csv));
});
test("the export still works with no standings at all", () => {
assert.doesNotThrow(() => HandHistoryExport.toCsv([], [], { notes: "just a note" }));
const csv = HandHistoryExport.toCsv([], [], { notes: "just a note" });
assert.match(csv, /Table Notes/);
});
test("asking for the standings doesn't change the seats", () => {
const state = tableWithNotes();
const before = JSON.stringify(state.seats);
HoldemState.sessionStandings(state);
assert.equal(JSON.stringify(state.seats), before);
});
-144
View File
@@ -1,144 +0,0 @@
// How tall the felt is allowed to be.
//
// The bar is fixed to the bottom of the screen and grows with the hand, so the table
// has to be told what is left. Everything below is the arithmetic that decides it —
// the part that can be wrong without anyone noticing until a seat is behind the Fold
// button.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { ActionBar } = require("./load");
// window height, bar height, and how far down the page the felt starts.
const room = (windowHeight, barHeight, top) => ActionBar.feltRoomFor(windowHeight, barHeight, top);
describe("the room left for the felt", () => {
test("is what the window has after the bar, the header and the bottom seat", () => {
const reserved = ActionBar.SEAT_OVERHANG_PX + ActionBar.FELT_GAP_PX;
assert.equal(room(900, 127, 146), 900 - 127 - 146 - reserved);
});
test("shrinks when the bar grows mid-hand", () => {
// Side pots make the bar taller exactly when the dealer most needs to see who
// is still in.
const quiet = room(900, 117, 146);
const sidePots = room(900, 172, 146);
assert.equal(quiet - sidePots, 55);
});
test("leaves the bottom seat's overhang out of it", () => {
// The seat pucks hang below the felt's edge; the felt has to stop short by that
// much or the ring ends up in the bar even though the felt doesn't.
assert.ok(ActionBar.SEAT_OVERHANG_PX > 30, "half a puck");
assert.ok(room(900, 127, 146) < 900 - 127 - 146);
});
});
describe("a window too short to give what was asked", () => {
// A phone on its side: 390px tall, 127px of that is the bar and 119px is
// everything above the felt. What's left is under 100.
const landscape = () => room(390, 127, 119);
test("gets the measurement, not a comfortable number", () => {
// The floor used to be 220px, which this window hasn't got. Holding out for it
// put the bottom row of seats 26px inside the action bar — the exact fault the
// measurement exists to prevent.
assert.ok(landscape() < 150, `${landscape()}px`);
assert.ok(landscape() + 119 + 127 <= 390, "the felt still ends above the bar");
});
test("still draws a table rather than a line", () => {
assert.equal(ActionBar.feltRoomFor(200, 160, 100), ActionBar.FELT_FLOOR_PX);
assert.equal(ActionBar.feltRoomFor(0, 0, 0), ActionBar.FELT_FLOOR_PX);
});
test("never returns something a browser can't lay out", () => {
[[390, 300, 200], [100, 90, 90], [-10, 0, 0]].forEach(([h, bar, top]) => {
const answer = ActionBar.feltRoomFor(h, bar, top);
assert.ok(Number.isFinite(answer) && answer > 0, `${h}/${bar}/${top} gave ${answer}`);
});
});
});
describe("a window with room to spare", () => {
test("hands over everything that's left, floor or no floor", () => {
const reserved = ActionBar.SEAT_OVERHANG_PX + ActionBar.FELT_GAP_PX;
assert.equal(room(1000, 127, 146), 1000 - 127 - 146 - reserved);
assert.equal(room(1366, 120, 206), 1366 - 120 - 206 - reserved);
});
test("gives a whole number of pixels", () => {
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$/);
});
});
-165
View File
@@ -1,165 +0,0 @@
// What shape the felt ends up, which is a question about which rule wins.
//
// feltRoom.test.js covers how much room there is. This covers what the stylesheet does
// with it, and it exists because of a bug that no amount of reading caught: the upright
// oval for phones was written into the `max-width: 700px` block, and the `max-width:
// 900px` block below it set the same custom property back to 1. Both queries match a
// phone, the two declarations have identical specificity, and the later one wins. The
// rule was correct, the arithmetic was correct, and the property was 1 on every phone
// on the site. It measured as a no-op and would have shipped as one.
//
// So this walks the media queries the way the cascade does — in source order, keeping
// the last one that matches — instead of trusting that a rule written for a viewport is
// the rule that viewport gets.
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 = fs.readFileSync(
path.join(__dirname, "..", "..", "JoshHeaps.Net", "wwwroot", "css", "casino", "holdem.css"), "utf8");
// Comments carry example numbers and at least one worked-through `--feltAspect: 1`, so
// they come out before anything here counts declarations.
const SOURCE = CSS.replace(/\/\*[\s\S]*?\*\//g, "");
// --- just enough of a media query engine to answer "does this viewport match?" -------
//
// Only the forms this stylesheet actually uses: width and height bounds, orientation,
// and `and` between them. Anything else is refused loudly rather than guessed at, so a
// new kind of query can't quietly start matching everything.
const matches = (condition, view) => {
if (!condition) return true;
return condition.split(/\s+and\s+/).every(part => {
const m = part.trim().match(/^\(\s*([a-z-]+)\s*:\s*([^)]+?)\s*\)$/);
assert.ok(m, `feltShape can't read the query "${part}" — teach it or simplify the CSS`);
const [, feature, raw] = m;
const px = parseFloat(raw);
switch (feature) {
case "min-width": return view.width >= px;
case "max-width": return view.width <= px;
case "min-height": return view.height >= px;
case "max-height": return view.height <= px;
case "orientation":
return raw === (view.width > view.height ? "landscape" : "portrait");
default:
assert.fail(`feltShape doesn't know the media feature "${feature}"`);
}
});
};
// Every style rule in the file, in source order, with the media condition it sits
// under. Written as a brace walk rather than a regex because a regex for `max-height`
// also finds it in `@media (orientation: landscape) and (max-height: 560px)`, and a
// media feature is not a declaration.
const rules = () => {
const out = [];
const open = [];
let prelude = "", i = 0;
while (i < SOURCE.length) {
const c = SOURCE[i];
if (c === "{") {
const head = prelude.trim();
prelude = "";
if (head.startsWith("@")) { open.push(head); i++; continue; }
let depth = 1, j = i + 1;
while (j < SOURCE.length && depth > 0) {
if (SOURCE[j] === "{") depth++;
else if (SOURCE[j] === "}") depth--;
j++;
}
const media = open.filter(h => h.startsWith("@media"))
.map(h => h.replace(/^@media\s*/, "")).join(" and ");
out.push({ selector: head, condition: media || null, body: SOURCE.slice(i + 1, j - 1) });
i = j;
continue;
}
if (c === "}") { open.pop(); prelude = ""; i++; continue; }
prelude += c;
i++;
}
return out;
};
const ALL_RULES = rules();
// The cascade, for equal-specificity declarations of one property on one selector: the
// last one whose query matches is the one the viewport gets.
const winnerAt = (selector, prop, view) => {
const winning = ALL_RULES
.filter(r => r.selector === selector && matches(r.condition, view))
.map(r => r.body.match(new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`)))
.filter(Boolean)
.pop();
assert.ok(winning, `nothing sets ${prop} on ${selector} at ${view.width}x${view.height}`);
return winning[1].trim();
};
const PHONES = [
{ width: 360, height: 640, name: "Galaxy S8" },
{ width: 375, height: 667, name: "iPhone SE" },
{ width: 390, height: 844, name: "iPhone 14" },
{ width: 412, height: 915, name: "Pixel 7" },
{ width: 430, height: 932, name: "Pro Max" },
];
// ---------------------------------------------------------------------------
describe("the shape a phone gets", () => {
test("is an oval standing up, on every one of them", () => {
PHONES.forEach(phone => {
const aspect = parseFloat(winnerAt("#pokerTableWrap", "--feltAspect", phone));
assert.ok(aspect > 1.2,
`${phone.name} lands on --feltAspect: ${aspect}. A portrait phone is ` +
`tall and this is what uses it; anything at or under 1 is the square ` +
`felt that threw the room away.`);
});
});
test("and a wide screen still gets one lying down", () => {
// The desktop felt is the shape it always was. Whatever the phones do, this is
// the one a poker table looks like when there is room for it.
assert.equal(parseFloat(winnerAt("#pokerTableWrap", "--feltAspect", { width: 1280, height: 900 })), 0.72);
});
test("with the middle widths in between left round", () => {
// 701-900px is one column and wide enough that neither oval is called for. It
// has to be written as a range: a bare max-width would match the phones too and,
// sitting lower in the file, would win there.
[{ width: 768, height: 1024 }, { width: 900, height: 700 }].forEach(view => {
assert.equal(parseFloat(winnerAt("#pokerTableWrap", "--feltAspect", view)), 1);
});
});
});
describe("what stops the oval", () => {
const phoneRule = winnerAt("#pokerTableWrap", "max-height", { width: 390, height: 844 });
test("is the room and nothing but the room", () => {
// The oval is a preference and the room is a fact. Whatever shape is asked for
// above, the felt gives way to the measurement rather than the other way round,
// because the thing on the other side of the cap is a seat behind the action bar.
assert.equal(phoneRule, "var(--feltRoomPx, 100vh)");
});
test("and it is not floored, however tempting that is", () => {
// A floor at the desktop oval — max(var(--feltRoomPx), 72cqw) — was written here
// and measured out again. Twelve players all in with nine side pots is the
// tallest the bar gets, 341px, and at 360x640 that leaves 142px of room. Floored
// to 242 the felt keeps its shape and hides five of the twelve seats behind the
// bar. Unfloored at 142 it is flat and all twelve are visible.
//
// The slit it was defending against wasn't reachable: that came from forcing
// --feltRoomPx to 10px by hand, and the real floor is FELT_FLOOR_PX at 96.
assert.doesNotMatch(phoneRule, /max\(/,
"a floor here trades a flat table for a covered seat, which is the worse of " +
"the two — see the comment above the rule");
});
test("and the width is let go of, so the height can be the one that binds", () => {
// The wide layout sizes the felt from its width and caps that. On a phone the
// width is the column and the height is what's scarce, so the cap moves.
assert.equal(winnerAt("#pokerTableWrap", "max-width", { width: 390, height: 844 }), "none");
});
});
-123
View File
@@ -1,123 +0,0 @@
// Finding one hand in a night of them.
//
// What the log is actually opened for is a single hand — the one somebody at the rail
// is arguing about. A night runs to sixty or more, five at a time in the panel, and
// there was no way to ask for one: the dealer scrolled and read every row.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Render } = require("./load");
const hand = (handNumber, pot, payouts, ledger = []) => ({
handNumber, pot, timestamp: Date.now(), payouts, ledger,
});
// A night as the tool records it: labels carry the cards the wizard was shown.
const NIGHT = [
hand(1, 40, [{ label: "Ann (A♠ K♠)", amount: 40 }], [{ name: "Ann", in: 20 }, { name: "Ben", in: 20 }]),
hand(2, 190, [{ label: "Fay", amount: 190 }], [{ name: "Fay", in: 95 }, { name: "Gus", in: 95 }]),
hand(12, 19, [{ label: "Ben", amount: 19 }], [{ name: "Ben", in: 10 }, { name: "Ann", in: 9 }]),
hand(120, 76, [{ label: "Cal", amount: 38 }, { label: "Dee", amount: 38 }], [{ name: "Cal" }, { name: "Dee" }]),
];
const found = query => NIGHT.filter(h => Render.handMatchesFilter(h, query)).map(h => h.handNumber);
describe("no filter", () => {
test("shows the whole night", () => {
assert.deepEqual(found(""), [1, 2, 12, 120]);
assert.deepEqual(found(" "), [1, 2, 12, 120]);
assert.deepEqual(found(null), [1, 2, 12, 120]);
});
});
describe("by name", () => {
test("finds the hand somebody won", () => {
assert.deepEqual(found("Fay"), [2]);
});
test("case doesn't matter — nobody types a capital at 2am", () => {
assert.deepEqual(found("fay"), [2]);
assert.deepEqual(found("FAY"), [2]);
});
test("a name inside a label with cards on it still matches", () => {
// The wizard writes the label as "Ann (A♠ K♠)", so the name is a substring
// rather than the whole cell.
assert.deepEqual(found("ann"), [1]);
});
test("matches what the row shows, not everyone who was in the hand", () => {
// Gus is in hand 2's ledger — he paid for it — but the row names the winner,
// and searching text the panel doesn't display is a filter that looks broken
// even when it's right. Measured on a seven-handed night where nobody folded,
// matching the ledger returned 60 of 60 for every name at the table.
assert.deepEqual(found("gus"), []);
});
test("a split pot is found by either winner", () => {
assert.deepEqual(found("cal"), [120]);
assert.deepEqual(found("dee"), [120]);
});
test("a name nobody has finds nothing rather than everything", () => {
assert.deepEqual(found("zed"), []);
});
});
describe("by amount", () => {
test("finds a pot", () => {
assert.deepEqual(found("190"), [2]);
});
test("a dollar sign and commas are ignored", () => {
assert.deepEqual(found("$190"), [2]);
assert.deepEqual(found("$1,90"), [2], "typed badly, still found");
});
test("finds a payout that isn't the whole pot", () => {
assert.deepEqual(found("38"), [120], "half of a chopped $76");
});
test("a partial amount narrows rather than missing", () => {
// Half remembering "something around forty" should still get there.
assert.deepEqual(found("4"), [1], "$40");
assert.deepEqual(found("19"), [2, 12], "the $190 pot and the $19 one");
});
test("a bare number is an exact hand number, not a prefix of one", () => {
// Amounts match on their leading digits, because half a remembered figure is
// still a lead. Hand numbers don't: typing 12 to mean the hand is a dealer who
// knows which hand they want, and dragging 120 and 128 along with it is noise.
// "#12" is there for when they do want the prefix.
assert.ok(!found("12").includes(120));
});
});
describe("by hand number", () => {
test("a bare number matches the hand number as well as amounts", () => {
assert.ok(found("12").includes(12));
});
test("a hash pins it to the hand number and nothing else", () => {
assert.deepEqual(found("#12"), [12, 120], "12 and 120 both start with 12");
assert.deepEqual(found("#2"), [2], "and not the $190 pot of hand 2's neighbours");
});
test("a hash with a number nobody played finds nothing", () => {
assert.deepEqual(found("#7"), []);
});
});
describe("odd input can't break it", () => {
test("punctuation on its own doesn't match everything", () => {
assert.deepEqual(found("$"), [], "no digits and no letters left to match on");
assert.deepEqual(found("#"), [1, 2, 12, 120], "an empty hand number is a prefix of them all");
});
test("an entry with pieces missing doesn't throw", () => {
const broken = { handNumber: 5, pot: 10 };
assert.doesNotThrow(() => Render.handMatchesFilter(broken, "ann"));
assert.equal(Render.handMatchesFilter(broken, "ann"), false);
assert.equal(Render.handMatchesFilter(broken, "10"), true, "the pot is still findable");
});
});
-415
View File
@@ -1,415 +0,0 @@
// 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");
});
});
-118
View File
@@ -1,118 +0,0 @@
// The hand-history panel is only rebuilt when its signature changes, which takes a
// full re-render from ~30ms to ~3ms. The whole saving depends on that signature
// noticing every way the log can actually change — a stale panel would have the
// dealer reading last hand's payouts while settling this one.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Render, HoldemState, makeTable } = require("./load");
// historySignature() reads Render.state, so point it at a table for each case.
const signatureOf = state => {
Render.state = state;
return Render.historySignature();
};
const tableWithHands = (count) => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2] });
for (let i = 0; i < count; i++) {
state.seats[0].amountOverride = 2;
state.seats[1].amountOverride = 2;
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 4 }]);
}
return state;
};
describe("the history panel knows when to redraw", () => {
test("nothing changes while a hand is being played", () => {
const state = tableWithHands(3);
const before = signatureOf(state);
// A whole street of betting touches no part of the log.
state.seats[0].committed = 5;
state.seats[1].folded = true;
state.actingSeatIndex = 2;
state.street = "flop";
assert.equal(signatureOf(state), before, "betting must not force a rebuild");
});
test("settling a hand changes it", () => {
const state = tableWithHands(3);
const before = signatureOf(state);
HoldemState.recordHand(state, [{ id: state.seats[1].id, label: "Ben", amount: 12 }]);
assert.notEqual(signatureOf(state), before);
});
test("clearing the history changes it", () => {
const state = tableWithHands(5);
const before = signatureOf(state);
HoldemState.clearHistory(state);
assert.notEqual(signatureOf(state), before);
});
test("undoing back to a shorter log changes it", () => {
const state = tableWithHands(2);
const snapshot = JSON.parse(JSON.stringify(state));
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 30 }]);
const afterRecord = signatureOf(state);
// The undo path swaps the state's contents in place.
Object.keys(state).forEach(k => delete state[k]);
Object.assign(state, snapshot);
assert.notEqual(signatureOf(state), afterRecord, "an undone hand must disappear from the panel");
});
test("two hands that differ only in payout are told apart", () => {
const a = tableWithHands(1);
const b = tableWithHands(1);
// Same count and hand number; different pot.
b.handHistory[0].pot = a.handHistory[0].pot + 25;
assert.notEqual(signatureOf(a), signatureOf(b));
});
test("the hand counter moving on changes it", () => {
// The counter badge is drawn by the same function, so a new hand number has
// to invalidate even when the log itself is untouched.
const state = tableWithHands(2);
const before = signatureOf(state);
state.handNumber += 1;
assert.notEqual(signatureOf(state), before);
});
test("an empty log has a stable signature of its own", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1] });
const first = signatureOf(state);
assert.equal(signatureOf(state), first);
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 4 }]);
assert.notEqual(signatureOf(state), first, "the first hand ever must draw the panel");
});
});
describe("the hand-time cache", () => {
test("the same timestamp is only formatted once, and formats the same", () => {
Render.handTimeCache.clear();
const stamp = Date.UTC(2026, 8, 1, 15, 4);
const first = Render.formatHandTime(stamp);
assert.equal(Render.handTimeCache.size, 1);
const second = Render.formatHandTime(stamp);
assert.equal(second, first);
assert.equal(Render.handTimeCache.size, 1, "not re-formatted");
});
test("different timestamps still format differently", () => {
Render.handTimeCache.clear();
const a = Render.formatHandTime(Date.UTC(2026, 8, 1, 15, 4));
const b = Render.formatHandTime(Date.UTC(2026, 8, 1, 18, 47));
assert.notEqual(a, b);
assert.equal(Render.handTimeCache.size, 2);
});
test("a nonsense timestamp doesn't throw", () => {
Render.handTimeCache.clear();
assert.doesNotThrow(() => Render.formatHandTime(undefined));
assert.doesNotThrow(() => Render.formatHandTime("not a date"));
});
});
-213
View File
@@ -1,213 +0,0 @@
// Randomised whole-hand play against the invariants a dealer would notice being broken.
//
// These ran once, by hand, in a browser console while the betting engine was being
// fixed, and then went away with the tab. The bugs they caught (blinds posted to empty
// chairs, the button skipping players, heads-up acting out of order) are all cases you
// only hit on a particular table shape, so a fixed set of examples misses them. Keeping
// the generator means the next change gets checked against the same thousand tables.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, PotCalculator, HoldemState, Money, makeTable, chipsOnTable, contributions } = require("./load");
// Deterministic PRNG: a failure has to be reproducible from the seed printed with it,
// otherwise a randomised suite is just a flaky one.
function rng(seed) {
let s = seed >>> 0;
return () => {
s = (s * 1664525 + 1013904223) >>> 0;
return s / 4294967296;
};
}
// Plays one hand to completion with random but legal-ish dealer input.
function playHand(random) {
const seatCount = 2 + Math.floor(random() * 9);
const seatIndexes = [...Array(seatCount).keys()];
const seated = seatIndexes.filter(() => random() < 0.7);
if (seated.length < 2) seated.push(...seatIndexes.filter(i => !seated.includes(i)).slice(0, 2 - seated.length));
const bigBlind = [2, 5, 0.5][Math.floor(random() * 3)];
const state = makeTable({
seatCount,
seated,
stack: 0,
smallBlind: bigBlind / 2,
bigBlind,
dealerSeatIndex: Math.floor(random() * seatCount),
});
// Varied stack depths, so short stacks and side pots actually happen.
seated.forEach(i => {
state.seats[i].stack = Money.round(bigBlind * (1 + Math.floor(random() * 60)));
});
const startingChips = chipsOnTable(state);
Betting.beginHand(state);
let guard = 0;
while (!Betting.isHandOver(state) && state.street !== "done" && guard++ < 400) {
if (state.actingSeatIndex === null) {
if (state.street === "river" || !Betting.canStillBet(state)) break;
Betting.closeStreet(state);
continue;
}
const index = state.actingSeatIndex;
const player = state.seats[index];
const toCall = Betting.toCall(state, player);
const roll = random();
if (roll < 0.15) Betting.fold(state, index);
else if (roll < 0.25) Betting.allIn(state, index);
else if (toCall > 0) Betting.call(state, index);
else if (roll < 0.75) Betting.check(state, index);
else Betting.raiseTo(state, index, Betting.minRaiseTo(state));
}
Betting.sweepToHandTotals(state);
return { state, startingChips, seated };
}
describe("randomised hands hold the dealer's invariants", () => {
const HANDS = 1000;
test(`${HANDS} hands never create or destroy a chip`, () => {
const random = rng(20260901);
for (let hand = 0; hand < HANDS; hand++) {
const { state, startingChips } = playHand(random);
assert.equal(
chipsOnTable(state),
startingChips,
`hand ${hand}: chips on the table changed during play`
);
}
});
test(`${HANDS} hands: pots plus uncalled returns always equal the money in`, () => {
const random = rng(778899);
let sidePotHands = 0;
let returnHands = 0;
for (let hand = 0; hand < HANDS; hand++) {
const { state } = playHand(random);
const players = contributions(state);
const inThePot = players.reduce((sum, p) => sum + p.contribution, 0);
if (inThePot <= 0) continue;
// Fold flags can leave nobody live, which the calculator deliberately
// refuses to guess at — that's a dealer correction, not an invariant.
if (players.every(p => p.folded)) continue;
const layered = PotCalculator.layers(players).reduce((s, l) => s + l.amount, 0);
const returned = PotCalculator.uncalledReturns(players).reduce((s, r) => s + r.amount, 0);
assert.equal(
Money.toCents(layered + returned),
Money.toCents(inThePot),
`hand ${hand}: pot breakdown doesn't add up to what went in`
);
if (PotCalculator.layers(players).length > 1) sidePotHands++;
if (returned > 0) returnHands++;
}
assert.ok(sidePotHands > 20, `expected side pots to occur; saw ${sidePotHands}`);
assert.ok(returnHands > 20, `expected uncalled bets to occur; saw ${returnHands}`);
});
test(`${HANDS} hands: what's left after returns is money somebody actually matched`, () => {
// The rule the pot breakdown rests on: you are only called up to what somebody
// else was willing to put in. Once the uncalled chips are handed back, no
// player should still be sitting above every other player at the table.
//
// A single-eligible pot is *not* the thing to look for here — that's legitimate
// when a player called and then folded, leaving dead money one contender
// collects. The bug this guards against is subtler: chips nobody ever matched
// being dressed up as a pot to play for.
const random = rng(13579);
for (let hand = 0; hand < HANDS; hand++) {
const { state } = playHand(random);
const players = contributions(state);
if (players.every(p => p.folded)) continue;
const returns = PotCalculator.uncalledReturns(players);
assert.ok(returns.length <= 1, `hand ${hand}: only the biggest bet can go uncalled`);
returns.forEach(r => {
const player = players.find(p => p.id === r.id);
assert.ok(r.amount <= player.contribution + 0.001, `hand ${hand}: returned more than was put in`);
});
const returned = new Map(returns.map(r => [r.id, r.amount]));
const capped = players.map(p => Money.toCents(p.contribution - (returned.get(p.id) || 0)));
capped.forEach((cents, index) => {
const others = capped.filter((_, i) => i !== index);
const mostAnyoneElsePaid = others.length ? Math.max(...others) : 0;
assert.ok(
cents <= mostAnyoneElsePaid,
`hand ${hand}: a player is still ${Money.fromCents(cents - mostAnyoneElsePaid)} ` +
`above everyone else after returns — that money was never matched`
);
});
}
});
test(`${HANDS} hands: paying the pot out settles it exactly`, () => {
const random = rng(24680);
for (let hand = 0; hand < HANDS; hand++) {
const { state } = playHand(random);
const players = contributions(state);
if (players.every(p => p.folded)) continue;
// Take the uncalled money off first, the way the dealer would.
const returned = new Map(PotCalculator.uncalledReturns(players).map(r => [r.id, r.amount]));
const contested = players.map(p => ({
...p,
contribution: Money.round(p.contribution - (returned.get(p.id) || 0)),
}));
let entries = PotCalculator.buildEntries(contested);
const potBefore = PotCalculator.totalPot(entries);
let paidOut = 0;
let rounds = 0;
while (PotCalculator.getContenders(entries).length > 0 && rounds++ < 30) {
const contenders = PotCalculator.getContenders(entries);
const winner = contenders[Math.floor(random() * contenders.length)];
const result = PotCalculator.resolveRound(entries, [winner.id]);
paidOut += result.perWinner.reduce((s, w) => s + w.amount, 0);
entries = result.updatedEntries;
}
assert.equal(
Money.toCents(paidOut),
Money.toCents(potBefore),
`hand ${hand}: paying out the pot left ${potBefore - paidOut} unaccounted for`
);
}
});
test(`${HANDS} hands: the button and blinds land on real players`, () => {
const random = rng(112233);
for (let hand = 0; hand < HANDS; hand++) {
const seatCount = 2 + Math.floor(random() * 9);
const seated = [...Array(seatCount).keys()].filter(() => random() < 0.6);
if (seated.length < 2) continue;
const state = makeTable({ seatCount, seated, dealerSeatIndex: Math.floor(random() * seatCount) });
HoldemState.advanceButton(state);
assert.ok(state.seats[state.dealerSeatIndex].inHand, `hand ${hand}: button on an empty chair`);
const { sbIndex, bbIndex, headsUp } = HoldemState.getBlindSeats(state);
assert.ok(state.seats[sbIndex].inHand, `hand ${hand}: small blind on an empty chair`);
assert.ok(state.seats[bbIndex].inHand, `hand ${hand}: big blind on an empty chair`);
assert.notEqual(sbIndex, bbIndex, `hand ${hand}: both blinds on one player`);
if (seated.length === 2) {
assert.ok(headsUp, `hand ${hand}: two players should be heads-up`);
assert.equal(sbIndex, state.dealerSeatIndex, `hand ${hand}: heads-up button posts the small blind`);
}
}
});
});
-105
View File
@@ -1,105 +0,0 @@
// Loads the dealer's browser modules into Node so they can be tested directly.
//
// The modules are plain script-tag files: each one declares a `const` namespace and
// ends with a `module.exports` guard. In the browser they find each other as globals,
// so the same names have to exist on `globalThis` here or `Betting` can't reach
// `HoldemState`. Load order matches the <script> order in TexasHoldem.cshtml.
const path = require("path");
const SRC = path.join(__dirname, "..", "..", "JoshHeaps.Net", "wwwroot", "js", "casino", "holdem");
function load(name) {
const mod = require(path.join(SRC, `${name}.js`));
globalThis[name.charAt(0).toUpperCase() + name.slice(1)] = mod;
return mod;
}
const Money = load("money");
const HandRank = load("handRank");
const PotCalculator = load("potCalculator");
const SplitCalculator = load("splitCalculator");
const Betting = load("betting");
const SettleUp = load("settleUp");
const HandHistoryExport = load("handHistoryExport");
// render.js exports { Render } rather than the namespace directly.
const Render = require(path.join(SRC, "render.js")).Render;
globalThis.Render = Render;
// state.js exports `HoldemState`, which doesn't match its filename.
const HoldemState = require(path.join(SRC, "state.js"));
globalThis.HoldemState = HoldemState;
// actionBar.js after state, since its own module-level code reaches for neither but
// 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");
// The wake lock's rule about when a table needs the screen is plain state work too.
// Its acquire/release bookkeeping is testable here as well, against a stand-in for
// navigator.wakeLock — see wakeLock.test.js.
const WakeLock = load("wakeLock");
// ---- Table builders ----------------------------------------------------------
// A table with `seatCount` chairs where `seated` (a list of seat indexes) are dealt
// in with `stack` chips each. Everything else is the app's own defaults, so a test
// that forgets to set a field gets whatever a real dealer would get.
function makeTable({ seatCount = 6, seated = null, stack = 100, smallBlind = 1, bigBlind = 2, dealerSeatIndex = 0 } = {}) {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, seatCount);
state.smallBlind = smallBlind;
state.bigBlind = bigBlind;
state.dealerSeatIndex = dealerSeatIndex;
const sitting = seated || state.seats.map((_, i) => i);
state.seats.forEach((player, index) => {
player.inHand = sitting.includes(index);
player.stack = sitting.includes(index) ? stack : null;
player.name = `P${index + 1}`;
});
return state;
}
// Total chips the table is accountable for: what's in front of everyone, plus what
// they've pushed in this street, plus what's already banked into the pot.
function chipsOnTable(state) {
return Money.round(
state.seats.reduce(
(sum, p) => sum + (Number(p.stack) || 0) + (Number(p.committed) || 0) + (Number(p.amountOverride) || 0),
0
)
);
}
// Contributions in the shape PotCalculator wants them.
function contributions(state) {
return state.seats
.filter(p => p.inHand)
.map(p => ({
id: p.id,
contribution: Betting.handTotal(p),
folded: p.folded,
}));
}
module.exports = {
Money,
HandRank,
Render,
HandHistoryExport,
PotCalculator,
SplitCalculator,
SettleUp,
Betting,
HoldemState,
ActionBar,
CardPicker,
WakeLock,
makeTable,
chipsOnTable,
contributions,
};
-114
View File
@@ -1,114 +0,0 @@
// What happens when the saved table can't be read.
//
// An unreadable save can only become an empty table. What it must not do is become
// one silently and then get written over by the first edit.
const test = require("node:test");
const assert = require("node:assert");
const { HoldemState } = require("./load");
function withStored(value, { readOnly = false } = {}) {
const store = new Map();
if (value !== undefined) store.set(HoldemState.STORAGE_KEY, value);
globalThis.localStorage = {
getItem: key => (store.has(key) ? store.get(key) : null),
setItem(key, val) {
if (readOnly) throw new Error("QuotaExceededError");
store.set(key, val);
},
removeItem: key => store.delete(key),
};
return store;
}
test.beforeEach(() => {
HoldemState.loadFailed = false;
HoldemState.onLoadFailed = null;
});
test.after(() => {
delete globalThis.localStorage;
HoldemState.loadFailed = false;
HoldemState.onLoadFailed = null;
});
test("nothing stored is a new table, not a failure", () => {
withStored(undefined);
const state = HoldemState.load();
assert.equal(HoldemState.loadFailed, false);
assert.ok(Array.isArray(state.seats));
});
test("a good save loads and reports nothing", () => {
const store = withStored(undefined);
const original = HoldemState.createDefault();
original.handNumber = 34;
HoldemState.save(original);
const state = HoldemState.load();
assert.equal(HoldemState.loadFailed, false);
assert.equal(state.handNumber, 34);
assert.equal(store.has(HoldemState.RECOVERY_KEY), false);
});
test("a truncated save is reported rather than silently becoming an empty table", () => {
const good = JSON.stringify(HoldemState.createDefault());
withStored(good.slice(0, Math.floor(good.length * 0.7)));
const state = HoldemState.load();
assert.equal(HoldemState.loadFailed, true);
assert.ok(Array.isArray(state.seats), "it still hands back a usable table");
});
test("valid JSON of the wrong shape counts as unreadable too", () => {
withStored(JSON.stringify({ hello: "world" }));
HoldemState.load();
assert.equal(HoldemState.loadFailed, true);
});
test("the unreadable copy is kept instead of being written over", () => {
// This is the half that matters: whatever a person could have picked out of the
// raw JSON used to be gone the moment the dealer touched a seat.
const broken = '{"seats":[{"name":"Ann","stack":250},{"name":"Ben"';
const store = withStored(broken);
HoldemState.load();
assert.equal(store.get(HoldemState.RECOVERY_KEY), broken);
});
test("a later save doesn't touch the copy that was set aside", () => {
const broken = '{"seats":[{"name":"Ann"';
const store = withStored(broken);
const state = HoldemState.load();
state.handNumber = 2;
HoldemState.save(state);
assert.equal(store.get(HoldemState.RECOVERY_KEY), broken);
assert.notEqual(store.get(HoldemState.STORAGE_KEY), broken);
});
test("the listener fires once, not on every read", () => {
withStored("{not json");
let told = 0;
HoldemState.onLoadFailed = () => { told++; };
HoldemState.load();
HoldemState.load();
HoldemState.load();
assert.equal(told, 1);
});
test("no room to keep the copy is not a crash", () => {
// Storage that refuses writes is exactly the storage most likely to hand back a
// half-written value in the first place.
withStored("{not json", { readOnly: true });
let state;
assert.doesNotThrow(() => { state = HoldemState.load(); });
assert.ok(Array.isArray(state.seats));
assert.equal(HoldemState.loadFailed, true);
});
-260
View File
@@ -1,260 +0,0 @@
// Home games are messy. People walk up mid-hand, storm off mid-hand, argue about
// whose blind it is, and pass the button round three times before anyone deals.
// These are the cases the positional rules quietly get wrong.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, HoldemState, PotCalculator, Money, makeTable, chipsOnTable, contributions } = require("./load");
const potOf = state => HoldemState.totalPot(state);
describe("a player leaves in the middle of a hand", () => {
test("their chips stay in the pot", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3); Betting.call(state, 0); Betting.call(state, 1); Betting.check(state, 2);
Betting.sweepToHandTotals(state);
const before = potOf(state);
assert.equal(before, 8);
state.seats[1].inHand = false; // dealer takes them out
assert.equal(potOf(state), before, "the pot must not shrink when a player is taken out");
});
test("they cannot be paid out of a pot they walked away from", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 0); Betting.call(state, 1); Betting.check(state, 2);
Betting.sweepToHandTotals(state);
state.seats[1].inHand = false;
const players = state.seats
.filter(p => HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount) > 0)
.map(p => ({
id: p.id,
contribution: HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount),
folded: p.folded || HoldemState.isDeadMoney(p),
}));
const layers = PotCalculator.layers(players);
assert.ok(!layers[0].eligible.includes(state.seats[1].id), "a departed player can't win");
assert.equal(layers.reduce((s, l) => s + l.amount, 0), 6, "but their money is still being played for");
});
test("taking out the player who is to act moves the action on", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
const acting = state.actingSeatIndex;
state.seats[acting].inHand = false;
Betting.passAction(state, acting);
assert.notEqual(state.actingSeatIndex, acting, "the table can't wait on somebody who left");
assert.ok(state.actingSeatIndex === null || state.seats[state.actingSeatIndex].inHand);
});
test("an empty chair still contributes nothing, base pot or not", () => {
// The table-wide default must not be read as an ante from seats nobody is in.
const state = makeTable({ seatCount: 6, seated: [0, 1], dealerSeatIndex: 0 });
state.basePotAmount = 25;
assert.equal(HoldemState.computeContribution(state.seats[4], state.chipLegend, 25), 0);
});
});
describe("a player joins in the middle of a hand", () => {
test("they sit the hand out rather than joining a pot they never paid into", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 0); Betting.call(state, 1); Betting.check(state, 2);
Betting.sweepToHandTotals(state);
// Walks up and is dealt in — the app marks them folded for this hand.
state.seats[4].inHand = true;
state.seats[4].stack = 100;
state.seats[4].folded = true;
assert.ok(!Betting.liveSeats(state).some(s => s.index === 4), "not live this hand");
assert.equal(HoldemState.computeContribution(state.seats[4], state.chipLegend, state.basePotAmount), 0);
});
test("they are a full player again on the next hand", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
state.seats[4].inHand = true;
state.seats[4].stack = 100;
state.seats[4].folded = true;
HoldemState.startNextHand(state);
Betting.beginHand(state);
assert.equal(state.seats[4].folded, false);
assert.ok(Betting.liveSeats(state).some(s => s.index === 4), "dealt in like anyone else");
});
});
describe("passing the button around before the cards come out", () => {
test("moving the button re-posts the blinds and keeps the chip count straight", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
const startingChips = chipsOnTable(state);
Betting.beginHand(state);
assert.equal(state.seats[1].committed, 1);
assert.equal(state.seats[2].committed, 2);
state.dealerSeatIndex = 2;
Betting.repostBlinds(state);
assert.equal(state.seats[1].committed, 0, "the old small blind got their chip back");
assert.equal(state.seats[3].committed, 1, "and the new one has posted");
assert.equal(state.seats[0].committed, 2);
assert.equal(chipsOnTable(state), startingChips, "no chips created or lost in the shuffle");
});
test("passing it round many times still balances", () => {
const state = makeTable({ seatCount: 8, seated: [0, 2, 3, 5, 7], dealerSeatIndex: 0 });
const startingChips = chipsOnTable(state);
Betting.beginHand(state);
[2, 5, 7, 3, 0, 5].forEach(seat => {
state.dealerSeatIndex = seat;
Betting.repostBlinds(state);
assert.equal(chipsOnTable(state), startingChips, `chips drifted after passing to seat ${seat}`);
});
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
assert.equal(Betting.committed(state.seats[sbIndex]), 1);
assert.equal(Betting.committed(state.seats[bbIndex]), 2);
});
test("once somebody has acted, the blinds are settled", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
assert.equal(Betting.onlyBlindsIn(state), true, "nothing but blinds so far");
Betting.call(state, 3);
assert.equal(Betting.onlyBlindsIn(state), false, "a call means the blinds are set where they are");
});
});
describe("naming the blinds by hand", () => {
test("a named blind wins over the button order", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
state.blindOverride = { sbIndex: 3, bbIndex: 0 };
const { sbIndex, bbIndex, manual } = HoldemState.getBlindSeats(state);
assert.equal(sbIndex, 3);
assert.equal(bbIndex, 0);
assert.equal(manual, true);
Betting.beginHand(state);
assert.equal(state.seats[3].committed, 1);
assert.equal(state.seats[0].committed, 2);
assert.equal(state.seats[1].committed, 0, "the positional small blind posts nothing");
});
test("a named blind on a player who isn't dealt in is ignored", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.blindOverride = { sbIndex: 4, bbIndex: 0 }; // seat 4 is an empty chair
const { sbIndex, manual } = HoldemState.getBlindSeats(state);
assert.ok(!manual, "falls back to the button order rather than posting to nobody");
assert.ok(state.seats[sbIndex].inHand);
});
test("both blinds on one player is refused", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.blindOverride = { sbIndex: 1, bbIndex: 1 };
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
assert.notEqual(sbIndex, bbIndex);
});
test("naming blinds heads-up still acts in the right order", () => {
const state = makeTable({ seatCount: 6, seated: [2, 5], dealerSeatIndex: 2 });
state.blindOverride = { sbIndex: 5, bbIndex: 2 }; // deliberately the reverse
Betting.beginHand(state);
assert.equal(state.seats[5].committed, 1);
assert.equal(state.seats[2].committed, 2);
assert.equal(state.actingSeatIndex, 5, "the small blind acts first pre-flop heads-up");
Betting.call(state, 5);
Betting.check(state, 2);
Betting.closeStreet(state);
assert.equal(state.actingSeatIndex, 2, "and the big blind leads after the flop");
});
test("the naming only lasts the hand it was made for", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
state.blindOverride = { sbIndex: 3, bbIndex: 0 };
Betting.beginHand(state);
HoldemState.startNextHand(state);
assert.equal(state.blindOverride, null, "blinds go back to following the button");
});
});
describe("the first hand on a fresh table", () => {
test("the button never starts on an empty chair", () => {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 9);
[4, 6, 7].forEach(i => { state.seats[i].inHand = true; state.seats[i].stack = 100; });
assert.equal(state.dealerSeatIndex, 0, "a fresh table starts the button on seat 1");
assert.equal(state.seats[0].inHand, false, "which nobody is sitting in");
Betting.beginHand(state);
assert.ok(state.seats[state.dealerSeatIndex].inHand, "the button moved to a real player");
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
assert.ok(state.seats[sbIndex].inHand);
assert.ok(state.seats[bbIndex].inHand);
assert.notEqual(sbIndex, bbIndex);
});
test("a table that empties out around the button recovers", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 3 });
state.seats[3].inHand = false; // the player holding the button leaves
HoldemState.ensureButtonOnPlayer(state);
assert.ok(state.seats[state.dealerSeatIndex].inHand);
});
test("two players left after everyone else walks is heads-up, blinds reversed", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
[2, 3].forEach(i => { state.seats[i].inHand = false; });
HoldemState.startNextHand(state);
Betting.beginHand(state);
const { sbIndex, headsUp } = HoldemState.getBlindSeats(state);
assert.equal(headsUp, true);
assert.equal(sbIndex, state.dealerSeatIndex, "heads-up the button posts the small blind");
});
});
describe("chips survive a messy table", () => {
test("joining, leaving and passing the button never changes the chip count", () => {
const state = makeTable({ seatCount: 8, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
state.seats[6].stack = 100; // sitting down but not dealt in yet
const startingChips = chipsOnTable(state);
Betting.beginHand(state);
state.dealerSeatIndex = 2;
Betting.repostBlinds(state);
state.seats[6].inHand = true; // walks up mid-hand
state.seats[6].folded = true;
assert.equal(chipsOnTable(state), startingChips);
Betting.call(state, state.actingSeatIndex);
state.seats[1].inHand = false; // and someone storms off
Betting.sweepToHandTotals(state);
assert.equal(chipsOnTable(state), startingChips, "every chip is still accounted for");
assert.equal(
Money.toCents(potOf(state) + state.seats.reduce((s, p) => s + (Number(p.stack) || 0), 0)),
Money.toCents(startingChips),
"and the pot plus the stacks is the whole table"
);
});
});
-155
View File
@@ -1,155 +0,0 @@
// 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);
});
});
-141
View File
@@ -1,141 +0,0 @@
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Money, HandHistoryExport } = require("./load");
describe("Money.format", () => {
test("whole amounts drop the pointless cents", () => {
assert.equal(Money.format(12), "$12");
assert.equal(Money.format(450), "$450");
assert.equal(Money.format(1250000), "$1,250,000");
assert.equal(Money.format(0), "$0");
});
test("amounts that carry cents still show them", () => {
assert.equal(Money.format(12.5), "$12.50");
assert.equal(Money.format(0.25), "$0.25");
assert.equal(Money.format(3.01), "$3.01");
});
test("a quarter-blind game reads exactly as it did", () => {
// The case that would be ruined by dropping cents unconditionally.
[0.25, 0.5, 1.75, 12.05].forEach(v => {
assert.match(Money.format(v), /\.\d\d$/, `${v} lost its cents`);
});
});
test("floating-point dust doesn't invent cents", () => {
assert.equal(Money.format(0.1 + 0.2), "$0.30");
assert.equal(Money.format(1.0000000001), "$1");
});
test("signed amounts put the sign out front, both scales", () => {
assert.equal(Money.formatSigned(87500), "+$87,500");
assert.equal(Money.formatSigned(-87500), "-$87,500");
assert.equal(Money.formatSigned(-12.5), "-$12.50");
assert.equal(Money.formatSigned(0), "$0");
});
test("rubbish in doesn't produce rubbish out", () => {
assert.equal(Money.format(null), "$0");
assert.equal(Money.format(undefined), "$0");
assert.equal(Money.format("nonsense"), "$0");
});
});
describe("Money.forSheet", () => {
test("a bare number a spreadsheet will add up", () => {
assert.equal(Money.forSheet(1250000), "1250000.00");
assert.equal(Money.forSheet(12.5), "12.50");
assert.equal(Money.forSheet(-87500), "-87500.00");
});
test("no currency symbol and no thousands separators", () => {
const written = Money.forSheet(1234567.89);
assert.ok(!written.includes("$"), "a $ makes the cell text");
assert.ok(!written.includes(","), "a comma makes the cell text");
assert.equal(Number(written), 1234567.89, "and it parses straight back to a number");
});
});
describe("the exported CSV", () => {
const history = [
{ handNumber: 2, timestamp: 0, pot: 1250000, payouts: [{ id: "a", label: "Alexandra", amount: 1250000 }] },
{ handNumber: 1, timestamp: 0, pot: 24.5, payouts: [{ id: "b", label: "Bob", amount: 24.5 }] },
];
const standings = [
{ id: "a", name: "Alexandra", in: 1250000, won: 1250000, net: 0, boughtIn: 3200000, chipsNow: 3200000, cashPosition: 0 },
{ id: "b", name: "Bob", in: 24.5, won: 0, net: -24.5, boughtIn: 100, chipsNow: 75.5, cashPosition: -24.5 },
];
// Splitting on commas isn't good enough: the timestamp column legitimately holds
// one ("1/1/1970, 5:00:00 PM") and is quoted for exactly that reason.
const splitRow = line => {
const fields = [];
let field = "";
let quoted = false;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (quoted) {
if (c === '"' && line[i + 1] === '"') { field += '"'; i++; }
else if (c === '"') quoted = false;
else field += c;
} else if (c === '"') quoted = true;
else if (c === ",") { fields.push(field); field = ""; }
else field += c;
}
fields.push(field);
return fields;
};
test("every money cell parses as a number", () => {
const csv = HandHistoryExport.toCsv(history, standings);
const lines = csv.split("\r\n");
lines.slice(1, 3).forEach(line => {
const cell = splitRow(line)[2]; // Pot
assert.ok(cell !== "" && !Number.isNaN(Number(cell)), `pot cell "${cell}" isn't a number`);
});
// Standings rows: the money columns have to be numeric. Named rather than
// "everything after the first", which is what this used to say — the row now
// ends with a Notes column carrying whatever the dealer typed against the seat,
// and that is text by definition. The point of this test is that a column
// somebody totals adds up, so it checks the columns somebody totals.
const standingsStart = lines.findIndex(l => l.startsWith("Player,"));
const header = splitRow(lines[standingsStart]);
const moneyColumns = ["Paid In", "Won", "Net", "Bought In", "Chips Now", "Up/Down"]
.map(name => {
const index = header.indexOf(name);
assert.ok(index > 0, `the standings header should still have a ${name} column`);
return index;
});
lines.slice(standingsStart + 1).filter(Boolean).forEach(line => {
const cells = splitRow(line);
moneyColumns.forEach(index => {
const cell = cells[index];
assert.ok(cell !== "" && !Number.isNaN(Number(cell)),
`standings cell "${cell}" in column ${header[index]} isn't a number`);
});
});
});
test("a million-dollar pot doesn't need quoting any more", () => {
const csv = HandHistoryExport.toCsv(history, []);
assert.ok(csv.includes("1250000.00"), "written plainly");
assert.ok(!csv.includes('"$1,250,000'), "not as a quoted, unsummable string");
});
test("names and payout descriptions stay human", () => {
const csv = HandHistoryExport.toCsv(history, standings);
assert.ok(csv.includes("Alexandra"), "the name column is still a name");
assert.ok(csv.includes("Alexandra: $1,250,000"), "the payout column still reads like a sentence");
});
test("a name with a comma is still quoted properly", () => {
const csv = HandHistoryExport.toCsv([], [
{ id: "x", name: "Smith, John", in: 0, won: 0, net: 0, boughtIn: 0, chipsNow: 0, cashPosition: 0 },
]);
assert.ok(csv.includes('"Smith, John"'), "the CSV escaping still applies where it's needed");
});
});
-133
View File
@@ -1,133 +0,0 @@
// 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");
});
});
-100
View File
@@ -1,100 +0,0 @@
// Noticing that the same table is open twice.
//
// Two tabs each hold their own copy in memory and each save writes the whole thing,
// so the second one to act throws the first one's work away. This doesn't merge them
// — replacing a table under a dealer's hands mid-hand would be its own hazard — it
// notices, which is what lets them decide.
const test = require("node:test");
const assert = require("node:assert");
const { HoldemState } = require("./load");
function withWindow() {
const listeners = [];
globalThis.window = {
addEventListener(type, fn) { if (type === "storage") listeners.push(fn); },
removeEventListener(type, fn) {
const i = listeners.indexOf(fn);
if (i >= 0) listeners.splice(i, 1);
},
};
return {
listeners,
fire(key) { listeners.forEach(fn => fn({ key })); },
};
}
test.beforeEach(() => {
HoldemState.otherTabActive = false;
HoldemState.onOtherTab = null;
HoldemState.tabWatcher = null;
});
test.after(() => {
delete globalThis.window;
HoldemState.otherTabActive = false;
HoldemState.onOtherTab = null;
HoldemState.tabWatcher = null;
});
test("a write to this table from elsewhere is noticed", () => {
const win = withWindow();
let told = 0;
HoldemState.onOtherTab = () => { told++; };
HoldemState.watchOtherTabs();
win.fire(HoldemState.STORAGE_KEY);
assert.equal(HoldemState.otherTabActive, true);
assert.equal(told, 1);
});
test("somebody else's storage key is not our business", () => {
const win = withWindow();
let told = 0;
HoldemState.onOtherTab = () => { told++; };
HoldemState.watchOtherTabs();
win.fire("some.other.app.state");
win.fire(HoldemState.RECOVERY_KEY);
assert.equal(HoldemState.otherTabActive, false);
assert.equal(told, 0);
});
test("told once, however many times the other tab acts", () => {
const win = withWindow();
let told = 0;
HoldemState.onOtherTab = () => { told++; };
HoldemState.watchOtherTabs();
for (let i = 0; i < 10; i++) win.fire(HoldemState.STORAGE_KEY);
assert.equal(told, 1);
});
test("watching twice doesn't listen twice", () => {
const win = withWindow();
HoldemState.watchOtherTabs();
HoldemState.watchOtherTabs();
HoldemState.watchOtherTabs();
assert.equal(win.listeners.length, 1);
});
test("no listener set is not an error", () => {
const win = withWindow();
HoldemState.onOtherTab = null;
HoldemState.watchOtherTabs();
assert.doesNotThrow(() => win.fire(HoldemState.STORAGE_KEY));
assert.equal(HoldemState.otherTabActive, true);
});
test("no window at all is not an error", () => {
// The same modules are loaded in Node by the test harness.
delete globalThis.window;
HoldemState.tabWatcher = null;
assert.doesNotThrow(() => HoldemState.watchOtherTabs());
assert.equal(HoldemState.otherTabActive, false);
});
-218
View File
@@ -1,218 +0,0 @@
// What a shut sidebar panel says about itself.
//
// The sidebar is eight <details>, every one exactly 60px tall with nothing in it but
// its own name — 480px of a phone's screen and 480px of a 660px desktop column, saying
// "Standings", "Hands", "Waiting list" and nothing else. Whether the box balances,
// whether anyone is waiting for a seat, how many hands have been played: the page had
// all three worked out and charged a tap for each of them, on rows two thirds empty.
//
// So each one now carries the fact you would have opened it for. Two rules hold this
// together, and both are checked here.
//
// A glance appears only when it has something a dealer would act on. Eight rows that
// always say something are eight rows that say nothing again, and a row reading
// "Nobody waiting" all night is the clutter this went in to remove.
//
// And a glance never says something the panel under it would contradict. It is the
// panel's own sentence with the explanation taken off, so it has to be read off the
// same state — never off the panel's DOM, which for a shut <details> isn't rendered
// at all.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { Render, HoldemState, makeTable } = require("./load");
const glances = state => Render.panelGlances(state);
const textOf = (state, id) => (glances(state)[id] || {}).text;
// A table part-way through a night: money on it, so the bank check has an opinion.
const night = () => {
const state = makeTable({ seatCount: 9, seated: [0, 1, 2, 3, 4], stack: 200,
smallBlind: 5, bigBlind: 10 });
state.seats.slice(0, 5).forEach(p => { p.buyIns = 200; });
return state;
};
describe("the rows that always have something to say", () => {
test("the table's own shape and stakes", () => {
assert.equal(textOf(night(), "glanceTableSetup"), "9 seats · $5/$10");
});
test("and the stakes drop out rather than reading as free", () => {
// A table set up with no blinds yet is a real state — it is what the panel
// opens on — and "9 seats · $0/$0" would be a claim about the game rather
// than an admission that nobody has said yet.
const state = night();
state.smallBlind = 0;
state.bigBlind = 0;
assert.equal(textOf(state, "glanceTableSetup"), "9 seats");
});
test("the chip values, as a range rather than a count of rows", () => {
// "Are the values right for tonight's set" is the question this answers.
// Five colours is the answer to a different one.
assert.equal(textOf(night(), "glanceChips"), "5 colours · $1–$500");
});
test("with a chip nobody has priced yet left out of the range", () => {
// A blank row in the legend is a chip the dealer hasn't got to, not a
// zero-dollar chip — and letting it in would read the range as starting at $0.
const state = night();
state.chipLegend.push({ id: "pink", color: "#ff88aa", value: 0 });
assert.equal(textOf(state, "glanceChips"), "5 colours · $1–$500");
});
test("and one chip is a value, not a range of one", () => {
const state = night();
state.chipLegend = [{ id: "red", color: "#c0392b", value: 5 }];
assert.equal(textOf(state, "glanceChips"), "1 colour · $5");
});
});
describe("the bank check, which is the one worth a colour", () => {
test("says so when the cash covers the chips", () => {
const state = night();
const { text, tone } = glances(state).glanceStandings;
assert.equal(text, "Balanced");
assert.equal(tone, "ok");
});
test("and names the gap when it doesn't", () => {
// Chips on the table that nobody paid for. The glance is the alarm and the
// amount; which seat is holding them is a paragraph, and that is the half
// that stays behind the tap.
const state = night();
state.seats[0].buyIns = 100;
const { text, tone } = glances(state).glanceStandings;
assert.equal(text, "Off by $100");
assert.equal(tone, "warn");
});
test("the same way round when the cash is the side that's over", () => {
// One word covers both signs on purpose: the number and the alarm are what a
// dealer acts on, and "short" against "over" is a direction they would have to
// hold in their head to read. The panel says which way in a sentence.
const state = night();
state.seats[0].buyIns = 400;
const { text, tone } = glances(state).glanceStandings;
assert.equal(text, "Off by $200");
assert.equal(tone, "warn");
});
test("and stays quiet over a table nobody has bought into", () => {
// The panel hides its own check here for the same reason. A glance reading
// "Balanced" over an empty table is answering for a count never taken.
const state = makeTable({ seatCount: 9, seated: [], smallBlind: 5, bigBlind: 10 });
state.seats.forEach(p => { p.stack = null; p.buyIns = 0; });
assert.equal(textOf(state, "glanceStandings"), "");
assert.equal(glances(state).glanceStandings.tone, "");
});
test("and agrees with the sentence the panel would print", () => {
// The two are read off one call apiece and must never disagree — a glance
// saying "Balanced" over a panel saying "$40 more in chips than cash taken"
// is worse than no glance at all.
[0, 100, 400].forEach(buyIn => {
const state = night();
state.seats[0].buyIns = buyIn;
const bank = HoldemState.bankReconciliation(state);
const { text, tone } = glances(state).glanceStandings;
assert.equal(tone === "ok", bank.balanced, `buy-in ${buyIn}`);
if (!bank.balanced) {
assert.ok(text.includes(String(Math.abs(bank.difference))),
`${text} doesn't carry the panel's own ${bank.difference}`);
}
});
});
});
describe("the rows that stay quiet until they have news", () => {
test("nobody waiting, no note, no hands played yet", () => {
const state = night();
assert.equal(textOf(state, "glanceWaiting"), "");
assert.equal(textOf(state, "glanceHands"), "");
assert.equal(textOf(state, "glanceNotes"), "");
});
test("and speak up the moment they do", () => {
const state = night();
state.waitingList = [{ id: "w1", name: "Nadia" }, { id: "w2", name: "Owen" }];
state.handHistory = [{ handNumber: 1, pot: 120, payouts: [], ledger: [] }];
assert.equal(textOf(state, "glanceWaiting"), "2 waiting");
assert.equal(textOf(state, "glanceHands"), "1 hand");
});
test("counting one of something as one of it", () => {
const state = night();
state.waitingList = [{ id: "w1", name: "Nadia" }];
state.handHistory = [{ handNumber: 1, pot: 120, payouts: [], ledger: [] },
{ handNumber: 2, pot: 80, payouts: [], ledger: [] }];
assert.equal(textOf(state, "glanceWaiting"), "1 waiting");
assert.equal(textOf(state, "glanceHands"), "2 hands");
});
test("and a note shows which note it is, not that there is one", () => {
// "Has notes" costs a tap to learn anything, which is the whole failure this
// is fixing. The text is what identifies it; the row's own width ellipsises.
const state = night();
state.notes = "Sam owes Dee $20 from last night";
assert.equal(textOf(state, "glanceNotes"), "Sam owes Dee $20 from last night");
});
test("reading past the blank lines a note gets typed under", () => {
// Notes get written as a list — a heading, a blank line, then the thing. The
// first line of the string is regularly not the first line of the note.
const state = night();
state.notes = "\n \n Sam owes Dee $20\nand Ted owes Al $5";
assert.equal(textOf(state, "glanceNotes"), "Sam owes Dee $20");
});
test("and a note of nothing but whitespace is no note", () => {
const state = night();
state.notes = "\n\n \t \n";
assert.equal(textOf(state, "glanceNotes"), "");
});
});
describe("what the row is allowed to be", () => {
const ROWS = ["glanceTableSetup", "glanceStandings", "glanceWaiting",
"glanceHands", "glanceChips", "glanceNotes"];
test("every glance the sidebar renders is one this knows about", () => {
// The list drives the DOM writes, so a glance computed and never listed is a
// row that silently keeps its old text for the rest of the night.
const state = night();
assert.deepEqual(Object.keys(glances(state)).sort(), [...ROWS].sort());
assert.deepEqual([...Render.PANEL_GLANCES].sort(), [...ROWS].sort());
});
test("and none of them is a paragraph", () => {
// The row is 44px of a 320px column with a label already on it. Anything
// long enough to need the panel's room belongs in the panel.
const state = night();
state.waitingList = [{ id: "w1", name: "Nadia" }];
state.handHistory = [{ handNumber: 1, pot: 120, payouts: [], ledger: [] }];
ROWS.filter(id => id !== "glanceNotes").forEach(id => {
const text = textOf(state, id);
assert.ok(text.length <= 24, `${id} is ${text.length} chars: "${text}"`);
assert.ok(!text.includes("\n"), `${id} has a line break in it`);
});
});
test("including a note, which is trimmed to one line and left to the ellipsis", () => {
// The one glance whose length isn't ours to choose. It must still be a single
// line — a second one would make the row taller, and the row is what holds the
// sidebar to eight equal slabs.
const state = night();
state.notes = "x".repeat(400) + "\nsecond line";
const text = textOf(state, "glanceNotes");
assert.ok(!text.includes("\n"));
assert.equal(text, "x".repeat(400));
});
test("and a state that isn't there yet asks for nothing", () => {
// renderAll runs before the first load has finished on a cold open.
assert.deepEqual(Render.panelGlances(null), {});
assert.deepEqual(Render.panelGlances(undefined), {});
});
});
-100
View File
@@ -1,100 +0,0 @@
// Just enough PNG to read pixels back out of a screenshot.
//
// The contrast audit needs to know what colour is actually behind a piece of text, and
// the only honest answer is the one the browser painted. Walking the DOM and
// compositing `background-color` up the ancestors gets it wrong wherever a gradient,
// a shadow or a border is doing the painting: tried that first, and it reported the
// gold dealer button as black-on-black at Lc 0.4 — a fault that does not exist, on an
// element anyone can see is legible. Sampling the screenshot cannot make that mistake.
//
// zlib is in Node, so this needs no dependency. Screenshots are 8-bit and
// non-interlaced; anything else throws rather than returning quietly wrong pixels.
const zlib = require("node:zlib");
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
function paeth(a, b, c) {
const p = a + b - c;
const pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
if (pa <= pb && pa <= pc) return a;
return pb <= pc ? b : c;
}
function decode(buffer) {
if (!buffer.subarray(0, 8).equals(SIGNATURE)) throw new Error("not a PNG");
let width = 0, height = 0, depth = 0, colorType = 0, interlace = 0;
const idat = [];
let at = 8;
while (at < buffer.length) {
const length = buffer.readUInt32BE(at);
const type = buffer.toString("ascii", at + 4, at + 8);
const data = buffer.subarray(at + 8, at + 8 + length);
at += 12 + length;
if (type === "IHDR") {
width = data.readUInt32BE(0);
height = data.readUInt32BE(4);
depth = data[8];
colorType = data[9];
interlace = data[12];
} else if (type === "IDAT") {
idat.push(data);
} else if (type === "IEND") {
break;
}
}
if (depth !== 8) throw new Error(`unsupported bit depth ${depth}`);
if (interlace !== 0) throw new Error("interlaced PNG not supported");
if (colorType !== 2 && colorType !== 6) throw new Error(`unsupported colour type ${colorType}`);
const channels = colorType === 6 ? 4 : 3;
const raw = zlib.inflateSync(Buffer.concat(idat));
const stride = width * channels;
const out = Buffer.alloc(width * height * 4);
let prior = Buffer.alloc(stride);
for (let y = 0; y < height; y++) {
const filter = raw[y * (stride + 1)];
const line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)));
for (let i = 0; i < stride; i++) {
const left = i >= channels ? line[i - channels] : 0;
const up = prior[i];
const upLeft = i >= channels ? prior[i - channels] : 0;
switch (filter) {
case 0: break;
case 1: line[i] = (line[i] + left) & 0xff; break;
case 2: line[i] = (line[i] + up) & 0xff; break;
case 3: line[i] = (line[i] + ((left + up) >> 1)) & 0xff; break;
case 4: line[i] = (line[i] + paeth(left, up, upLeft)) & 0xff; break;
default: throw new Error(`unknown filter ${filter} on row ${y}`);
}
}
for (let x = 0; x < width; x++) {
const from = x * channels;
const to = (y * width + x) * 4;
out[to] = line[from];
out[to + 1] = line[from + 1];
out[to + 2] = line[from + 2];
out[to + 3] = channels === 4 ? line[from + 3] : 255;
}
prior = line;
}
return { width, height, data: out };
}
// Nearest pixel, clamped. A rect can sit a hair outside the shot after rounding, and
// clamping is the right answer there rather than an exception or a black pixel.
function pixelAt(image, x, y) {
const px = Math.min(image.width - 1, Math.max(0, Math.round(x)));
const py = Math.min(image.height - 1, Math.max(0, Math.round(y)));
const at = (py * image.width + px) * 4;
return [image.data[at], image.data[at + 1], image.data[at + 2]];
}
module.exports = { decode, pixelAt };
-178
View File
@@ -1,178 +0,0 @@
// The screenshot reader, tested by building PNGs whose pixels are already known.
//
// This matters more than it looks. If a filter is decoded wrong the pixels are still
// plausible colours — slightly off greys and greens, not obvious garbage — and the
// contrast audit would report confident, wrong numbers about a page nobody would think
// to re-check. So every filter type gets encoded here and read back.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const zlib = require("node:zlib");
const { decode, pixelAt } = require("./png");
const CRC_TABLE = (() => {
const table = new Int32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c;
}
return table;
})();
function crc32(buf) {
let c = 0xffffffff;
for (const b of buf) c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type, data) {
const head = Buffer.alloc(8);
head.writeUInt32BE(data.length, 0);
head.write(type, 4, "ascii");
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, "ascii"), data])), 0);
return Buffer.concat([head, data, crc]);
}
function paeth(a, b, c) {
const p = a + b - c;
const pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
if (pa <= pb && pa <= pc) return a;
return pb <= pc ? b : c;
}
// pixels: [y][x] = [r,g,b(,a)]. filter is applied to every row, which is legal PNG and
// is exactly how each decoder branch gets exercised.
function encode(pixels, filter = 0, channels = 4) {
const height = pixels.length, width = pixels[0].length;
const stride = width * channels;
const rows = [];
let prior = Buffer.alloc(stride);
for (let y = 0; y < height; y++) {
const raw = Buffer.alloc(stride);
for (let x = 0; x < width; x++) {
for (let c = 0; c < channels; c++) {
raw[x * channels + c] = pixels[y][x][c] !== undefined ? pixels[y][x][c] : 255;
}
}
const filtered = Buffer.alloc(stride);
for (let i = 0; i < stride; i++) {
const left = i >= channels ? raw[i - channels] : 0;
const up = prior[i];
const upLeft = i >= channels ? prior[i - channels] : 0;
switch (filter) {
case 0: filtered[i] = raw[i]; break;
case 1: filtered[i] = (raw[i] - left) & 0xff; break;
case 2: filtered[i] = (raw[i] - up) & 0xff; break;
case 3: filtered[i] = (raw[i] - ((left + up) >> 1)) & 0xff; break;
case 4: filtered[i] = (raw[i] - paeth(left, up, upLeft)) & 0xff; break;
default: throw new Error("bad filter");
}
}
rows.push(Buffer.concat([Buffer.from([filter]), filtered]));
prior = raw;
}
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr[8] = 8;
ihdr[9] = channels === 4 ? 6 : 2;
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk("IHDR", ihdr),
chunk("IDAT", zlib.deflateSync(Buffer.concat(rows))),
chunk("IEND", Buffer.alloc(0)),
]);
}
// Deliberately awkward: neighbouring values that differ, so a filter decoded with the
// wrong neighbour produces a different answer rather than the same one by luck.
const PIXELS = [
[[20, 30, 40], [200, 10, 90], [18, 18, 18], [255, 255, 255]],
[[0, 0, 0], [28, 108, 60], [108, 68, 39], [1, 2, 3]],
[[240, 217, 168], [47, 122, 77], [200, 200, 200], [17, 17, 17]],
];
describe("every filter type reads back exactly", () => {
[0, 1, 2, 3, 4].forEach(filter => {
test(`filter ${filter}`, () => {
const image = decode(encode(PIXELS, filter));
assert.equal(image.width, 4);
assert.equal(image.height, 3);
for (let y = 0; y < PIXELS.length; y++) {
for (let x = 0; x < PIXELS[y].length; x++) {
assert.deepEqual(pixelAt(image, x, y), PIXELS[y][x],
`pixel ${x},${y} under filter ${filter}`);
}
}
});
});
test("and a three-channel image reads back too", () => {
const image = decode(encode(PIXELS, 4, 3));
assert.deepEqual(pixelAt(image, 1, 2), [47, 122, 77]);
});
test("including where Paeth has to choose between close neighbours", () => {
// Written first to catch paeth(left, up, ...) decoded as paeth(up, left, ...),
// on the assumption that the two differ on a tie. They don't, anywhere: the
// predictor is symmetric in its first two arguments, checked over all 16,777,216
// byte triples. The reason is that a tie between pa and pb requires
// left + up == 2 * upLeft, and that is exactly the condition making pc zero — so
// every tie is resolved by returning upLeft, whichever order the other two
// arrived in. Swapping them is a no-op and no test can catch it, which is worth
// knowing rather than papering over with a fixture that appears to.
//
// What this does catch is the mistake that is actually available: reading the
// wrong neighbour. The values sit close together so a predictor that reaches one
// pixel off produces a different answer rather than the same one by luck.
const CLOSE = [
[[100, 10, 20], [110, 40, 25]],
[[90, 70, 30], [55, 95, 35]],
];
const image = decode(encode(CLOSE, 4));
assert.deepEqual(pixelAt(image, 1, 1), [55, 95, 35]);
assert.deepEqual(pixelAt(image, 0, 1), [90, 70, 30]);
assert.deepEqual(pixelAt(image, 1, 0), [110, 40, 25]);
});
});
describe("sampling", () => {
const image = decode(encode(PIXELS, 0));
test("rounds to the nearest pixel", () => {
assert.deepEqual(pixelAt(image, 0.4, 0.4), [20, 30, 40]);
assert.deepEqual(pixelAt(image, 0.6, 0.4), [200, 10, 90]);
});
test("clamps rather than throwing or reading black", () => {
// A rect can sit a hair outside the shot once it's been rounded, and a silent
// black pixel there would read as a contrast failure that isn't one.
assert.deepEqual(pixelAt(image, -5, -5), [20, 30, 40]);
assert.deepEqual(pixelAt(image, 999, 999), [17, 17, 17]);
});
});
describe("what it refuses", () => {
test("something that isn't a PNG at all", () => {
assert.throws(() => decode(Buffer.from("not a png at all, honestly")), /not a PNG/);
});
test("an interlaced one, rather than returning scrambled pixels", () => {
const png = encode(PIXELS, 0);
// Byte 12 of the IHDR data: 8 signature + 8 chunk header + 12 = interlace flag.
const broken = Buffer.from(png);
broken[8 + 8 + 12] = 1;
assert.throws(() => decode(broken), /interlaced/);
});
test("a colour type it cannot read", () => {
const broken = Buffer.from(encode(PIXELS, 0));
broken[8 + 8 + 9] = 3; // palette
assert.throws(() => decode(broken), /colour type/);
});
});
-238
View File
@@ -1,238 +0,0 @@
// Somebody who walks up and sits down after the blinds have gone past them.
//
// Dealing them straight in is a free hand in late position — which is what posting
// exists to stop, and it comes out of everybody else's night a couple of dollars at a
// time. The tool used to do it silently. It now says so, and takes the post if the
// dealer says to.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { HoldemState, Betting, makeTable } = require("./load");
const NAMES = ["Ann", "Ben", "Cal", "Dee"];
const table = (dealerSeatIndex = 0) => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 200, dealerSeatIndex });
NAMES.forEach((name, i) => { state.seats[i].name = name; });
return state;
};
// Eve walks up and takes seat 5 while the table is running.
const seatEve = state => {
state.seats[4].name = "Eve";
state.seats[4].inHand = true;
state.seats[4].stack = 200;
state.seats[4].buyIns = 200;
return 4;
};
const debtors = state => {
const { bbIndex } = HoldemState.getBlindSeats(state);
return HoldemState.blindDebtors(state, bbIndex).map(i => state.seats[i].name);
};
describe("who is owed a blind", () => {
test("nobody, at a table that hasn't dealt a hand yet", () => {
// Everyone is new on the first hand. Asking the whole table to post would be
// the tool mistaking the start of the night for five people walking up late.
const state = table();
assert.deepEqual(debtors(state), []);
});
test("nobody, on an ordinary hand where the same people are still sitting there", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
assert.deepEqual(debtors(state), []);
});
test("the player who has just sat down", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
seatEve(state);
assert.deepEqual(debtors(state), ["Eve"]);
});
test("not once they've been dealt a hand", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
seatEve(state);
Betting.beginHand(state);
HoldemState.startNextHand(state);
assert.deepEqual(debtors(state), [], "she's one of the regulars now");
});
test("not somebody who is the big blind this hand — they're paying already", () => {
const state = table(0); // blinds Ben and Cal
Betting.beginHand(state);
HoldemState.startNextHand(state); // blinds move to Cal and Dee
// Dee sits out for a hand and comes straight back into her own big blind.
state.seats[3].inHand = false;
Betting.beginHand(state);
HoldemState.startNextHand(state);
state.seats[3].inHand = true;
const { bbIndex } = HoldemState.getBlindSeats(state);
assert.ok(!HoldemState.blindDebtors(state, bbIndex).includes(bbIndex),
"the big blind is never asked to post on top of their blind");
});
test("somebody back from sitting out is owed one just like a newcomer", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
state.seats[3].inHand = false; // Dee stands up for a hand
Betting.beginHand(state);
HoldemState.startNextHand(state);
state.seats[3].inHand = true; // and sits back down
assert.ok(debtors(state).includes("Dee"), "the blinds went past her while she was up");
});
test("a seat sat out for having no chips isn't owed anything", () => {
// They aren't being dealt in, so there's no free hand to charge for.
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
const eve = seatEve(state);
state.seats[eve].stack = 0;
const preview = Betting.blindPreview(state);
assert.ok(!preview.debtors.includes(eve), "she's sitting out until she buys chips");
});
});
describe("posting to come in", () => {
test("the post goes in the middle and buys a hand", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
const eve = seatEve(state);
state.postingIn = [state.seats[eve].id];
const before = Betting.stackOf(state, state.seats[eve]);
Betting.beginHand(state);
assert.equal(Betting.committed(state.seats[eve]), state.bigBlind, "she's posted a big blind");
assert.equal(Betting.stackOf(state, state.seats[eve]), before - state.bigBlind,
"out of her own stack, not conjured");
assert.equal(state.currentBet, state.bigBlind, "and it doesn't raise the hand");
});
test("not posting leaves her stack alone", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
const eve = seatEve(state);
const before = Betting.stackOf(state, state.seats[eve]);
Betting.beginHand(state);
assert.equal(Betting.committed(state.seats[eve]), 0);
assert.equal(Betting.stackOf(state, state.seats[eve]), before);
});
test("the pot is what the blinds and the post add up to", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
const eve = seatEve(state);
state.postingIn = [state.seats[eve].id];
Betting.beginHand(state);
const middle = state.seats.reduce((sum, p) => sum + Betting.committed(p), 0);
assert.equal(middle, state.smallBlind + state.bigBlind + state.bigBlind);
});
test("it's spent after the hand, not a standing charge", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
const eve = seatEve(state);
state.postingIn = [state.seats[eve].id];
Betting.beginHand(state);
HoldemState.startNextHand(state);
assert.deepEqual(state.postingIn, [], "or she'd pay an extra blind every hand all night");
Betting.beginHand(state);
assert.ok(Betting.committed(state.seats[eve]) === 0 ||
state.seats[eve].id === state.seats[HoldemState.getBlindSeats(state).bbIndex]?.id,
"she pays nothing extra on the next hand");
});
test("moving the button after a post doesn't lose it", () => {
// repostBlinds takes every posted chip back and deals again. A post that
// cleared itself on the way in would be refunded and never retaken.
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
const eve = seatEve(state);
state.postingIn = [state.seats[eve].id];
Betting.beginHand(state);
const chips = () => state.seats.reduce(
(sum, p) => sum + Betting.stackOf(state, p) + Betting.handTotal(p), 0);
const before = chips();
state.dealerSeatIndex = 2;
Betting.repostBlinds(state);
assert.equal(Betting.committed(state.seats[eve]), state.bigBlind, "still posted");
assert.equal(chips(), before, "and no chips made or lost in the shuffle");
});
test("a post from somebody who isn't owed one is not taken", () => {
// Only seats actually being dealt in can post, and only for their own chips.
const state = table();
state.postingIn = [state.seats[3].id];
state.seats[3].inHand = false;
Betting.beginHand(state);
assert.equal(Betting.committed(state.seats[3]), 0, "she isn't even in the hand");
});
});
describe("what the dealer is shown", () => {
test("the prompt has something to say about it, and something to press", () => {
const state = table();
Betting.beginHand(state);
HoldemState.startNextHand(state);
const eve = seatEve(state);
const preview = Betting.blindPreview(state);
assert.deepEqual(preview.debtors, [eve]);
assert.deepEqual(preview.posting, [], "not posting until the dealer says so");
state.postingIn = [state.seats[eve].id];
assert.deepEqual(Betting.blindPreview(state).posting, [state.seats[eve].id]);
});
test("an old save reads as a table nobody has just walked up to", () => {
const state = table();
Betting.beginHand(state);
const parsed = JSON.parse(JSON.stringify(state));
delete parsed.dealtLastHand;
delete parsed.postingIn;
const store = new Map([[HoldemState.STORAGE_KEY, JSON.stringify(parsed)]]);
globalThis.localStorage = {
getItem: key => (store.has(key) ? store.get(key) : null),
setItem: (key, value) => store.set(key, value),
removeItem: key => store.delete(key),
};
const loaded = HoldemState.load();
assert.deepEqual(loaded.dealtLastHand, []);
assert.deepEqual(loaded.postingIn, []);
assert.deepEqual(debtors(loaded), [],
"reopening the tab doesn't ask the whole table to post");
delete globalThis.localStorage;
});
});

Some files were not shown because too many files have changed in this diff Show More