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/CHANGELOG.md +8 -0
- package/README.md +44 -8
- package/README.zh-CN.md +10 -4
- package/dist/index.cjs +343 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +58 -2
- package/dist/index.d.ts +58 -2
- package/dist/index.js +341 -65
- package/dist/index.js.map +1 -1
- package/package.json +7 -5
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented here. The project follows [Semantic Versioning](https://semver.org/).
|
|
4
4
|
|
|
5
|
+
## 0.2.0 — hand ranges
|
|
6
|
+
|
|
7
|
+
- Ranges: `parseRange` reads standard notation — `QQ`, `AKs` / `AKo` / `AK`, `QQ+`, `ATs+`, `99-66`, `KTs-K8s`, `T9s-65s`, exact hands such as `AsKs`, and `random` — into distinct two-card combos; `comboClass` names a combo's class (`"AKs"`).
|
|
8
|
+
- Equity: `calculateRangeEquity` for 2–10 ranges with board and dead-card removal. Every non-clashing deal is equally likely; it enumerates exactly when deals × runouts fit in `exactLimit` and samples otherwise (seedable). Exact results match a deal-by-deal brute force to 12 decimal places.
|
|
9
|
+
- Errors: new code `INVALID_RANGE`.
|
|
10
|
+
- `calculateEquity` now shares its showdown tally with the range code; its results are unchanged.
|
|
11
|
+
- Releases are staged on npm from GitHub Actions (Trusted Publishing with provenance) and published only after a maintainer approves them with 2FA.
|
|
12
|
+
|
|
5
13
|
## 0.1.0 — first release
|
|
6
14
|
|
|
7
15
|
- Cards: parsing (`"As"`, `"10h"`, `"K♠"`), formatting, rank/suit helpers, duplicate checks.
|
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# holdem-core
|
|
2
2
|
|
|
3
3
|
**Fast, zero-dependency Texas Hold'em toolkit for TypeScript and JavaScript.**
|
|
4
|
-
Card parsing, unbiased shuffling, 5–7 card hand evaluation, exact equity and side-pot settlement — verified exhaustively.
|
|
4
|
+
Card parsing, unbiased shuffling, 5–7 card hand evaluation, hand ranges, exact equity and side-pot settlement — verified exhaustively.
|
|
5
5
|
|
|
6
|
-
[](https://github.com/HoldemForge/holdem-core/actions/workflows/ci.yml)
|
|
7
7
|
[](https://www.npmjs.com/package/holdem-core)
|
|
8
8
|
[](LICENSE)
|
|
9
9
|

|
|
@@ -12,13 +12,16 @@ Card parsing, unbiased shuffling, 5–7 card hand evaluation, exact equity and s
|
|
|
12
12
|
[中文说明](README.zh-CN.md)
|
|
13
13
|
|
|
14
14
|
```ts
|
|
15
|
-
import { parseCards, evaluateHand, calculateEquity, settlePots } from 'holdem-core';
|
|
15
|
+
import { parseCards, evaluateHand, calculateEquity, calculateRangeEquity, settlePots } from 'holdem-core';
|
|
16
16
|
|
|
17
17
|
evaluateHand(parseCards('Kh Kd Ks Tc Td 2s 3h')).description;
|
|
18
18
|
// → "Full House, Kings full of Tens"
|
|
19
19
|
|
|
20
20
|
calculateEquity([parseCards('As Ah'), parseCards('Kd Kc')]).players[0].equity;
|
|
21
|
-
// → 0.812555… (exact, all 1,712,304 runouts in ~
|
|
21
|
+
// → 0.812555… (exact, all 1,712,304 runouts in ~80 ms)
|
|
22
|
+
|
|
23
|
+
calculateRangeEquity(['QQ+, AKs', 'JJ-99, AQs'], { board: parseCards('Kh 7d 2c') }).players[0].equity;
|
|
24
|
+
// → 0.928378… (exact, every deal of the two ranges and every turn and river)
|
|
22
25
|
|
|
23
26
|
settlePots(
|
|
24
27
|
[{ id: 'alice', amount: 50 }, { id: 'bob', amount: 100 }, { id: 'carol', amount: 100 }],
|
|
@@ -32,6 +35,7 @@ settlePots(
|
|
|
32
35
|
- **Correct, and proven.** Every one of the **133,784,560** seven-card hands is evaluated in CI and matches the published category totals. 1,000,000 random hands and 1,000,000 showdowns agree with [pokersolver](https://www.npmjs.com/package/pokersolver) with zero mismatches.
|
|
33
36
|
- **Fast.** About **20 million** 7-card evaluations per second on one core — no 21-combination loop, no allocations, no giant lookup files (≈ 24 KB of tables built at load).
|
|
34
37
|
- **Complete for real games.** Side pots, folded chips, uncalled bets and odd-chip rules are handled; every settlement is checked to be zero-sum.
|
|
38
|
+
- **Ranges, not just hands.** Standard notation (`QQ+`, `AKs`, `T9s-65s`, `random`) with card removal; range-vs-range equity is exact whenever it can be enumerated and matches a deal-by-deal brute force.
|
|
35
39
|
- **Safe defaults.** Shuffles use `crypto.getRandomValues` with rejection sampling — no modulo bias. A seeded generator is available for tests and replays.
|
|
36
40
|
- **Small and typed.** Zero runtime dependencies, ESM + CommonJS, full `.d.ts`. Tested on Node 20, 22 and 24; uses only standard Web APIs, so it also runs in modern browsers.
|
|
37
41
|
|
|
@@ -104,6 +108,37 @@ calculateEquity(hands, { iterations: 500_000, random: createSeededRandom(1) });
|
|
|
104
108
|
|
|
105
109
|
Options: `board`, `dead`, `exactLimit` (default 2,000,000 runouts — heads-up and 3-way preflop are exact), `iterations`, `random`.
|
|
106
110
|
|
|
111
|
+
### Hand ranges
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { parseRange, comboClass, calculateRangeEquity, parseCards } from 'holdem-core';
|
|
115
|
+
|
|
116
|
+
parseRange('QQ+, AKs').length; // 22 two-card combos
|
|
117
|
+
parseRange('T9s-65s').map(comboClass); // ['T9s', 'T9s', 'T9s', 'T9s', '98s', …, '65s']
|
|
118
|
+
|
|
119
|
+
calculateRangeEquity(['AA', 'random']).players[0].equity;
|
|
120
|
+
// → ≈ 0.852 (sampled: 7,350 deals × 1,712,304 runouts each is too many to enumerate)
|
|
121
|
+
|
|
122
|
+
calculateRangeEquity(['QQ+, AKs', 'JJ-99, AQs'], { board: parseCards('Kh 7d 2c') });
|
|
123
|
+
// → { exact: true, runouts: 365310, combos: [18, 22], players: [{ equity: 0.928…, … }, …] }
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
| Notation | Meaning | Combos |
|
|
127
|
+
|---|---|---|
|
|
128
|
+
| `QQ` | one pair | 6 |
|
|
129
|
+
| `AKs` / `AKo` / `AK` | suited / offsuit / both | 4 / 12 / 16 |
|
|
130
|
+
| `QQ+` | QQ, KK, AA | 18 |
|
|
131
|
+
| `ATs+` | ATs, AJs, AQs, AKs | 16 |
|
|
132
|
+
| `99-66` | 99, 88, 77, 66 | 24 |
|
|
133
|
+
| `KTs-K8s` | KTs, K9s, K8s | 12 |
|
|
134
|
+
| `T9s-65s` | T9s, 98s, 87s, 76s, 65s | 20 |
|
|
135
|
+
| `AsKs` | one exact hand | 1 |
|
|
136
|
+
| `random` (or `any`) | every hand | 1,326 |
|
|
137
|
+
|
|
138
|
+
Separate tokens with commas or spaces; overlapping tokens count each hand once. A range can also be an array of two-card hands, so `calculateRangeEquity` accepts `parseRange` output, your own hand lists or a single exact hand.
|
|
139
|
+
|
|
140
|
+
Every way to deal one hand to each player without a shared card is equally likely, and hands that clash with the board or dead cards are removed (`combos` reports what is left). Here `exactLimit` counts deals × runouts, so small ranges — and most ranges on the turn or river — are exact. Beyond that, random deals that share a card are redrawn; with many players on overlapping ranges this slows sampling down (nine random hands take about two seconds at the default 200,000 iterations).
|
|
141
|
+
|
|
107
142
|
### Side pots and settlement
|
|
108
143
|
|
|
109
144
|
```ts
|
|
@@ -144,7 +179,8 @@ Results on Node 24, Apple M5:
|
|
|
144
179
|
| Seven-card hands evaluated exhaustively | 133,784,560 in 2.8 s — all category totals and the 4,824 distinct values match |
|
|
145
180
|
| Cross-check vs pokersolver | 0 mismatches in 1,000,000 categories and 1,000,000 showdowns |
|
|
146
181
|
| `scoreHand`, 7 cards | ~20,000,000 hands/s (pokersolver: ~120,000 hands/s, ~166× slower) |
|
|
147
|
-
| AA vs KK preflop, exact | 1,712,304 runouts in
|
|
182
|
+
| AA vs KK preflop, exact | 1,712,304 runouts in ~80 ms — equity 81.2555%, identical to a pokersolver brute force |
|
|
183
|
+
| Range vs range | exact results equal a deal-by-deal brute force to 12 decimal places; AA vs a random hand 85.22% over 4,000,000 samples (published: 85.20%) |
|
|
148
184
|
| Test coverage | 100% lines and functions |
|
|
149
185
|
|
|
150
186
|
## API
|
|
@@ -155,15 +191,15 @@ Results on Node 24, Apple M5:
|
|
|
155
191
|
| Randomness | `RandomSource`, `secureRandom`, `createSecureRandom`, `createSeededRandom` |
|
|
156
192
|
| Deck | `Deck`, `createDeck`, `shuffle`, `shuffled` |
|
|
157
193
|
| Evaluation | `scoreHand`, `evaluateHand`, `compareHands`, `compareScores`, `winners`, `categoryOf`, `handName`, `describeScore`, `HandCategory`, `HandScore`, `HandResult` |
|
|
158
|
-
| Equity | `calculateEquity`, `EquityOptions`, `EquityResult`, `PlayerEquity` |
|
|
194
|
+
| Equity | `calculateEquity`, `calculateRangeEquity`, `EquityOptions`, `EquityResult`, `RangeEquityResult`, `PlayerEquity` |
|
|
195
|
+
| Ranges | `parseRange`, `comboClass`, `Combo` |
|
|
159
196
|
| Pots | `buildPots`, `settlePots`, `Contribution`, `Pot`, `SettledPot`, `Settlement`, `SettleOptions` |
|
|
160
|
-
| Errors | `HoldemError` with a `code` (`INVALID_CARD`, `DUPLICATE_CARD`, `INVALID_HAND_SIZE`, …) |
|
|
197
|
+
| Errors | `HoldemError` with a `code` (`INVALID_CARD`, `DUPLICATE_CARD`, `INVALID_HAND_SIZE`, `INVALID_RANGE`, …) |
|
|
161
198
|
|
|
162
199
|
Exports carry TSDoc comments, so your editor shows the details inline.
|
|
163
200
|
|
|
164
201
|
## Roadmap
|
|
165
202
|
|
|
166
|
-
- Hand-range notation (`QQ+`, `AKs`, `T9s-65s`) for range-vs-range equity
|
|
167
203
|
- Omaha (4 and 5 cards) evaluation
|
|
168
204
|
- Run-it-twice settlement helpers
|
|
169
205
|
|
package/README.zh-CN.md
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
# holdem-core
|
|
2
2
|
|
|
3
3
|
**快速、零依赖的德州扑克工具库(TypeScript / JavaScript)。**
|
|
4
|
-
提供牌面解析、无偏洗牌、5–7
|
|
4
|
+
提供牌面解析、无偏洗牌、5–7 张牌型判断、手牌范围、精确胜率和边池结算,全部经过穷举验证。
|
|
5
5
|
|
|
6
6
|
[English](README.md)
|
|
7
7
|
|
|
8
8
|
```ts
|
|
9
|
-
import { parseCards, evaluateHand, calculateEquity, settlePots } from 'holdem-core';
|
|
9
|
+
import { parseCards, evaluateHand, calculateEquity, calculateRangeEquity, settlePots } from 'holdem-core';
|
|
10
10
|
|
|
11
11
|
evaluateHand(parseCards('Kh Kd Ks Tc Td 2s 3h')).description;
|
|
12
12
|
// → "Full House, Kings full of Tens"(葫芦,三条 K 带一对 10)
|
|
13
13
|
|
|
14
14
|
calculateEquity([parseCards('As Ah'), parseCards('Kd Kc')]).players[0].equity;
|
|
15
|
-
// → 0.812555…(精确值,穷举全部 1,712,304 种公共牌,约
|
|
15
|
+
// → 0.812555…(精确值,穷举全部 1,712,304 种公共牌,约 80 毫秒)
|
|
16
|
+
|
|
17
|
+
calculateRangeEquity(['QQ+, AKs', 'JJ-99, AQs'], { board: parseCards('Kh 7d 2c') }).players[0].equity;
|
|
18
|
+
// → 0.928378…(精确值,两个范围的每种发法、每种转牌河牌都算到)
|
|
16
19
|
|
|
17
20
|
settlePots(
|
|
18
21
|
[{ id: 'alice', amount: 50 }, { id: 'bob', amount: 100 }, { id: 'carol', amount: 100 }],
|
|
@@ -26,6 +29,7 @@ settlePots(
|
|
|
26
29
|
- **结果可验证。** 持续集成中穷举全部 **133,784,560** 种七张牌组合,各牌型数量与理论值完全一致;随机抽取 100 万手牌和 100 万次摊牌,与 [pokersolver](https://www.npmjs.com/package/pokersolver) 对比,结果零差异。
|
|
27
30
|
- **速度快。** 单核每秒约 **2000 万** 次七张牌判断:无需枚举 21 种组合,计算过程零内存分配,也不依赖几十 MB 的查找表(启动时仅生成约 24 KB)。
|
|
28
31
|
- **覆盖真实牌局。** 边池、弃牌玩家已投入的筹码、无人跟注时的退还、平分时的零头分配都已处理;每次结算都会校验所有人输赢合计为零。
|
|
32
|
+
- **支持手牌范围。** 通用写法(`QQ+`、`AKs`、`T9s-65s`、`random`),自动扣除撞牌;范围对范围的胜率能穷举时给精确值,并与逐个发法硬算的结果核对一致。
|
|
29
33
|
- **默认安全。** 洗牌使用 `crypto.getRandomValues` 加拒绝采样,没有取模偏差;另提供可固定种子的随机源,供测试和回放使用。
|
|
30
34
|
- **轻量,自带类型。** 零运行时依赖,同时提供 ESM 和 CommonJS 两种格式,附完整类型声明;已在 Node 20 / 22 / 24 上测试,只用标准 Web API,在现代浏览器中也能直接运行。
|
|
31
35
|
|
|
@@ -43,6 +47,7 @@ npm install holdem-core
|
|
|
43
47
|
- **洗牌发牌**:`new Deck()` 用安全随机数洗牌,`deck.deal(n)` 发牌;`new Deck(createSeededRandom('种子'))` 每次顺序相同,只用于测试和回放。
|
|
44
48
|
- **比牌**:`scoreHand(cards)` 返回可直接比较的整数(越大越强,相等即平分);`evaluateHand` 额外给出牌型名称、描述和组成的五张牌。
|
|
45
49
|
- **胜率**:`calculateEquity(hands, { board, dead })`,能穷举时给精确值,否则自动蒙特卡洛。
|
|
50
|
+
- **手牌范围**:`parseRange('QQ+, AKs')` 展开成具体手牌(22 手);写法有 `QQ`、`AKs` / `AKo` / `AK`、`QQ+`、`ATs+`、`99-66`、`KTs-K8s`、`T9s-65s`、`AsKs`、`random`。`calculateRangeEquity(['QQ+, AKs', 'JJ-99, AQs'], { board })` 算范围对范围的胜率:每种不撞牌的发法等概率,与公共牌、死牌撞的手牌自动去掉;能穷举时给精确值(`exactLimit` 按「发法数 × 公共牌种数」算),否则随机抽样。人多且范围重叠多时抽样会变慢(9 人全随机手牌、默认 20 万次约 2 秒)。
|
|
46
51
|
- **结算**:`settlePots(contributions, { scores, oddChipOrder })` 算出主池、边池、每池赢家和每人净输赢。
|
|
47
52
|
|
|
48
53
|
## 验证与性能
|
|
@@ -61,7 +66,8 @@ Node 24、Apple M5 上的结果:
|
|
|
61
66
|
| 七张牌穷举 | 133,784,560 种,2.8 秒;各牌型数量和 4,824 种不同牌力全部吻合 |
|
|
62
67
|
| 与 pokersolver 对比 | 100 万手牌型、100 万次摊牌,0 处不一致 |
|
|
63
68
|
| `scoreHand`(七张) | 约每秒 2000 万手(pokersolver 约每秒 12 万手,慢约 166 倍) |
|
|
64
|
-
| AA 对 KK 翻前精确胜率 | 1,712,304
|
|
69
|
+
| AA 对 KK 翻前精确胜率 | 1,712,304 种公共牌,约 80 毫秒;81.2555%,与 pokersolver 穷举结果完全相同 |
|
|
70
|
+
| 范围对范围 | 精确结果与逐个发法硬算一致到小数点后 12 位;AA 对随机手牌抽样 400 万次 85.22%(公认值 85.20%) |
|
|
65
71
|
| 测试覆盖率 | 代码行、函数 100% |
|
|
66
72
|
|
|
67
73
|
## 需要完整的德州扑克平台?
|
package/dist/index.cjs
CHANGED
|
@@ -452,48 +452,176 @@ function bestFive(cards, score, category) {
|
|
|
452
452
|
}
|
|
453
453
|
}
|
|
454
454
|
|
|
455
|
+
// src/range.ts
|
|
456
|
+
var HAND_CLASS = /^([2-9tjqka])([2-9tjqka])([so]?)$/i;
|
|
457
|
+
var TOKEN_SEPARATOR = /[\s,;]+/;
|
|
458
|
+
function rankIndex(ch) {
|
|
459
|
+
return RANKS.indexOf(ch.toUpperCase());
|
|
460
|
+
}
|
|
461
|
+
function parseClass(text, token) {
|
|
462
|
+
const m = HAND_CLASS.exec(text);
|
|
463
|
+
if (!m) throw new HoldemError("INVALID_RANGE", `Invalid hand "${text}" in range token "${token}"`);
|
|
464
|
+
const a = rankIndex(m[1]);
|
|
465
|
+
const b = rankIndex(m[2]);
|
|
466
|
+
const suited = m[3].toLowerCase();
|
|
467
|
+
if (a === b && suited !== "") {
|
|
468
|
+
throw new HoldemError("INVALID_RANGE", `A pair cannot be suited or offsuit: "${text}" in "${token}"`);
|
|
469
|
+
}
|
|
470
|
+
return { high: Math.max(a, b), low: Math.min(a, b), suited };
|
|
471
|
+
}
|
|
472
|
+
function classLabel(high, low, suited) {
|
|
473
|
+
return RANKS[high] + RANKS[low] + suited;
|
|
474
|
+
}
|
|
475
|
+
function combosOf(high, low, suited, out) {
|
|
476
|
+
for (let s1 = 3; s1 >= 0; s1--) {
|
|
477
|
+
for (let s2 = 3; s2 >= 0; s2--) {
|
|
478
|
+
if (high === low) {
|
|
479
|
+
if (s2 >= s1) continue;
|
|
480
|
+
} else if (suited === "s" && s1 !== s2 || suited === "o" && s1 === s2) {
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
out.push([high * 4 + s1, low * 4 + s2]);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
function expandToken(token, out) {
|
|
488
|
+
const lower = token.toLowerCase();
|
|
489
|
+
if (lower === "random" || lower === "any") {
|
|
490
|
+
for (let high = 12; high >= 0; high--) {
|
|
491
|
+
for (let low = high; low >= 0; low--) combosOf(high, low, "", out);
|
|
492
|
+
}
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
const dash = token.split("-");
|
|
496
|
+
if (dash.length > 2) throw new HoldemError("INVALID_RANGE", `Invalid range token "${token}"`);
|
|
497
|
+
if (dash.length === 2) {
|
|
498
|
+
const a = parseClass(dash[0], token);
|
|
499
|
+
const b = parseClass(dash[1], token);
|
|
500
|
+
const aPair = a.high === a.low;
|
|
501
|
+
const bPair = b.high === b.low;
|
|
502
|
+
if (aPair && bPair) {
|
|
503
|
+
for (let r = Math.max(a.high, b.high); r >= Math.min(a.high, b.high); r--) combosOf(r, r, "", out);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
if (aPair || bPair || a.suited !== b.suited) {
|
|
507
|
+
throw new HoldemError("INVALID_RANGE", `Both ends of "${token}" must be the same kind of hand`);
|
|
508
|
+
}
|
|
509
|
+
if (a.high === b.high) {
|
|
510
|
+
for (let k = Math.max(a.low, b.low); k >= Math.min(a.low, b.low); k--) combosOf(a.high, k, a.suited, out);
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
if (a.high - a.low === b.high - b.low) {
|
|
514
|
+
const top = a.high > b.high ? a : b;
|
|
515
|
+
const steps = Math.abs(a.high - b.high);
|
|
516
|
+
for (let i = 0; i <= steps; i++) combosOf(top.high - i, top.low - i, a.suited, out);
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
throw new HoldemError(
|
|
520
|
+
"INVALID_RANGE",
|
|
521
|
+
`"${token}" must keep the same top card (e.g. KTs-K8s) or the same gap (e.g. T9s-65s)`
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
if (token.endsWith("+")) {
|
|
525
|
+
const c = parseClass(token.slice(0, -1), token);
|
|
526
|
+
if (c.high === c.low) {
|
|
527
|
+
for (let r = 12; r >= c.high; r--) combosOf(r, r, "", out);
|
|
528
|
+
} else {
|
|
529
|
+
for (let k = c.high - 1; k >= c.low; k--) combosOf(c.high, k, c.suited, out);
|
|
530
|
+
}
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
if (HAND_CLASS.test(token)) {
|
|
534
|
+
const c = parseClass(token, token);
|
|
535
|
+
combosOf(c.high, c.low, c.suited, out);
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
let cards;
|
|
539
|
+
try {
|
|
540
|
+
cards = parseCards(token);
|
|
541
|
+
} catch {
|
|
542
|
+
throw new HoldemError("INVALID_RANGE", `Invalid range token "${token}"`);
|
|
543
|
+
}
|
|
544
|
+
if (cards.length !== 2) throw new HoldemError("INVALID_RANGE", `"${token}" must name exactly two cards`);
|
|
545
|
+
try {
|
|
546
|
+
assertDistinctCards(cards);
|
|
547
|
+
} catch {
|
|
548
|
+
throw new HoldemError("INVALID_RANGE", `"${token}" uses the same card twice`);
|
|
549
|
+
}
|
|
550
|
+
const [x, y] = cards;
|
|
551
|
+
out.push(x > y ? [x, y] : [y, x]);
|
|
552
|
+
}
|
|
553
|
+
function parseRange(text) {
|
|
554
|
+
const normalized = text.trim().replace(/\s*-\s*/g, "-");
|
|
555
|
+
if (normalized === "") throw new HoldemError("INVALID_RANGE", "Range is empty");
|
|
556
|
+
const all = [];
|
|
557
|
+
for (const token of normalized.split(TOKEN_SEPARATOR)) expandToken(token, all);
|
|
558
|
+
const seen = /* @__PURE__ */ new Set();
|
|
559
|
+
return all.filter(([a, b]) => {
|
|
560
|
+
const key = a * 52 + b;
|
|
561
|
+
if (seen.has(key)) return false;
|
|
562
|
+
seen.add(key);
|
|
563
|
+
return true;
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
function comboClass(combo) {
|
|
567
|
+
if (combo.length !== 2) throw new HoldemError("INVALID_HAND_SIZE", `A combo has exactly 2 cards, got ${combo.length}`);
|
|
568
|
+
assertDistinctCards(combo);
|
|
569
|
+
const [x, y] = combo;
|
|
570
|
+
const high = Math.max(x >> 2, y >> 2);
|
|
571
|
+
const low = Math.min(x >> 2, y >> 2);
|
|
572
|
+
if (high === low) return classLabel(high, low, "");
|
|
573
|
+
return classLabel(high, low, (x & 3) === (y & 3) ? "s" : "o");
|
|
574
|
+
}
|
|
575
|
+
|
|
455
576
|
// src/equity.ts
|
|
456
577
|
function binomial(n, k) {
|
|
457
578
|
let r = 1;
|
|
458
579
|
for (let i = 1; i <= k; i++) r = r * (n - k + i) / i;
|
|
459
580
|
return Math.round(r);
|
|
460
581
|
}
|
|
461
|
-
function
|
|
462
|
-
const
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
582
|
+
function readOptions(players, options) {
|
|
583
|
+
const settings = {
|
|
584
|
+
board: options.board ?? [],
|
|
585
|
+
dead: options.dead ?? [],
|
|
586
|
+
exactLimit: options.exactLimit ?? 2e6,
|
|
587
|
+
iterations: options.iterations ?? 2e5,
|
|
588
|
+
random: options.random ?? secureRandom
|
|
589
|
+
};
|
|
590
|
+
if (players < 2 || players > 10) {
|
|
591
|
+
throw new HoldemError("INVALID_ARGUMENT", `Expected 2 to 10 hands, got ${players}`);
|
|
469
592
|
}
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
});
|
|
473
|
-
if (board.length > 5) throw new HoldemError("INVALID_ARGUMENT", `Board can have at most 5 cards, got ${board.length}`);
|
|
474
|
-
if (!Number.isInteger(iterations) || iterations < 1) {
|
|
475
|
-
throw new HoldemError("INVALID_ARGUMENT", `iterations must be a positive integer, got ${iterations}`);
|
|
593
|
+
if (settings.board.length > 5) {
|
|
594
|
+
throw new HoldemError("INVALID_ARGUMENT", `Board can have at most 5 cards, got ${settings.board.length}`);
|
|
476
595
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
596
|
+
if (!Number.isInteger(settings.iterations) || settings.iterations < 1) {
|
|
597
|
+
throw new HoldemError("INVALID_ARGUMENT", `iterations must be a positive integer, got ${settings.iterations}`);
|
|
598
|
+
}
|
|
599
|
+
return settings;
|
|
600
|
+
}
|
|
601
|
+
var Showdown = class {
|
|
602
|
+
constructor(players, board) {
|
|
603
|
+
this.players = players;
|
|
604
|
+
/** Positions in the stub of the cards currently on the board (reused by every enumeration). */
|
|
605
|
+
this.idx = new Int32Array(5);
|
|
606
|
+
this.seven = Array.from({ length: players }, () => {
|
|
607
|
+
const cards = new Array(7);
|
|
608
|
+
board.forEach((c, i) => cards[2 + i] = c);
|
|
609
|
+
return cards;
|
|
610
|
+
});
|
|
611
|
+
this.first = 2 + board.length;
|
|
612
|
+
this.wins = new Float64Array(players);
|
|
613
|
+
this.ties = new Float64Array(players);
|
|
614
|
+
this.shares = new Float64Array(players);
|
|
615
|
+
this.scores = new Int32Array(players);
|
|
616
|
+
}
|
|
617
|
+
/** Puts `card` in the `slot`-th missing board position for every player. */
|
|
618
|
+
place(slot, card) {
|
|
619
|
+
const at = this.first + slot;
|
|
620
|
+
for (let p = 0; p < this.players; p++) this.seven[p][at] = card;
|
|
621
|
+
}
|
|
622
|
+
/** Scores the current seven cards of every player and credits the winners. */
|
|
623
|
+
settle() {
|
|
624
|
+
const { players, seven, scores, wins, ties, shares } = this;
|
|
497
625
|
let best = -1;
|
|
498
626
|
let count = 0;
|
|
499
627
|
for (let p = 0; p < players; p++) {
|
|
@@ -506,54 +634,202 @@ function calculateEquity(hands, options = {}) {
|
|
|
506
634
|
count++;
|
|
507
635
|
}
|
|
508
636
|
}
|
|
637
|
+
if (count === 1) {
|
|
638
|
+
let p = 0;
|
|
639
|
+
while (scores[p] !== best) p++;
|
|
640
|
+
wins[p]++;
|
|
641
|
+
shares[p]++;
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
509
644
|
for (let p = 0; p < players; p++) {
|
|
510
645
|
if (scores[p] !== best) continue;
|
|
511
|
-
|
|
512
|
-
else ties[p]++;
|
|
646
|
+
ties[p]++;
|
|
513
647
|
shares[p] += 1 / count;
|
|
514
648
|
}
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
let runouts = 0;
|
|
522
|
-
if (exact) {
|
|
523
|
-
const idx = Array.from({ length: missing }, (_, i) => i);
|
|
649
|
+
}
|
|
650
|
+
/** Every way to complete the board from `stub`, settled in turn; returns how many there were. */
|
|
651
|
+
enumerate(stub, missing) {
|
|
652
|
+
const { players, seven, first, idx } = this;
|
|
653
|
+
for (let i = 0; i < missing; i++) idx[i] = i;
|
|
654
|
+
let runouts = 0;
|
|
524
655
|
for (; ; ) {
|
|
525
|
-
for (let k2 = 0; k2 < missing; k2++)
|
|
526
|
-
|
|
656
|
+
for (let k2 = 0; k2 < missing; k2++) {
|
|
657
|
+
const card = stub[idx[k2]];
|
|
658
|
+
for (let p = 0; p < players; p++) seven[p][first + k2] = card;
|
|
659
|
+
}
|
|
660
|
+
this.settle();
|
|
527
661
|
runouts++;
|
|
528
662
|
let k = missing - 1;
|
|
529
663
|
while (k >= 0 && idx[k] === stub.length - missing + k) k--;
|
|
530
|
-
if (k < 0)
|
|
664
|
+
if (k < 0) return runouts;
|
|
531
665
|
idx[k]++;
|
|
532
666
|
for (let j = k + 1; j < missing; j++) idx[j] = idx[j - 1] + 1;
|
|
533
667
|
}
|
|
668
|
+
}
|
|
669
|
+
/** Completes the board with a random draw from the first cards of `deck` (shuffled in place) and settles it. */
|
|
670
|
+
sample(deck, length, missing, random) {
|
|
671
|
+
for (let k = 0; k < missing; k++) {
|
|
672
|
+
const j = k + random.int(length - k);
|
|
673
|
+
const tmp = deck[k];
|
|
674
|
+
deck[k] = deck[j];
|
|
675
|
+
deck[j] = tmp;
|
|
676
|
+
this.place(k, deck[k]);
|
|
677
|
+
}
|
|
678
|
+
this.settle();
|
|
679
|
+
}
|
|
680
|
+
result(runouts) {
|
|
681
|
+
return Array.from({ length: this.players }, (_, p) => ({
|
|
682
|
+
equity: this.shares[p] / runouts,
|
|
683
|
+
win: this.wins[p] / runouts,
|
|
684
|
+
tie: this.ties[p] / runouts
|
|
685
|
+
}));
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
function calculateEquity(hands, options = {}) {
|
|
689
|
+
const { board, dead, exactLimit, iterations, random } = readOptions(hands.length, options);
|
|
690
|
+
hands.forEach((hand, i) => {
|
|
691
|
+
if (hand.length !== 2) throw new HoldemError("INVALID_ARGUMENT", `Hand ${i} must have exactly 2 cards, got ${hand.length}`);
|
|
692
|
+
});
|
|
693
|
+
assertDistinctCards(...hands, board, dead);
|
|
694
|
+
const used = /* @__PURE__ */ new Set([...hands.flat(), ...board, ...dead]);
|
|
695
|
+
const stub = [];
|
|
696
|
+
for (let c = 0; c < 52; c++) if (!used.has(c)) stub.push(c);
|
|
697
|
+
const missing = 5 - board.length;
|
|
698
|
+
if (stub.length < missing) throw new HoldemError("NOT_ENOUGH_CARDS", "Not enough cards left to complete the board");
|
|
699
|
+
const table = new Showdown(hands.length, board);
|
|
700
|
+
hands.forEach((hand, p) => {
|
|
701
|
+
table.seven[p][0] = hand[0];
|
|
702
|
+
table.seven[p][1] = hand[1];
|
|
703
|
+
});
|
|
704
|
+
const exact = binomial(stub.length, missing) <= exactLimit;
|
|
705
|
+
let runouts;
|
|
706
|
+
if (exact) {
|
|
707
|
+
runouts = table.enumerate(stub, missing);
|
|
534
708
|
} else {
|
|
535
709
|
const deck = stub.slice();
|
|
710
|
+
for (let t = 0; t < iterations; t++) table.sample(deck, deck.length, missing, random);
|
|
711
|
+
runouts = iterations;
|
|
712
|
+
}
|
|
713
|
+
return { players: table.result(runouts), runouts, exact };
|
|
714
|
+
}
|
|
715
|
+
var MAX_REJECTIONS = 1e5;
|
|
716
|
+
function toCombos(range, index) {
|
|
717
|
+
if (typeof range === "string") return parseRange(range);
|
|
718
|
+
const seen = /* @__PURE__ */ new Set();
|
|
719
|
+
const combos = [];
|
|
720
|
+
for (const hand of range) {
|
|
721
|
+
if (hand.length !== 2) {
|
|
722
|
+
throw new HoldemError("INVALID_HAND_SIZE", `Range ${index} has a hand with ${hand.length} cards; each needs exactly 2`);
|
|
723
|
+
}
|
|
724
|
+
assertDistinctCards(hand);
|
|
725
|
+
const combo = hand[0] > hand[1] ? [hand[0], hand[1]] : [hand[1], hand[0]];
|
|
726
|
+
const key = combo[0] * 52 + combo[1];
|
|
727
|
+
if (seen.has(key)) continue;
|
|
728
|
+
seen.add(key);
|
|
729
|
+
combos.push(combo);
|
|
730
|
+
}
|
|
731
|
+
return combos;
|
|
732
|
+
}
|
|
733
|
+
function calculateRangeEquity(ranges, options = {}) {
|
|
734
|
+
const { board, dead, exactLimit, iterations, random } = readOptions(ranges.length, options);
|
|
735
|
+
assertDistinctCards(board, dead);
|
|
736
|
+
const blocked = new Uint8Array(52);
|
|
737
|
+
for (const c of board) blocked[c] = 1;
|
|
738
|
+
for (const c of dead) blocked[c] = 1;
|
|
739
|
+
const lists = ranges.map((range, i) => {
|
|
740
|
+
const live = toCombos(range, i).filter(([a, b]) => !blocked[a] && !blocked[b]);
|
|
741
|
+
if (live.length === 0) {
|
|
742
|
+
throw new HoldemError("INVALID_RANGE", `Range ${i} has no hands left once the board and dead cards are removed`);
|
|
743
|
+
}
|
|
744
|
+
return live;
|
|
745
|
+
});
|
|
746
|
+
const players = lists.length;
|
|
747
|
+
const base = [];
|
|
748
|
+
for (let c = 0; c < 52; c++) if (!blocked[c]) base.push(c);
|
|
749
|
+
const missing = 5 - board.length;
|
|
750
|
+
const left = base.length - 2 * players;
|
|
751
|
+
if (left < missing) throw new HoldemError("NOT_ENOUGH_CARDS", "Not enough cards left to complete the board");
|
|
752
|
+
const perDeal = binomial(left, missing);
|
|
753
|
+
const taken = new Uint8Array(52);
|
|
754
|
+
const pick = new Int32Array(players);
|
|
755
|
+
const walk = (p, visit) => {
|
|
756
|
+
if (p === players) return visit();
|
|
757
|
+
const list = lists[p];
|
|
758
|
+
for (let i = 0; i < list.length; i++) {
|
|
759
|
+
const [a, b] = list[i];
|
|
760
|
+
if (taken[a] || taken[b]) continue;
|
|
761
|
+
taken[a] = 1;
|
|
762
|
+
taken[b] = 1;
|
|
763
|
+
pick[p] = i;
|
|
764
|
+
const more = walk(p + 1, visit);
|
|
765
|
+
taken[a] = 0;
|
|
766
|
+
taken[b] = 0;
|
|
767
|
+
if (!more) return false;
|
|
768
|
+
}
|
|
769
|
+
return true;
|
|
770
|
+
};
|
|
771
|
+
const cap = perDeal <= exactLimit ? Math.floor(exactLimit / perDeal) : 0;
|
|
772
|
+
let deals = 0;
|
|
773
|
+
walk(0, () => ++deals <= cap);
|
|
774
|
+
if (deals === 0) {
|
|
775
|
+
throw new HoldemError("INVALID_RANGE", "These ranges can never be dealt together: every combination shares a card");
|
|
776
|
+
}
|
|
777
|
+
const exact = deals <= cap;
|
|
778
|
+
const table = new Showdown(players, board);
|
|
779
|
+
const seat = () => {
|
|
780
|
+
for (let p = 0; p < players; p++) {
|
|
781
|
+
const [a, b] = lists[p][pick[p]];
|
|
782
|
+
table.seven[p][0] = a;
|
|
783
|
+
table.seven[p][1] = b;
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
const stub = new Array(left);
|
|
787
|
+
const fillStub = () => {
|
|
788
|
+
let n = 0;
|
|
789
|
+
for (const c of base) if (!taken[c]) stub[n++] = c;
|
|
790
|
+
};
|
|
791
|
+
let runouts = 0;
|
|
792
|
+
if (exact) {
|
|
793
|
+
walk(0, () => {
|
|
794
|
+
seat();
|
|
795
|
+
fillStub();
|
|
796
|
+
runouts += table.enumerate(stub, missing);
|
|
797
|
+
return true;
|
|
798
|
+
});
|
|
799
|
+
} else {
|
|
800
|
+
const release = (count) => {
|
|
801
|
+
for (let q = 0; q < count; q++) {
|
|
802
|
+
const [a, b] = lists[q][pick[q]];
|
|
803
|
+
taken[a] = 0;
|
|
804
|
+
taken[b] = 0;
|
|
805
|
+
}
|
|
806
|
+
};
|
|
536
807
|
for (let t = 0; t < iterations; t++) {
|
|
537
|
-
for (let
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
808
|
+
for (let failures = 0; ; ) {
|
|
809
|
+
let p = 0;
|
|
810
|
+
for (; p < players; p++) {
|
|
811
|
+
const list = lists[p];
|
|
812
|
+
const i = list.length === 1 ? 0 : random.int(list.length);
|
|
813
|
+
const [a, b] = list[i];
|
|
814
|
+
if (taken[a] || taken[b]) break;
|
|
815
|
+
taken[a] = 1;
|
|
816
|
+
taken[b] = 1;
|
|
817
|
+
pick[p] = i;
|
|
818
|
+
}
|
|
819
|
+
if (p === players) break;
|
|
820
|
+
release(p);
|
|
821
|
+
if (++failures >= MAX_REJECTIONS) {
|
|
822
|
+
throw new HoldemError("INVALID_RANGE", "These ranges overlap too much to sample: almost every deal shares a card");
|
|
823
|
+
}
|
|
543
824
|
}
|
|
544
|
-
|
|
825
|
+
seat();
|
|
826
|
+
fillStub();
|
|
827
|
+
table.sample(stub, left, missing, random);
|
|
828
|
+
release(players);
|
|
545
829
|
}
|
|
546
830
|
runouts = iterations;
|
|
547
831
|
}
|
|
548
|
-
return {
|
|
549
|
-
players: Array.from({ length: players }, (_, p) => ({
|
|
550
|
-
equity: shares[p] / runouts,
|
|
551
|
-
win: wins[p] / runouts,
|
|
552
|
-
tie: ties[p] / runouts
|
|
553
|
-
})),
|
|
554
|
-
runouts,
|
|
555
|
-
exact
|
|
556
|
-
};
|
|
832
|
+
return { players: table.result(runouts), runouts, exact, combos: lists.map((l) => l.length) };
|
|
557
833
|
}
|
|
558
834
|
|
|
559
835
|
// src/pots.ts
|
|
@@ -651,7 +927,9 @@ exports.SUITS = SUITS;
|
|
|
651
927
|
exports.assertDistinctCards = assertDistinctCards;
|
|
652
928
|
exports.buildPots = buildPots;
|
|
653
929
|
exports.calculateEquity = calculateEquity;
|
|
930
|
+
exports.calculateRangeEquity = calculateRangeEquity;
|
|
654
931
|
exports.categoryOf = categoryOf;
|
|
932
|
+
exports.comboClass = comboClass;
|
|
655
933
|
exports.compareHands = compareHands;
|
|
656
934
|
exports.compareScores = compareScores;
|
|
657
935
|
exports.createDeck = createDeck;
|
|
@@ -666,6 +944,7 @@ exports.isCard = isCard;
|
|
|
666
944
|
exports.makeCard = makeCard;
|
|
667
945
|
exports.parseCard = parseCard;
|
|
668
946
|
exports.parseCards = parseCards;
|
|
947
|
+
exports.parseRange = parseRange;
|
|
669
948
|
exports.rankName = rankName;
|
|
670
949
|
exports.rankOf = rankOf;
|
|
671
950
|
exports.scoreHand = scoreHand;
|