games: the hand that becomes two, and the bet that has to follow it
Blackjack has a split. It was the last rule missing from a game that has been live for a week, and it is the only move in blackjack that takes chips out of your stack *after* the cards are out — which is most of what there is to get wrong about it. So the state stops pretending. State.Player is gone; there is a slice of Hands, each with its own cards, its own bet, its own outcome and its own payout, and an Active index the player works left to right. Settle runs per hand and rakes per hand: netting them against each other first would mean a player who won one and lost one paid no rake at all, which is not a rake, it's a discount for splitting. The web layer takes the second bet before the move and hands it straight back if the engine refuses — the same shape double already used, except double was staking st.Bet, the whole table's stake, which was the same number as the hand's until today and is now emphatically not. DoubleCost/SplitCost are the active hand's, and the felt would have found this by charging you 300 to double the third hand of a split. The rules that cost money if you guess them: split aces get one card each and no say (a pair of aces is otherwise the best hand in the game, forever), 21 on a split hand is twenty-one and not a natural (it does not pay 3:2 — the test that pins this is the most expensive one in the file), same rank rather than same value (a king and a queen are not a pair), four hands maximum, double after split allowed, and if every hand busts the dealer does not turn over. A live hand outlives a deploy, so State.UnmarshalJSON still reads the old blobs: "player" with no "hands" becomes one hand holding the whole stake. Without it, a player mid-hand at restart is a player whose cards vanished — which is not a decode error, and would not have looked like one. On the felt a hand is now a box with its own spot, and a split is a card lifting out of one hand into a new one with a second stack of chips flying after it from your pile. Verified in a browser against a real pair: chips 4738 -> 4638 on the split, two hands played out, one push and one loss, "Down on the deal. -100", 4738 back. Three hands stack without collision at 390px. Settled hands come back to full brightness — dimming means "not your turn", and when the deal is over they are the thing you are reading. Claude-Session: https://claude.ai/code/session_013M5nD7PgUboJXoDcYHzpuJ
This commit is contained in:
@@ -15,6 +15,7 @@
|
||||
package blackjack
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
@@ -29,15 +30,21 @@ var (
|
||||
ErrNotYourTurn = errors.New("blackjack: it is not the player's turn to act")
|
||||
ErrUnknownMove = errors.New("blackjack: unknown move")
|
||||
ErrCantDouble = errors.New("blackjack: double is only allowed on the opening two cards")
|
||||
ErrCantSplit = errors.New("blackjack: split is only allowed on two cards of the same rank")
|
||||
ErrDeckExhausted = errors.New("blackjack: the shoe is empty")
|
||||
ErrBadBet = errors.New("blackjack: bet must be positive")
|
||||
)
|
||||
|
||||
// MaxHands is how many hands one deal can turn into: the opening hand, plus
|
||||
// three splits. Four is the usual house limit and it is also the point past
|
||||
// which the felt runs out of room.
|
||||
const MaxHands = 4
|
||||
|
||||
// Phase is whose turn it is.
|
||||
type Phase string
|
||||
|
||||
const (
|
||||
PhasePlayer Phase = "player" // the player is acting
|
||||
PhasePlayer Phase = "player" // the player is acting on the active hand
|
||||
PhaseDealer Phase = "dealer" // transient: the dealer is drawing out
|
||||
PhaseDone Phase = "done" // settled, Outcome and Payout are final
|
||||
)
|
||||
@@ -72,37 +79,77 @@ type Rules struct {
|
||||
|
||||
// DefaultRules match the blackjack gogobee has been dealing in Matrix for years:
|
||||
// six decks, 3:2 on a natural, dealer hits soft 17. The rake is the one new term
|
||||
// — see Settle for exactly what it touches.
|
||||
// — see settle for exactly what it touches.
|
||||
func DefaultRules() Rules {
|
||||
return Rules{Decks: 6, BlackjackPays: 1.5, DealerHitsSoft17: true, RakePct: 0.05}
|
||||
}
|
||||
|
||||
// State is one hand of heads-up blackjack: one player, one dealer. Splitting
|
||||
// isn't in v1, so there's exactly one player hand.
|
||||
// Hand is one hand the player is holding, with the chips that are on it.
|
||||
//
|
||||
// A deal starts with one. A split turns one into two, and the new hand carries a
|
||||
// bet of its own — which is the whole reason split is not just a card trick: it
|
||||
// is the only move in the game that takes more chips out of a player's stack
|
||||
// *after* the cards are out.
|
||||
type Hand struct {
|
||||
Cards []cards.Card `json:"cards"`
|
||||
Bet int64 `json:"bet"`
|
||||
Doubled bool `json:"doubled"`
|
||||
|
||||
// Split marks a hand that came out of a split. It exists for one rule: 21 on
|
||||
// a split hand is twenty-one, not a natural, and is paid 1:1 like any other.
|
||||
// Otherwise splitting aces would print money.
|
||||
Split bool `json:"split"`
|
||||
|
||||
// Done means this hand will not be acted on again: it stood, it busted, it
|
||||
// doubled, or it is a split ace, which gets exactly one card and no say.
|
||||
Done bool `json:"done"`
|
||||
|
||||
Outcome Outcome `json:"outcome"`
|
||||
Payout int64 `json:"payout"` // stake plus winnings, net of rake. Zero on a loss.
|
||||
Rake int64 `json:"rake"`
|
||||
}
|
||||
|
||||
// Value totals the hand. See HandValue.
|
||||
func (h Hand) Value() (int, bool) { return HandValue(h.Cards) }
|
||||
|
||||
// Natural reports a blackjack: 21 on the opening two cards of a hand that was
|
||||
// dealt, not split.
|
||||
func (h Hand) Natural() bool { return !h.Split && IsBlackjack(h.Cards) }
|
||||
|
||||
// State is one deal of heads-up blackjack: the player's hands against the
|
||||
// dealer's one.
|
||||
type State struct {
|
||||
Rules Rules `json:"rules"`
|
||||
Deck cards.Deck `json:"deck"` // the shoe, top card first — never shown to the browser
|
||||
Player []cards.Card `json:"player"`
|
||||
Dealer []cards.Card `json:"dealer"`
|
||||
|
||||
Bet int64 `json:"bet"` // chips at risk; doubles on a double-down
|
||||
Doubled bool `json:"doubled"`
|
||||
// Hands is always at least one, and Active indexes the one being played. The
|
||||
// player works left to right: a hand is finished before the next is looked at,
|
||||
// which is both how a real table does it and what keeps the felt legible.
|
||||
Hands []Hand `json:"hands"`
|
||||
Active int `json:"active"`
|
||||
|
||||
Phase Phase `json:"phase"`
|
||||
Outcome Outcome `json:"outcome"`
|
||||
Outcome Outcome `json:"outcome"` // the deal as a whole; per-hand outcomes live on the hands
|
||||
|
||||
// Payout is what returns to the player's chip stack when the hand is done:
|
||||
// stake plus winnings, net of rake. Zero on a loss. Rake is the house's cut,
|
||||
// recorded so the ledger can account for every chip that left the table.
|
||||
// Bet, Payout and Rake are the totals across every hand: what the player has
|
||||
// staked, what comes back, and what the house kept. The ledger and the chip
|
||||
// stack only ever deal in these.
|
||||
Bet int64 `json:"bet"`
|
||||
Payout int64 `json:"payout"`
|
||||
Rake int64 `json:"rake"`
|
||||
}
|
||||
|
||||
// Event is something the table can narrate or animate. The engine emits them
|
||||
// instead of drawing anything itself.
|
||||
//
|
||||
// Hand is which of the player's hands an event landed on — meaningless for the
|
||||
// dealer's, and the reason it is here at all is that after a split the browser
|
||||
// has to know which fan a card is flying to.
|
||||
type Event struct {
|
||||
Kind string `json:"kind"` // "deal" | "player_card" | "dealer_card" | "reveal" | "settle"
|
||||
Kind string `json:"kind"` // "deal" | "player_card" | "dealer_card" | "split" | "reveal" | "settle"
|
||||
Card *cards.Card `json:"card,omitempty"`
|
||||
Hand int `json:"hand"`
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
@@ -113,6 +160,7 @@ const (
|
||||
Hit Move = "hit"
|
||||
Stand Move = "stand"
|
||||
Double Move = "double"
|
||||
Split Move = "split"
|
||||
)
|
||||
|
||||
// HandValue totals a hand, counting each ace as 11 until that would bust, then
|
||||
@@ -161,36 +209,52 @@ func New(bet int64, r Rules, rng *rand.Rand) (State, []Event, error) {
|
||||
deck := cards.NewDeck(r.Decks)
|
||||
deck.Shuffle(rng)
|
||||
|
||||
s := State{Rules: r, Deck: deck, Bet: bet, Phase: PhasePlayer}
|
||||
s := State{
|
||||
Rules: r,
|
||||
Deck: deck,
|
||||
Hands: []Hand{{Bet: bet}},
|
||||
Bet: bet,
|
||||
Phase: PhasePlayer,
|
||||
}
|
||||
evs := []Event{{Kind: "deal"}}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := s.draw(&s.Player, "player_card", &evs); err != nil {
|
||||
if err := s.hit(0, &evs); err != nil {
|
||||
return State{}, nil, err
|
||||
}
|
||||
if err := s.draw(&s.Dealer, "dealer_card", &evs); err != nil {
|
||||
if err := s.drawDealer(&evs); err != nil {
|
||||
return State{}, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// A natural on either side ends it before the player ever acts.
|
||||
if IsBlackjack(s.Player) || IsBlackjack(s.Dealer) {
|
||||
if s.Hands[0].Natural() || IsBlackjack(s.Dealer) {
|
||||
s.settle(&evs)
|
||||
}
|
||||
return s, evs, nil
|
||||
}
|
||||
|
||||
// draw takes one card off the shoe onto the given hand and records the event.
|
||||
// Pointer receiver: it mutates the deck and the hand together, and neither may
|
||||
// end up applied to a stale copy of the state.
|
||||
func (s *State) draw(hand *[]cards.Card, kind string, evs *[]Event) error {
|
||||
// hit puts one card on a player hand. Pointer receiver: it mutates the deck and
|
||||
// the hand together, and neither may end up applied to a stale copy of the state.
|
||||
func (s *State) hit(i int, evs *[]Event) error {
|
||||
c, ok := s.Deck.Draw()
|
||||
if !ok {
|
||||
return ErrDeckExhausted
|
||||
}
|
||||
*hand = append(*hand, c)
|
||||
s.Hands[i].Cards = append(s.Hands[i].Cards, c)
|
||||
card := c
|
||||
*evs = append(*evs, Event{Kind: kind, Card: &card})
|
||||
*evs = append(*evs, Event{Kind: "player_card", Card: &card, Hand: i})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *State) drawDealer(evs *[]Event) error {
|
||||
c, ok := s.Deck.Draw()
|
||||
if !ok {
|
||||
return ErrDeckExhausted
|
||||
}
|
||||
s.Dealer = append(s.Dealer, c)
|
||||
card := c
|
||||
*evs = append(*evs, Event{Kind: "dealer_card", Card: &card})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -210,39 +274,120 @@ func ApplyMove(s State, m Move) (State, []Event, error) {
|
||||
if s.Phase != PhasePlayer {
|
||||
return s, nil, ErrNotYourTurn
|
||||
}
|
||||
if m == Double && len(s.Player) != 2 {
|
||||
switch m {
|
||||
case Hit, Stand, Double, Split:
|
||||
default:
|
||||
return s, nil, ErrUnknownMove
|
||||
}
|
||||
if m == Double && !s.CanDouble() {
|
||||
// Doubling means doubling the stake for exactly one more card. Only ever
|
||||
// legal on the opening two — after that you're just describing a hit.
|
||||
return s, nil, ErrCantDouble
|
||||
}
|
||||
if m != Hit && m != Stand && m != Double {
|
||||
return s, nil, ErrUnknownMove
|
||||
if m == Split && !s.CanSplit() {
|
||||
return s, nil, ErrCantSplit
|
||||
}
|
||||
|
||||
i := s.Active
|
||||
evs := []Event{}
|
||||
|
||||
if m == Double {
|
||||
s.Bet *= 2
|
||||
s.Doubled = true
|
||||
}
|
||||
switch m {
|
||||
case Split:
|
||||
// The second card moves to a hand of its own, carrying a bet the same size
|
||||
// as the one it came from, and both hands are topped up to two cards.
|
||||
h := &s.Hands[i]
|
||||
moved := h.Cards[1]
|
||||
h.Cards = h.Cards[:1]
|
||||
h.Split = true
|
||||
|
||||
if m == Hit || m == Double {
|
||||
if err := s.draw(&s.Player, "player_card", &evs); err != nil {
|
||||
fresh := Hand{Cards: []cards.Card{moved}, Bet: h.Bet, Split: true}
|
||||
s.Hands = append(s.Hands, Hand{})
|
||||
copy(s.Hands[i+2:], s.Hands[i+1:]) // the new hand sits immediately to the right
|
||||
s.Hands[i+1] = fresh
|
||||
s.Bet += fresh.Bet
|
||||
|
||||
evs = append(evs, Event{Kind: "split", Hand: i})
|
||||
if err := s.hit(i, &evs); err != nil {
|
||||
return s, nil, err
|
||||
}
|
||||
if v, _ := HandValue(s.Player); v > 21 {
|
||||
s.settle(&evs) // bust; the dealer never has to play
|
||||
if err := s.hit(i+1, &evs); err != nil {
|
||||
return s, nil, err
|
||||
}
|
||||
|
||||
// Split aces get one card each and no say in it. Without this rule a pair
|
||||
// of aces is the best hand in the game and everybody would split them
|
||||
// forever; with it, splitting aces is a gamble like everything else.
|
||||
if moved.Rank == cards.Ace {
|
||||
s.Hands[i].Done = true
|
||||
s.Hands[i+1].Done = true
|
||||
}
|
||||
// A hand that has just been dealt a card can still be sitting on 21, and a
|
||||
// 21 has nothing left to decide.
|
||||
s.finishIfDone(i)
|
||||
s.finishIfDone(i + 1)
|
||||
|
||||
case Double:
|
||||
h := &s.Hands[i]
|
||||
s.Bet += h.Bet
|
||||
h.Bet *= 2
|
||||
h.Doubled = true
|
||||
// Announced before the card, because that is the order it happens in: the
|
||||
// chips go down, and *then* you find out what you bought with them.
|
||||
evs = append(evs, Event{Kind: "double", Hand: i})
|
||||
if err := s.hit(i, &evs); err != nil {
|
||||
return s, nil, err
|
||||
}
|
||||
h.Done = true // one card, and that is the deal you made
|
||||
|
||||
case Hit:
|
||||
if err := s.hit(i, &evs); err != nil {
|
||||
return s, nil, err
|
||||
}
|
||||
s.finishIfDone(i)
|
||||
|
||||
case Stand:
|
||||
s.Hands[i].Done = true
|
||||
}
|
||||
|
||||
s.advance(&evs)
|
||||
return s, evs, nil
|
||||
}
|
||||
if m == Hit {
|
||||
return s, evs, nil // still the player's turn
|
||||
|
||||
// finishIfDone closes a hand that has nothing left to decide: it busted, or it
|
||||
// is sitting on 21 and would only be hitting it to be polite.
|
||||
func (s *State) finishIfDone(i int) {
|
||||
if v, _ := s.Hands[i].Value(); v >= 21 {
|
||||
s.Hands[i].Done = true
|
||||
}
|
||||
}
|
||||
|
||||
// Stand, or a double that survived its card: the dealer draws out.
|
||||
// advance moves to the next hand still owed a decision. When there are none, the
|
||||
// dealer plays — unless every hand busted, in which case there is nothing to beat
|
||||
// and the dealer does not bother turning over.
|
||||
func (s *State) advance(evs *[]Event) {
|
||||
for i := s.Active; i < len(s.Hands); i++ {
|
||||
if !s.Hands[i].Done {
|
||||
s.Active = i
|
||||
return
|
||||
}
|
||||
}
|
||||
s.Active = len(s.Hands) - 1
|
||||
|
||||
if s.allBust() {
|
||||
s.settle(evs)
|
||||
return
|
||||
}
|
||||
s.Phase = PhaseDealer
|
||||
s.dealerPlay(&evs)
|
||||
return s, evs, nil
|
||||
s.dealerPlay(evs)
|
||||
}
|
||||
|
||||
func (s *State) allBust() bool {
|
||||
for _, h := range s.Hands {
|
||||
if v, _ := h.Value(); v <= 21 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// dealerPlay draws the dealer out to the house rule, then settles. The dealer
|
||||
@@ -255,74 +400,104 @@ func (s *State) dealerPlay(evs *[]Event) {
|
||||
if v >= 17 && !hitSoft17 {
|
||||
break
|
||||
}
|
||||
if err := s.draw(&s.Dealer, "dealer_card", evs); err != nil {
|
||||
if err := s.drawDealer(evs); err != nil {
|
||||
break // shoe ran dry mid-draw; settle on what's on the table
|
||||
}
|
||||
}
|
||||
s.settle(evs)
|
||||
}
|
||||
|
||||
// settle decides the outcome and the payout, and is the only place chips are
|
||||
// computed.
|
||||
// settle decides every hand against the dealer and adds up what comes back. It
|
||||
// is the only place chips are computed.
|
||||
//
|
||||
// The rake comes off winnings, never off the stake: a player who pushes gets
|
||||
// exactly their bet back, and a player who loses is never charged for the
|
||||
// privilege. The house only takes a cut of money the house was going to hand
|
||||
// over anyway. That's a rake, as opposed to a fee for showing up.
|
||||
//
|
||||
// Each hand is raked on its own winnings. Netting the hands against each other
|
||||
// first would let a player who won one and lost one pay no rake at all, which is
|
||||
// not a rake, it's a discount for splitting.
|
||||
func (s *State) settle(evs *[]Event) {
|
||||
playerVal, _ := HandValue(s.Player)
|
||||
dealerVal, _ := HandValue(s.Dealer)
|
||||
playerBJ := IsBlackjack(s.Player)
|
||||
dealerBJ := IsBlackjack(s.Dealer)
|
||||
|
||||
// profit is what the player wins on top of their stake. Negative means the
|
||||
s.Payout, s.Rake = 0, 0
|
||||
for i := range s.Hands {
|
||||
h := &s.Hands[i]
|
||||
playerVal, _ := h.Value()
|
||||
|
||||
// profit is what this hand wins on top of its stake. Negative means the
|
||||
// stake is gone.
|
||||
var profit int64
|
||||
|
||||
switch {
|
||||
case playerVal > 21:
|
||||
s.Outcome = OutcomeBust
|
||||
profit = -s.Bet
|
||||
case playerBJ && dealerBJ:
|
||||
s.Outcome = OutcomePush
|
||||
case playerBJ:
|
||||
s.Outcome = OutcomeBlackjack
|
||||
profit = int64(math.Floor(float64(s.Bet) * s.Rules.BlackjackPays))
|
||||
h.Outcome = OutcomeBust
|
||||
profit = -h.Bet
|
||||
case h.Natural() && dealerBJ:
|
||||
h.Outcome = OutcomePush
|
||||
case h.Natural():
|
||||
h.Outcome = OutcomeBlackjack
|
||||
profit = int64(math.Floor(float64(h.Bet) * s.Rules.BlackjackPays))
|
||||
case dealerBJ:
|
||||
s.Outcome = OutcomeLose
|
||||
profit = -s.Bet
|
||||
h.Outcome = OutcomeLose
|
||||
profit = -h.Bet
|
||||
case dealerVal > 21:
|
||||
s.Outcome = OutcomeDealerBust
|
||||
profit = s.Bet
|
||||
h.Outcome = OutcomeDealerBust
|
||||
profit = h.Bet
|
||||
case playerVal > dealerVal:
|
||||
s.Outcome = OutcomeWin
|
||||
profit = s.Bet
|
||||
h.Outcome = OutcomeWin
|
||||
profit = h.Bet
|
||||
case playerVal == dealerVal:
|
||||
s.Outcome = OutcomePush
|
||||
h.Outcome = OutcomePush
|
||||
default:
|
||||
s.Outcome = OutcomeLose
|
||||
profit = -s.Bet
|
||||
h.Outcome = OutcomeLose
|
||||
profit = -h.Bet
|
||||
}
|
||||
|
||||
if profit > 0 {
|
||||
s.Rake = int64(math.Floor(float64(profit) * s.Rules.RakePct))
|
||||
if s.Rake < 0 {
|
||||
s.Rake = 0
|
||||
h.Rake = int64(math.Floor(float64(profit) * s.Rules.RakePct))
|
||||
if h.Rake < 0 {
|
||||
h.Rake = 0
|
||||
}
|
||||
profit -= s.Rake
|
||||
profit -= h.Rake
|
||||
}
|
||||
if profit < 0 {
|
||||
s.Payout = 0 // stake is lost; nothing comes back
|
||||
h.Payout = 0 // stake is lost; nothing comes back
|
||||
} else {
|
||||
s.Payout = s.Bet + profit
|
||||
h.Payout = h.Bet + profit
|
||||
}
|
||||
|
||||
s.Payout += h.Payout
|
||||
s.Rake += h.Rake
|
||||
}
|
||||
|
||||
s.Outcome = s.overall()
|
||||
s.Phase = PhaseDone
|
||||
*evs = append(*evs, Event{Kind: "settle", Text: string(s.Outcome)})
|
||||
}
|
||||
|
||||
// Net is what the hand did to the player's chip stack: payout minus the stake
|
||||
// they put up. Negative on a loss, zero on a push.
|
||||
// overall is the deal's outcome as one word, which is what the ledger and the
|
||||
// history line want. With one hand it is simply that hand's. With several there
|
||||
// is no honest single word for "won one, lost one", so it reports what the deal
|
||||
// did to the player's chips, which is the thing anybody actually means.
|
||||
func (s State) overall() Outcome {
|
||||
if len(s.Hands) == 1 {
|
||||
return s.Hands[0].Outcome
|
||||
}
|
||||
switch net := s.Payout - s.Bet; {
|
||||
case net > 0:
|
||||
return OutcomeWin
|
||||
case net < 0:
|
||||
return OutcomeLose
|
||||
default:
|
||||
return OutcomePush
|
||||
}
|
||||
}
|
||||
|
||||
// Net is what the deal did to the player's chip stack: everything paid out minus
|
||||
// everything staked. Negative on a loss, zero on a push.
|
||||
func (s State) Net() int64 {
|
||||
if s.Phase != PhaseDone {
|
||||
return 0
|
||||
@@ -330,17 +505,85 @@ func (s State) Net() int64 {
|
||||
return s.Payout - s.Bet
|
||||
}
|
||||
|
||||
// Hand returns the hand being played. There is always one.
|
||||
func (s State) Hand() Hand {
|
||||
if s.Active < 0 || s.Active >= len(s.Hands) {
|
||||
return Hand{}
|
||||
}
|
||||
return s.Hands[s.Active]
|
||||
}
|
||||
|
||||
// CanDouble reports whether Double is legal right now — the shell asks this to
|
||||
// decide whether to light the button up.
|
||||
func (s State) CanDouble() bool {
|
||||
return s.Phase == PhasePlayer && len(s.Player) == 2
|
||||
h := s.Hand()
|
||||
return s.Phase == PhasePlayer && !h.Done && len(h.Cards) == 2
|
||||
}
|
||||
|
||||
// CanSplit reports whether Split is legal: two cards of the same rank, and room
|
||||
// at the table for another hand.
|
||||
//
|
||||
// Same *rank*, not same value: a king and a queen are both worth ten and are not
|
||||
// a pair, which is the stricter of the two house rules and the one that doesn't
|
||||
// need explaining on the felt.
|
||||
func (s State) CanSplit() bool {
|
||||
h := s.Hand()
|
||||
if s.Phase != PhasePlayer || h.Done || len(h.Cards) != 2 || len(s.Hands) >= MaxHands {
|
||||
return false
|
||||
}
|
||||
return h.Cards[0].Rank == h.Cards[1].Rank
|
||||
}
|
||||
|
||||
// SplitCost is what splitting the active hand would take out of the player's
|
||||
// stack: another bet the same size as the one already on it. The shell has to
|
||||
// take these chips before the move, because a split the player cannot cover is
|
||||
// not a legal move.
|
||||
func (s State) SplitCost() int64 { return s.Hand().Bet }
|
||||
|
||||
// DoubleCost is the same idea for a double: the stake again.
|
||||
func (s State) DoubleCost() int64 { return s.Hand().Bet }
|
||||
|
||||
// clone deep-copies the slices so a derived state shares no backing array with
|
||||
// the one it came from.
|
||||
func (s State) clone() State {
|
||||
s.Deck = append(cards.Deck(nil), s.Deck...)
|
||||
s.Player = append([]cards.Card(nil), s.Player...)
|
||||
s.Dealer = append([]cards.Card(nil), s.Dealer...)
|
||||
hands := make([]Hand, len(s.Hands))
|
||||
copy(hands, s.Hands)
|
||||
for i := range hands {
|
||||
hands[i].Cards = append([]cards.Card(nil), hands[i].Cards...)
|
||||
}
|
||||
s.Hands = hands
|
||||
return s
|
||||
}
|
||||
|
||||
// UnmarshalJSON reads a state, including one written before split existed.
|
||||
//
|
||||
// A live hand outlives a deploy: it is a blob in the database, and somebody is
|
||||
// mid-hand when the new binary starts. Those blobs have a "player" array and no
|
||||
// "hands", and without this they would come back as a state with no hands at all
|
||||
// — which is not a decoding error, it's a player whose cards vanished. So the old
|
||||
// shape is read as what it always was: one hand, holding the whole stake.
|
||||
func (s *State) UnmarshalJSON(b []byte) error {
|
||||
type state State // shed the method, or this recurses forever
|
||||
var v struct {
|
||||
state
|
||||
Player []cards.Card `json:"player"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
*s = State(v.state)
|
||||
if len(s.Hands) == 0 && len(v.Player) > 0 {
|
||||
s.Hands = []Hand{{
|
||||
Cards: v.Player,
|
||||
Bet: s.Bet,
|
||||
Outcome: s.Outcome,
|
||||
Payout: s.Payout,
|
||||
Rake: s.Rake,
|
||||
Done: s.Phase == PhaseDone,
|
||||
}}
|
||||
s.Active = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func TestIsBlackjack_OnlyOnTwoCards(t *testing.T) {
|
||||
// deal so the payout math can be checked case by case.
|
||||
func settleWith(t *testing.T, r Rules, bet int64, player, dealer []cards.Card) State {
|
||||
t.Helper()
|
||||
s := State{Rules: r, Bet: bet, Player: player, Dealer: dealer}
|
||||
s := State{Rules: r, Bet: bet, Hands: []Hand{{Cards: player, Bet: bet}}, Dealer: dealer}
|
||||
evs := []Event{}
|
||||
s.settle(&evs)
|
||||
if s.Phase != PhaseDone {
|
||||
@@ -164,8 +164,8 @@ func TestNew_DealsFourCardsAndAskThePlayer(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Player) != 2 || len(s.Dealer) != 2 {
|
||||
t.Fatalf("dealt %d/%d cards, want 2/2", len(s.Player), len(s.Dealer))
|
||||
if len(s.Hands[0].Cards) != 2 || len(s.Dealer) != 2 {
|
||||
t.Fatalf("dealt %d/%d cards, want 2/2", len(s.Hands[0].Cards), len(s.Dealer))
|
||||
}
|
||||
if len(s.Deck) != 6*52-4 {
|
||||
t.Fatalf("shoe has %d cards left, want %d", len(s.Deck), 6*52-4)
|
||||
@@ -174,7 +174,7 @@ func TestNew_DealsFourCardsAndAskThePlayer(t *testing.T) {
|
||||
t.Fatal("no deal event")
|
||||
}
|
||||
// Unless somebody was dealt a natural, it's the player's move.
|
||||
if !IsBlackjack(s.Player) && !IsBlackjack(s.Dealer) && s.Phase != PhasePlayer {
|
||||
if !IsBlackjack(s.Hands[0].Cards) && !IsBlackjack(s.Dealer) && s.Phase != PhasePlayer {
|
||||
t.Fatalf("phase = %q, want %q", s.Phase, PhasePlayer)
|
||||
}
|
||||
}
|
||||
@@ -195,7 +195,7 @@ func TestNew_NaturalSettlesImmediately(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if IsBlackjack(s.Player) {
|
||||
if IsBlackjack(s.Hands[0].Cards) {
|
||||
if s.Phase != PhaseDone {
|
||||
t.Fatalf("seed %d: player has a natural but phase = %q", seed, s.Phase)
|
||||
}
|
||||
@@ -225,7 +225,7 @@ func TestApplyMove_HitUntilBustSettles(t *testing.T) {
|
||||
if s.Phase != PhaseDone {
|
||||
t.Fatal("hitting a dozen times never ended the hand")
|
||||
}
|
||||
if v, _ := HandValue(s.Player); v <= 21 {
|
||||
if v, _ := HandValue(s.Hands[0].Cards); v <= 21 {
|
||||
t.Fatalf("player stopped at %d without busting — the loop should have gone over", v)
|
||||
}
|
||||
if s.Outcome != OutcomeBust || s.Payout != 0 {
|
||||
@@ -285,11 +285,11 @@ func TestApplyMove_DoubleTakesOneCardThenStands(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !s.Doubled || s.Bet != 200 {
|
||||
t.Fatalf("bet = %d doubled = %v, want 200/true", s.Bet, s.Doubled)
|
||||
if !s.Hands[0].Doubled || s.Bet != 200 {
|
||||
t.Fatalf("bet = %d doubled = %v, want 200/true", s.Bet, s.Hands[0].Doubled)
|
||||
}
|
||||
if len(s.Player) != 3 {
|
||||
t.Fatalf("player has %d cards after a double, want exactly 3", len(s.Player))
|
||||
if len(s.Hands[0].Cards) != 3 {
|
||||
t.Fatalf("player has %d cards after a double, want exactly 3", len(s.Hands[0].Cards))
|
||||
}
|
||||
if s.Phase != PhaseDone {
|
||||
t.Fatal("a double must end the player's turn")
|
||||
@@ -378,9 +378,9 @@ func TestNew_IsReproducibleFromItsSeed(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cards.Hand(a.Player) != cards.Hand(b.Player) || cards.Hand(a.Dealer) != cards.Hand(b.Dealer) {
|
||||
if cards.Hand(a.Hands[0].Cards) != cards.Hand(b.Hands[0].Cards) || cards.Hand(a.Dealer) != cards.Hand(b.Dealer) {
|
||||
t.Fatalf("same seed dealt different hands: %s/%s vs %s/%s",
|
||||
cards.Hand(a.Player), cards.Hand(a.Dealer), cards.Hand(b.Player), cards.Hand(b.Dealer))
|
||||
cards.Hand(a.Hands[0].Cards), cards.Hand(a.Dealer), cards.Hand(b.Hands[0].Cards), cards.Hand(b.Dealer))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,21 +395,21 @@ func TestApplyMove_DerivedStatesDoNotShareCards(t *testing.T) {
|
||||
if s.Phase == PhaseDone {
|
||||
t.Skip("dealt a natural")
|
||||
}
|
||||
before := cards.Hand(s.Player)
|
||||
before := cards.Hand(s.Hands[0].Cards)
|
||||
|
||||
a, _, err := ApplyMove(s, Hit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
aHand := cards.Hand(a.Player)
|
||||
aHand := cards.Hand(a.Hands[0].Cards)
|
||||
|
||||
if _, _, err := ApplyMove(s, Hit); err != nil { // same start, applied again
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := cards.Hand(a.Player); got != aHand {
|
||||
if got := cards.Hand(a.Hands[0].Cards); got != aHand {
|
||||
t.Fatalf("the first hand changed under us: %q became %q", aHand, got)
|
||||
}
|
||||
if got := cards.Hand(s.Player); got != before {
|
||||
if got := cards.Hand(s.Hands[0].Cards); got != before {
|
||||
t.Fatalf("ApplyMove mutated the state it was given: %q became %q", before, got)
|
||||
}
|
||||
}
|
||||
|
||||
374
internal/games/blackjack/split_test.go
Normal file
374
internal/games/blackjack/split_test.go
Normal file
@@ -0,0 +1,374 @@
|
||||
package blackjack
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"pete/internal/games/cards"
|
||||
)
|
||||
|
||||
// Split is the only move in blackjack that takes chips out of a player's stack
|
||||
// after the cards are already out, so most of what can go wrong with it is money
|
||||
// rather than cards. These tests are mostly about the money.
|
||||
|
||||
// dealt builds a state mid-hand: the player holding `player`, the dealer showing
|
||||
// `dealer`, and a shoe stacked with `shoe` so the next cards are known. It skips
|
||||
// New() because a split needs a pair, and waiting for one out of a shuffled shoe
|
||||
// is not a test, it's a slot machine.
|
||||
func dealt(bet int64, player, dealer, shoe []cards.Card) State {
|
||||
return State{
|
||||
Rules: DefaultRules(),
|
||||
Deck: cards.Deck(shoe),
|
||||
Dealer: dealer,
|
||||
Hands: []Hand{{Cards: player, Bet: bet}},
|
||||
Bet: bet,
|
||||
Phase: PhasePlayer,
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitDealsTwoHandsAndTakesASecondBet(t *testing.T) {
|
||||
s := dealt(100,
|
||||
hand(8, 8),
|
||||
hand(cards.King, 6),
|
||||
hand(3, 9, 5, 5), // one card to each hand, then whatever the dealer needs
|
||||
)
|
||||
if !s.CanSplit() {
|
||||
t.Fatal("CanSplit says no to a pair of eights")
|
||||
}
|
||||
if s.SplitCost() != 100 {
|
||||
t.Fatalf("SplitCost = %d, want the same bet again (100)", s.SplitCost())
|
||||
}
|
||||
|
||||
s, evs, err := ApplyMove(s, Split)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Hands) != 2 {
|
||||
t.Fatalf("split made %d hands, want 2", len(s.Hands))
|
||||
}
|
||||
for i, h := range s.Hands {
|
||||
if len(h.Cards) != 2 {
|
||||
t.Errorf("hand %d holds %d cards after the split, want 2", i, len(h.Cards))
|
||||
}
|
||||
if h.Cards[0].Rank != 8 {
|
||||
t.Errorf("hand %d didn't keep an eight: %s", i, cards.Hand(h.Cards))
|
||||
}
|
||||
if h.Bet != 100 {
|
||||
t.Errorf("hand %d carries a bet of %d, want 100", i, h.Bet)
|
||||
}
|
||||
if !h.Split {
|
||||
t.Errorf("hand %d isn't marked as split", i)
|
||||
}
|
||||
}
|
||||
// The whole point, in one line: there is twice as much on the table as there
|
||||
// was, and the shell has to have taken it.
|
||||
if s.Bet != 200 {
|
||||
t.Fatalf("total stake = %d after splitting a 100 hand, want 200", s.Bet)
|
||||
}
|
||||
if s.Active != 0 {
|
||||
t.Fatalf("active hand = %d, want the left one first", s.Active)
|
||||
}
|
||||
|
||||
var split, cardsDealt int
|
||||
for _, e := range evs {
|
||||
switch e.Kind {
|
||||
case "split":
|
||||
split++
|
||||
case "player_card":
|
||||
cardsDealt++
|
||||
}
|
||||
}
|
||||
if split != 1 || cardsDealt != 2 {
|
||||
t.Fatalf("the split emitted %d split and %d card events, want 1 and 2", split, cardsDealt)
|
||||
}
|
||||
}
|
||||
|
||||
// Split aces get one card each and no further say. Without that rule a pair of
|
||||
// aces is the best hand in the game every single time.
|
||||
func TestSplitAcesGetOneCardEachAndNoMore(t *testing.T) {
|
||||
s := dealt(50,
|
||||
hand(cards.Ace, cards.Ace),
|
||||
hand(9, 7), // dealer sits on 16, has to draw
|
||||
hand(cards.King, 9, 5),
|
||||
)
|
||||
s, _, err := ApplyMove(s, Split)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, h := range s.Hands {
|
||||
if len(h.Cards) != 2 {
|
||||
t.Errorf("split ace %d holds %d cards, want exactly 2", i, len(h.Cards))
|
||||
}
|
||||
if !h.Done {
|
||||
t.Errorf("split ace %d is still being asked for a decision", i)
|
||||
}
|
||||
}
|
||||
// Both hands are finished the moment they're dealt, so the dealer plays and
|
||||
// the deal settles without the player ever acting again.
|
||||
if s.Phase != PhaseDone {
|
||||
t.Fatalf("phase = %q after splitting aces, want the deal to have run to the end", s.Phase)
|
||||
}
|
||||
}
|
||||
|
||||
// An ace and a ten on a split hand is twenty-one. It is not a blackjack, and the
|
||||
// house does not pay 3:2 for it — which is the single most expensive rule in this
|
||||
// file, because splitting aces makes 21s for a living.
|
||||
func TestTwentyOneOnASplitHandIsNotANatural(t *testing.T) {
|
||||
s := dealt(100,
|
||||
hand(cards.Ace, cards.Ace),
|
||||
hand(cards.King, 7), // dealer stands on 17
|
||||
hand(cards.King, cards.Queen),
|
||||
)
|
||||
s, _, err := ApplyMove(s, Split)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Phase != PhaseDone {
|
||||
t.Fatalf("phase = %q, want done", s.Phase)
|
||||
}
|
||||
for i, h := range s.Hands {
|
||||
if v, _ := h.Value(); v != 21 {
|
||||
t.Fatalf("hand %d is %d, want the 21 this test is about", i, v)
|
||||
}
|
||||
if h.Natural() {
|
||||
t.Errorf("hand %d counts as a natural — a split 21 must not pay 3:2", i)
|
||||
}
|
||||
if h.Outcome != OutcomeWin {
|
||||
t.Errorf("hand %d settled as %q, want a plain win", i, h.Outcome)
|
||||
}
|
||||
// 100 staked, 100 profit, 5% rake off the profit: 195 back, not 245.
|
||||
if h.Payout != 195 {
|
||||
t.Errorf("hand %d paid %d, want 195 (a 1:1 win less the rake), not a 3:2 payout", i, h.Payout)
|
||||
}
|
||||
}
|
||||
if s.Payout != 390 {
|
||||
t.Fatalf("the deal paid %d, want 390", s.Payout)
|
||||
}
|
||||
}
|
||||
|
||||
// Same rank, not same value. A king and a queen are both worth ten and are not a
|
||||
// pair.
|
||||
func TestSplitNeedsAPairOfTheSameRank(t *testing.T) {
|
||||
s := dealt(100, hand(cards.King, cards.Queen), hand(9, 9), hand(5))
|
||||
if s.CanSplit() {
|
||||
t.Error("CanSplit says a king and a queen are a pair")
|
||||
}
|
||||
if _, _, err := ApplyMove(s, Split); err != ErrCantSplit {
|
||||
t.Errorf("splitting K+Q gave %v, want ErrCantSplit", err)
|
||||
}
|
||||
|
||||
// And you cannot split a hand you have already hit.
|
||||
s = dealt(100, hand(8, 8, 5), hand(9, 9), hand(5))
|
||||
if s.CanSplit() {
|
||||
t.Error("CanSplit says yes to a three-card hand")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplittingStopsAtFourHands(t *testing.T) {
|
||||
// Every card an eight, so every hand splits again for as long as it's allowed.
|
||||
shoe := make([]cards.Card, 0, 12)
|
||||
for i := 0; i < 12; i++ {
|
||||
shoe = append(shoe, cards.Card{Rank: 8, Suit: cards.Spades})
|
||||
}
|
||||
s := dealt(100, hand(8, 8), hand(9, 7), shoe)
|
||||
|
||||
for i := 0; i < MaxHands-1; i++ {
|
||||
var err error
|
||||
if s, _, err = ApplyMove(s, Split); err != nil {
|
||||
t.Fatalf("split %d: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
if len(s.Hands) != MaxHands {
|
||||
t.Fatalf("ended with %d hands, want %d", len(s.Hands), MaxHands)
|
||||
}
|
||||
if s.CanSplit() {
|
||||
t.Fatalf("CanSplit says yes at %d hands", MaxHands)
|
||||
}
|
||||
if _, _, err := ApplyMove(s, Split); err != ErrCantSplit {
|
||||
t.Errorf("the fifth split gave %v, want ErrCantSplit", err)
|
||||
}
|
||||
if s.Bet != 400 {
|
||||
t.Errorf("four hands of 100 = %d staked, want 400", s.Bet)
|
||||
}
|
||||
}
|
||||
|
||||
// Each hand is raked on its own winnings. Netting the hands against each other
|
||||
// first would mean a player who wins one and loses one pays no rake at all, which
|
||||
// is not a rake, it's a discount for splitting.
|
||||
func TestEachSplitHandIsSettledAndRakedOnItsOwn(t *testing.T) {
|
||||
s := dealt(100,
|
||||
hand(8, 8),
|
||||
hand(cards.King, 9), // dealer stands on 19
|
||||
// left hand gets a 2 (10, then it hits to 20 and stands);
|
||||
// right hand gets a 3 (11) and will bust on a king.
|
||||
hand(2, 3, cards.King, cards.King),
|
||||
)
|
||||
s, _, err := ApplyMove(s, Split)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s, _, err = ApplyMove(s, Hit); err != nil { // left: 8+2+K = 20
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v, _ := s.Hands[0].Value(); v != 20 {
|
||||
t.Fatalf("left hand is %d, want 20", v)
|
||||
}
|
||||
if s, _, err = ApplyMove(s, Stand); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Active != 1 {
|
||||
t.Fatalf("standing on the left hand left the active hand at %d, want 1", s.Active)
|
||||
}
|
||||
if s, _, err = ApplyMove(s, Hit); err != nil { // right: 8+3+K = 21... no: 8+3=11, +K = 21
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Phase != PhaseDone {
|
||||
t.Fatalf("phase = %q, want done", s.Phase)
|
||||
}
|
||||
|
||||
left, right := s.Hands[0], s.Hands[1]
|
||||
if left.Outcome != OutcomeWin { // 20 beats 19
|
||||
t.Errorf("left hand settled %q, want a win", left.Outcome)
|
||||
}
|
||||
if right.Outcome != OutcomeWin { // 21 beats 19
|
||||
t.Errorf("right hand settled %q, want a win", right.Outcome)
|
||||
}
|
||||
// Two 100 hands, each winning 100, each raked 5 on its own profit.
|
||||
if left.Rake != 5 || right.Rake != 5 || s.Rake != 10 {
|
||||
t.Errorf("rake = %d/%d (total %d), want 5/5 (10) — each hand raked on its own winnings", left.Rake, right.Rake, s.Rake)
|
||||
}
|
||||
if s.Payout != 390 || s.Net() != 190 {
|
||||
t.Errorf("payout = %d net = %d, want 390 and 190", s.Payout, s.Net())
|
||||
}
|
||||
}
|
||||
|
||||
// A hand that busts loses its own bet and nothing else. The other hand is a
|
||||
// separate bet and settles on its own merits.
|
||||
func TestBustingOneSplitHandDoesNotTouchTheOther(t *testing.T) {
|
||||
s := dealt(100,
|
||||
hand(9, 9),
|
||||
hand(cards.King, 8), // dealer stands on 18
|
||||
hand(5, 2, cards.King, cards.King),
|
||||
)
|
||||
s, _, err := ApplyMove(s, Split) // left: 9+5=14, right: 9+2=11
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s, _, err = ApplyMove(s, Hit); err != nil { // left: 14+K = 24, bust
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Hands[0].Outcome != "" && s.Hands[0].Outcome != OutcomeBust {
|
||||
t.Fatalf("left hand outcome %q before settling", s.Hands[0].Outcome)
|
||||
}
|
||||
if !s.Hands[0].Done || s.Active != 1 {
|
||||
t.Fatalf("a bust hand didn't hand over: done=%v active=%d", s.Hands[0].Done, s.Active)
|
||||
}
|
||||
if s, _, err = ApplyMove(s, Hit); err != nil { // right: 11+K = 21
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if s.Hands[0].Outcome != OutcomeBust || s.Hands[0].Payout != 0 {
|
||||
t.Errorf("left hand = %q paying %d, want a bust paying nothing", s.Hands[0].Outcome, s.Hands[0].Payout)
|
||||
}
|
||||
if s.Hands[1].Outcome != OutcomeWin || s.Hands[1].Payout != 195 {
|
||||
t.Errorf("right hand = %q paying %d, want a win paying 195", s.Hands[1].Outcome, s.Hands[1].Payout)
|
||||
}
|
||||
// Staked 200, got 195 back: down 5 on the deal, and the word for that is lose.
|
||||
if s.Payout != 195 || s.Net() != -5 || s.Outcome != OutcomeLose {
|
||||
t.Errorf("deal settled %q paying %d (net %d), want lose/195/-5", s.Outcome, s.Payout, s.Net())
|
||||
}
|
||||
}
|
||||
|
||||
// If every hand busts there is nothing left to beat, and the dealer does not turn
|
||||
// over — same as it always was with one hand.
|
||||
func TestTheDealerDoesNotPlayWhenEveryHandIsBust(t *testing.T) {
|
||||
s := dealt(100,
|
||||
hand(9, 9),
|
||||
hand(cards.King, 6),
|
||||
hand(8, 8, cards.King, cards.King, 4), // both hands reach 17 then bust on a king
|
||||
)
|
||||
s, _, err := ApplyMove(s, Split)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s, _, err = ApplyMove(s, Hit); err != nil { // left 9+8+K = 27
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s, _, err = ApplyMove(s, Hit); err != nil { // right 9+8+K = 27
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Phase != PhaseDone {
|
||||
t.Fatalf("phase = %q, want done", s.Phase)
|
||||
}
|
||||
if len(s.Dealer) != 2 {
|
||||
t.Errorf("the dealer drew to %d cards with every hand already bust", len(s.Dealer))
|
||||
}
|
||||
if s.Payout != 0 {
|
||||
t.Errorf("two bust hands paid %d, want nothing", s.Payout)
|
||||
}
|
||||
}
|
||||
|
||||
// Doubling after a split doubles *that hand's* bet, not the whole table's.
|
||||
func TestDoublingAfterASplitOnlyDoublesThatHand(t *testing.T) {
|
||||
s := dealt(100,
|
||||
hand(5, 5),
|
||||
hand(cards.King, 7),
|
||||
hand(6, 4, 9, cards.King),
|
||||
)
|
||||
s, _, err := ApplyMove(s, Split) // left: 5+6=11, right: 5+4=9
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.DoubleCost() != 100 {
|
||||
t.Fatalf("DoubleCost = %d on a split hand of 100, want 100", s.DoubleCost())
|
||||
}
|
||||
s, _, err = ApplyMove(s, Double) // left doubles: 11 + 9 = 20
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Hands[0].Bet != 200 || s.Hands[1].Bet != 100 {
|
||||
t.Fatalf("bets are %d/%d after doubling the left hand, want 200/100", s.Hands[0].Bet, s.Hands[1].Bet)
|
||||
}
|
||||
if s.Bet != 300 {
|
||||
t.Fatalf("total staked = %d, want 300 (100 + a doubled 100 + 100)", s.Bet)
|
||||
}
|
||||
if !s.Hands[0].Done || s.Active != 1 {
|
||||
t.Fatal("a doubled hand takes one card and hands over")
|
||||
}
|
||||
}
|
||||
|
||||
// A live hand outlives a deploy. The blobs written before split existed have a
|
||||
// "player" array and no "hands", and a state that decodes to no hands at all is a
|
||||
// player whose cards vanished mid-deal.
|
||||
func TestALiveHandDealtBeforeSplitExistedStillLoads(t *testing.T) {
|
||||
legacy := []byte(`{
|
||||
"rules": {"decks": 6, "blackjack_pays": 1.5, "dealer_hits_soft17": true, "rake_pct": 0.05},
|
||||
"deck": [],
|
||||
"player": [{"r": 10, "s": 1}, {"r": 7, "s": 2}],
|
||||
"dealer": [{"r": 9, "s": 0}, {"r": 5, "s": 3}],
|
||||
"bet": 250,
|
||||
"doubled": false,
|
||||
"phase": "player"
|
||||
}`)
|
||||
|
||||
var s State
|
||||
if err := json.Unmarshal(legacy, &s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Hands) != 1 {
|
||||
t.Fatalf("an old live hand decoded to %d hands, want 1 — the player's cards went missing", len(s.Hands))
|
||||
}
|
||||
if len(s.Hands[0].Cards) != 2 {
|
||||
t.Fatalf("the revived hand holds %d cards, want 2", len(s.Hands[0].Cards))
|
||||
}
|
||||
if s.Hands[0].Bet != 250 || s.Bet != 250 {
|
||||
t.Fatalf("the revived hand carries %d of the %d staked, want all of it", s.Hands[0].Bet, s.Bet)
|
||||
}
|
||||
if v, _ := s.Hands[0].Value(); v != 17 {
|
||||
t.Fatalf("the revived hand is worth %d, want 17", v)
|
||||
}
|
||||
// And it can still be played to the end.
|
||||
if _, _, err := ApplyMove(s, Stand); err != nil {
|
||||
t.Fatalf("the revived hand could not be stood on: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -92,34 +92,61 @@ func viewCard(c cards.Card) cardView {
|
||||
// somebody reads in devtools.
|
||||
type handView struct {
|
||||
Phase string `json:"phase"`
|
||||
Bet int64 `json:"bet"`
|
||||
Player []cardView `json:"player"`
|
||||
Bet int64 `json:"bet"` // everything staked this deal, across every hand
|
||||
Hands []spotView `json:"hands"`
|
||||
Active int `json:"active"`
|
||||
Dealer []cardView `json:"dealer"`
|
||||
Hole bool `json:"hole"` // true: the dealer has a face-down card
|
||||
Total int `json:"total"`
|
||||
Soft bool `json:"soft"`
|
||||
DTotal int `json:"dealer_total"` // what the *shown* dealer cards add to
|
||||
|
||||
Outcome string `json:"outcome,omitempty"`
|
||||
Payout int64 `json:"payout,omitempty"`
|
||||
Rake int64 `json:"rake,omitempty"`
|
||||
Net int64 `json:"net"`
|
||||
Double bool `json:"can_double"`
|
||||
Split bool `json:"can_split"`
|
||||
}
|
||||
|
||||
// spotView is one of the player's hands: its cards, its own chips, its own
|
||||
// verdict. Before split there was only ever one and it was flattened into the
|
||||
// hand itself; a split is the moment that stops being true.
|
||||
type spotView struct {
|
||||
Cards []cardView `json:"cards"`
|
||||
Bet int64 `json:"bet"`
|
||||
Total int `json:"total"`
|
||||
Soft bool `json:"soft"`
|
||||
Doubled bool `json:"doubled"`
|
||||
Done bool `json:"done"`
|
||||
Outcome string `json:"outcome,omitempty"`
|
||||
Payout int64 `json:"payout,omitempty"`
|
||||
}
|
||||
|
||||
func viewHand(st blackjack.State) handView {
|
||||
v := handView{
|
||||
Phase: string(st.Phase),
|
||||
Bet: st.Bet,
|
||||
Active: st.Active,
|
||||
Outcome: string(st.Outcome),
|
||||
Payout: st.Payout,
|
||||
Rake: st.Rake,
|
||||
Net: st.Net(),
|
||||
Double: st.CanDouble(),
|
||||
Split: st.CanSplit(),
|
||||
}
|
||||
for _, c := range st.Player {
|
||||
v.Player = append(v.Player, viewCard(c))
|
||||
for _, h := range st.Hands {
|
||||
s := spotView{
|
||||
Bet: h.Bet,
|
||||
Doubled: h.Doubled,
|
||||
Done: h.Done,
|
||||
Outcome: string(h.Outcome),
|
||||
Payout: h.Payout,
|
||||
}
|
||||
for _, c := range h.Cards {
|
||||
s.Cards = append(s.Cards, viewCard(c))
|
||||
}
|
||||
s.Total, s.Soft = h.Value()
|
||||
v.Hands = append(v.Hands, s)
|
||||
}
|
||||
v.Total, v.Soft = blackjack.HandValue(st.Player)
|
||||
|
||||
dealer := st.Dealer
|
||||
if st.Phase == blackjack.PhasePlayer && len(dealer) > 1 {
|
||||
@@ -139,6 +166,7 @@ func viewHand(st blackjack.State) handView {
|
||||
type eventView struct {
|
||||
Kind string `json:"kind"`
|
||||
Card *cardView `json:"card,omitempty"`
|
||||
Hand int `json:"hand"` // which of the player's hands the card landed on
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
@@ -149,7 +177,7 @@ func viewEvents(evs []blackjack.Event, phase blackjack.Phase) []eventView {
|
||||
out := make([]eventView, 0, len(evs))
|
||||
dealerCards := 0
|
||||
for _, e := range evs {
|
||||
v := eventView{Kind: e.Kind, Text: e.Text}
|
||||
v := eventView{Kind: e.Kind, Text: e.Text, Hand: e.Hand}
|
||||
if e.Card != nil {
|
||||
c := viewCard(*e.Card)
|
||||
v.Card = &c
|
||||
@@ -492,31 +520,45 @@ func (s *Server) handleMove(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
move := blackjack.Move(req.Move)
|
||||
|
||||
// A double doubles the stake, so the extra chips have to be taken before the
|
||||
// move is applied — and if they aren't there, the move simply isn't legal.
|
||||
// Take them first: if the engine then refuses the move, they go straight back.
|
||||
doubled := false
|
||||
if move == blackjack.Double {
|
||||
// Double and split are the two moves that put more chips on the table *after*
|
||||
// the cards are out, so the money has to move before the move does — and if the
|
||||
// chips aren't there, the move simply isn't legal. Take them first: if the
|
||||
// engine then refuses the move, they go straight back.
|
||||
//
|
||||
// Both cost the active hand's bet, not the whole stake. Once a hand can be
|
||||
// split those are different numbers, and doubling the third hand of a split for
|
||||
// the total of all three would be quite a thing to discover in production.
|
||||
var staked int64
|
||||
switch move {
|
||||
case blackjack.Double:
|
||||
if !st.CanDouble() {
|
||||
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "you can only double on the first two cards"})
|
||||
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "you can only double on the first two cards of a hand"})
|
||||
return
|
||||
}
|
||||
if err := storage.Stake(user, st.Bet); err != nil {
|
||||
staked = st.DoubleCost()
|
||||
case blackjack.Split:
|
||||
if !st.CanSplit() {
|
||||
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "you can only split two cards of the same rank, and only up to four hands"})
|
||||
return
|
||||
}
|
||||
staked = st.SplitCost()
|
||||
}
|
||||
if staked > 0 {
|
||||
if err := storage.Stake(user, staked); err != nil {
|
||||
if errors.Is(err, storage.ErrInsufficientChips) {
|
||||
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "not enough chips to double"})
|
||||
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "not enough chips for that"})
|
||||
return
|
||||
}
|
||||
slog.Error("games: stake double", "user", user, "err", err)
|
||||
slog.Error("games: stake raise", "user", user, "move", move, "err", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
doubled = true
|
||||
}
|
||||
|
||||
next, evs, err := blackjack.ApplyMove(st, move)
|
||||
if err != nil {
|
||||
if doubled {
|
||||
_ = storage.Award(user, st.Bet) // the move didn't happen; neither did the raise
|
||||
if staked > 0 {
|
||||
_ = storage.Award(user, staked) // the move didn't happen; neither did the raise
|
||||
}
|
||||
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "that move isn't legal here"})
|
||||
return
|
||||
|
||||
@@ -99,8 +99,8 @@ func TestDealTakesTheStakeAndHidesTheHoleCard(t *testing.T) {
|
||||
if v.Hand == nil {
|
||||
t.Fatal("deal returned no hand")
|
||||
}
|
||||
if len(v.Hand.Player) != 2 {
|
||||
t.Fatalf("player was dealt %d cards, want 2", len(v.Hand.Player))
|
||||
if len(v.Hand.Hands[0].Cards) != 2 {
|
||||
t.Fatalf("player was dealt %d cards, want 2", len(v.Hand.Hands[0].Cards))
|
||||
}
|
||||
|
||||
// A natural settles on the spot and legitimately shows both dealer cards.
|
||||
@@ -181,12 +181,14 @@ func TestOneHandAtATime(t *testing.T) {
|
||||
t.Fatalf("the live hand went missing: %v", err)
|
||||
}
|
||||
var st struct {
|
||||
Player []struct{} `json:"player"`
|
||||
Hands []struct {
|
||||
Cards []struct{} `json:"cards"`
|
||||
} `json:"hands"`
|
||||
}
|
||||
if err := json.Unmarshal(live.State, &st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(st.Player) != len(first.Hand.Player) {
|
||||
if len(st.Hands) != 1 || len(st.Hands[0].Cards) != len(first.Hand.Hands[0].Cards) {
|
||||
t.Fatal("the refused deal replaced the hand in progress")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -767,6 +767,55 @@ html[data-phase="night"] {
|
||||
}
|
||||
.pete-spot[data-live="1"] .pete-spot-label { opacity: 0; }
|
||||
|
||||
/* The player's hands at blackjack. There is one of them, until you split.
|
||||
Then there are up to four, side by side, each with its own chips on its own
|
||||
spot — because after a split they are not one bet in two piles, they are two
|
||||
bets that win and lose separately. */
|
||||
.bj-hands {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem 1rem;
|
||||
}
|
||||
.bj-hand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.85rem;
|
||||
border-radius: 1.5rem;
|
||||
padding: 0.4rem 0.7rem 0.4rem 0.4rem;
|
||||
transition: opacity 0.25s ease, box-shadow 0.25s ease, background 0.25s ease;
|
||||
}
|
||||
/* Which hand you are actually playing. The rest are still on the table; they
|
||||
are simply not your problem this second. */
|
||||
.bj-hand[data-live="0"] { opacity: 0.5; }
|
||||
.bj-hand[data-live="1"] {
|
||||
background: rgba(0,0,0,0.16);
|
||||
box-shadow: 0 0 0 2px rgba(var(--glow, 242,181,61), 0.5);
|
||||
}
|
||||
/* Four hands do not fit at one hand's worth of card, and the fix is to tell the
|
||||
row what a card *is* rather than to squash the box a card is in: everything
|
||||
about a card is sized off these two vars. The spot shrinks with them, or the
|
||||
chips end up bigger than the cards they're riding on. */
|
||||
.bj-hands[data-count="2"] { --card-h: 6.6rem; --card-w: 4.7rem; }
|
||||
.bj-hands[data-count="3"],
|
||||
.bj-hands[data-count="4"] { --card-h: 5rem; --card-w: 3.6rem; }
|
||||
.bj-hands[data-count="2"] .pete-hand { min-height: 6.8rem; }
|
||||
.bj-hands[data-count="3"] .pete-hand,
|
||||
.bj-hands[data-count="4"] .pete-hand { min-height: 5.2rem; gap: 0.35rem; }
|
||||
.bj-hands[data-count="2"] .pete-spot { height: 5.5rem; width: 5.5rem; }
|
||||
.bj-hands[data-count="3"] .pete-spot,
|
||||
.bj-hands[data-count="4"] .pete-spot { height: 4.25rem; width: 4.25rem; }
|
||||
.bj-hands[data-count="3"] .pete-spot-label,
|
||||
.bj-hands[data-count="4"] .pete-spot-label { display: none; }
|
||||
|
||||
/* The card a split is about to take away. It lifts, and then it's gone —
|
||||
otherwise a card simply teleports into a hand that didn't exist yet. */
|
||||
.bj-splitting { animation: bj-split-lift 0.32s ease forwards; }
|
||||
@keyframes bj-split-lift {
|
||||
from { transform: translateY(0) rotate(0); }
|
||||
to { transform: translateY(-1.1rem) rotate(6deg); }
|
||||
}
|
||||
|
||||
/* The stack in the spot. Each chip is offset up the pile by its index, so ten
|
||||
chips look like ten chips rather than one chip with a number on it. */
|
||||
.pete-stack {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,8 +1,8 @@
|
||||
// The blackjack table.
|
||||
//
|
||||
// The browser holds no game. It sends intents — deal, hit, stand, double — and
|
||||
// the server answers with the cards you're allowed to see plus the *script* of
|
||||
// how they got there: one event per card off the shoe, in the order the shoe
|
||||
// The browser holds no game. It sends intents — deal, hit, stand, double, split
|
||||
// — and the server answers with the cards you're allowed to see plus the *script*
|
||||
// of how they got there: one event per card off the shoe, in the order the shoe
|
||||
// gave them up. This file's job is to play that script back at a human speed
|
||||
// rather than snapping the finished hand into place.
|
||||
//
|
||||
@@ -16,6 +16,10 @@
|
||||
// taken away. Nothing about the money changes on this table without something
|
||||
// crossing the felt to make it change — including the count in the chip bar,
|
||||
// which is deliberately not updated until the chips that justify it have landed.
|
||||
//
|
||||
// Since split, "the spot" is not one place. A hand has a spot, and a split makes
|
||||
// a second hand with a second bet on a second spot — two bets that win and lose
|
||||
// separately, which is the whole point of splitting and has to look like it.
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
@@ -25,9 +29,7 @@
|
||||
var FX = window.PeteFX;
|
||||
|
||||
var dealerEl = root.querySelector("[data-dealer]");
|
||||
var playerEl = root.querySelector("[data-player]");
|
||||
var dTotalEl = root.querySelector("[data-dealer-total]");
|
||||
var pTotalEl = root.querySelector("[data-player-total]");
|
||||
var dLabelEl = root.querySelector("[data-dealer-label]");
|
||||
var verdictEl = root.querySelector("[data-verdict]");
|
||||
var betting = root.querySelector("[data-betting]");
|
||||
@@ -36,26 +38,22 @@
|
||||
var dealBtn = root.querySelector("[data-deal]");
|
||||
var msgEl = root.querySelector("[data-table-msg]");
|
||||
|
||||
// The three places a chip can be: your pile (in the bar above), the spot in
|
||||
// front of you, and the house's rack on the felt.
|
||||
// Where the chips live: your pile (in the bar above), a spot in front of each
|
||||
// hand, and the house's rack on the felt.
|
||||
var purseEl = document.querySelector("[data-chips]");
|
||||
var spotEl = root.querySelector("[data-spot]");
|
||||
var stackEl = root.querySelector("[data-stack]");
|
||||
var spotTotalEl = root.querySelector("[data-spot-total]");
|
||||
var houseEl = root.querySelector("[data-house]");
|
||||
|
||||
// The spot owns the chips on the felt and the number under them — see PeteFX.
|
||||
// Nothing is bet until a chip is on it, so `bet` starts at nothing rather than
|
||||
// at a default stake nobody put down.
|
||||
var spot = FX.spot({ spot: spotEl, stack: stackEl, total: spotTotalEl });
|
||||
var handsEl = root.querySelector("[data-hands]");
|
||||
var handTpl = root.querySelector("[data-hand-template]");
|
||||
|
||||
var bet = 0; // what you're building between hands
|
||||
var base = 0; // what one hand of the last deal cost, for standing it back up
|
||||
var busy = false; // a request is in flight, or cards are still landing
|
||||
var hand = null; // the hand as the server last described it
|
||||
var hand = null; // the deal as the server last described it
|
||||
|
||||
var DEAL_MS = 380; // one card's flight, and the gap before the next
|
||||
var FLIP_MS = 450;
|
||||
var BEAT_MS = 600; // the dealer thinking before they draw out
|
||||
var SPLIT_MS = 340; // the card lifting out of the hand it's leaving
|
||||
|
||||
var reduced = FX.reduced;
|
||||
function pace(ms) { return reduced ? 0 : ms; }
|
||||
@@ -80,46 +78,137 @@
|
||||
function cardEl(face) { return CARDS.el(face); }
|
||||
var turnOver = CARDS.turnOver;
|
||||
|
||||
// ---- the money on the felt -------------------------------------------------
|
||||
// ---- the hands -------------------------------------------------------------
|
||||
//
|
||||
// A box per hand: its chips, its cards, its total, its own verdict. There is
|
||||
// always at least one, and before a deal that one is where you build your bet —
|
||||
// so the chips you stack are already sitting on the hand they're about to buy.
|
||||
|
||||
// stake moves chips from your pile onto the spot: the bet you build before a
|
||||
// deal, and the second bet a double puts down beside it.
|
||||
function stake(amount, from) {
|
||||
return spot.pour(from || purseEl, amount);
|
||||
var hands = [];
|
||||
|
||||
function makeHand(at) {
|
||||
var el = handTpl.content.firstElementChild.cloneNode(true);
|
||||
var spotEl = el.querySelector("[data-spot]");
|
||||
var box = {
|
||||
el: el,
|
||||
spotEl: spotEl, // where a chip flies to, as opposed to what counts it
|
||||
cards: el.querySelector("[data-cards]"),
|
||||
total: el.querySelector("[data-total]"),
|
||||
verdict: el.querySelector("[data-hand-outcome]"),
|
||||
ranks: [], // what's in it, for a running total while the cards are landing
|
||||
spot: FX.spot({
|
||||
spot: spotEl,
|
||||
stack: el.querySelector("[data-stack]"),
|
||||
total: el.querySelector("[data-spot-total]"),
|
||||
}),
|
||||
};
|
||||
if (at === undefined || at >= hands.length) {
|
||||
handsEl.appendChild(el);
|
||||
hands.push(box);
|
||||
} else {
|
||||
handsEl.insertBefore(el, hands[at].el);
|
||||
hands.splice(at, 0, box);
|
||||
}
|
||||
handsEl.dataset.count = hands.length;
|
||||
return box;
|
||||
}
|
||||
|
||||
// reset tears the row down to n empty hands. It does not preserve chips: a
|
||||
// caller that has some to keep (a deal, whose stake is already on the spot)
|
||||
// reads the amount first and puts it back.
|
||||
function reset(n) {
|
||||
handsEl.innerHTML = "";
|
||||
hands = [];
|
||||
for (var i = 0; i < (n || 1); i++) makeHand();
|
||||
}
|
||||
|
||||
function ensure(n) { while (hands.length < n) makeHand(); }
|
||||
|
||||
// The bet you build between hands is hand zero's.
|
||||
function betSpot() { return hands[0].spot; }
|
||||
|
||||
// live marks the hand you're being asked about, and dims the ones you aren't.
|
||||
//
|
||||
// -1 means nobody is acting — the dealer is drawing, or the deal is over — and
|
||||
// that is *not* the same as every hand being inactive: a settled hand is the
|
||||
// thing you are reading, so it goes back to full brightness rather than sitting
|
||||
// there greyed out. Hence the empty string: it matches neither CSS rule.
|
||||
function live(i) {
|
||||
hands.forEach(function (h, k) {
|
||||
h.el.dataset.live = i < 0 ? "" : k === i ? "1" : "0";
|
||||
});
|
||||
}
|
||||
|
||||
// The running total under a hand, worked out from the cards you can see. The
|
||||
// server sends totals too, but only with the finished state — and a hand you're
|
||||
// playing needs to know what it's holding *now*, not once it's over. It's a
|
||||
// readout, never a decision: every ruling is the server's.
|
||||
var TEN = { K: 10, Q: 10, J: 10 };
|
||||
function totalOf(ranks) {
|
||||
var total = 0, aces = 0;
|
||||
ranks.forEach(function (r) {
|
||||
if (r === "A") { aces++; total += 11; }
|
||||
else total += TEN[r] || parseInt(r, 10) || 0;
|
||||
});
|
||||
while (total > 21 && aces > 0) { total -= 10; aces--; }
|
||||
return { total: total, soft: aces > 0 };
|
||||
}
|
||||
|
||||
function showTotal(box) {
|
||||
if (!box.ranks.length) { box.total.classList.add("hidden"); return; }
|
||||
var v = totalOf(box.ranks);
|
||||
box.total.textContent = v.total + (v.soft ? " (soft)" : "");
|
||||
box.total.classList.remove("hidden");
|
||||
}
|
||||
|
||||
var SHORT = {
|
||||
blackjack: "Blackjack", win: "Won", dealer_bust: "Won",
|
||||
lose: "Lost", bust: "Bust", push: "Push",
|
||||
};
|
||||
|
||||
// A hand's own result, on the hand. With one hand this says the same thing as
|
||||
// the pill above it and is a bit redundant; with four it is the only way to
|
||||
// read what happened, because "you win" is not true of all of them.
|
||||
function showHandVerdict(box, h) {
|
||||
var text = h && SHORT[h.outcome];
|
||||
if (!text) { box.verdict.classList.add("hidden"); return; }
|
||||
box.verdict.textContent = text;
|
||||
box.verdict.classList.remove("hidden");
|
||||
}
|
||||
|
||||
// ---- the money on the felt -------------------------------------------------
|
||||
|
||||
// settleChips is what the felt does about the outcome, after the cards have
|
||||
// finished telling you what it is. It reads the same two numbers the ledger
|
||||
// moved: `bet` (already off your pile since the deal) and `payout` (what comes
|
||||
// back — stake plus winnings less rake, or nothing at all).
|
||||
// finished telling you what it is. Each hand is paid on its own, in order, left
|
||||
// to right — because each hand *is* its own bet, and a split that lost one and
|
||||
// won the other has to be watchable as exactly that.
|
||||
function settleChips(final) {
|
||||
var payout = final.payout || 0;
|
||||
var back = payout - final.bet; // what the house is adding, if anything
|
||||
var chain = Promise.resolve();
|
||||
(final.hands || []).forEach(function (h, i) {
|
||||
chain = chain.then(function () {
|
||||
var box = hands[i];
|
||||
if (!box) return;
|
||||
var payout = h.payout || 0;
|
||||
|
||||
if (payout <= 0) {
|
||||
// The house takes it. The stack goes to the rack and doesn't come back.
|
||||
return spot.sweep(houseEl, final.bet, { gap: 45, lift: 0.6, fade: true });
|
||||
return box.spot.sweep(houseEl, h.bet, { gap: 45, lift: 0.6, fade: true });
|
||||
}
|
||||
|
||||
// The house pays first, into the spot beside your stake, so you watch the
|
||||
// The house pays first, into the spot beside the stake, so you watch the
|
||||
// winnings arrive on top of the bet that earned them.
|
||||
return spot
|
||||
var back = payout - h.bet;
|
||||
return box.spot
|
||||
.pour(houseEl, back, { gap: 60 })
|
||||
.then(function () { return wait(back > 0 ? 380 : 200); })
|
||||
// Paid, then swept up: the whole lot comes back to your pile, and only then
|
||||
// does the number in the bar move.
|
||||
.then(function () { return spot.sweep(purseEl, payout, { gap: 40, lift: 0.8 }); });
|
||||
.then(function () { return wait(back > 0 ? 340 : 160); })
|
||||
.then(function () { return box.spot.sweep(purseEl, payout, { gap: 40, lift: 0.8 }); });
|
||||
});
|
||||
});
|
||||
return chain;
|
||||
}
|
||||
|
||||
function totals(v) {
|
||||
if (v.total) {
|
||||
pTotalEl.textContent = v.total + (v.soft ? " (soft)" : "");
|
||||
pTotalEl.classList.remove("hidden");
|
||||
} else {
|
||||
pTotalEl.classList.add("hidden");
|
||||
}
|
||||
// While the hole card is down, the dealer's total is only what's showing —
|
||||
// so say so, rather than printing a number that quietly means something else.
|
||||
// While the hole card is down, the dealer's total is only what's showing — so
|
||||
// say so, rather than printing a number that quietly means something else.
|
||||
function dealerTotal(v) {
|
||||
if (v.dealer && v.dealer.length) {
|
||||
dTotalEl.textContent = v.hole ? v.dealer_total + " showing" : String(v.dealer_total);
|
||||
dTotalEl.classList.remove("hidden");
|
||||
@@ -128,19 +217,28 @@
|
||||
}
|
||||
}
|
||||
|
||||
// paint puts a hand on the felt with no animation. This is the resume path:
|
||||
// you reloaded, or Pete restarted, and your cards are simply there — including
|
||||
// the stake, which is still on the spot because the server still has it.
|
||||
// paint puts a deal on the felt with no animation. This is the resume path: you
|
||||
// reloaded, or Pete restarted, and your cards are simply there — including the
|
||||
// stakes, which are still on their spots because the server still has them.
|
||||
function paint(v) {
|
||||
dealerEl.innerHTML = "";
|
||||
playerEl.innerHTML = "";
|
||||
if (!v) { setPhase(null); spot.render(0); return; }
|
||||
if (!v) { reset(1); setPhase(null); return; }
|
||||
|
||||
reset(v.hands.length || 1);
|
||||
v.hands.forEach(function (h, i) {
|
||||
var box = hands[i];
|
||||
(h.cards || []).forEach(function (c) {
|
||||
box.cards.appendChild(cardEl(c));
|
||||
box.ranks.push(c.rank);
|
||||
});
|
||||
box.spot.render(v.phase === "done" ? 0 : h.bet);
|
||||
showTotal(box);
|
||||
showHandVerdict(box, v.phase === "done" ? h : null);
|
||||
});
|
||||
|
||||
v.player.forEach(function (c) { playerEl.appendChild(cardEl(c)); });
|
||||
v.dealer.forEach(function (c) { dealerEl.appendChild(cardEl(c)); });
|
||||
if (v.hole) dealerEl.appendChild(cardEl(null));
|
||||
spot.render(v.phase === "done" ? 0 : v.bet);
|
||||
totals(v);
|
||||
dealerTotal(v);
|
||||
setPhase(v);
|
||||
}
|
||||
|
||||
@@ -155,12 +253,17 @@
|
||||
|
||||
function verdict(v) {
|
||||
var text = VERDICTS[v.outcome] || "";
|
||||
// Across several hands "you win" is a claim about the money, not about the
|
||||
// cards: you can win one, lose one, and still be up. The pill reports the
|
||||
// deal; the badge on each hand reports the hand.
|
||||
if ((v.hands || []).length > 1) {
|
||||
text = v.net > 0 ? "You're up on the deal." : v.net < 0 ? "Down on the deal." : "All square.";
|
||||
}
|
||||
if (!text) { verdictEl.classList.add("hidden"); return; }
|
||||
if (v.net > 0) text += " +" + v.net.toLocaleString();
|
||||
else if (v.net < 0) text += " " + v.net.toLocaleString();
|
||||
verdictEl.textContent = text;
|
||||
verdictEl.classList.remove("hidden");
|
||||
playerEl.dataset.won = v.net > 0 ? "1" : v.net < 0 ? "-1" : "0";
|
||||
|
||||
// The one thing in this room that gets confetti. A natural is rare, it pays
|
||||
// 3:2, and if everything celebrated then nothing would.
|
||||
@@ -176,15 +279,20 @@
|
||||
// setPhase swaps the controls: bet between hands, act during one.
|
||||
function setPhase(v) {
|
||||
hand = v;
|
||||
var live = !!v && v.phase === "player";
|
||||
betting.classList.toggle("hidden", live);
|
||||
actions.classList.toggle("hidden", !live);
|
||||
var acting = !!v && v.phase === "player";
|
||||
betting.classList.toggle("hidden", acting);
|
||||
actions.classList.toggle("hidden", !acting);
|
||||
|
||||
if (live) {
|
||||
if (acting) {
|
||||
var dbl = actions.querySelector('[data-move="double"]');
|
||||
var spl = actions.querySelector('[data-move="split"]');
|
||||
if (dbl) dbl.disabled = !v.can_double;
|
||||
if (spl) spl.disabled = !v.can_split;
|
||||
live(v.active || 0);
|
||||
} else {
|
||||
live(-1);
|
||||
}
|
||||
if (!v || v.phase !== "player") verdictEl.classList.toggle("hidden", !(v && v.outcome));
|
||||
if (!acting) verdictEl.classList.toggle("hidden", !(v && v.outcome));
|
||||
}
|
||||
|
||||
// ---- the script -----------------------------------------------------------
|
||||
@@ -209,38 +317,77 @@
|
||||
|
||||
if (!settles) money();
|
||||
|
||||
// Whatever the server says the stake is, that's what has to be on the spot.
|
||||
// Two things get here: a double, which puts a second bet down beside the
|
||||
// first, and a deal whose bet was typed rather than stacked (you kept last
|
||||
// hand's number and just pressed Deal). Either way the chips go down before
|
||||
// the card they're buying does.
|
||||
if (final && final.bet > spot.amount) {
|
||||
var extra = final.bet - spot.amount;
|
||||
chain = chain.then(function () { return stake(extra); });
|
||||
// A deal whose bet was typed rather than stacked (you kept last hand's number
|
||||
// and just pressed Deal) has chips to put down before the first card does.
|
||||
// Everything else that costs money — a double, a split — announces itself as
|
||||
// an event, and pays for itself there.
|
||||
if (final && final.hands && final.hands.length && events.length && events[0].kind === "deal") {
|
||||
var want = final.hands[0].bet;
|
||||
var have = betSpot().amount;
|
||||
if (want > have) {
|
||||
chain = chain.then(function () { return betSpot().pour(purseEl, want - have); });
|
||||
}
|
||||
}
|
||||
|
||||
events.forEach(function (e) {
|
||||
chain = chain.then(function () {
|
||||
var box;
|
||||
switch (e.kind) {
|
||||
case "deal":
|
||||
// Clear the felt, but not the stake: those chips are yours, they are
|
||||
// already on the spot, and they are what this deal is riding on.
|
||||
var staked = betSpot().amount;
|
||||
dealerEl.innerHTML = "";
|
||||
playerEl.innerHTML = "";
|
||||
playerEl.dataset.won = "0";
|
||||
reset(1);
|
||||
betSpot().render(staked);
|
||||
verdictEl.classList.add("hidden");
|
||||
FX.sfx("shuffle");
|
||||
return;
|
||||
|
||||
case "player_card":
|
||||
playerEl.appendChild(cardEl(e.card));
|
||||
ensure(e.hand + 1);
|
||||
box = hands[e.hand];
|
||||
box.cards.appendChild(cardEl(e.card));
|
||||
box.ranks.push(e.card.rank);
|
||||
showTotal(box);
|
||||
live(e.hand);
|
||||
FX.sfx("deal");
|
||||
return wait(DEAL_MS);
|
||||
|
||||
case "split":
|
||||
// The second card lifts out of the hand it was in and becomes a hand
|
||||
// of its own, and the bet that follows it is a second bet: the same
|
||||
// chips again, out of your pile, onto a spot that didn't exist a
|
||||
// moment ago.
|
||||
var src = hands[e.hand];
|
||||
var moved = src.cards.lastElementChild;
|
||||
var stake = src.spot.amount;
|
||||
var fresh = makeHand(e.hand + 1);
|
||||
if (moved) moved.classList.add("bj-splitting");
|
||||
FX.sfx("deal", { v: 1 });
|
||||
return wait(SPLIT_MS).then(function () {
|
||||
if (moved) {
|
||||
moved.classList.remove("bj-splitting");
|
||||
fresh.cards.appendChild(moved);
|
||||
}
|
||||
fresh.ranks.push(src.ranks.pop());
|
||||
showTotal(src);
|
||||
showTotal(fresh);
|
||||
return fresh.spot.pour(purseEl, stake);
|
||||
});
|
||||
|
||||
case "double":
|
||||
// The stake goes down again on that hand, and only that hand.
|
||||
box = hands[e.hand];
|
||||
return box.spot.pour(purseEl, box.spot.amount);
|
||||
|
||||
case "dealer_card":
|
||||
// The dealer takes a moment before the first card they draw out.
|
||||
// Card, card, card with no breath in between is a machine dealing;
|
||||
// the pause is the only thing on this table that plays as suspense.
|
||||
var beat = drew ? Promise.resolve() : think();
|
||||
drew = true;
|
||||
live(-1);
|
||||
return beat.then(function () {
|
||||
dealerEl.appendChild(cardEl(e.card));
|
||||
FX.sfx("deal", { v: 1 });
|
||||
@@ -256,6 +403,7 @@
|
||||
case "reveal":
|
||||
// The hole card turns over. Its face is in the final hand — this is
|
||||
// the first moment the server has been willing to say what it was.
|
||||
live(-1);
|
||||
if (!hole) hole = dealerEl.querySelector('.pete-card[data-face="down"]');
|
||||
if (hole && final && final.dealer && final.dealer[1]) {
|
||||
turnOver(hole, final.dealer[1]);
|
||||
@@ -271,12 +419,16 @@
|
||||
return chain.then(function () {
|
||||
if (!final) { paint(null); money(); return; }
|
||||
|
||||
totals(final);
|
||||
dealerTotal(final);
|
||||
if (!settles) { setPhase(final); return; }
|
||||
|
||||
// The hand is over: nothing is on offer while the money is moving. Hit and
|
||||
// Stand go now, and Deal comes back at the far end.
|
||||
// The deal is over: nothing is on offer while the money is moving. The
|
||||
// actions go now, and Deal comes back at the far end.
|
||||
actions.classList.add("hidden");
|
||||
live(-1);
|
||||
(final.hands || []).forEach(function (h, i) {
|
||||
if (hands[i]) showHandVerdict(hands[i], h);
|
||||
});
|
||||
verdict(final);
|
||||
// The chips move, and the bar catches up with them when they arrive. The
|
||||
// betting controls come back last, once the felt is clear: offering Deal
|
||||
@@ -284,16 +436,20 @@
|
||||
// has to refuse.
|
||||
return settleChips(final)
|
||||
.then(money)
|
||||
.then(function () { return standing(final.bet); })
|
||||
.then(function () { return standing(base || (final.hands[0] && final.hands[0].bet)); })
|
||||
.then(function () { setPhase(final); });
|
||||
});
|
||||
}
|
||||
|
||||
// standing leaves your bet up for the next hand, the way you would at a table:
|
||||
// the stake that just settled goes straight back on the spot. It costs nothing
|
||||
// — chips on the spot are a proposal until you press Deal — and it's what keeps
|
||||
// the number in the panel honest, because otherwise a settled hand leaves
|
||||
// "your bet: 300" printed over an empty spot.
|
||||
// one hand's stake goes straight back on the spot. It costs nothing — chips on
|
||||
// the spot are a proposal until you press Deal — and it's what keeps the number
|
||||
// in the panel honest, because otherwise a settled hand leaves "your bet: 300"
|
||||
// printed over an empty spot.
|
||||
//
|
||||
// It's one hand's worth, not the whole deal's: a split cost you four hundred,
|
||||
// and standing four hundred back up on one spot would be betting a stranger's
|
||||
// money on your behalf.
|
||||
function standing(amount) {
|
||||
var money = window.PeteGames.view();
|
||||
if (!amount || !money || money.chips < amount) {
|
||||
@@ -303,7 +459,7 @@
|
||||
}
|
||||
bet = amount;
|
||||
showBet();
|
||||
return stake(amount);
|
||||
return betSpot().pour(purseEl, amount);
|
||||
}
|
||||
|
||||
// think is the dealer's beat: a pause with something to look at, so it reads as
|
||||
@@ -331,7 +487,8 @@
|
||||
say(err.message, "bad");
|
||||
// Whatever we thought was on the felt, the server is the authority on it.
|
||||
return window.PeteGames.refresh().then(function (v) {
|
||||
if (v && !v.hand) spot.render(0);
|
||||
if (v && !v.hand) { reset(1); setPhase(null); }
|
||||
else if (v && v.hand) paint(v.hand);
|
||||
});
|
||||
})
|
||||
.then(function () { busy = false; });
|
||||
@@ -368,8 +525,9 @@
|
||||
// but the spot's total moves now, so a Deal pressed mid-flight still knows
|
||||
// the chip is on its way and doesn't put a second one down.
|
||||
var target = bet;
|
||||
var spot = betSpot();
|
||||
spot.amount = bet;
|
||||
FX.fly(btn, spotEl, { denom: d }).then(function () {
|
||||
FX.fly(btn, hands[0].spotEl, { denom: d }).then(function () {
|
||||
if (bet >= target) spot.render(target); // unless Clear got there first
|
||||
});
|
||||
});
|
||||
@@ -378,8 +536,8 @@
|
||||
var clearBtn = root.querySelector("[data-bet-clear]");
|
||||
if (clearBtn) {
|
||||
clearBtn.addEventListener("click", function () {
|
||||
if (busy || !spot.amount) { bet = 0; showBet(); return; }
|
||||
spot.sweep(purseEl, null, { gap: 40, lift: 0.7 });
|
||||
if (busy || !betSpot().amount) { bet = 0; showBet(); return; }
|
||||
betSpot().sweep(purseEl, null, { gap: 40, lift: 0.7 });
|
||||
bet = 0;
|
||||
showBet();
|
||||
});
|
||||
@@ -388,6 +546,7 @@
|
||||
if (dealBtn) {
|
||||
dealBtn.addEventListener("click", function () {
|
||||
if (bet <= 0) { say("Put something on it first.", "bad"); return; }
|
||||
base = bet; // one hand's worth, which is what a split doubles and a stand puts back
|
||||
send("/api/games/blackjack/deal", { bet: bet });
|
||||
});
|
||||
}
|
||||
@@ -403,15 +562,17 @@
|
||||
if (/^(input|textarea|select)$/i.test((e.target.tagName || ""))) return;
|
||||
if (!hand || hand.phase !== "player" || busy) return;
|
||||
|
||||
var move = { h: "hit", s: "stand", d: "double" }[e.key.toLowerCase()];
|
||||
var move = { h: "hit", s: "stand", d: "double", p: "split" }[e.key.toLowerCase()];
|
||||
if (!move) return;
|
||||
if (move === "double" && !hand.can_double) return;
|
||||
if (move === "split" && !hand.can_split) return;
|
||||
e.preventDefault();
|
||||
send("/api/games/blackjack/move", { move: move });
|
||||
});
|
||||
|
||||
// The money bar owns the first fetch; the table picks up whatever it found,
|
||||
// including a hand left sitting on the felt by a reload or a redeploy.
|
||||
// including a deal left sitting on the felt by a reload or a redeploy.
|
||||
reset(1);
|
||||
var resumed = false;
|
||||
window.PeteGames.onUpdate(function (v) {
|
||||
if (!resumed) {
|
||||
|
||||
@@ -51,21 +51,36 @@
|
||||
<p data-verdict class="hidden rounded-full bg-white/95 px-5 py-2 font-display text-lg font-bold text-[#2b2118] shadow-pete"></p>
|
||||
</div>
|
||||
|
||||
<!-- Player: the bet sits in front of the cards it's riding on. -->
|
||||
<!-- Player: the bet sits in front of the cards it's riding on.
|
||||
|
||||
The hands themselves are built by blackjack.js, because how many there
|
||||
are is a thing that changes mid-hand: you split, and one hand with one
|
||||
bet on it becomes two hands with a bet each. The template below is the
|
||||
shape of one of them; the row starts with exactly one, which is also
|
||||
the spot you build your bet on before any cards exist. -->
|
||||
<div>
|
||||
<div class="mb-2 flex items-center gap-2">
|
||||
<span class="text-xs font-bold uppercase tracking-wider text-white/60">You</span>
|
||||
<span data-player-total class="hidden rounded-full bg-black/25 px-2.5 py-0.5 text-xs font-bold tabular-nums text-white"></span>
|
||||
</div>
|
||||
<div class="flex items-center gap-5">
|
||||
<div class="bj-hands" data-hands data-count="1" aria-live="polite"></div>
|
||||
</div>
|
||||
|
||||
<template data-hand-template>
|
||||
<div class="bj-hand" data-hand data-live="1">
|
||||
<div class="pete-spot" data-spot>
|
||||
<span class="pete-spot-label">Bet</span>
|
||||
<div class="pete-stack" data-stack></div>
|
||||
<span data-spot-total class="pete-spot-total hidden"></span>
|
||||
</div>
|
||||
<div data-player class="pete-hand flex-1" aria-live="polite"></div>
|
||||
<div class="min-w-0">
|
||||
<div class="mb-1 flex h-5 items-center gap-1.5">
|
||||
<span data-total class="hidden rounded-full bg-black/25 px-2.5 py-0.5 text-xs font-bold tabular-nums text-white"></span>
|
||||
<span data-hand-outcome class="hidden rounded-full bg-white/90 px-2 py-0.5 text-[0.65rem] font-bold uppercase tracking-wide text-[#2b2118]"></span>
|
||||
</div>
|
||||
<div data-cards class="pete-hand"></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
@@ -116,9 +131,14 @@
|
||||
hover:bg-[color:var(--ink)]/5 active:translate-y-px disabled:opacity-40 disabled:pointer-events-none transition">
|
||||
Double
|
||||
</button>
|
||||
<button type="button" data-move="split"
|
||||
class="rounded-full bg-[color:var(--card)] px-8 py-3 font-display text-lg font-bold shadow-pete border-2 border-[color:var(--ink)]/10
|
||||
hover:bg-[color:var(--ink)]/5 active:translate-y-px disabled:opacity-40 disabled:pointer-events-none transition">
|
||||
Split
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-3 text-center text-xs text-[color:var(--ink)]/40">
|
||||
<kbd>h</kbd> hit · <kbd>s</kbd> stand · <kbd>d</kbd> double
|
||||
<kbd>h</kbd> hit · <kbd>s</kbd> stand · <kbd>d</kbd> double · <kbd>p</kbd> split
|
||||
</p>
|
||||
</section>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user