Package cardrank is a library of types, utilities, and interfaces for working
with playing cards, card decks, evaluating poker hand ranks, and managing deals
and run outs for different game types.
The cardrank package contains types for working with cards,
suits, ranks, and decks, evaluating poker
ranks, and managing deals and run outs.
In most cases, the high-level Dealer with any registered
Type is all that is needed. An in-depth example is provided in the
package documentation.
A Type wraps a type description defining the type's
streets, deck, eval, Hi/Lo
description, and other metadata needed for dealing streets and
managing run outs.
Evaluation and ranking of types is done with pure Go implementations of well-known poker hand evaluators, which are among the fastest available in Go. Evals can be compared and ordered to determine the winners of a hand.
The paycalc package contains tournament payout tables, and
calculates tournament payouts.
Supports evaluating and ranking the following types:
| Holdem Variants | Omaha Variants | Hybrid Variants | Draw Variants | Other |
|---|---|---|---|---|
Holdem |
Omaha |
Dallas |
Video |
Soko |
Split |
OmahaHiLo |
DallasDouble |
Draw |
SokoHiLo |
Short |
OmahaDouble |
Houston |
DrawHiLo |
Lowball |
Manila |
OmahaFive |
Fusion |
Stud |
LowballTriple |
Spanish |
OmahaSix |
FusionHiLo |
StudHiLo |
Razz |
Royal |
Jakarta |
StudFive |
Badugi |
|
Double |
Courchevel |
|||
Showtime |
CourchevelHiLo |
|||
Swap |
||||
River |
See the package's Type documentation for a description of each.
Requires Go 1.27 or later. To use within a Go package:
go get github.com/cardrank/cardrankSee the Go package documentation for in-depth overviews of the APIs.
Examples of the types, utilities, and interfaces are available in the Go package documentation.
Additional examples for a Dealer and the Holdem and
OmahaHiLo types are included in the example directory:
- dealer - uses the
Dealerto deal cards, handle multiple run outs, and determine winners for anyType - holdem - uses types and utilities to deal
Holdem - omahahilo - uses types and utilities to deal
OmahaHiLo, splitting Hi and Lo wins
An EvalRank is determined using the Evaluator
registered for a Type. EvalRank values are ordered low to high, and
a lower rank is a better hand:
fmt.Printf("%t\n", cardrank.StraightFlush < cardrank.FullHouse)
// Output:
// truePocket and board cards can be passed to a type's Eval method, which
uses the type's registered Evaluator and returns an
Eval, containing the Hi and Lo Hand:
pocket, board := cardrank.Must("Ah Kh"), cardrank.Must("Qh Jh Th 2s 3s")
ev := cardrank.Holdem.Eval(pocket, board)
fmt.Printf("%s - %d\n", ev, ev.Hi.Rank)
// Output:
// Straight Flush, Ace-high, Royal Flush [Ah Kh Qh Jh Th] - 1Usually 5, 6, or 7 cards are evaluated, but some types can evaluate fewer cards:
pocket := cardrank.Must("2h 3s 4c")
ev := cardrank.Badugi.Eval(pocket, nil)
fmt.Printf("%s\n", ev)
// Output:
// Four, Three, Two-low [4c 3s 2h]If an invalid number of cards is passed to a type's Eval, the
Hand's Rank is set to Invalid.
Some types have both a Hi and Lo Hand, such as Double
board Holdem and the *HiLo variants like OmahaHiLo. An
Eval contains both as its Hi and Lo. A Hand formats its own
description:
ev := cardrank.OmahaHiLo.Eval(cardrank.Must("Ah 2h Kc Qd"), cardrank.Must("3c 4d 8s Kh Ts"))
fmt.Printf("%s %s\n", ev.Hi, ev.Hi.Best)
fmt.Printf("%s %s\n", ev.Lo, ev.Lo.Best)For most types, the EvalRank is determined by Go implementations
of a few well-known Cactus Kev algorithms:
Cactus- the original Cactus Kev poker hand evaluatorCactusFast- the Fast Cactus poker hand evaluator, using Paul Senzee's perfect hash lookupTwoPlusTwo- the 2+2 forum poker hand evaluator, using a 124 MiB lookup table (see below)
The package-level RankCactus variable is the rank func used for
standard poker evaluation, and defaults to CactusFast.
Use SetRankCactus to change the rank func used by the
built-in types, such as when using a third-party implementation, or
experimenting with new Cactus implementations. Like registering types, it
should only be called during initialization:
func init() {
cardrank.SetRankCactus(cardrank.Cactus)
}The twoplustwo package provides the Two-Plus-Two evaluator,
which uses a large (124 MiB) lookup table for extremely fast 5, 6, and 7 card
evaluation. Importing the package registers the evaluator, and the built-in
types then use it for 7 card evals:
import (
"github.com/cardrank/cardrank"
_ "github.com/cardrank/cardrank/twoplustwo"
)The lookup table is embedded in the twoplustwo package, so it is only
included in binaries that import it: a small program is about 3 MB without the
import, and about 134 MB with it. The table is decoded into memory the first
time it is used (about 140 ms), so the import adds no startup cost.
Without the import, 7 card evals use RankCactus to rank every
5 card combination, which is slower (see benchmarks) but gives
identical results. Leaving out the import is useful for client applications
and constrained environments, such as WASM.
twoplustwo.New returns the Two-Plus-Two eval func for
direct use.
Winners are determined by the lowest EvalRank of either the Hi
or Lo Hand. Hands with equal ranks are equivalent, and split the win.
A Hand can be compared to another Hand using
Compare, which returns -1, 0, or +1, making it easy to
compare or sort hands:
// Compare a and b's Hi:
if a.Hi.Compare(b.Hi) < 0 {
fmt.Printf("%s is a winner!", a.Hi)
}
// Compare a and b's Lo:
if a.Lo.Compare(b.Lo) == 0 {
fmt.Printf("%s and %s are equal!", a.Lo, b.Lo)
}
// Sort []*Eval by Hi:
slices.SortFunc(evs, func(a, b *cardrank.Eval) int {
return a.Hi.Compare(b.Hi)
})HiOrder and LoOrder determine the winners of a
hand by ordering the positions of a []*Eval, returning a
Ranking (see Order to order a []Hand):
hi := cardrank.HiOrder(evs)
for _, i := range hi.Winners() {
fmt.Printf("%s is a Hi winner!", evs[i].Hi)
}When ordering by Hi there is always at least 1 winner (except for
Video types), but when ordering by Lo there may be no winners:
lo := cardrank.LoOrder(evs)
if len(lo.Winners()) == 0 {
fmt.Println("no qualifying Lo")
}A Dealer deals the streets of a Type, with
Deal iterating over each street of each run, and
Results iterating over each run's result. Positions can be
folded, and the runs changed, from within the loop:
d := cardrank.Holdem.Dealer(r, 4)
for run := range d.Deal() {
if d.Street().ID == 'f' && run == 0 {
// run it twice, after the flop
if err := d.ChangeRuns(2); err != nil {
panic(err)
}
}
}
for run, res := range d.Results() {
fmt.Printf("run %d: %s\n", run, res.Hi.Describe("Alice", "Bob", "Carl", "Dave"))
}HandCatalog returns a catalog of every registered type, for
clients showing hands: each game's deck, streets, blinds, and tracks (the Hi,
and the Lo or second board's Hi), and the evaluator profiles ranking each track,
with their hand levels and variants, best first:
c := cardrank.HandCatalog()
for _, l := range c.Profiles[0].Levels {
fmt.Printf("%s: %s %b\n", l.ID, l.Name.Text, l.Example)
}
// Output:
// straight_flush: Straight Flush [K♥ Q♥ J♥ T♥ 9♥]
// four_of_a_kind: Four of a Kind [9♠ 9♥ 9♦ 9♣ K♦]
// ...
// high_card: High Card [A♠ Q♥ 9♦ 6♣ 3♠]IDs (such as straight_flush and its variant royal_flush) are stable, and
every name is a Label with a stable key for translation and its
English text. The catalog's Revision is the SHA-256 of its JSON encoding, so
it changes whenever anything in the catalog changes.
Eval.Classes classifies an evaluated hand into the catalog,
for each of its type's tracks:
ev := cardrank.OmahaHiLo.Eval(cardrank.Must("Ah 2h Kc Qd"), cardrank.Must("3c 4d 8s Kh Ts"))
for _, class := range ev.Classes() {
fmt.Printf("%s: profile %s, level %s, variant %q\n", class.Track, class.Profile, class.Level, class.Variant)
}
// Output:
// hi: profile high, level pair, variant ""
// lo: profile low_8, level no_pair, variant "eight_low"CalcOuts (and Type.Outs and
Dealer.Outs) calculates each position's outs for the next
street: the cards after which the position wins, ties, or loses. For a
position that is ahead, the cards that cost it the lead are its fades. A
position is drawing dead when it can't win or tie on any remaining board:
pockets := []cardrank.Cards{
cardrank.Must("Kd 7s"),
cardrank.Must("Ah Qh"),
cardrank.Must("3c 4c"),
}
board := cardrank.Must("Ks 7d 2h 9h")
outs, err := cardrank.Holdem.Outs(ctx, pockets, board)
if err != nil {
panic(err)
}
for i, out := range outs.Hi {
fmt.Printf("%d (%s, %s): %s\n", i, out.Status, out.Hand, outs.Summary(i, false))
}
// Output:
// 0 (ahead, Two Pair, Kings over Sevens, kicker Nine): 7 fades: any ♥ except K♥ 7♥
// 1 (behind, Ace-high, kickers King, Queen, Nine, Seven): 7 outs: any ♥ except K♥ 7♥
// 2 (behind, King-high, kickers Nine, Seven, Four, Three): drawing deadOuts are calculated when the next street deals a single board card, such as
on the flop and turn of Hold'em and Omaha (including Hi/Lo). Cards are described
with DescribeCards, using whichever is shortest: listing
the cards, "any ♥", or "any ♥ except K♥ 7♥". See the outs
design for details.
The test directory is a separate module that benchmarks cardrank
against other well-known, pure Go poker hand evaluators, and verifies that
every evaluator ranks the same randomly dealt Hold'em and Omaha hands
identically:
cd test && go test -bench .Results with Go 1.27.3 on linux/amd64, single-threaded, over 1,048,576
randomly dealt hands, with the twoplustwo package imported
(time per hand, with allocations per hand in parentheses when non-zero).
Best 5 of 5, 6, or 7 cards:
| Evaluator | 5 cards | 6 cards | 7 cards |
|---|---|---|---|
cardrank CactusFast |
6.4 ns | 67 ns (3) | 129 ns (3) |
cardrank Cactus |
8.2 ns | 98 ns (3) | 244 ns (3) |
cardrank TwoPlusTwo |
29.4 ns | 61.6 ns | 65.6 ns |
cardrank Holdem.Rank |
20.8 ns (1) | 69 ns (3) | 123 ns (1) |
cardrank Holdem.Eval |
114 ns (2) | 179 ns (4) | 222 ns (2) |
| paulhankin/poker | 5.4 ns | 20.3 ns | |
| alexclewontin/riverboat | 7.3 ns | 63 ns (1) | 388 ns (7) |
| chehsunliu/poker | 10.3 ns | 74 ns | 531 ns |
| notnil/joker | 1.30 µs (48) | 7.0 µs (269) | 25.2 µs (982) |
Omaha, best of any 2 pocket and 3 board cards, with 5 board cards:
| Evaluator | 4 pocket | 5 pocket | 6 pocket |
|---|---|---|---|
cardrank CactusFast |
230 ns | 376 ns | 554 ns |
cardrank Omaha.Eval |
381 ns (2) | 518 ns (2) | 676 ns (2) |
| alexclewontin/riverboat | 311 ns | 511 ns | 757 ns |
| chehsunliu/poker | 1.29 µs | 2.14 µs | 3.20 µs |
| paulhankin/poker | 1.29 µs | 2.12 µs | 3.16 µs |
| notnil/joker | 73.9 µs (2971) | 123 µs (4939) | 182 µs (7395) |
Notes:
CactusFastandCactusevaluate 6 and 7 cards by ranking every 5 card combination (seeRankEvaluator).- Evaluating random hands means most lookups into large tables miss the CPU
cache, so the
TwoPlusTwotable (124 MiB) is much slower here than over a small, repeated set of hands (65.6 ns vs 24.7 ns for 7 cards), and even the much smallerCactusFasttables are slower (6.4 ns vs 2.7 ns for 5 cards). Holdem.Rankis theRankmethod of Holdem'sEvaluator(ranking only, as used for odds calculations), which usesRankCactus(CactusFast) for 5 and 6 cards, andTwoPlusTwofor 7 cards when thetwoplustwopackage is imported.Holdem.EvalandOmaha.Evalare the high-level APIs (Omaha,OmahaFive, andOmahaSix): they also determine and order the best five and unused cards, and allocate the returnedEval.- None of the other evaluators support Omaha, so their Omaha results (and the
CactusFastOmaha result) rank every combination of 2 pocket and 3 board cards with the evaluator's 5 card eval: 60, 100, and 150 evals for 4, 5, and 6 pocket cards. - paulhankin/poker does not evaluate 6 cards, and decodes its lookup tables when the package is initialized (about 150 ms and 40 MB).
- The
TwoPlusTwolookup table is decoded on first use (about 140 ms).
Generated code and data can be regenerated with go generate ./..., using the
commands in internal/cmd:
cgengenerates the combination tables incombin.gotwoplustwogengenerates theinternal/tpt/twoplustwo*.datlookup table, verifying it against the reference table's MD5 hashpaycalcgengenerates thepaycalc/top*.csvpayout tables from the WSOP website
Card parsing has fuzz tests:
go test -fuzz FuzzParseSome long-running tests are skipped unless enabled with the TESTS
environment variable:
TESTS=all go test ./...- Overview of Cactus Kev - original Cactus Kev article
- Coding the Wheel - article covering various poker hand evaluators
- Paul Senzee Perfect Hash for Cactus Kev - overview of the "Fast Cactus" perfect hash by Paul Senzee
- TwoPlusTwoHandEvaluator - original implementation of the Two-Plus-Two evaluator
