aboutsummaryrefslogtreecommitdiff
path: root/internal/casino
diff options
context:
space:
mode:
authorhistoria <[not public]>2026-10-01 14:38:08 -0400
committerhistoria <[not public]>2026-10-01 14:38:08 -0400
commit1082f3336085c15992ca83d5553c0ba52208d70a (patch)
tree4fcedaa90bc01c41456258a9d57f492f31754948 /internal/casino
parentd4eae333a8d8a96452bbf3617aa85b50466c11a7 (diff)
downloadthehouseoficarus-1082f3336085c15992ca83d5553c0ba52208d70a.tar.gz
feat: pai gow poker added to the casino
Diffstat (limited to 'internal/casino')
-rw-r--r--internal/casino/core.go2
-rw-r--r--internal/casino/pai_gow.go498
-rw-r--r--internal/casino/pai_gow_rules.go503
-rw-r--r--internal/casino/pai_gow_test.go464
-rw-r--r--internal/casino/registry.go14
-rw-r--r--internal/casino/table_ux.go3
-rw-r--r--internal/casino/types.go2
-rw-r--r--internal/casino/video_poker_config.go2
-rw-r--r--internal/casino/video_poker_rules.go2
9 files changed, 1487 insertions, 3 deletions
diff --git a/internal/casino/core.go b/internal/casino/core.go
index fdb7877..8ab44f5 100644
--- a/internal/casino/core.go
+++ b/internal/casino/core.go
@@ -157,7 +157,7 @@ func resolveStakeIDs(w Wallet, ids []string) {
// settleStakeOutcome applies one wager's outcome through the wallet and
// reports whether the settlement could NOT be made durable. It carries the
// money-critical ordering shared by every table game (documented in
-// building_guide/concurrency.md): compute the payout, pay it via PayCredits
+// dev_guide/concurrency.md): compute the payout, pay it via PayCredits
// BEFORE announcing the win — that one save credits the payout and resolves
// the stakes it returns, so a crash can never pay the payout AND refund the
// same stake — and only then stand the hand down. On a persistence failure
diff --git a/internal/casino/pai_gow.go b/internal/casino/pai_gow.go
new file mode 100644
index 0000000..21abf4b
--- /dev/null
+++ b/internal/casino/pai_gow.go
@@ -0,0 +1,498 @@
+package casino
+
+import (
+ "fmt"
+ "math/rand"
+ "strings"
+ "sync"
+)
+
+type PaiGowSnapshot struct {
+ Config TableConfig
+ Phase string
+ Cards, High, Low, DealerHigh, DealerLow []CardView
+ Tiebreaker []CardView
+ Result string
+}
+
+func (*PaiGowSnapshot) snapshot() {}
+
+type pgPlayer struct {
+ name string
+ wallet Wallet
+ main, fortune Wager
+ pushace Wager
+ last int
+ cards []card
+ split pgSplit
+ ready, disconnected, paid bool
+ payout int
+ result string
+}
+type paiGowTable struct {
+ *tableBase
+ mu sync.Mutex
+ rng *rand.Rand
+ players []*pgPlayer // stable seat/deal/settlement order
+ phase string
+ ticks int
+ dealer []card
+ dealerSplit pgSplit
+ tie [2]card
+}
+
+func newPaiGowTable(room int, c TableConfig, rng *rand.Rand) tableGame {
+ return &paiGowTable{tableBase: &tableBase{RoomID: room, Config: c}, rng: rng, phase: "waiting"}
+}
+func (t *paiGowTable) base() *tableBase { return t.tableBase }
+func (t *paiGowTable) player(name string) *pgPlayer {
+ for _, p := range t.players {
+ if p.name == name {
+ return p
+ }
+ }
+ return nil
+}
+func (t *paiGowTable) remove(name string) {
+ for i, p := range t.players {
+ if p.name == name {
+ t.players = append(t.players[:i], t.players[i+1:]...)
+ return
+ }
+ }
+}
+func (t *paiGowTable) idle() bool { t.mu.Lock(); defer t.mu.Unlock(); return len(t.players) == 0 }
+func (t *paiGowTable) hasParticipant(name string) bool {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return t.player(name) != nil
+}
+func (t *paiGowTable) overview() string {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return fmt.Sprintf("%s | %s | %d/%d seats", t.Config.Label(), t.phase, len(t.players), t.Config.MaxPlayers)
+}
+func (t *paiGowTable) hintsLocked(name string) []MenuCommand {
+ p := t.player(name)
+ if p == nil {
+ return nil
+ }
+ commands := []MenuCommand{}
+ switch t.phase {
+ case "waiting", "betting":
+ if p.main.Total == 0 {
+ commands = append(commands, MenuCommand{Command: "bet <amount>", Desc: "Main wager; opens a timed betting window"})
+ } else {
+ if p.fortune.Total == 0 {
+ commands = append(commands, MenuCommand{Command: "bet <amount> fortune", Desc: "Optional Fortune side bet before deal"})
+ }
+ if t.Config.PaiGow.Variant == PaiGowFaceUp && p.pushace.Total == 0 {
+ commands = append(commands, MenuCommand{Command: "bet <amount> pushace", Desc: "Optional Push Ace High side bet (max half the main wager)"})
+ }
+ commands = append(commands, MenuCommand{Command: "deal", Desc: "Mark ready; deal when all bettors are ready"})
+ }
+ case "setting":
+ if p.main.Total > 0 && !p.ready {
+ commands = append(commands, MenuCommand{Command: "24 / 13456", Desc: "Choose two low cards OR five high cards; locks the hand"}, MenuCommand{Command: "house", Desc: "Set your hand the house way"})
+ }
+ case "settling":
+ commands = append(commands, MenuCommand{Command: "settle", Desc: "Retry the same pending payment"})
+ }
+ return append(commands, MenuCommand{Command: "table rules", Desc: "Rules and Fortune felt"}, MenuCommand{Command: "rules", Desc: "Learn Pai Gow"}, MenuCommand{Command: "stop", Desc: "Leave after finishing your wager"})
+}
+func (t *paiGowTable) hints(name string) []MenuCommand {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return t.hintsLocked(name)
+}
+func (t *paiGowTable) wagers(name string) []WagerRow {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p := t.player(name)
+ if p == nil || t.phase == "setting" || t.phase == "settling" {
+ return nil
+ }
+ rows := []WagerRow{{Bet: "main", Payout: "See table rules", Win: "Beat both dealer hands"}, {Bet: "fortune", Payout: "See Fortune felt", Win: "Best seven-card bonus; independent of main result"}}
+ if t.Config.PaiGow.Variant == PaiGowFaceUp {
+ rows = append(rows, WagerRow{Bet: "pushace", Payout: "40/15/5:1", Win: "Dealer ace-high pai gow; both 40:1"})
+ }
+ return rows
+}
+func pgViews(cards []card) []CardView {
+ var out []CardView
+ for _, c := range cards {
+ out = append(out, CardView{Rank: c.rank, Suit: c.suit})
+ }
+ return out
+}
+func (t *paiGowTable) statusLocked(name string) []Event {
+ s := &PaiGowSnapshot{Config: t.Config, Phase: t.phase}
+ if p := t.player(name); p != nil {
+ s.Cards = pgViews(p.cards)
+ s.High = pgViews(p.split.high)
+ s.Low = pgViews(p.split.low)
+ s.Result = p.result
+ if t.phase == "settling" && !p.paid && p.main.Total > 0 {
+ s.Result += "; PAYMENT PENDING (not yet credited)"
+ }
+ }
+ if t.phase == "settling" || t.phase == "waiting" || t.phase == "setting" && t.Config.PaiGow.Variant == PaiGowFaceUp {
+ s.DealerHigh = pgViews(t.dealerSplit.high)
+ s.DealerLow = pgViews(t.dealerSplit.low)
+ if len(t.dealer) > 0 && t.Config.PaiGow.Variant == PaiGowNoPush {
+ s.Tiebreaker = pgViews(t.tie[:])
+ }
+ }
+ e := t.private(name, t.Config.Label())
+ e.Snapshot = s
+ e.Menu = &MenuView{Heading: t.Config.Label() + " | " + t.phase, ShowBalance: true, Commands: t.hintsLocked(name)}
+ return []Event{e}
+}
+func (t *paiGowTable) status(name string) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return t.statusLocked(name)
+}
+func (t *paiGowTable) join(name string) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if p := t.player(name); p != nil {
+ p.disconnected = false
+ return t.statusLocked(name)
+ }
+ if len(t.players) >= t.Config.MaxPlayers {
+ return []Event{t.private(name, "This Pai Gow table is full.")}
+ }
+ t.players = append(t.players, &pgPlayer{name: name})
+ return t.statusLocked(name)
+}
+func (t *paiGowTable) leave(name string) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if p := t.player(name); p != nil && p.main.Total > 0 {
+ return []Event{t.private(name, "Finish your Pai Gow round before leaving; house sets your hand.")}
+ }
+ t.remove(name)
+ return []Event{t.private(name, "You leave Pai Gow Poker.")}
+}
+func (t *paiGowTable) rebet(name string) (string, int) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if p := t.player(name); p != nil && p.last > 0 {
+ return "main", p.last
+ }
+ return "main", t.Config.MinBet
+}
+func (t *paiGowTable) bet(name, spot string, amount int, w Wallet) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p := t.player(name)
+ if p == nil {
+ return nil
+ }
+ fail := func(s string) []Event { return []Event{t.private(name, s)} }
+ if t.phase != "waiting" && t.phase != "betting" {
+ return fail("Betting is closed.")
+ }
+ if spot == "" {
+ spot = "main"
+ }
+ if spot != "main" && spot != "fortune" && spot != "pushace" {
+ return fail("Bet on main or fortune.")
+ }
+ if spot == "pushace" && t.Config.PaiGow.Variant != PaiGowFaceUp {
+ return fail("Push Ace High is a Face Up side bet only.")
+ }
+ if spot == "main" && p.main.Total > 0 || spot == "fortune" && p.fortune.Total > 0 || spot == "pushace" && p.pushace.Total > 0 {
+ return fail("That wager is already committed.")
+ }
+ if spot != "main" && (p.main.Total == 0 || p.ready) {
+ return fail("Place a main bet first, then side bets before marking ready with deal.")
+ }
+ if spot == "pushace" && amount > p.main.Total/2 {
+ return fail("Push Ace High is capped at half the main wager.")
+ }
+ if amount < t.Config.MinBet || amount > t.Config.MaxBet || amount > pgMaxWager {
+ return fail("Wager must be " + betRangeText(t.Config.MinBet, min(t.Config.MaxBet, pgMaxWager)) + ".")
+ }
+ if w == nil {
+ return fail("Wallet unavailable.")
+ }
+ stake, err := w.Wager(amount)
+ if err != nil {
+ return fail(walletErrorMessage(err))
+ }
+ p.wallet = w
+ if spot == "main" {
+ p.main = stake
+ p.last = amount
+ p.cards = nil
+ p.split = pgSplit{}
+ p.result = ""
+ p.ready = false
+ p.paid = false
+ p.fortune = Wager{}
+ p.pushace = Wager{}
+ } else if spot == "pushace" {
+ p.pushace = stake
+ } else {
+ p.fortune = stake
+ }
+ if t.phase == "waiting" {
+ t.phase = "betting"
+ t.ticks = t.Config.BettingTicks
+ t.dealer = nil
+ t.dealerSplit = pgSplit{}
+ }
+ return append(fail(fmt.Sprintf("Committed %d on %s. Betting closes in %d ticks; Fortune is optional, then deal.", amount, spot, t.ticks)), t.statusLocked(name)...)
+}
+func (t *paiGowTable) allReady() bool {
+ found := false
+ for _, p := range t.players {
+ if p.main.Total > 0 {
+ found = true
+ if !p.ready {
+ return false
+ }
+ }
+ }
+ return found
+}
+func (t *paiGowTable) dealLocked() []Event {
+ deck := newShoe(1, 0, t.rng)
+ deck.cards = append(deck.cards, card{"JK", "joker"})
+ t.rng.Shuffle(len(deck.cards), func(i, j int) { deck.cards[i], deck.cards[j] = deck.cards[j], deck.cards[i] })
+ // Seven packets, including unused seats, leave the published No Push
+ // tiebreakers at cards 50 and 51. Empty packets never qualify for Envy.
+ packets := [7][]card{}
+ for i := range packets {
+ for j := 0; j < 7; j++ {
+ packets[i] = append(packets[i], deck.draw())
+ }
+ }
+ t.dealer = packets[6]
+ t.dealerSplit = pgHouse(t.dealer)
+ t.tie = [2]card{deck.draw(), deck.draw()}
+ t.phase = "setting"
+ t.ticks = t.Config.PaiGow.ActionTicks
+ // Face Up ace-high settles immediately: there is no decision to make.
+ // Still assign every player's seven cards for independent Fortune/Envy.
+ autoPush := t.Config.PaiGow.Variant == PaiGowFaceUp && pgDealerPush(t.dealer, PaiGowFaceUp) != ""
+ var events []Event
+ for i, p := range t.players {
+ if p.main.Total == 0 {
+ continue
+ }
+ p.cards = packets[i]
+ p.ready = p.disconnected || autoPush
+ if p.ready {
+ p.split = pgHouse(p.cards)
+ }
+ if !autoPush {
+ events = append(events, t.statusLocked(p.name)...)
+ }
+ }
+ if t.allReady() {
+ events = append(events, t.prepareSettlementLocked()...)
+ }
+ return events
+}
+func (t *paiGowTable) action(name, action string) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p := t.player(name)
+ if p == nil {
+ return nil
+ }
+ action = strings.TrimSpace(strings.ToLower(action))
+ if action == "paytable" || action == "status" {
+ return t.statusLocked(name)
+ }
+ if t.phase == "settling" && action == "settle" {
+ return t.payLocked()
+ }
+ if action == "deal" && t.phase == "betting" && p.main.Total > 0 {
+ p.ready = true
+ if t.allReady() {
+ return t.dealLocked()
+ }
+ return []Event{t.private(name, "Ready. Waiting for other bettors or the betting timer.")}
+ }
+ if t.phase != "setting" || p.main.Total == 0 {
+ return []Event{t.private(name, "Place your bets, then deal; set cards only after they are dealt.")}
+ }
+ if p.ready {
+ return []Event{t.private(name, "Your hand is locked; waiting for the other players.")}
+ }
+ var split pgSplit
+ if action == "house" || action == "house way" || action == "set house" {
+ split = pgHouse(p.cards)
+ } else {
+ digits, ok := ParsePaiGowDigits(strings.TrimPrefix(action, "set "))
+ if !ok {
+ return []Event{t.private(name, "Enter exactly two or five different numbers from 1-7 (24 or 13456), or house.")}
+ }
+ split = pgSet(p.cards, digits)
+ }
+ if !split.valid() {
+ return []Event{t.private(name, "FOUL HAND: your five-card high hand must be higher than your two-card low hand. Nothing was set; choose again or use house.")}
+ }
+ p.split = split
+ p.ready = true
+ if t.allReady() {
+ return t.prepareSettlementLocked()
+ }
+ return t.statusLocked(name)
+}
+func (t *paiGowTable) prepareSettlementLocked() []Event {
+ t.phase = "settling"
+ for _, p := range t.players {
+ if p.main.Total == 0 {
+ continue
+ }
+ result := pgMainResult(p.split, t.dealerSplit, t.dealer, t.Config.PaiGow.Variant, t.tie)
+ p.payout = pgMainPay(p.main.Total, result, t.Config.PaiGow.Variant)
+ p.result = "Main: " + result
+ if t.Config.PaiGow.Variant == PaiGowFaceUp {
+ rates, _ := t.Config.PaiGow.pushAceRates()
+ if class := pgPushAceClass(t.dealer, p.cards, rates); class.klass != "none" {
+ p.payout = p.pushace.Total * (class.rate + 1)
+ p.result += fmt.Sprintf("; Push Ace High: %s (%d:1)", class.desc, class.rate)
+ } else if p.pushace.Total > 0 {
+ p.result += "; Push Ace High: lost (dealer not ace-high)"
+ }
+ }
+ if p.fortune.Total > 0 {
+ row, win := pgFortune(p.cards, t.Config.PaiGow.Envy)
+ p.result += "; Fortune: " + row.Hand
+ if win {
+ p.payout += p.fortune.Total * (row.Odds + 1)
+ }
+ if t.Config.PaiGow.Envy && p.fortune.Total >= 5 {
+ envy := 0
+ for _, other := range t.players {
+ if other != p && other.main.Total > 0 {
+ row, _ := pgFortune(other.cards, true)
+ envy += row.Envy
+ }
+ }
+ p.payout += envy
+ p.result += fmt.Sprintf("; Envy: %d", envy)
+ }
+ }
+ }
+ return t.payLocked()
+}
+func (t *paiGowTable) payLocked() []Event {
+ var events []Event
+ var newlyPaid []string
+ pending := false
+ for _, p := range t.players {
+ if p.main.Total == 0 || p.paid {
+ continue
+ }
+ ids := []string{p.main.ID}
+ if p.fortune.Total > 0 {
+ ids = append(ids, p.fortune.ID)
+ }
+ if p.pushace.Total > 0 {
+ ids = append(ids, p.pushace.ID)
+ }
+ // One durable transaction settles both wagers and Envy, including zero
+ // returns. Freeze the round on failure; retries never redeal or pay twice.
+ if err := p.wallet.PayCredits(p.payout, ids...); err != nil {
+ pending = true
+ events = append(events, t.private(p.name, payoutFailedMessage()+" Use settle to retry the same result."))
+ continue
+ }
+ p.paid = true
+ p.result += fmt.Sprintf("; total returned %d credits", p.payout)
+ newlyPaid = append(newlyPaid, p.name)
+ }
+ if pending {
+ for _, name := range newlyPaid {
+ events = append(events, t.statusLocked(name)...)
+ }
+ return events
+ }
+ t.phase = "waiting"
+ kept := t.players[:0]
+ for _, p := range t.players {
+ p.main = Wager{}
+ p.fortune = Wager{}
+ p.ready = false
+ if !p.disconnected {
+ kept = append(kept, p)
+ }
+ }
+ t.players = kept
+ for _, p := range t.players {
+ events = append(events, t.statusLocked(p.name)...)
+ }
+ return events
+}
+func (t *paiGowTable) tick() []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ switch t.phase {
+ case "settling":
+ return t.payLocked()
+ case "betting", "setting":
+ t.ticks--
+ if t.ticks > 0 {
+ return nil
+ }
+ if t.phase == "betting" {
+ return t.dealLocked()
+ }
+ for _, p := range t.players {
+ if p.main.Total > 0 && !p.ready {
+ p.split = pgHouse(p.cards)
+ p.ready = true
+ }
+ }
+ return t.prepareSettlementLocked()
+ }
+ return nil
+}
+func (t *paiGowTable) markDisconnected(name string) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p := t.player(name)
+ if p == nil {
+ return nil
+ }
+ if p.main.Total == 0 {
+ t.remove(name)
+ return nil
+ }
+ p.disconnected = true
+ p.ready = true
+ if t.phase == "setting" {
+ if p.split.high == nil {
+ p.split = pgHouse(p.cards)
+ }
+ if t.allReady() {
+ return t.prepareSettlementLocked()
+ }
+ }
+ return nil
+}
+func (t *paiGowTable) refundAll() []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ var events []Event
+ for _, p := range t.players {
+ if p.wallet == nil || p.main.Total == 0 || p.paid {
+ continue
+ }
+ if _, _, err := p.wallet.RefundOutstanding(); err != nil {
+ events = append(events, t.private(p.name, "Shutdown refund remains pending for startup recovery."))
+ } else {
+ p.main = Wager{}
+ p.fortune = Wager{}
+ p.pushace = Wager{}
+ }
+ }
+ return events
+}
diff --git a/internal/casino/pai_gow_rules.go b/internal/casino/pai_gow_rules.go
new file mode 100644
index 0000000..8a9842c
--- /dev/null
+++ b/internal/casino/pai_gow_rules.go
@@ -0,0 +1,503 @@
+package casino
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "unicode"
+)
+
+const (
+ PaiGowClassic = "classic"
+ PaiGowEZ = "ez"
+ PaiGowNoPush = "no_push"
+ PaiGowFaceUp = "face_up"
+ // Two independently funded wagers plus all five Envy bonuses must fit
+ // MaxCredits. 2000 conservatively exceeds the maximum combined multiplier.
+ pgMaxWager = MaxCredits / 2000
+)
+
+type PaiGowConfig struct {
+ Variant string `yaml:"variant,omitempty"`
+ Envy bool `yaml:"envy,omitempty"`
+ PushAceHigh string `yaml:"push_ace_high,omitempty"` // Face Up only: 5_15_40 or 5_12_40
+ ActionTicks int `yaml:"action_ticks,omitempty"`
+}
+
+func (c PaiGowConfig) Normalize() PaiGowConfig {
+ if c.Variant == "" {
+ c.Variant = PaiGowClassic
+ }
+ if c.ActionTicks == 0 {
+ c.ActionTicks = 60
+ }
+ return c
+}
+
+// pushAceRates returns the three published rates (plain/joker/both) for a
+// Face Up table's configured schedule; ok is false on any other value.
+func (c PaiGowConfig) pushAceRates() ([3]int, bool) {
+ switch c.Normalize().PushAceHigh {
+ case "5_15_40":
+ return [3]int{5, 15, 40}, true
+ case "5_12_40":
+ return [3]int{5, 12, 40}, true
+ }
+ return [3]int{}, false
+}
+func validatePaiGow(c TableConfig) error {
+ r := c.PaiGow.Normalize()
+ if c.MinBet > pgMaxWager {
+ return fmt.Errorf("pai_gow min_bet must not exceed %d", pgMaxWager)
+ }
+ if r.Variant != PaiGowClassic && r.Variant != PaiGowEZ && r.Variant != PaiGowNoPush && r.Variant != PaiGowFaceUp {
+ return fmt.Errorf("pai_gow variant must be classic, ez, no_push, or face_up")
+ }
+ if c.MaxPlayers > 6 {
+ return fmt.Errorf("pai gow allows at most six players")
+ }
+ if r.ActionTicks < 1 || r.ActionTicks > 600 {
+ return fmt.Errorf("pai_gow action_ticks must be 1-600")
+ }
+ if r.PushAceHigh != "" {
+ if r.Variant != PaiGowFaceUp {
+ return fmt.Errorf("push_ace_high belongs on a face_up table")
+ }
+ if _, ok := r.pushAceRates(); !ok {
+ return fmt.Errorf("push_ace_high must be 5_15_40 or 5_12_40")
+ }
+ }
+ if r.Variant == PaiGowFaceUp && r.PushAceHigh == "" {
+ return fmt.Errorf("face_up requires push_ace_high 5_15_40 or 5_12_40")
+ }
+ return nil
+}
+func (c PaiGowConfig) Label() string {
+ switch c.Normalize().Variant {
+ case PaiGowEZ:
+ return "EZ Pai Gow Poker"
+ case PaiGowNoPush:
+ return "No Push Pai Gow Poker"
+ case PaiGowFaceUp:
+ return "Face Up Pai Gow Poker"
+ }
+ return "Pai Gow Poker"
+}
+func paiGowRules(c TableConfig) string {
+ r := c.PaiGow.Normalize()
+ s := r.Label() + "\nSeven cards from a fresh 53-card deck. Joker is an ace unless completing a straight, flush or straight flush. A2345 is the second-highest straight.\nSet two cards low and five high: 24 chooses low cards 2/4; 13456 chooses the high hand. High must strictly outrank low. Copies go to the dealer.\nBoth hands win: win; both lose: loss; one wins: push."
+ switch r.Variant {
+ case PaiGowClassic:
+ s += " Wins pay 0.95:1 (profit rounded down, minimum one credit)."
+ case PaiGowEZ:
+ s += " No commission; dealer's best five-card hand exactly queen-high pushes all main bets."
+ case PaiGowFaceUp:
+ s += " No commission; dealer sets and reveals both hands before you set yours. Dealer's best five-card hand exactly ace-high automatically pushes all main bets; Fortune and Envy still settle."
+ case PaiGowNoPush:
+ s += " No commission; split results use two extra cards: player must beat dealer, ties lose; Joker is ace."
+ }
+ s += "\nHouse way: preserve the best high-hand category, maximize low within it; split two pair, full houses and trips-pairs when this improves low to a pair. Never foul. Use house or set <digits>; set locks your hand. Timeout/disconnect uses house way.\nBet main first, optionally bet <amount> fortune before dealing. Fortune uses all seven cards regardless of split; highest listed prize only, profit odds plus stake returned."
+ if r.Envy {
+ s += "\nEnvy: Fortune stake of at least 5 qualifies for fixed bonuses on OTHER active players' hands, never your own or dealer; multiple bonuses add."
+ } else {
+ s += "\nEnvy off: four of a kind pays 30:1 instead of 25:1 (custom enhancement)."
+ }
+ return s
+}
+
+// ParsePaiGowDigits accepts exactly two or five UNIQUE card positions; unlike
+// video poker toggles, repeated digits are an error rather than silently ignored.
+func ParsePaiGowDigits(s string) ([]int, bool) {
+ var out []int
+ var seen [7]bool
+ for _, r := range s {
+ if unicode.IsSpace(r) {
+ continue
+ }
+ if r < '1' || r > '7' || seen[r-'1'] {
+ return nil, false
+ }
+ seen[r-'1'] = true
+ out = append(out, int(r-'1'))
+ }
+ return out, len(out) == 2 || len(out) == 5
+}
+
+// Lexicographic category and kickers. Zero padding permits comparisons between
+// five and two cards without treating a two-card flush/straight as a hand.
+type pgRank [6]int
+
+func pgCompare(a, b pgRank) int {
+ for i := range a {
+ if a[i] > b[i] {
+ return 1
+ }
+ if a[i] < b[i] {
+ return -1
+ }
+ }
+ return 0
+}
+func pgNatural(cards []card) pgRank {
+ counts := [15]int{}
+ flush := len(cards) == 5
+ for _, c := range cards {
+ counts[pokerRank(c)]++
+ if c.suit != cards[0].suit {
+ flush = false
+ }
+ }
+ var ranks []int
+ for r := 14; r >= 2; r-- {
+ if counts[r] > 0 {
+ ranks = append(ranks, r)
+ }
+ }
+ sort.SliceStable(ranks, func(i, j int) bool { return counts[ranks[i]] > counts[ranks[j]] })
+ straight := 0
+ if len(cards) == 5 && len(ranks) == 5 {
+ sorted := append([]int(nil), ranks...)
+ sort.Ints(sorted)
+ if sorted[4]-sorted[0] == 4 {
+ straight = sorted[4]
+ }
+ if sorted[0] == 2 && sorted[1] == 3 && sorted[2] == 4 && sorted[3] == 5 && sorted[4] == 14 {
+ straight = 15
+ }
+ if straight == 14 {
+ straight = 16
+ }
+ }
+ out := pgRank{}
+ switch {
+ case counts[ranks[0]] == 5:
+ out[0] = 9
+ case straight > 0 && flush:
+ out[0] = 8
+ out[1] = straight
+ return out
+ case counts[ranks[0]] == 4:
+ out[0] = 7
+ case len(ranks) > 1 && counts[ranks[0]] == 3 && counts[ranks[1]] == 2:
+ out[0] = 6
+ case flush:
+ out[0] = 5
+ case straight > 0:
+ out[0] = 4
+ out[1] = straight
+ return out
+ case counts[ranks[0]] == 3:
+ out[0] = 3
+ case len(ranks) > 1 && counts[ranks[0]] == 2 && counts[ranks[1]] == 2:
+ out[0] = 2
+ case counts[ranks[0]] == 2:
+ out[0] = 1
+ }
+ copy(out[1:], ranks)
+ return out
+}
+func pgEvaluate(cards []card) pgRank {
+ j := -1
+ for i, c := range cards {
+ if c.rank == "JK" {
+ j = i
+ break
+ }
+ }
+ if j < 0 {
+ return pgNatural(cards)
+ }
+ copyCards := append([]card(nil), cards...)
+ copyCards[j] = card{"A", "joker"}
+ best := pgNatural(copyCards)
+ if len(cards) != 5 {
+ return best
+ }
+ for _, s := range []string{"clubs", "diamonds", "hearts", "spades"} {
+ for _, r := range []string{"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"} {
+ replacement := card{r, s}
+ duplicate := false
+ for i, c := range cards {
+ if i != j && c == replacement {
+ duplicate = true
+ }
+ }
+ if duplicate {
+ continue
+ }
+ copyCards[j] = replacement
+ v := pgNatural(copyCards)
+ if (v[0] == 4 || v[0] == 5 || v[0] == 8) && pgCompare(v, best) > 0 {
+ best = v
+ }
+ }
+ }
+ return best
+}
+
+type pgSplit struct{ high, low []card }
+
+func pgSet(cards []card, digits []int) pgSplit {
+ var selected [7]bool
+ for _, i := range digits {
+ selected[i] = true
+ }
+ s := pgSplit{}
+ for i, c := range cards {
+ if selected[i] == (len(digits) == 2) {
+ s.low = append(s.low, c)
+ } else {
+ s.high = append(s.high, c)
+ }
+ }
+ return s
+}
+func (s pgSplit) valid() bool {
+ return len(s.high) == 5 && len(s.low) == 2 && pgCompare(pgEvaluate(s.high), pgEvaluate(s.low)) > 0
+}
+func pgHouse(cards []card) pgSplit {
+ var options []pgSplit
+ best := pgRank{}
+ for i := 0; i < 7; i++ {
+ for j := i + 1; j < 7; j++ {
+ s := pgSet(cards, []int{i, j})
+ if !s.valid() {
+ continue
+ }
+ options = append(options, s)
+ if pgCompare(pgEvaluate(s.high), best) > 0 {
+ best = pgEvaluate(s.high)
+ }
+ }
+ }
+ var chosen pgSplit
+ var low, high pgRank
+ for _, s := range options {
+ h, l := pgEvaluate(s.high), pgEvaluate(s.low)
+ eligible := h[0] == best[0]
+ // Split two pair/full house only for a paired front with at least a pair behind.
+ if (best[0] == 2 || best[0] == 6) && l[0] == 1 && h[0] >= 1 {
+ eligible = true
+ }
+ if !eligible {
+ continue
+ }
+ if chosen.high == nil || pgCompare(l, low) > 0 || pgCompare(l, low) == 0 && pgCompare(h, high) > 0 {
+ chosen, low, high = s, l, h
+ }
+ }
+ return chosen
+}
+
+type FortuneRow struct {
+ Hand string
+ Odds, Envy int
+}
+
+// Wizard of Odds Fortune table 8, the lowest-edge published fixed schedule
+// among its eight tables. With Envy disabled, quads receive a custom +5.
+func FortunePayTable(envy bool) []FortuneRow {
+ rows := []FortuneRow{{"Natural seven-card straight flush", 1000, 500}, {"Royal flush + royal match", 750, 250}, {"Wild seven-card straight flush", 500, 150}, {"Five aces", 250, 100}, {"Royal flush", 150, 50}, {"Straight flush", 50, 20}, {"Four of a kind", 25, 5}, {"Full house", 5, 0}, {"Flush", 4, 0}, {"Three of a kind", 3, 0}, {"Straight", 2, 0}, {"Three pair", 1, 0}}
+ if !envy {
+ rows[6].Odds = 30
+ for i := range rows {
+ rows[i].Envy = 0
+ }
+ }
+ return rows
+}
+func pgSevenFlush(cards []card) bool {
+ suit := ""
+ counts := [15]int{}
+ wild := 0
+ for _, c := range cards {
+ if c.rank == "JK" {
+ wild++
+ continue
+ }
+ if suit == "" {
+ suit = c.suit
+ }
+ if suit != c.suit {
+ return false
+ }
+ counts[pokerRank(c)]++
+ }
+ for high := 7; high <= 14; high++ {
+ missing := 0
+ for r := high - 6; r <= high; r++ {
+ v := r
+ if v == 1 {
+ v = 14
+ }
+ if counts[v] == 0 {
+ missing++
+ }
+ }
+ if missing == wild {
+ return true
+ }
+ }
+ return false
+}
+func pgFortune(cards []card, envy bool) (FortuneRow, bool) {
+ rows := FortunePayTable(envy)
+ joker := false
+ counts := [15]int{}
+ for _, c := range cards {
+ if c.rank == "JK" {
+ joker = true
+ counts[14]++
+ } else {
+ counts[pokerRank(c)]++
+ }
+ }
+ if pgSevenFlush(cards) && !joker {
+ return rows[0], true
+ }
+ bestIndex := len(rows)
+ // Enumerate all 21 five-card subsets. Fortune ranks trips above straights,
+ // so choose by pay-table priority, NOT conventional poker rank.
+ for i := 0; i < 7; i++ {
+ for j := i + 1; j < 7; j++ {
+ s := pgSet(cards, []int{i, j})
+ v := pgEvaluate(s.high)
+ index := len(rows)
+ switch v[0] {
+ case 9:
+ index = 3
+ case 8:
+ if v[1] == 16 {
+ index = 4
+ if s.low[0].suit == s.low[1].suit && (s.low[0].rank == "K" && s.low[1].rank == "Q" || s.low[0].rank == "Q" && s.low[1].rank == "K") {
+ index = 1
+ }
+ } else {
+ index = 5
+ }
+ case 7:
+ index = 6
+ case 6:
+ index = 7
+ case 5:
+ index = 8
+ case 3:
+ index = 9
+ case 4:
+ index = 10
+ }
+ if index < bestIndex {
+ bestIndex = index
+ }
+ }
+ }
+ if joker && pgSevenFlush(cards) && bestIndex > 2 {
+ bestIndex = 2
+ }
+ pairs := 0
+ for _, n := range counts {
+ if n >= 2 {
+ pairs++
+ }
+ }
+ if pairs >= 3 && bestIndex > 11 {
+ bestIndex = 11
+ }
+ if bestIndex == len(rows) {
+ return FortuneRow{Hand: "No Fortune win"}, false
+ }
+ return rows[bestIndex], true
+}
+func pgBest(cards []card) pgRank {
+ var best pgRank
+ for i := 0; i < 7; i++ {
+ for j := i + 1; j < 7; j++ {
+ v := pgEvaluate(pgSet(cards, []int{i, j}).high)
+ if pgCompare(v, best) > 0 {
+ best = v
+ }
+ }
+ }
+ return best
+}
+
+// Automatic pushes use the best of all seven dealer cards, not just the
+// chosen high hand. Pair/straight/flush hands headed by an ace do not qualify.
+func pgDealerPush(cards []card, variant string) string {
+ if variant != PaiGowEZ && variant != PaiGowFaceUp {
+ return ""
+ }
+ v := pgBest(cards)
+ if v[0] == 0 {
+ if variant == PaiGowEZ && v[1] == 12 {
+ return "push (dealer queen-high)"
+ }
+ if variant == PaiGowFaceUp && v[1] == 14 {
+ return "push (dealer ace-high)"
+ }
+ }
+ return ""
+}
+func pgMainResult(player, dealer pgSplit, dealerCards []card, variant string, tie [2]card) string {
+ if push := pgDealerPush(dealerCards, variant); push != "" {
+ return push
+ }
+ high := pgCompare(pgEvaluate(player.high), pgEvaluate(dealer.high)) > 0
+ low := pgCompare(pgEvaluate(player.low), pgEvaluate(dealer.low)) > 0
+ if high && low {
+ return "win"
+ }
+ if !high && !low {
+ return "loss"
+ }
+ if variant == PaiGowNoPush {
+ rank := func(c card) int {
+ if c.rank == "JK" {
+ return 14
+ }
+ return pokerRank(c)
+ }
+ if rank(tie[0]) > rank(tie[1]) {
+ return "win (tiebreaker)"
+ }
+ return "loss (tiebreaker)"
+ }
+ return "push"
+}
+
+// pgPushAceClass resolves Face Up's optional Push Ace High side bet.
+// The dealer's seven cards decide the base event at reveal time; ace-high
+// with a Joker pays 15:1, without a Joker 5:1, and both sides ace-high 40:1
+type pgPushAce struct {
+ klass string // "both", "joker", "plain", or "none"
+ rate int
+ desc string
+}
+
+func pgPushAceClass(dealer, player []card, rates [3]int) pgPushAce {
+ if pgBest(dealer)[0] != 0 || pgBest(dealer)[1] != 14 {
+ return pgPushAce{klass: "none"}
+ }
+ for _, c := range dealer {
+ if c.rank == "JK" {
+ return pgPushAce{klass: "joker", rate: rates[1], desc: "dealer ace-high with Joker"}
+ }
+ }
+ if pgBest(player)[0] == 0 && pgBest(player)[1] == 14 {
+ return pgPushAce{klass: "both", rate: rates[2], desc: "both ace-high"}
+ }
+ return pgPushAce{klass: "plain", rate: rates[0], desc: "dealer ace-high without Joker"}
+}
+
+func pgMainPay(stake int, result, variant string) int {
+ if strings.HasPrefix(result, "push") {
+ return stake
+ }
+ if !strings.HasPrefix(result, "win") {
+ return 0
+ }
+ if variant == PaiGowClassic {
+ return stake + max(1, stake*95/100)
+ }
+ return stake * 2
+}
diff --git a/internal/casino/pai_gow_test.go b/internal/casino/pai_gow_test.go
new file mode 100644
index 0000000..f258b04
--- /dev/null
+++ b/internal/casino/pai_gow_test.go
@@ -0,0 +1,464 @@
+package casino
+
+import (
+ "math"
+ "math/rand"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func pgCards(s string) []card {
+ var out []card
+ for _, v := range strings.Fields(s) {
+ if v == "JK" {
+ out = append(out, card{"JK", "joker"})
+ continue
+ }
+ suit := map[byte]string{'s': "spades", 'h': "hearts", 'd': "diamonds", 'c': "clubs"}[v[len(v)-1]]
+ out = append(out, card{v[:len(v)-1], suit})
+ }
+ return out
+}
+func TestPaiGowParsingAndFouls(t *testing.T) {
+ for _, s := range []string{"24", "42", "2 4", "13456", "6 5 4 3 1"} {
+ d, ok := ParsePaiGowDigits(s)
+ if !ok {
+ t.Fatal(s)
+ }
+ split := pgSet(pgCards("As Ah 2c 3d 4s 7h 9c"), d)
+ if len(split.high) != 5 || len(split.low) != 2 {
+ t.Fatal(split)
+ }
+ }
+ for _, s := range []string{"", "2", "123", "1234", "123456", "1234567", "22", "11234", "08", "28", "-24", "2x4"} {
+ if _, ok := ParsePaiGowDigits(s); ok {
+ t.Fatalf("accepted %q", s)
+ }
+ }
+ cards := pgCards("As Ah 2c 3d 4s 7h 9c")
+ if pgSet(cards, []int{0, 1}).valid() {
+ t.Fatal("pair low above high-card high")
+ }
+ if !pgSet(cards, []int{5, 6}).valid() {
+ t.Fatal("legal pair high")
+ }
+ if !reflect.DeepEqual(pgSet(cards, []int{1, 3}), pgSet(cards, []int{0, 2, 4, 5, 6})) {
+ t.Fatal("complement selection differs")
+ }
+}
+func TestPaiGowRanksAndBug(t *testing.T) {
+ cases := []struct {
+ cards string
+ rank pgRank
+ }{
+ {"As Ah", pgRank{1, 14}}, {"JK Kh", pgRank{0, 14, 13}},
+ {"Ks Qh Jc 10d 9s", pgRank{4, 13}}, {"As 2h 3c 4d 5s", pgRank{4, 15}}, {"As Kh Qc Jd 10s", pgRank{4, 16}},
+ {"Ks Kh Kd JK 2s", pgRank{3, 13, 14, 2}}, // Joker cannot become a fourth king.
+ {"As Ah Ad Ac JK", pgRank{9, 14}},
+ {"2h 5h 8h Kh JK", pgRank{5, 14, 13, 8, 5, 2}},
+ {"10s Js Qs Ks JK", pgRank{8, 16}}, {"As 2h 3c 4d JK", pgRank{4, 15}},
+ }
+ for _, tt := range cases {
+ if got := pgEvaluate(pgCards(tt.cards)); got != tt.rank {
+ t.Errorf("%s = %v want %v", tt.cards, got, tt.rank)
+ }
+ }
+}
+func TestPaiGowFortuneCategories(t *testing.T) {
+ cases := []struct {
+ cards, hand string
+ odds int
+ }{
+ {"2s 3s 4s 5s 6s 7s 8s", "Natural seven-card straight flush", 1000},
+ {"As 2s 3s 4s 5s 6s 7s", "Natural seven-card straight flush", 1000},
+ {"10s Js Qs Ks As Kh Qh", "Royal flush + royal match", 750},
+ {"10s Js Qs Ks JK Kh Qh", "Royal flush + royal match", 750},
+ {"2s 3s 4s 5s 6s 8s JK", "Wild seven-card straight flush", 500},
+ {"As Ah Ac Ad JK 2c 3s", "Five aces", 250},
+ {"10s Js Qs Ks As 2h 3d", "Royal flush", 150},
+ {"2s 3s 4s 5s 6s 8h 9d", "Straight flush", 50},
+ {"Ks Kh Kc Kd 2s 3c JK", "Four of a kind", 25},
+ {"Ks Kh Kc Qd Qs 3c 8h", "Full house", 5},
+ {"2s 4s 6s 8s Ks 3h 9d", "Flush", 4},
+ {"2s 3h 4c 5d 6s 6h 6c", "Three of a kind", 3}, // trips outrank straight for Fortune
+ {"2s 3h 4c 5d 6s 9h Kc", "Straight", 2},
+ {"As Ah Kc Kd 2s 2h 7c", "Three pair", 1},
+ {"2s 4h 6c 8d Js Qh Ac", "No Fortune win", 0},
+ }
+ for _, tt := range cases {
+ row, win := pgFortune(pgCards(tt.cards), true)
+ if row.Hand != tt.hand || row.Odds != tt.odds || win != (tt.odds > 0) {
+ t.Errorf("%s: %+v %v", tt.cards, row, win)
+ }
+ }
+ rows := FortunePayTable(false)
+ if rows[6].Odds != 30 {
+ t.Fatal(rows)
+ }
+ for _, r := range rows {
+ if r.Envy != 0 {
+ t.Fatal(r)
+ }
+ }
+}
+
+// Published category combination counts also check that the effective
+// schedules and the documented theoretical edges cannot silently drift.
+func TestPaiGowFortunePublishedEdge(t *testing.T) {
+ counts := []int{32, 72, 196, 1128, 26020, 184644, 307472, 4188528, 6172088, 7672500, 11034204, 2862000}
+ for _, envy := range []bool{false, true} {
+ profit := -121694196
+ for i, row := range FortunePayTable(envy) {
+ profit += row.Odds * counts[i]
+ }
+ edge := -float64(profit) / 154143080
+ want := 0.034318
+ if envy {
+ want = 0.044292
+ }
+ if math.Abs(edge-want) > 0.000001 {
+ t.Fatalf("envy %v edge %g", envy, edge)
+ }
+ }
+}
+func TestPaiGowHouseNeverFouls(t *testing.T) {
+ rng := rand.New(rand.NewSource(21))
+ for n := 0; n < 500; n++ {
+ deck := newShoe(1, 0, rng)
+ cards := append([]card(nil), deck.cards[:7]...)
+ if n%2 == 0 {
+ cards[0] = card{"JK", "joker"}
+ }
+ s := pgHouse(cards)
+ if !s.valid() {
+ t.Fatalf("foul %v: %+v", cards, s)
+ }
+ if !reflect.DeepEqual(s, pgHouse(cards)) {
+ t.Fatal("nondeterministic house way")
+ }
+ }
+ s := pgHouse(pgCards("As Ah Ks Kh 2s 4h 7c"))
+ if pgEvaluate(s.low)[0] != 1 || pgEvaluate(s.high)[0] != 1 {
+ t.Fatal("house should split two pair", s)
+ }
+}
+func TestPaiGowVariants(t *testing.T) {
+ dealer := pgSplit{high: pgCards("Ks Kh 8s 7d 2c"), low: pgCards("Qs Jh")}
+ win := pgSplit{high: pgCards("As Ah 8h 6d 3c"), low: pgCards("Ks Qh")}
+ split := pgSplit{high: win.high, low: pgCards("10s 9h")}
+ for _, variant := range []string{PaiGowClassic, PaiGowEZ, PaiGowNoPush} {
+ if pgMainResult(win, dealer, append(append([]card(nil), dealer.high...), dealer.low...), variant, [2]card{}) != "win" {
+ t.Fatal(variant)
+ }
+ }
+ if pgMainResult(dealer, dealer, nil, PaiGowClassic, [2]card{}) != "loss" {
+ t.Fatal("copies must lose")
+ }
+ if pgMainResult(split, dealer, nil, PaiGowClassic, [2]card{}) != "push" {
+ t.Fatal("split should push")
+ }
+ for _, tt := range []struct{ cards, result string }{{"Ks Qh", "win (tiebreaker)"}, {"Ks Kh", "loss (tiebreaker)"}, {"JK As", "loss (tiebreaker)"}, {"JK Ks", "win (tiebreaker)"}} {
+ cards := pgCards(tt.cards)
+ if got := pgMainResult(split, dealer, nil, PaiGowNoPush, [2]card{cards[0], cards[1]}); got != tt.result {
+ t.Fatal(tt, got)
+ }
+ }
+ queen := pgCards("Qs Jh 9c 8d 6s 4h 2c")
+ if got := pgMainResult(win, dealer, queen, PaiGowEZ, [2]card{}); got != "push (dealer queen-high)" {
+ t.Fatal(got)
+ }
+ if pgMainPay(20, "win", PaiGowClassic) != 39 || pgMainPay(20, "win", PaiGowEZ) != 40 || pgMainPay(20, "push", PaiGowEZ) != 20 || pgMainPay(20, "loss", PaiGowClassic) != 0 {
+ t.Fatal("wrong payout")
+ }
+}
+func pgTestTable(envy bool) *paiGowTable {
+ cfg := TableConfig{ID: "pg", Game: GamePaiGow, BettingTicks: 2, PaiGow: PaiGowConfig{Envy: envy, ActionTicks: 2}}.Normalize()
+ return newPaiGowTable(1, cfg, rand.New(rand.NewSource(3))).(*paiGowTable)
+}
+func TestPaiGowLifecyclePrivacyAndUniqueDeck(t *testing.T) {
+ tab := pgTestTable(true)
+ wallets := map[string]*testWallet{}
+ for _, name := range []string{"a", "b", "c", "d", "e", "f"} {
+ tab.join(name)
+ w := &testWallet{chips: 100}
+ wallets[name] = w
+ tab.bet(name, "main", 10, w)
+ tab.bet(name, "fortune", 5, w)
+ }
+ tab.join("overflow")
+ if tab.hasParticipant("overflow") {
+ t.Fatal("seventh seat")
+ }
+ tab.tick()
+ events := tab.tick()
+ if tab.phase != "setting" {
+ t.Fatal(tab.phase)
+ }
+ seen := map[card]bool{}
+ for _, p := range tab.players {
+ for _, c := range p.cards {
+ if seen[c] {
+ t.Fatal("duplicate", c)
+ }
+ seen[c] = true
+ }
+ }
+ for _, c := range append(append([]card(nil), tab.dealer...), tab.tie[:]...) {
+ if seen[c] {
+ t.Fatal("duplicate", c)
+ }
+ seen[c] = true
+ }
+ if len(seen) != 51 {
+ t.Fatal(len(seen))
+ }
+ for _, e := range events {
+ if e.Public || e.PrivateTo == "" {
+ t.Fatal("private cards leaked")
+ }
+ s := e.Snapshot.(*PaiGowSnapshot)
+ if len(s.DealerHigh) > 0 || len(s.Tiebreaker) > 0 {
+ t.Fatal("dealer revealed before set")
+ }
+ }
+ tab.leave("a")
+ if !tab.hasParticipant("a") {
+ t.Fatal("left committed round")
+ }
+ before := wallets["a"].chips
+ tab.bet("a", "fortune", 5, wallets["a"])
+ if wallets["a"].chips != before {
+ t.Fatal("late bet charged")
+ }
+ tab.markDisconnected("a")
+ tab.tick()
+ tab.tick()
+ if tab.phase != "waiting" || tab.hasParticipant("a") {
+ t.Fatal("disconnect/timeout did not finish")
+ }
+ for _, w := range wallets {
+ if len(w.open) > 0 {
+ t.Fatal("unresolved stakes")
+ }
+ }
+}
+
+type pgFailWallet struct {
+ testWallet
+ fail bool
+ calls int
+ ids []string
+}
+
+func (w *pgFailWallet) PayCredits(n int, ids ...string) error {
+ w.calls++
+ if w.fail {
+ return ErrWalletPersistence
+ }
+ w.ids = append([]string(nil), ids...)
+ return w.testWallet.PayCredits(n, ids...)
+}
+func TestPaiGowAtomicRetryAndEnvy(t *testing.T) {
+ tab := pgTestTable(true)
+ a := &pgFailWallet{testWallet: testWallet{chips: 100}, fail: true}
+ b := &pgFailWallet{testWallet: testWallet{chips: 100}}
+ tab.join("a")
+ tab.join("b")
+ tab.bet("a", "main", 20, a)
+ tab.bet("a", "fortune", 5, a)
+ tab.bet("b", "main", 20, b)
+ tab.action("a", "deal")
+ tab.action("b", "deal")
+ // Script the dealt cards before either player sets. a loses Fortune but
+ // collects b's fixed quad Envy, even though b didn't bet Fortune.
+ tab.player("a").cards = pgCards("2s 4h 6c 8d Js Qh Ac")
+ tab.player("b").cards = pgCards("Ks Kh Kc Kd 2h 3c 7h")
+ tab.action("a", "house")
+ tab.action("b", "house")
+ if tab.phase != "settling" || len(a.open) != 2 || len(b.open) != 0 || b.calls != 1 {
+ t.Fatal("failed settlement wasn't held atomically")
+ }
+ p := tab.player("a")
+ if !strings.Contains(p.result, "Envy: 5") {
+ t.Fatal(p.result)
+ }
+ cards := append([]card(nil), p.cards...)
+ amount := p.payout
+ tab.action("a", "house")
+ if !reflect.DeepEqual(cards, p.cards) {
+ t.Fatal("redrew pending result")
+ }
+ a.fail = false
+ tab.action("a", "settle")
+ if tab.phase != "waiting" || a.paid != amount || len(a.ids) != 2 || len(a.open) != 0 || b.calls != 1 {
+ t.Fatal("retry did not settle exactly once")
+ }
+ tab.tick()
+ if a.calls != 2 || b.calls != 1 {
+ t.Fatal("double payout")
+ }
+}
+func TestPaiGowRejectedFoulDoesNotLock(t *testing.T) {
+ tab := pgTestTable(false)
+ w := &testWallet{chips: 100}
+ tab.join("a")
+ tab.bet("a", "", 10, w)
+ tab.action("a", "deal")
+ p := tab.player("a")
+ p.cards = pgCards("As Ah 2c 3d 4s 7h 9c")
+ events := tab.action("a", "12")
+ if p.ready || p.split.high != nil || !strings.Contains(events[0].Message, "FOUL HAND") {
+ t.Fatal(events)
+ }
+ tab.action("a", "34567")
+ if p.ready {
+ t.Fatal("complement foul should fail")
+ }
+ tab.action("a", "67")
+ if tab.phase != "waiting" {
+ t.Fatal("legal set did not settle")
+ }
+}
+func TestPaiGowEnvyEligibilityAndMultipleAwards(t *testing.T) {
+ for _, tt := range []struct {
+ enabled bool
+ stake, envy int
+ }{{true, 5, 25}, {true, 4, 0}, {false, 5, 0}} {
+ tab := pgTestTable(tt.enabled)
+ for _, name := range []string{"a", "b", "c"} {
+ tab.join(name)
+ w := &testWallet{chips: 100}
+ tab.bet(name, "main", 20, w)
+ if name == "a" {
+ tab.bet(name, "fortune", tt.stake, w)
+ }
+ }
+ tab.tick()
+ tab.tick()
+ // Own royal and dealer seven-card straight flush must NOT earn Envy.
+ tab.player("a").cards = pgCards("10s Js Qs Ks As 2h 3d")
+ tab.player("b").cards = pgCards("Ks Kh Kc Kd 2h 3c 7h")
+ tab.player("c").cards = pgCards("2s 3s 4s 5s 6s 8h 9d")
+ tab.dealer = pgCards("2h 3h 4h 5h 6h 7h 8h")
+ tab.dealerSplit = pgHouse(tab.dealer)
+ for _, name := range []string{"a", "b", "c"} {
+ tab.action(name, "house")
+ }
+ p := tab.player("a")
+ main := pgMainPay(20, pgMainResult(p.split, tab.dealerSplit, tab.dealer, PaiGowClassic, tab.tie), PaiGowClassic)
+ if want := main + tt.stake*151 + tt.envy; p.payout != want {
+ t.Fatalf("%+v payout=%d want=%d", tt, p.payout, want)
+ }
+ }
+}
+func TestPaiGowFaceUpAndPushAceHigh(t *testing.T) {
+ // A pair of aces or an ace-headed flush is NOT an ace-high pai gow; only
+ // a genuine best-five=ace-high triggers the automatic push.
+ aceHigh := pgCards("As Ks Qh 9c 7d 4s 3h")
+ pairAces := pgCards("As Ah Ks Qh 9c 7d 3s")
+ flushAce := pgCards("Ah Kh Qh Jh 9h 3d 2c")
+ for _, c := range []struct {
+ cards []card
+ push bool
+ }{{aceHigh, true}, {pairAces, false}, {flushAce, false}} {
+ if got := pgDealerPush(c.cards, PaiGowFaceUp) != ""; got != c.push {
+ t.Fatalf("%v push=%v", c.cards, got)
+ }
+ }
+ if pgDealerPush(aceHigh, PaiGowEZ) != "" {
+ t.Fatal("ace-high must not trigger the EZ queen-high push")
+ }
+ if pgDealerPush(pgCards("Qs Jh 9c 8d 6s 4h 2c"), PaiGowEZ) == "" {
+ t.Fatal("EZ queen-high detection drifted")
+ }
+ rates, _ := (PaiGowConfig{PushAceHigh: "5_12_40"}).pushAceRates()
+ if rates[0] != 5 || rates[1] != 12 {
+ t.Fatal(rates)
+ }
+ // Side-bet classes: plain, with-Joker, both-ace-high, and no win.
+ for _, tt := range []struct {
+ dealer, player []card
+ klass string
+ rate int
+ }{{
+ pgCards("As Kh Qd 9c 7d 4s 3h"), pgCards("2h 3c 4d 5s 6h 7d 8c"), "plain", 5,
+ }, {
+ pgCards("JK Kh Qd 9c 7d 4s 2h"), pgCards("2h 3c 4d 5s 6h 7d 8c"), "joker", 15,
+ }, {
+ pgCards("Ah Kh Qd 9c 7d 4s 3h"), pgCards("Ad Kd Qh Jc 9s 5d 2c"), "both", 40,
+ }, {
+ pgCards("2h 3c 4d 5s 6h 7d 8c"), pgCards("As Kh Qd 9c 7d 4s 3h"), "none", 0,
+ }} {
+ got := pgPushAceClass(tt.dealer, tt.player, [3]int{5, 15, 40})
+ if got.klass != tt.klass || got.rate != tt.rate {
+ t.Fatalf("class %v want %v/%d", got, tt.klass, tt.rate)
+ }
+ }
+ // Full engine pass on a Face Up table with the side bet.
+ cfg := TableConfig{ID: "pg", Game: GamePaiGow, BettingTicks: 1, PaiGow: PaiGowConfig{Variant: PaiGowFaceUp, PushAceHigh: "5_15_40", Envy: true, ActionTicks: 1}}.Normalize()
+ tab := newPaiGowTable(1, cfg, rand.New(rand.NewSource(5))).(*paiGowTable)
+ w := &testWallet{chips: 500}
+ tab.join("a")
+ tab.bet("a", "pushace", 10, w)
+ if len(w.open) > 0 {
+ t.Fatal("pushace before main")
+ }
+ tab.bet("a", "main", 20, w)
+ if events := tab.bet("a", "pushace", 11, w); len(w.open) != 1 || !strings.Contains(events[0].Message, "half the main wager") {
+ t.Fatal("pushace cap not enforced", events, w.open)
+ }
+ tab.bet("a", "pushace", 10, w)
+ tab.bet("a", "fortune", 5, w)
+ tab.action("a", "deal")
+ snap := tab.status("a")[0].Snapshot.(*PaiGowSnapshot)
+ // The dealer acts first and the reveal happens in the setting phase.
+ if len(snap.DealerHigh) != 5 || len(snap.DealerLow) != 2 {
+ t.Fatal("Face Up dealer was not revealed during setting")
+ }
+ // The player must still set (or time out) unless the round auto-pushed.
+ if tab.phase == "waiting" {
+ t.Fatal("round resolved before player set")
+ }
+ tab.action("a", "house")
+ if tab.phase != "waiting" || len(w.open) != 0 {
+ t.Fatal("Face Up settlement did not finish", tab.phase, w.open)
+ }
+ // Reconstruct the outcome class from the announced result.
+ p := tab.player("a")
+ main := pgMainPay(20, pgMainResult(p.split, tab.dealerSplit, tab.dealer, PaiGowFaceUp, tab.tie), PaiGowFaceUp)
+ expect := main
+ if row, win := pgFortune(p.cards, true); win {
+ expect += 5 * (row.Odds + 1) // the Fortune stake, before settlement resets it
+ }
+ if class := pgPushAceClass(tab.dealer, p.cards, [3]int{5, 15, 40}); class.klass != "none" {
+ expect += p.pushace.Total * (class.rate + 1)
+ }
+ if p.payout != expect {
+ t.Fatalf("payout %d want %d (dealer %v, result %s)", p.payout, expect, tab.dealer, p.result)
+ }
+}
+func TestPaiGowConfigurationAndRefund(t *testing.T) {
+ for _, c := range []TableConfig{{ID: "pg", Game: GamePaiGow, MaxPlayers: 7}, {ID: "pg", Game: GamePaiGow, PaiGow: PaiGowConfig{Variant: "fake"}}, {ID: "pg", Game: GamePaiGow, PaiGow: PaiGowConfig{ActionTicks: -1}}, {ID: "pg", Game: GamePaiGow, PaiGow: PaiGowConfig{Variant: PaiGowFaceUp}}, {ID: "pg", Game: GamePaiGow, PaiGow: PaiGowConfig{Variant: PaiGowFaceUp, PushAceHigh: "9_9_9"}}, {ID: "pg", Game: GamePaiGow, PaiGow: PaiGowConfig{Variant: PaiGowEZ, PushAceHigh: "5_15_40"}}, {ID: "bj", Game: GameBlackjack, PaiGow: PaiGowConfig{Envy: true}}} {
+ if c.Validate() == nil {
+ t.Fatal("accepted", c)
+ }
+ }
+ c := TableConfig{ID: "pg", Game: GamePaiGow}
+ if c.Validate() != nil || c.Normalize().MaxPlayers != 6 {
+ t.Fatal("defaults")
+ }
+ tab := pgTestTable(false)
+ w := &testWallet{chips: 100}
+ tab.join("a")
+ tab.bet("a", "fortune", 5, w)
+ if len(w.open) > 0 {
+ t.Fatal("side before main")
+ }
+ tab.bet("a", "main", 10, w)
+ tab.bet("a", "fortune", 5, w)
+ tab.refundAll()
+ if w.chips != 100 || len(w.open) > 0 {
+ t.Fatal("refund failed")
+ }
+}
diff --git a/internal/casino/registry.go b/internal/casino/registry.go
index dfce704..25fbce5 100644
--- a/internal/casino/registry.go
+++ b/internal/casino/registry.go
@@ -41,6 +41,20 @@ var tableGames map[GameName]tableGameDef
func init() {
tableGames = map[GameName]tableGameDef{
+ GamePaiGow: {
+ validate: validatePaiGow,
+ normalize: func(c TableConfig) TableConfig {
+ c.PaiGow = c.PaiGow.Normalize()
+ c.MaxPlayers = min(c.MaxPlayers, 6)
+ c.MaxBet = min(c.MaxBet, pgMaxWager)
+ return c
+ },
+ ruleBlockName: "pai_gow",
+ hasRuleBlock: func(c TableConfig) bool { return c.PaiGow != (PaiGowConfig{}) },
+ new: newPaiGowTable,
+ ruleText: paiGowRules,
+ helpTopic: func(TableConfig) string { return "pai gow poker" },
+ },
GameVideoPoker: {
validate: func(c TableConfig) error {
if c.MaxPlayers > 1 {
diff --git a/internal/casino/table_ux.go b/internal/casino/table_ux.go
index 7c3ab36..55c491b 100644
--- a/internal/casino/table_ux.go
+++ b/internal/casino/table_ux.go
@@ -40,6 +40,9 @@ func withTableHints(commands []MenuCommand, wagerRows []WagerRow) []MenuCommand
func (c TableConfig) RulesText() string { return rulesTextOnTable(c) }
func (c TableConfig) Label() string {
+ if c.Game == GamePaiGow {
+ return c.PaiGow.Label()
+ }
if c.Game == GameVideoPoker {
return c.VideoPoker.CabinetLabel()
}
diff --git a/internal/casino/types.go b/internal/casino/types.go
index b863ee7..1b0826a 100644
--- a/internal/casino/types.go
+++ b/internal/casino/types.go
@@ -14,6 +14,7 @@ func betRangeText(minBet, maxBet int) string {
type GameName string
const (
+ GamePaiGow GameName = "pai_gow"
GameVideoPoker GameName = "video_poker"
GameSlots GameName = "slots"
GameBlackjack GameName = "blackjack"
@@ -133,6 +134,7 @@ type TableConfig struct {
Roulette RouletteConfig `yaml:"roulette,omitempty"`
Craps CrapsConfig `yaml:"craps,omitempty"`
VideoPoker VideoPokerConfig `yaml:"video_poker,omitempty"`
+ PaiGow PaiGowConfig `yaml:"pai_gow,omitempty"`
}
type MachineConfig struct {
diff --git a/internal/casino/video_poker_config.go b/internal/casino/video_poker_config.go
index 8d67252..0a39913 100644
--- a/internal/casino/video_poker_config.go
+++ b/internal/casino/video_poker_config.go
@@ -56,7 +56,7 @@ var cabinetGames = map[string][]string{
// Each tuple is low, normal, full. These are named published schedules, not
// interpolated payouts. Full means the highest offered on this cabinet, not
-// a promise of identical RTP across games. Sources: building_guide/video_poker.md.
+// a promise of identical RTP across games. Sources: dev_guide/video_poker.md.
var cabinetSchedules = map[string]map[string][3]string{
CabinetClassic: {
"jacks_or_better": {"7/5", "8/5", "9/6"},
diff --git a/internal/casino/video_poker_rules.go b/internal/casino/video_poker_rules.go
index 340815d..bfff0c4 100644
--- a/internal/casino/video_poker_rules.go
+++ b/internal/casino/video_poker_rules.go
@@ -15,7 +15,7 @@ var pokerCategories = []string{"Natural royal flush", "Royal flush", "Four deuce
// pokerPayTable resolves the per-coin (five-coin) rates for a resolved
// game/pay-table pair. Every listed schedule is a published one; see
-// building_guide/video_poker.md for the sources.
+// dev_guide/video_poker.md for the sources.
func pokerPayTable(c VideoPokerConfig) (pokerSchedule, bool) {
c = c.Normalize()
if c.Variant == "" {