holdem-core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -450,48 +450,176 @@ function bestFive(cards, score, category) {
450
450
  }
451
451
  }
452
452
 
453
+ // src/range.ts
454
+ var HAND_CLASS = /^([2-9tjqka])([2-9tjqka])([so]?)$/i;
455
+ var TOKEN_SEPARATOR = /[\s,;]+/;
456
+ function rankIndex(ch) {
457
+ return RANKS.indexOf(ch.toUpperCase());
458
+ }
459
+ function parseClass(text, token) {
460
+ const m = HAND_CLASS.exec(text);
461
+ if (!m) throw new HoldemError("INVALID_RANGE", `Invalid hand "${text}" in range token "${token}"`);
462
+ const a = rankIndex(m[1]);
463
+ const b = rankIndex(m[2]);
464
+ const suited = m[3].toLowerCase();
465
+ if (a === b && suited !== "") {
466
+ throw new HoldemError("INVALID_RANGE", `A pair cannot be suited or offsuit: "${text}" in "${token}"`);
467
+ }
468
+ return { high: Math.max(a, b), low: Math.min(a, b), suited };
469
+ }
470
+ function classLabel(high, low, suited) {
471
+ return RANKS[high] + RANKS[low] + suited;
472
+ }
473
+ function combosOf(high, low, suited, out) {
474
+ for (let s1 = 3; s1 >= 0; s1--) {
475
+ for (let s2 = 3; s2 >= 0; s2--) {
476
+ if (high === low) {
477
+ if (s2 >= s1) continue;
478
+ } else if (suited === "s" && s1 !== s2 || suited === "o" && s1 === s2) {
479
+ continue;
480
+ }
481
+ out.push([high * 4 + s1, low * 4 + s2]);
482
+ }
483
+ }
484
+ }
485
+ function expandToken(token, out) {
486
+ const lower = token.toLowerCase();
487
+ if (lower === "random" || lower === "any") {
488
+ for (let high = 12; high >= 0; high--) {
489
+ for (let low = high; low >= 0; low--) combosOf(high, low, "", out);
490
+ }
491
+ return;
492
+ }
493
+ const dash = token.split("-");
494
+ if (dash.length > 2) throw new HoldemError("INVALID_RANGE", `Invalid range token "${token}"`);
495
+ if (dash.length === 2) {
496
+ const a = parseClass(dash[0], token);
497
+ const b = parseClass(dash[1], token);
498
+ const aPair = a.high === a.low;
499
+ const bPair = b.high === b.low;
500
+ if (aPair && bPair) {
501
+ for (let r = Math.max(a.high, b.high); r >= Math.min(a.high, b.high); r--) combosOf(r, r, "", out);
502
+ return;
503
+ }
504
+ if (aPair || bPair || a.suited !== b.suited) {
505
+ throw new HoldemError("INVALID_RANGE", `Both ends of "${token}" must be the same kind of hand`);
506
+ }
507
+ if (a.high === b.high) {
508
+ for (let k = Math.max(a.low, b.low); k >= Math.min(a.low, b.low); k--) combosOf(a.high, k, a.suited, out);
509
+ return;
510
+ }
511
+ if (a.high - a.low === b.high - b.low) {
512
+ const top = a.high > b.high ? a : b;
513
+ const steps = Math.abs(a.high - b.high);
514
+ for (let i = 0; i <= steps; i++) combosOf(top.high - i, top.low - i, a.suited, out);
515
+ return;
516
+ }
517
+ throw new HoldemError(
518
+ "INVALID_RANGE",
519
+ `"${token}" must keep the same top card (e.g. KTs-K8s) or the same gap (e.g. T9s-65s)`
520
+ );
521
+ }
522
+ if (token.endsWith("+")) {
523
+ const c = parseClass(token.slice(0, -1), token);
524
+ if (c.high === c.low) {
525
+ for (let r = 12; r >= c.high; r--) combosOf(r, r, "", out);
526
+ } else {
527
+ for (let k = c.high - 1; k >= c.low; k--) combosOf(c.high, k, c.suited, out);
528
+ }
529
+ return;
530
+ }
531
+ if (HAND_CLASS.test(token)) {
532
+ const c = parseClass(token, token);
533
+ combosOf(c.high, c.low, c.suited, out);
534
+ return;
535
+ }
536
+ let cards;
537
+ try {
538
+ cards = parseCards(token);
539
+ } catch {
540
+ throw new HoldemError("INVALID_RANGE", `Invalid range token "${token}"`);
541
+ }
542
+ if (cards.length !== 2) throw new HoldemError("INVALID_RANGE", `"${token}" must name exactly two cards`);
543
+ try {
544
+ assertDistinctCards(cards);
545
+ } catch {
546
+ throw new HoldemError("INVALID_RANGE", `"${token}" uses the same card twice`);
547
+ }
548
+ const [x, y] = cards;
549
+ out.push(x > y ? [x, y] : [y, x]);
550
+ }
551
+ function parseRange(text) {
552
+ const normalized = text.trim().replace(/\s*-\s*/g, "-");
553
+ if (normalized === "") throw new HoldemError("INVALID_RANGE", "Range is empty");
554
+ const all = [];
555
+ for (const token of normalized.split(TOKEN_SEPARATOR)) expandToken(token, all);
556
+ const seen = /* @__PURE__ */ new Set();
557
+ return all.filter(([a, b]) => {
558
+ const key = a * 52 + b;
559
+ if (seen.has(key)) return false;
560
+ seen.add(key);
561
+ return true;
562
+ });
563
+ }
564
+ function comboClass(combo) {
565
+ if (combo.length !== 2) throw new HoldemError("INVALID_HAND_SIZE", `A combo has exactly 2 cards, got ${combo.length}`);
566
+ assertDistinctCards(combo);
567
+ const [x, y] = combo;
568
+ const high = Math.max(x >> 2, y >> 2);
569
+ const low = Math.min(x >> 2, y >> 2);
570
+ if (high === low) return classLabel(high, low, "");
571
+ return classLabel(high, low, (x & 3) === (y & 3) ? "s" : "o");
572
+ }
573
+
453
574
  // src/equity.ts
454
575
  function binomial(n, k) {
455
576
  let r = 1;
456
577
  for (let i = 1; i <= k; i++) r = r * (n - k + i) / i;
457
578
  return Math.round(r);
458
579
  }
459
- function calculateEquity(hands, options = {}) {
460
- const board = options.board ?? [];
461
- const dead = options.dead ?? [];
462
- const exactLimit = options.exactLimit ?? 2e6;
463
- const iterations = options.iterations ?? 2e5;
464
- const random = options.random ?? secureRandom;
465
- if (hands.length < 2 || hands.length > 10) {
466
- throw new HoldemError("INVALID_ARGUMENT", `Expected 2 to 10 hands, got ${hands.length}`);
580
+ function readOptions(players, options) {
581
+ const settings = {
582
+ board: options.board ?? [],
583
+ dead: options.dead ?? [],
584
+ exactLimit: options.exactLimit ?? 2e6,
585
+ iterations: options.iterations ?? 2e5,
586
+ random: options.random ?? secureRandom
587
+ };
588
+ if (players < 2 || players > 10) {
589
+ throw new HoldemError("INVALID_ARGUMENT", `Expected 2 to 10 hands, got ${players}`);
467
590
  }
468
- hands.forEach((hand, i) => {
469
- if (hand.length !== 2) throw new HoldemError("INVALID_ARGUMENT", `Hand ${i} must have exactly 2 cards, got ${hand.length}`);
470
- });
471
- if (board.length > 5) throw new HoldemError("INVALID_ARGUMENT", `Board can have at most 5 cards, got ${board.length}`);
472
- if (!Number.isInteger(iterations) || iterations < 1) {
473
- throw new HoldemError("INVALID_ARGUMENT", `iterations must be a positive integer, got ${iterations}`);
591
+ if (settings.board.length > 5) {
592
+ throw new HoldemError("INVALID_ARGUMENT", `Board can have at most 5 cards, got ${settings.board.length}`);
474
593
  }
475
- assertDistinctCards(...hands, board, dead);
476
- const used = /* @__PURE__ */ new Set([...hands.flat(), ...board, ...dead]);
477
- const stub = [];
478
- for (let c = 0; c < 52; c++) if (!used.has(c)) stub.push(c);
479
- const missing = 5 - board.length;
480
- if (stub.length < missing) throw new HoldemError("NOT_ENOUGH_CARDS", "Not enough cards left to complete the board");
481
- const players = hands.length;
482
- const seven = hands.map((hand) => {
483
- const cards = new Array(7);
484
- cards[0] = hand[0];
485
- cards[1] = hand[1];
486
- board.forEach((c, i) => cards[2 + i] = c);
487
- return cards;
488
- });
489
- const wins = new Float64Array(players);
490
- const ties = new Float64Array(players);
491
- const shares = new Float64Array(players);
492
- const scores = new Int32Array(players);
493
- const first = 2 + board.length;
494
- const settle = () => {
594
+ if (!Number.isInteger(settings.iterations) || settings.iterations < 1) {
595
+ throw new HoldemError("INVALID_ARGUMENT", `iterations must be a positive integer, got ${settings.iterations}`);
596
+ }
597
+ return settings;
598
+ }
599
+ var Showdown = class {
600
+ constructor(players, board) {
601
+ this.players = players;
602
+ /** Positions in the stub of the cards currently on the board (reused by every enumeration). */
603
+ this.idx = new Int32Array(5);
604
+ this.seven = Array.from({ length: players }, () => {
605
+ const cards = new Array(7);
606
+ board.forEach((c, i) => cards[2 + i] = c);
607
+ return cards;
608
+ });
609
+ this.first = 2 + board.length;
610
+ this.wins = new Float64Array(players);
611
+ this.ties = new Float64Array(players);
612
+ this.shares = new Float64Array(players);
613
+ this.scores = new Int32Array(players);
614
+ }
615
+ /** Puts `card` in the `slot`-th missing board position for every player. */
616
+ place(slot, card) {
617
+ const at = this.first + slot;
618
+ for (let p = 0; p < this.players; p++) this.seven[p][at] = card;
619
+ }
620
+ /** Scores the current seven cards of every player and credits the winners. */
621
+ settle() {
622
+ const { players, seven, scores, wins, ties, shares } = this;
495
623
  let best = -1;
496
624
  let count = 0;
497
625
  for (let p = 0; p < players; p++) {
@@ -504,54 +632,202 @@ function calculateEquity(hands, options = {}) {
504
632
  count++;
505
633
  }
506
634
  }
635
+ if (count === 1) {
636
+ let p = 0;
637
+ while (scores[p] !== best) p++;
638
+ wins[p]++;
639
+ shares[p]++;
640
+ return;
641
+ }
507
642
  for (let p = 0; p < players; p++) {
508
643
  if (scores[p] !== best) continue;
509
- if (count === 1) wins[p]++;
510
- else ties[p]++;
644
+ ties[p]++;
511
645
  shares[p] += 1 / count;
512
646
  }
513
- };
514
- const place = (slot, card) => {
515
- for (let p = 0; p < players; p++) seven[p][first + slot] = card;
516
- };
517
- const total = binomial(stub.length, missing);
518
- const exact = total <= exactLimit;
519
- let runouts = 0;
520
- if (exact) {
521
- const idx = Array.from({ length: missing }, (_, i) => i);
647
+ }
648
+ /** Every way to complete the board from `stub`, settled in turn; returns how many there were. */
649
+ enumerate(stub, missing) {
650
+ const { players, seven, first, idx } = this;
651
+ for (let i = 0; i < missing; i++) idx[i] = i;
652
+ let runouts = 0;
522
653
  for (; ; ) {
523
- for (let k2 = 0; k2 < missing; k2++) place(k2, stub[idx[k2]]);
524
- settle();
654
+ for (let k2 = 0; k2 < missing; k2++) {
655
+ const card = stub[idx[k2]];
656
+ for (let p = 0; p < players; p++) seven[p][first + k2] = card;
657
+ }
658
+ this.settle();
525
659
  runouts++;
526
660
  let k = missing - 1;
527
661
  while (k >= 0 && idx[k] === stub.length - missing + k) k--;
528
- if (k < 0) break;
662
+ if (k < 0) return runouts;
529
663
  idx[k]++;
530
664
  for (let j = k + 1; j < missing; j++) idx[j] = idx[j - 1] + 1;
531
665
  }
666
+ }
667
+ /** Completes the board with a random draw from the first cards of `deck` (shuffled in place) and settles it. */
668
+ sample(deck, length, missing, random) {
669
+ for (let k = 0; k < missing; k++) {
670
+ const j = k + random.int(length - k);
671
+ const tmp = deck[k];
672
+ deck[k] = deck[j];
673
+ deck[j] = tmp;
674
+ this.place(k, deck[k]);
675
+ }
676
+ this.settle();
677
+ }
678
+ result(runouts) {
679
+ return Array.from({ length: this.players }, (_, p) => ({
680
+ equity: this.shares[p] / runouts,
681
+ win: this.wins[p] / runouts,
682
+ tie: this.ties[p] / runouts
683
+ }));
684
+ }
685
+ };
686
+ function calculateEquity(hands, options = {}) {
687
+ const { board, dead, exactLimit, iterations, random } = readOptions(hands.length, options);
688
+ hands.forEach((hand, i) => {
689
+ if (hand.length !== 2) throw new HoldemError("INVALID_ARGUMENT", `Hand ${i} must have exactly 2 cards, got ${hand.length}`);
690
+ });
691
+ assertDistinctCards(...hands, board, dead);
692
+ const used = /* @__PURE__ */ new Set([...hands.flat(), ...board, ...dead]);
693
+ const stub = [];
694
+ for (let c = 0; c < 52; c++) if (!used.has(c)) stub.push(c);
695
+ const missing = 5 - board.length;
696
+ if (stub.length < missing) throw new HoldemError("NOT_ENOUGH_CARDS", "Not enough cards left to complete the board");
697
+ const table = new Showdown(hands.length, board);
698
+ hands.forEach((hand, p) => {
699
+ table.seven[p][0] = hand[0];
700
+ table.seven[p][1] = hand[1];
701
+ });
702
+ const exact = binomial(stub.length, missing) <= exactLimit;
703
+ let runouts;
704
+ if (exact) {
705
+ runouts = table.enumerate(stub, missing);
532
706
  } else {
533
707
  const deck = stub.slice();
708
+ for (let t = 0; t < iterations; t++) table.sample(deck, deck.length, missing, random);
709
+ runouts = iterations;
710
+ }
711
+ return { players: table.result(runouts), runouts, exact };
712
+ }
713
+ var MAX_REJECTIONS = 1e5;
714
+ function toCombos(range, index) {
715
+ if (typeof range === "string") return parseRange(range);
716
+ const seen = /* @__PURE__ */ new Set();
717
+ const combos = [];
718
+ for (const hand of range) {
719
+ if (hand.length !== 2) {
720
+ throw new HoldemError("INVALID_HAND_SIZE", `Range ${index} has a hand with ${hand.length} cards; each needs exactly 2`);
721
+ }
722
+ assertDistinctCards(hand);
723
+ const combo = hand[0] > hand[1] ? [hand[0], hand[1]] : [hand[1], hand[0]];
724
+ const key = combo[0] * 52 + combo[1];
725
+ if (seen.has(key)) continue;
726
+ seen.add(key);
727
+ combos.push(combo);
728
+ }
729
+ return combos;
730
+ }
731
+ function calculateRangeEquity(ranges, options = {}) {
732
+ const { board, dead, exactLimit, iterations, random } = readOptions(ranges.length, options);
733
+ assertDistinctCards(board, dead);
734
+ const blocked = new Uint8Array(52);
735
+ for (const c of board) blocked[c] = 1;
736
+ for (const c of dead) blocked[c] = 1;
737
+ const lists = ranges.map((range, i) => {
738
+ const live = toCombos(range, i).filter(([a, b]) => !blocked[a] && !blocked[b]);
739
+ if (live.length === 0) {
740
+ throw new HoldemError("INVALID_RANGE", `Range ${i} has no hands left once the board and dead cards are removed`);
741
+ }
742
+ return live;
743
+ });
744
+ const players = lists.length;
745
+ const base = [];
746
+ for (let c = 0; c < 52; c++) if (!blocked[c]) base.push(c);
747
+ const missing = 5 - board.length;
748
+ const left = base.length - 2 * players;
749
+ if (left < missing) throw new HoldemError("NOT_ENOUGH_CARDS", "Not enough cards left to complete the board");
750
+ const perDeal = binomial(left, missing);
751
+ const taken = new Uint8Array(52);
752
+ const pick = new Int32Array(players);
753
+ const walk = (p, visit) => {
754
+ if (p === players) return visit();
755
+ const list = lists[p];
756
+ for (let i = 0; i < list.length; i++) {
757
+ const [a, b] = list[i];
758
+ if (taken[a] || taken[b]) continue;
759
+ taken[a] = 1;
760
+ taken[b] = 1;
761
+ pick[p] = i;
762
+ const more = walk(p + 1, visit);
763
+ taken[a] = 0;
764
+ taken[b] = 0;
765
+ if (!more) return false;
766
+ }
767
+ return true;
768
+ };
769
+ const cap = perDeal <= exactLimit ? Math.floor(exactLimit / perDeal) : 0;
770
+ let deals = 0;
771
+ walk(0, () => ++deals <= cap);
772
+ if (deals === 0) {
773
+ throw new HoldemError("INVALID_RANGE", "These ranges can never be dealt together: every combination shares a card");
774
+ }
775
+ const exact = deals <= cap;
776
+ const table = new Showdown(players, board);
777
+ const seat = () => {
778
+ for (let p = 0; p < players; p++) {
779
+ const [a, b] = lists[p][pick[p]];
780
+ table.seven[p][0] = a;
781
+ table.seven[p][1] = b;
782
+ }
783
+ };
784
+ const stub = new Array(left);
785
+ const fillStub = () => {
786
+ let n = 0;
787
+ for (const c of base) if (!taken[c]) stub[n++] = c;
788
+ };
789
+ let runouts = 0;
790
+ if (exact) {
791
+ walk(0, () => {
792
+ seat();
793
+ fillStub();
794
+ runouts += table.enumerate(stub, missing);
795
+ return true;
796
+ });
797
+ } else {
798
+ const release = (count) => {
799
+ for (let q = 0; q < count; q++) {
800
+ const [a, b] = lists[q][pick[q]];
801
+ taken[a] = 0;
802
+ taken[b] = 0;
803
+ }
804
+ };
534
805
  for (let t = 0; t < iterations; t++) {
535
- for (let k = 0; k < missing; k++) {
536
- const j = k + random.int(deck.length - k);
537
- const tmp = deck[k];
538
- deck[k] = deck[j];
539
- deck[j] = tmp;
540
- place(k, deck[k]);
806
+ for (let failures = 0; ; ) {
807
+ let p = 0;
808
+ for (; p < players; p++) {
809
+ const list = lists[p];
810
+ const i = list.length === 1 ? 0 : random.int(list.length);
811
+ const [a, b] = list[i];
812
+ if (taken[a] || taken[b]) break;
813
+ taken[a] = 1;
814
+ taken[b] = 1;
815
+ pick[p] = i;
816
+ }
817
+ if (p === players) break;
818
+ release(p);
819
+ if (++failures >= MAX_REJECTIONS) {
820
+ throw new HoldemError("INVALID_RANGE", "These ranges overlap too much to sample: almost every deal shares a card");
821
+ }
541
822
  }
542
- settle();
823
+ seat();
824
+ fillStub();
825
+ table.sample(stub, left, missing, random);
826
+ release(players);
543
827
  }
544
828
  runouts = iterations;
545
829
  }
546
- return {
547
- players: Array.from({ length: players }, (_, p) => ({
548
- equity: shares[p] / runouts,
549
- win: wins[p] / runouts,
550
- tie: ties[p] / runouts
551
- })),
552
- runouts,
553
- exact
554
- };
830
+ return { players: table.result(runouts), runouts, exact, combos: lists.map((l) => l.length) };
555
831
  }
556
832
 
557
833
  // src/pots.ts
@@ -641,6 +917,6 @@ function settlePots(contributions, options = {}) {
641
917
  return { pots: settled, payouts, net };
642
918
  }
643
919
 
644
- export { Deck, HandCategory, HoldemError, RANKS, SUITS, assertDistinctCards, buildPots, calculateEquity, categoryOf, compareHands, compareScores, createDeck, createSecureRandom, createSeededRandom, describeScore, evaluateHand, formatCard, formatCards, handName, isCard, makeCard, parseCard, parseCards, rankName, rankOf, scoreHand, secureRandom, settlePots, shuffle, shuffled, suitOf, winners };
920
+ export { Deck, HandCategory, HoldemError, RANKS, SUITS, assertDistinctCards, buildPots, calculateEquity, calculateRangeEquity, categoryOf, comboClass, compareHands, compareScores, createDeck, createSecureRandom, createSeededRandom, describeScore, evaluateHand, formatCard, formatCards, handName, isCard, makeCard, parseCard, parseCards, parseRange, rankName, rankOf, scoreHand, secureRandom, settlePots, shuffle, shuffled, suitOf, winners };
645
921
  //# sourceMappingURL=index.js.map
646
922
  //# sourceMappingURL=index.js.map