poker-bitvaljs 1.0.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.
Files changed (3) hide show
  1. package/README.md +186 -0
  2. package/bitval.js +707 -0
  3. package/package.json +28 -0
package/README.md ADDED
@@ -0,0 +1,186 @@
1
+ # BitVal
2
+
3
+ High-performance poker hand evaluator optimized for browser environments, using bitwise operations for rapid poker hand analysis and equity calculations.
4
+
5
+ **🌐 [Try it online - Range vs Range Evaluator](https://darraghgeo.github.io/poker-bitvaljs/)**
6
+
7
+ ## Features
8
+
9
+ - **Fast hand evaluation** using bitwise operations
10
+ - **Range vs range equity calculations** with canonical key caching optimization
11
+ - **Monte Carlo simulation** for preflop and postflop scenarios
12
+ - **Exhaustive enumeration** for flop/turn scenarios (2 or fewer cards to come)
13
+ - **Progress callbacks** for long-running calculations
14
+ - **Browser and Node.js compatible**
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install poker-bitvaljs
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ### Basic Hand Evaluation
25
+
26
+ ```javascript
27
+ const BitVal = require('poker-bitvaljs');
28
+ const bitval = new BitVal();
29
+
30
+ // Evaluate a hand (7 cards: 2 hole cards + 5 board cards)
31
+ const handMask = bitval.getBitMasked(['As', 'Ah', 'Ks', 'Qs', 'Js', 'Ts', '9s']);
32
+ const [evaluation, kickers] = bitval.evaluate(handMask);
33
+
34
+ // Returns [evaluation_score, kickers]
35
+ // Higher evaluation score = stronger hand
36
+ ```
37
+
38
+ ### Range vs Range Comparison
39
+
40
+ ```javascript
41
+ const BitVal = require('poker-bitvaljs');
42
+ const bitval = new BitVal();
43
+
44
+ // Compare two ranges
45
+ const heroHands = ['AsAh', 'AsAd', 'AsAc', 'AhAd', 'AhAc', 'AdAc']; // All AA combinations
46
+ const villainHands = ['KsKh', 'KsKd', 'KsKc', 'KhKd', 'KhKc', 'KdKc']; // All KK combinations
47
+
48
+ const result = await bitval.compareRange(
49
+ heroHands,
50
+ villainHands,
51
+ [], // board cards (empty for preflop)
52
+ [], // dead cards
53
+ 5, // number of board cards
54
+ 10000, // iterations
55
+ true, // optimize (use canonical caching)
56
+ null // progress callback (optional)
57
+ );
58
+
59
+ // Result: { win: 8120, tie: 30, lose: 1850 }
60
+ // Calculate equity: (win + tie/2) / (win + tie + lose) * 100
61
+ ```
62
+
63
+ ### With Progress Callback
64
+
65
+ ```javascript
66
+ const result = await bitval.compareRange(
67
+ heroHands,
68
+ villainHands,
69
+ [],
70
+ [],
71
+ 5,
72
+ 100000,
73
+ true,
74
+ (current, total, message) => {
75
+ console.log(`${Math.round((current/total)*100)}% - ${message}`);
76
+ }
77
+ );
78
+ ```
79
+
80
+ ### With Board Cards (Postflop)
81
+
82
+ ```javascript
83
+ // Compare ranges on a flop
84
+ const boardCards = ['As', 'Ks', 'Qs'];
85
+ const result = await bitval.compareRange(
86
+ heroHands,
87
+ villainHands,
88
+ boardCards,
89
+ [],
90
+ 5,
91
+ 10000,
92
+ true
93
+ );
94
+ ```
95
+
96
+ ## API
97
+
98
+ ### `new BitVal()`
99
+
100
+ Creates a new BitVal instance.
101
+
102
+ ### `evaluate(handMask)`
103
+
104
+ Evaluates a poker hand represented as a BigInt bitmask.
105
+
106
+ **Parameters:**
107
+ - `handMask` (BigInt): Bitmask representing 5-7 cards
108
+
109
+ **Returns:**
110
+ - `[evaluation, kickers]` (Array): Evaluation score and kicker bits
111
+
112
+ ### `getBitMasked(cards)`
113
+
114
+ Converts an array of card strings to a BigInt bitmask.
115
+
116
+ **Parameters:**
117
+ - `cards` (Array): Array of card strings (e.g., `['As', 'Kh', 'Qd']`)
118
+
119
+ **Returns:**
120
+ - `BigInt`: Bitmask representing the cards
121
+
122
+ ### `simulate(iterations, numberOfBoardCards, hero, villain, board, deadCards)`
123
+
124
+ Simulates a single hand vs hand matchup.
125
+
126
+ **Parameters:**
127
+ - `iterations` (Number): Number of simulations
128
+ - `numberOfBoardCards` (Number): Total board cards (default: 5)
129
+ - `hero` (Array): Hero's hole cards as bitmask
130
+ - `villain` (Array): Villain's hole cards as bitmask
131
+ - `board` (Array): Board cards as bitmask
132
+ - `deadCards` (Array): Dead cards as bitmask
133
+
134
+ **Returns:**
135
+ - `{ win, tie, lose }`: Results object
136
+
137
+ ### `compareRange(heroHands, villainHands, boardCards, deadCards, numberOfBoardCards, iterations, optimize, progressCallback)`
138
+
139
+ Compares two ranges of hands with optional optimization.
140
+
141
+ **Parameters:**
142
+ - `heroHands` (Array): Array of hero hand strings (e.g., `['AsAh', 'AsAd']`)
143
+ - `villainHands` (Array): Array of villain hand strings
144
+ - `boardCards` (Array): Board cards as strings (default: `[]`)
145
+ - `deadCards` (Array): Dead cards as strings (default: `[]`)
146
+ - `numberOfBoardCards` (Number): Total board cards (default: `5`)
147
+ - `iterations` (Number): Number of simulations per matchup (default: `10000`)
148
+ - `optimize` (Boolean): Use canonical key caching for performance (default: `true`). **Note:** Optimizations may result in a ±0.5% margin of error compared to unoptimized calculations.
149
+ - `progressCallback` (Function): Optional callback `(current, total, message) => {}`
150
+
151
+ **Returns:**
152
+ - `Promise<{ win, tie, lose }>`: Results object
153
+
154
+ ## Performance
155
+
156
+ - **Optimized for browser environments** with efficient bitwise operations
157
+ - Canonical key caching reduces redundant evaluations (may introduce ±0.5% margin of error)
158
+ - Exhaustive enumeration for flop/turn (2 or fewer cards to come)
159
+ - Monte Carlo simulation for preflop and river scenarios
160
+
161
+ **Test performance and benchmark online:** [https://darraghgeo.github.io/poker-bitvaljs/](https://darraghgeo.github.io/poker-bitvaljs/)
162
+
163
+ ## License
164
+
165
+ MIT
166
+
167
+ Copyright (c) 2024
168
+
169
+ Permission is hereby granted, free of charge, to any person obtaining a copy
170
+ of this software and associated documentation files (the "Software"), to deal
171
+ in the Software without restriction, including without limitation the rights
172
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
173
+ copies of the Software, and to permit persons to whom the Software is
174
+ furnished to do so, subject to the following conditions:
175
+
176
+ The above copyright notice and this permission notice shall be included in all
177
+ copies or substantial portions of the Software.
178
+
179
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
180
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
181
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
182
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
183
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
184
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
185
+ SOFTWARE.
186
+
package/bitval.js ADDED
@@ -0,0 +1,707 @@
1
+ class XorShift32 {
2
+ constructor(seed = null) {
3
+ this.state = seed !== null ? seed : Math.floor(Math.random() * 2147483647) || 1;
4
+ }
5
+
6
+ next(max) {
7
+ let x = this.state;
8
+ x ^= x << 13;
9
+ x ^= x >> 17;
10
+ x ^= x << 5;
11
+ this.state = x;
12
+ return Math.abs(x) % max;
13
+ }
14
+ }
15
+
16
+ class BitVal {
17
+ constructor() {
18
+ this._DIAMOND = 3n;
19
+ this._HEART = 2n;
20
+ this._CLUB = 1n;
21
+ this._SPADE = 0n;
22
+ this._ACE = (1n << 52n) | 1n;
23
+ this._KING = 1n << 48n;
24
+ this._QUEEN = 1n << 44n;
25
+ this._JACK = 1n << 40n;
26
+ this._TEN = 1n << 36n;
27
+ this._NINE = 1n << 32n;
28
+ this._EIGHT = 1n << 28n;
29
+ this._SEVEN = 1n << 24n;
30
+ this._SIX = 1n << 20n;
31
+ this._FIVE = 1n << 16n;
32
+ this._FOUR = 1n << 12n;
33
+ this._THREE = 1n << 8n;
34
+ this._TWO = 1n << 4n;
35
+
36
+ this.CARD_MASKS = {
37
+ 'As': this._ACE << this._SPADE,
38
+ 'Ah': this._ACE << this._HEART,
39
+ 'Ad': this._ACE << this._DIAMOND,
40
+ 'Ac': this._ACE << this._CLUB,
41
+ 'Ks': this._KING << this._SPADE,
42
+ 'Kh': this._KING << this._HEART,
43
+ 'Kd': this._KING << this._DIAMOND,
44
+ 'Kc': this._KING << this._CLUB,
45
+ 'Qs': this._QUEEN << this._SPADE,
46
+ 'Qh': this._QUEEN << this._HEART,
47
+ 'Qd': this._QUEEN << this._DIAMOND,
48
+ 'Qc': this._QUEEN << this._CLUB,
49
+ 'Js': this._JACK << this._SPADE,
50
+ 'Jh': this._JACK << this._HEART,
51
+ 'Jd': this._JACK << this._DIAMOND,
52
+ 'Jc': this._JACK << this._CLUB,
53
+ 'Ts': this._TEN << this._SPADE,
54
+ 'Th': this._TEN << this._HEART,
55
+ 'Td': this._TEN << this._DIAMOND,
56
+ 'Tc': this._TEN << this._CLUB,
57
+ '9s': this._NINE << this._SPADE,
58
+ '9h': this._NINE << this._HEART,
59
+ '9d': this._NINE << this._DIAMOND,
60
+ '9c': this._NINE << this._CLUB,
61
+ '8s': this._EIGHT << this._SPADE,
62
+ '8h': this._EIGHT << this._HEART,
63
+ '8d': this._EIGHT << this._DIAMOND,
64
+ '8c': this._EIGHT << this._CLUB,
65
+ '7s': this._SEVEN << this._SPADE,
66
+ '7h': this._SEVEN << this._HEART,
67
+ '7d': this._SEVEN << this._DIAMOND,
68
+ '7c': this._SEVEN << this._CLUB,
69
+ '6s': this._SIX << this._SPADE,
70
+ '6h': this._SIX << this._HEART,
71
+ '6d': this._SIX << this._DIAMOND,
72
+ '6c': this._SIX << this._CLUB,
73
+ '5s': this._FIVE << this._SPADE,
74
+ '5h': this._FIVE << this._HEART,
75
+ '5d': this._FIVE << this._DIAMOND,
76
+ '5c': this._FIVE << this._CLUB,
77
+ '4s': this._FOUR << this._SPADE,
78
+ '4h': this._FOUR << this._HEART,
79
+ '4d': this._FOUR << this._DIAMOND,
80
+ '4c': this._FOUR << this._CLUB,
81
+ '3s': this._THREE << this._SPADE,
82
+ '3h': this._THREE << this._HEART,
83
+ '3d': this._THREE << this._DIAMOND,
84
+ '3c': this._THREE << this._CLUB,
85
+ '2s': this._TWO << this._SPADE,
86
+ '2h': this._TWO << this._HEART,
87
+ '2d': this._TWO << this._DIAMOND,
88
+ '2c': this._TWO << this._CLUB
89
+ }
90
+
91
+ this.ALL_CARD_MASKS = Object.values(this.CARD_MASKS);
92
+
93
+ this.PAIR_SCORE = 1n << 56n;
94
+ this.TWO_PAIRS_SCORE = 1n << 57n;
95
+ this.TRIPS_SCORE = 1n << 58n;
96
+ this.STRAIGHT_SCORE = 1n << 59n;
97
+ this.FLUSH_SCORE = 1n << 60n;
98
+ this.FULL_HOUSE_SCORE = 1n << 61n;
99
+ this.QUADS_SCORE = 1n << 62n;
100
+ this.STRAIGHT_FLUSH_SCORE = 1n << 63n;
101
+
102
+ this.BIT_1 = BigInt("0b00010001000100010001000100010001000100010001000100010001");
103
+ this.BIT_2 = BigInt("0b00100010001000100010001000100010001000100010001000100010");
104
+ this.BIT_3 = BigInt("0b01000100010001000100010001000100010001000100010001000100");
105
+ this.BIT_4 = BigInt("0b10001000100010001000100010001000100010001000100010001000");
106
+
107
+ this.RANK_MASKS = [
108
+ 240n,
109
+ 3840n,
110
+ 61440n,
111
+ 983040n,
112
+ 15728640n,
113
+ 251658240n,
114
+ 4026531840n,
115
+ 64424509440n,
116
+ 1030792151040n,
117
+ 16492674416640n,
118
+ 263882790666240n,
119
+ 4222124650659840n,
120
+ 67553994410557455n
121
+ ];
122
+
123
+ this.RANK_MASK_LOOKUP = {
124
+ 16n: 240n,
125
+ 256n: 3840n,
126
+ 4096n: 61440n,
127
+ 65536n: 983040n,
128
+ 1048576n: 15728640n,
129
+ 16777216n: 251658240n,
130
+ 268435456n: 4026531840n,
131
+ 4294967296n: 64424509440n,
132
+ 68719476736n: 1030792151040n,
133
+ 1099511627776n: 16492674416640n,
134
+ 17592186044416n: 263882790666240n,
135
+ 281474976710656n: 4222124650659840n,
136
+ 4503599627370496n: 67553994410557455n,
137
+ 1n: 67553994410557455n
138
+ };
139
+ }
140
+
141
+ getHandStrengthFromMask(handMask) {
142
+ if (handMask & this.PAIR_SCORE) {
143
+ return "Pair";
144
+ }
145
+ if (handMask & this.TWO_PAIRS_SCORE) {
146
+ return "Two Pair";
147
+ }
148
+ if (handMask & this.TRIPS_SCORE) {
149
+ return "Trips";
150
+ }
151
+ if (handMask & this.STRAIGHT_SCORE) {
152
+ return "Straight";
153
+ }
154
+ if (handMask & this.FLUSH_SCORE) {
155
+ return "Flush";
156
+ }
157
+ if (handMask & this.FULL_HOUSE_SCORE) {
158
+ return "Full House";
159
+ }
160
+ if (handMask & this.QUADS_SCORE) {
161
+ return "Quads";
162
+ }
163
+ if (handMask & this.STRAIGHT_FLUSH_SCORE) {
164
+ return "Straight Flush";
165
+ }
166
+ return "High Card";
167
+ }
168
+
169
+ simulate(iterations, numberOfBoardCards = 5, hero = [], villain = [], board = [], deadCards = []) {
170
+ let numberOfCardsToDeal = (numberOfBoardCards + 2) - (hero.length + board.length);
171
+ this.xorShift = new XorShift32();
172
+
173
+ const allDeadCards = [...hero, ...villain, ...board, ...deadCards];
174
+ deadCards = this.getBitMasked(allDeadCards);
175
+ numberOfCardsToDeal = numberOfBoardCards - board.length;
176
+ hero = this.getBitMasked(hero);
177
+ villain = this.getBitMasked(villain);
178
+ board = this.getBitMasked(board);
179
+
180
+ const availableCards = 52 - new Set(allDeadCards).size;
181
+ const exhaustiveCombinations = this.combinations(availableCards, numberOfCardsToDeal);
182
+ iterations = Math.min(iterations, exhaustiveCombinations);
183
+
184
+ const isExhaustive = iterations === exhaustiveCombinations && numberOfCardsToDeal > 0 && numberOfCardsToDeal <= 2;
185
+ let comboArray = null;
186
+ if (isExhaustive) {
187
+ const availableMasks = this._getAvailableCardMasksByLookUp(deadCards);
188
+ comboArray = this._getCombinations(availableMasks, numberOfCardsToDeal);
189
+ }
190
+
191
+ let result = {
192
+ "win": 0,
193
+ "tie": 0,
194
+ "lose": 0,
195
+ "High Card": 0,
196
+ "Pair": 0,
197
+ "Two Pair": 0,
198
+ "Trips": 0,
199
+ "Straight": 0,
200
+ "Flush": 0,
201
+ "Full House": 0,
202
+ "Quads": 0,
203
+ "Straight Flush": 0
204
+ };
205
+
206
+ for (let i = 0; i < iterations; i++) {
207
+ let _board = isExhaustive && comboArray
208
+ ? board | comboArray[i]
209
+ : this.deal(board, deadCards, numberOfCardsToDeal) | board;
210
+
211
+ let [hero_eval, hero_tiebreaker] = this.evaluate(hero | _board);
212
+ let [villain_eval, villain_tiebreaker] = this.evaluate(villain | _board);
213
+
214
+ if (hero_eval > villain_eval) {
215
+ result["win"]++;
216
+ continue;
217
+ }
218
+ if (hero_eval < villain_eval) {
219
+ result["lose"]++;
220
+ continue;
221
+ }
222
+ if (hero_tiebreaker > villain_tiebreaker) {
223
+ result["win"]++;
224
+ continue;
225
+ }
226
+ if (hero_tiebreaker < villain_tiebreaker) {
227
+ result["lose"]++;
228
+ continue;
229
+ }
230
+
231
+ result["tie"]++
232
+ }
233
+
234
+ return result;
235
+ }
236
+
237
+ deal(hand, deadCards = 0n, numberOfCards = 7) {
238
+ if (numberOfCards < 1) return hand;
239
+ let deck = ~(hand | deadCards);
240
+ let card;
241
+
242
+ for (let i = 0; i < numberOfCards; i++) {
243
+ do {
244
+ card = this.ALL_CARD_MASKS[this.xorShift.next(52)];
245
+ } while ((card & deck) !== card);
246
+
247
+ hand |= card;
248
+ deck &= ~card;
249
+ }
250
+
251
+ return hand;
252
+ }
253
+
254
+ _extractKickers(hand, madeHandRanksMask, numKickers) {
255
+ const kickersOnly = hand & ~madeHandRanksMask;
256
+ let kickerValue = 0n;
257
+ let kickersFound = 0;
258
+
259
+ for (let i = 12n; i >= 0n && kickersFound < numKickers; i--) {
260
+ const rankMask = this.RANK_MASKS[i];
261
+ if (kickersOnly & rankMask) {
262
+ kickerValue |= (1n << (i + 13n));
263
+ kickersFound++;
264
+ }
265
+ }
266
+
267
+ return kickerValue;
268
+ }
269
+
270
+ _getRankMaskFromBitmask(bitmask) {
271
+ return (this.RANK_MASK_LOOKUP[bitmask & 1n] || 0n) |
272
+ (this.RANK_MASK_LOOKUP[bitmask & (1n << 52n)] || 0n) |
273
+ (this.RANK_MASK_LOOKUP[bitmask] || 0n);
274
+ }
275
+
276
+ _getTwoPairRanksMask(pairsBitmask) {
277
+ const firstBit = pairsBitmask & -pairsBitmask;
278
+ const firstMask = this._getRankMaskFromBitmask(firstBit);
279
+
280
+ const remaining = pairsBitmask & ~firstBit;
281
+ const secondBit = remaining & -remaining;
282
+ const secondMask = this._getRankMaskFromBitmask(secondBit);
283
+
284
+ return firstMask | secondMask;
285
+ }
286
+
287
+ normalize(hand, bitShift = 4) {
288
+ let shift_bits = ((hand | hand >> 1n | hand >> 2n | hand >> 3n) & this.BIT_1) >> 4n;
289
+ let normal_bits = 0n;
290
+ bitShift = BigInt(bitShift);
291
+
292
+ for (let i = 0n; i < 13n; i++) {
293
+ let bit = (shift_bits & (1n << i * bitShift)) >> i * bitShift;
294
+ normal_bits += bit << i;
295
+ }
296
+ return normal_bits;
297
+ }
298
+
299
+ stripBits(hand, desiredSizeOfMask = 5) {
300
+ let numberOfBitsToStrip = this.countBits(hand) - desiredSizeOfMask;
301
+
302
+ while (numberOfBitsToStrip > 0) {
303
+ hand &= (hand - 1n);
304
+ numberOfBitsToStrip--;
305
+ }
306
+ return hand;
307
+ }
308
+
309
+ getBitMasked(cards) {
310
+ let sf_mask = 0n;
311
+
312
+ for (let card of cards) {
313
+ sf_mask |= this.CARD_MASKS[card];
314
+ }
315
+
316
+ return sf_mask;
317
+ }
318
+
319
+ countBits(handMask) {
320
+ let count = 0;
321
+
322
+ while (handMask) {
323
+ handMask &= (handMask - 1n);
324
+ count++;
325
+ }
326
+ return count;
327
+ }
328
+
329
+ combinations(n, k) {
330
+ if (k > n || k < 0) return 0;
331
+ if (k === 0 || k === n) return 1;
332
+ k = Math.min(k, n - k);
333
+ let result = 1;
334
+ for (let i = 0; i < k; i++) {
335
+ result = result * (n - i) / (i + 1);
336
+ }
337
+ return Math.floor(result);
338
+ }
339
+
340
+ _getAvailableCardMasksByLookUp(deadCards) {
341
+ let masks = [];
342
+ let deck = ~deadCards;
343
+
344
+ for (const card in this.CARD_MASKS) {
345
+ const cardMask = this.CARD_MASKS[card];
346
+ if ((cardMask & deck) === cardMask) {
347
+ masks.push(cardMask);
348
+ }
349
+ }
350
+
351
+ return masks;
352
+ }
353
+
354
+ _getCombinations(availableMasks, k) {
355
+ if (k === 1) return availableMasks;
356
+ if (k === 2) {
357
+ let combos = [];
358
+ for (let i = 0; i < availableMasks.length; i++) {
359
+ for (let j = i + 1; j < availableMasks.length; j++) {
360
+ combos.push(availableMasks[i] | availableMasks[j]);
361
+ }
362
+ }
363
+ return combos;
364
+ }
365
+ return [];
366
+ }
367
+
368
+ evaluate(hand) {
369
+ let response = 0n;
370
+ if (response = this._bitStraightFlush(hand)) {
371
+ return [response | this.STRAIGHT_FLUSH_SCORE, null];
372
+ }
373
+
374
+ if (response = this._bitQuads(hand)) {
375
+ let quadsRanksMask = this._getRankMaskFromBitmask(response);
376
+ let kickers = this._extractKickers(hand, quadsRanksMask, 1);
377
+ return [(response | this.QUADS_SCORE), kickers];
378
+ }
379
+
380
+ let trips = this._bitTrips(hand) & (0xFFFFFFFFFFFF0n | (1n << 52n));
381
+ let pairs = this._bitPairs(hand) & (0xFFFFFFFFFFFF0n | (1n << 52n));
382
+
383
+ if ((trips && pairs && trips ^ pairs) || this.countBits(trips) > 1) {
384
+ return [trips | this.FULL_HOUSE_SCORE, this.stripBits(pairs & ~trips, 1)];
385
+ }
386
+
387
+ if (response = this._bitFlush(hand)) {
388
+ return [response | this.FLUSH_SCORE, null];
389
+ }
390
+
391
+ if (response = this._bitStraight(hand)) {
392
+ return [response | this.STRAIGHT_SCORE, null];
393
+ }
394
+
395
+ if (response = trips) {
396
+ let tripsRanksMask = this._getRankMaskFromBitmask(response);
397
+ let kickers = this._extractKickers(hand, tripsRanksMask, 2);
398
+ return [(response | this.TRIPS_SCORE), kickers];
399
+ }
400
+
401
+ if (response = pairs) {
402
+ if (this.countBits(response) > 1) {
403
+ let pairRanksMask = this._getTwoPairRanksMask(response);
404
+ let kickers = this._extractKickers(hand, pairRanksMask, 1);
405
+ return [(response | this.TWO_PAIRS_SCORE), kickers];
406
+ }
407
+ let pairRanksMask = this._getRankMaskFromBitmask(response);
408
+ let kickers = this._extractKickers(hand, pairRanksMask, 3);
409
+ return [(response | this.PAIR_SCORE), kickers];
410
+ }
411
+
412
+ return [this.stripBits(this.normalize(hand), 5), null];
413
+ }
414
+
415
+ _bitPairs(hand) {
416
+ let pairs = (
417
+ ((this.BIT_1 & hand) << 1n) & (this.BIT_2 & hand) |
418
+ ((this.BIT_1 & hand) << 2n) & (this.BIT_3 & hand) |
419
+ ((this.BIT_1 & hand) << 3n) & (this.BIT_4 & hand) |
420
+ ((this.BIT_2 & hand) << 1n) & (this.BIT_3 & hand) |
421
+ ((this.BIT_2 & hand) << 2n) & (this.BIT_4 & hand) |
422
+ ((this.BIT_3 & hand) << 1n) & (this.BIT_4 & hand));
423
+ pairs = (pairs >> 1n | pairs >> 2n | pairs >> 3n) & this.BIT_1;
424
+ return this.stripBits(pairs, 2);
425
+ }
426
+
427
+ _bitTrips(hand) {
428
+ let a = (((this.BIT_1 & hand) << 1n & (this.BIT_2 & hand)) << 1n & (this.BIT_3 & hand)) >> 2n;
429
+ let b = (((this.BIT_2 & hand) << 1n & (this.BIT_3 & hand)) << 1n & (this.BIT_4 & hand)) >> 3n;
430
+ let c = (((this.BIT_1 & hand) << 2n & (this.BIT_3 & hand)) << 1n & (this.BIT_4 & hand)) >> 3n;
431
+ let d = (((this.BIT_1 & hand) << 1n & (this.BIT_2 & hand)) << 2n & (this.BIT_4 & hand)) >> 3n;
432
+ return this.stripBits((a | b | c | d) & this.BIT_1, 1);
433
+ }
434
+
435
+ _bitFlush(hand) {
436
+ let i = 0n;
437
+ while (i < 4) {
438
+ if (this.countBits((hand >> 4n) & (this.BIT_1 << i)) >= 5) {
439
+ return this.stripBits(((hand >> 4n) & (this.BIT_1 << i)) >> i, 5);
440
+ }
441
+ i++;
442
+ }
443
+ return 0n;
444
+ }
445
+
446
+ _bitStraight(hand) {
447
+ hand = (hand | hand >> 1n | hand >> 2n | hand >> 3n) & this.BIT_1;
448
+
449
+ hand = hand &
450
+ (hand << 4n) &
451
+ (hand << 8n) &
452
+ (hand << 12n) &
453
+ (hand << 16n);
454
+
455
+ return this.stripBits(hand, 1);
456
+ }
457
+
458
+ _bitQuads(hand) {
459
+ return ((((
460
+ (hand & this.BIT_1) << 1n &
461
+ (hand & this.BIT_2)) << 1n &
462
+ (hand & this.BIT_3)) << 1n &
463
+ (hand & this.BIT_4))
464
+ & this.BIT_4) >> 3n;
465
+ }
466
+
467
+ _bitStraightFlush(hand) {
468
+ hand = hand &
469
+ (hand << 4n) &
470
+ (hand << 8n) &
471
+ (hand << 12n) &
472
+ (hand << 16n);
473
+
474
+ return this.stripBits(hand, 1);
475
+ }
476
+
477
+ _getBoardSuitCounts(boardCards) {
478
+ const suitCounts = new Map();
479
+ for (const card of boardCards) {
480
+ const suit = card[1];
481
+ suitCounts.set(suit, (suitCounts.get(suit) || 0) + 1);
482
+ }
483
+ return suitCounts;
484
+ }
485
+
486
+ _getCardsToCome(boardCards, numberOfBoardCards) {
487
+ return numberOfBoardCards - boardCards.length;
488
+ }
489
+
490
+ _suitHasFlushPotential(suit, boardSuitCounts, cardsToCome) {
491
+ return (boardSuitCounts.get(suit) || 0) + cardsToCome >= 4;
492
+ }
493
+
494
+ _getCanonicalKey(hand, boardCards = [], numberOfBoardCards = 5, boardSuitCounts = null) {
495
+ const r1 = hand[0], r2 = hand[2], s1 = hand[1], s2 = hand[3];
496
+ const rankOrder = 'AKQJT98765432';
497
+ const r1Idx = rankOrder.indexOf(r1), r2Idx = rankOrder.indexOf(r2);
498
+ const high = r1Idx < r2Idx ? r1 : r2, low = r1Idx < r2Idx ? r2 : r1;
499
+ const highSuit = r1Idx < r2Idx ? s1 : s2, lowSuit = r1Idx < r2Idx ? s2 : s1;
500
+ if (boardCards.length === 0) {
501
+ if (r1 === r2) return high + low;
502
+ return high + low + (s1 === s2 ? 's' : 'o');
503
+ }
504
+ if (!boardSuitCounts) boardSuitCounts = this._getBoardSuitCounts(boardCards);
505
+ const cardsToCome = this._getCardsToCome(boardCards, numberOfBoardCards);
506
+ if (r1 === r2) {
507
+ const s1Pot = this._suitHasFlushPotential(s1, boardSuitCounts, cardsToCome);
508
+ const s2Pot = this._suitHasFlushPotential(s2, boardSuitCounts, cardsToCome);
509
+ if (s1Pot) return high + low + s1;
510
+ if (s2Pot) return high + low + s2;
511
+ return high + low;
512
+ }
513
+ const highPot = this._suitHasFlushPotential(highSuit, boardSuitCounts, cardsToCome);
514
+ const lowPot = this._suitHasFlushPotential(lowSuit, boardSuitCounts, cardsToCome);
515
+ return (highPot ? high + highSuit : high) + (lowPot ? low + lowSuit : low);
516
+ }
517
+
518
+ _flattenHandsToCanonical(hands, boardCards = [], numberOfBoardCards = 5) {
519
+ const canonicalMap = new Map();
520
+ const canonicalToHand = new Map();
521
+ const boardSuitCounts = boardCards.length > 0 ? this._getBoardSuitCounts(boardCards) : null;
522
+ for (const hand of hands) {
523
+ const key = this._getCanonicalKey(hand, boardCards, numberOfBoardCards, boardSuitCounts);
524
+ canonicalMap.set(key, (canonicalMap.get(key) || 0) + 1);
525
+ if (!canonicalToHand.has(key)) {
526
+ canonicalToHand.set(key, hand);
527
+ }
528
+ }
529
+ return { canonicalMap, canonicalToHand };
530
+ }
531
+
532
+ _generateValidMatchups(heroHands, villainHands, boardCards = []) {
533
+ const valid = [];
534
+ const boardMask = boardCards.length > 0 ? this.getBitMasked(boardCards) : 0n;
535
+ for (const h of heroHands) {
536
+ const hMask = this.getBitMasked(this._handStringToCards(h));
537
+ if (boardMask && (hMask & boardMask) !== 0n) continue;
538
+ for (const v of villainHands) {
539
+ const vMask = this.getBitMasked(this._handStringToCards(v));
540
+ if ((vMask & boardMask) !== 0n || (hMask & vMask) !== 0n) continue;
541
+ valid.push({ heroHand: h, villainHand: v, heroMask: hMask, villainMask: vMask });
542
+ }
543
+ }
544
+ return valid;
545
+ }
546
+
547
+ _calculateValidCounts(validMatchups, hCanon, vCanon, boardCards, numberOfBoardCards) {
548
+ const counts = new Map();
549
+ const boardSuitCounts = boardCards.length > 0 ? this._getBoardSuitCounts(boardCards) : null;
550
+ for (const { heroHand, villainHand } of validMatchups) {
551
+ const hKey = this._getCanonicalKey(heroHand, boardCards, numberOfBoardCards, boardSuitCounts);
552
+ const vKey = this._getCanonicalKey(villainHand, boardCards, numberOfBoardCards, boardSuitCounts);
553
+ const key = `${hKey}:${vKey}`;
554
+ counts.set(key, (counts.get(key) || 0) + 1);
555
+ }
556
+ return counts;
557
+ }
558
+
559
+ _compareRangeSetup(heroHands, villainHands, boardCards, deadCards, numberOfBoardCards, iterations, optimize) {
560
+ const validMatchups = this._generateValidMatchups(heroHands, villainHands, boardCards);
561
+ const hCanon = optimize ? this._flattenHandsToCanonical(heroHands, boardCards, numberOfBoardCards) : null;
562
+ const vCanon = optimize ? this._flattenHandsToCanonical(villainHands, boardCards, numberOfBoardCards) : null;
563
+ const validCounts = optimize ? this._calculateValidCounts(validMatchups, hCanon, vCanon, boardCards, numberOfBoardCards) : null;
564
+ const boardMask = this.getBitMasked(boardCards);
565
+ const allDeadCards = [...boardCards, ...deadCards];
566
+ const deadCardsMask = this.getBitMasked(allDeadCards);
567
+ const numberOfCardsToDeal = numberOfBoardCards - boardCards.length;
568
+ const availableCards = 52 - new Set(allDeadCards).size;
569
+ const exhaustiveCombinations = numberOfCardsToDeal > 0 && numberOfCardsToDeal <= 2 ? this.combinations(availableCards, numberOfCardsToDeal) : Infinity;
570
+ iterations = Math.min(iterations, exhaustiveCombinations);
571
+ const isExhaustive = iterations === exhaustiveCombinations && numberOfCardsToDeal > 0 && numberOfCardsToDeal <= 2 && exhaustiveCombinations < Infinity;
572
+ const comboArray = isExhaustive ? this._getCombinations(this._getAvailableCardMasksByLookUp(deadCardsMask), numberOfCardsToDeal) : null;
573
+ return { hCanon, vCanon, boardMask, deadCardsMask, iterations, isExhaustive, comboArray, numberOfCardsToDeal, validMatchups, validCounts, boardCards, numberOfBoardCards };
574
+ }
575
+
576
+ _getCachedEvaluation(canonicalKey, originalHand, completeBoard, evalCache) {
577
+ const cacheKey = canonicalKey + completeBoard.toString();
578
+ if (evalCache.has(cacheKey)) return evalCache.get(cacheKey);
579
+ const handMask = this.getBitMasked(this._handStringToCards(originalHand));
580
+ const evaluation = this.evaluate(handMask | completeBoard);
581
+ evalCache.set(cacheKey, evaluation);
582
+ return evaluation;
583
+ }
584
+
585
+ _compareEvaluations(heroEval, heroKicker, villainEval, villainKicker) {
586
+ if (heroEval > villainEval || (heroEval === villainEval && heroKicker > villainKicker)) return 1;
587
+ if (villainEval > heroEval || (villainEval === heroEval && villainKicker > heroKicker)) return -1;
588
+ return 0;
589
+ }
590
+
591
+ async _evaluateMatchup(heroMask, villainMask, setup, evalCache = null, progressCallback = null, matchupIndex = 0, totalMatchups = 1) {
592
+ let win = 0, tie = 0, lose = 0;
593
+ const deadMask = heroMask | villainMask | setup.deadCardsMask;
594
+ if (!setup.isExhaustive) this.xorShift = new XorShift32();
595
+
596
+ // For exhaustive, generate comboArray excluding THIS matchup's hero/villain cards
597
+ let comboArray = null;
598
+ let iterations = setup.iterations;
599
+ if (setup.isExhaustive) {
600
+ const matchupDeadMask = heroMask | villainMask | setup.deadCardsMask;
601
+ const availableMasks = this._getAvailableCardMasksByLookUp(matchupDeadMask);
602
+ comboArray = this._getCombinations(availableMasks, setup.numberOfCardsToDeal);
603
+ iterations = comboArray.length;
604
+ }
605
+
606
+ const yieldInterval = 1000;
607
+ for (let i = 0; i < iterations; i++) {
608
+ const board = setup.isExhaustive && comboArray ? setup.boardMask | comboArray[i] : this.deal(setup.boardMask, deadMask, setup.numberOfCardsToDeal) | setup.boardMask;
609
+ const [hEval, hKick] = evalCache ? this._getCachedEvaluation(evalCache.heroKey, evalCache.heroHand, board, evalCache.cache) : this.evaluate(heroMask | board);
610
+ const [vEval, vKick] = evalCache ? this._getCachedEvaluation(evalCache.villainKey, evalCache.villainHand, board, evalCache.cache) : this.evaluate(villainMask | board);
611
+ const result = this._compareEvaluations(hEval, hKick, vEval, vKick);
612
+ if (result === 1) win++; else if (result === -1) lose++; else tie++;
613
+ if (progressCallback && i > 0 && i % yieldInterval === 0) {
614
+ const total = totalMatchups * iterations;
615
+ const current = matchupIndex * iterations + i;
616
+ progressCallback(current, total, `Matchup ${matchupIndex + 1}/${totalMatchups}: ${i.toLocaleString()}/${iterations.toLocaleString()}`);
617
+ await new Promise(resolve => setTimeout(resolve, 0));
618
+ }
619
+ }
620
+ return { matchupWin: win, matchupTie: tie, matchupLose: lose };
621
+ }
622
+
623
+ async _compareRangeUnoptimized(heroHands, villainHands, setup, progressCallback = null) {
624
+ let win = 0, tie = 0, lose = 0;
625
+ const total = setup.validMatchups.length;
626
+ for (let i = 0; i < total; i++) {
627
+ const { heroMask, villainMask } = setup.validMatchups[i];
628
+ const { matchupWin, matchupTie, matchupLose } = await this._evaluateMatchup(heroMask, villainMask, setup, null, progressCallback, i, total);
629
+ win += matchupWin; tie += matchupTie; lose += matchupLose;
630
+ if (progressCallback && i % 10 === 0) {
631
+ progressCallback(i, total, `Evaluating ${i}/${total}`);
632
+ await new Promise(resolve => setTimeout(resolve, 0));
633
+ }
634
+ }
635
+ if (progressCallback) progressCallback(total, total, 'Complete');
636
+ return { win, tie, lose };
637
+ }
638
+
639
+ async _compareRangeOptimized(setup, progressCallback = null) {
640
+ let win = 0, tie = 0, lose = 0;
641
+ const evalCache = new Map();
642
+ const totalMatchups = setup.hCanon.canonicalMap.size * setup.vCanon.canonicalMap.size;
643
+ let matchupIndex = 0;
644
+ for (const [hKey, hMult] of setup.hCanon.canonicalMap) {
645
+ const hHand = setup.hCanon.canonicalToHand.get(hKey);
646
+ const hMask = this.getBitMasked(this._handStringToCards(hHand));
647
+ for (const [vKey, vMult] of setup.vCanon.canonicalMap) {
648
+ const vHand = setup.vCanon.canonicalToHand.get(vKey);
649
+ const vMask = this.getBitMasked(this._handStringToCards(vHand));
650
+ const key = `${hKey}:${vKey}`;
651
+ const validCount = setup.validCounts.get(key) || 0;
652
+ if (validCount === 0) {
653
+ matchupIndex++;
654
+ continue;
655
+ }
656
+ // ALWAYS find a valid pair from validMatchups to ensure no board overlap
657
+ const boardSuitCounts = setup.boardCards.length > 0 ? this._getBoardSuitCounts(setup.boardCards) : null;
658
+ const validPair = setup.validMatchups.find(m => {
659
+ const mHKey = this._getCanonicalKey(m.heroHand, setup.boardCards, setup.numberOfBoardCards, boardSuitCounts);
660
+ const mVKey = this._getCanonicalKey(m.villainHand, setup.boardCards, setup.numberOfBoardCards, boardSuitCounts);
661
+ return mHKey === hKey && mVKey === vKey;
662
+ });
663
+ if (!validPair) {
664
+ console.error(`[DIAG] ERROR: No valid pair found for ${hKey}:${vKey} despite validCount=${validCount}`);
665
+ matchupIndex++;
666
+ continue;
667
+ }
668
+ const evalHand = validPair.heroHand;
669
+ const evalVillain = validPair.villainHand;
670
+ const evalHMask = validPair.heroMask;
671
+ const evalVMask = validPair.villainMask;
672
+ const cache = { heroKey: hKey, heroHand: evalHand, villainKey: vKey, villainHand: evalVillain, cache: evalCache };
673
+ const { matchupWin, matchupTie, matchupLose } = await this._evaluateMatchup(evalHMask, evalVMask, setup, cache, progressCallback, matchupIndex, totalMatchups);
674
+ win += matchupWin * validCount; tie += matchupTie * validCount; lose += matchupLose * validCount;
675
+ matchupIndex++;
676
+ if (progressCallback && matchupIndex % 10 === 0) {
677
+ progressCallback(matchupIndex, totalMatchups, `Evaluating ${matchupIndex}`);
678
+ await new Promise(resolve => setTimeout(resolve, 0));
679
+ }
680
+ }
681
+ }
682
+ if (progressCallback) progressCallback(matchupIndex, matchupIndex, 'Complete');
683
+ return { win, tie, lose };
684
+ }
685
+
686
+ _handStringToCards(hand) {
687
+ return [hand.substring(0, 2), hand.substring(2, 4)];
688
+ }
689
+
690
+ _simulateMatchup(heroHand, villainHand, board, deadCards, numberOfBoardCards, iterations) {
691
+ const heroCards = this._handStringToCards(heroHand);
692
+ const villainCards = this._handStringToCards(villainHand);
693
+ return this.simulate(iterations, numberOfBoardCards, heroCards, villainCards, board, deadCards);
694
+ }
695
+
696
+ async compareRange(heroHands, villainHands, boardCards = [], deadCards = [], numberOfBoardCards = 5, iterations = 10000, optimize = true, progressCallback = null) {
697
+ const setup = this._compareRangeSetup(heroHands, villainHands, boardCards, deadCards, numberOfBoardCards, iterations, optimize);
698
+ return optimize ? await this._compareRangeOptimized(setup, progressCallback) : await this._compareRangeUnoptimized(heroHands, villainHands, setup, progressCallback);
699
+ }
700
+ }
701
+
702
+ if (typeof module !== 'undefined' && module.exports) {
703
+ module.exports = BitVal;
704
+ }
705
+ if (typeof window !== 'undefined') {
706
+ window.BitVal = BitVal;
707
+ }
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "poker-bitvaljs",
3
+ "version": "1.0.0",
4
+ "description": "High-performance poker hand evaluator optimized for browser environments, using bitwise operations for rapid poker hand analysis and equity calculations.",
5
+ "main": "bitval.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [
10
+ "poker",
11
+ "hand",
12
+ "evaluator",
13
+ "bitwise",
14
+ "equity",
15
+ "simulation",
16
+ "texas-holdem"
17
+ ],
18
+ "author": "Darragh Geoghegan",
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/DarraghGeo/poker-bitvaljs.git"
23
+ },
24
+ "files": [
25
+ "bitval.js",
26
+ "README.md"
27
+ ]
28
+ }