Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

betting.gno

package holdem

import "errors"

// Streets.
const (
	Preflop = iota
	Flop
	Turn
	River
)

// Player is one hand player's betting state.
type Player struct {
	Stack       int64 // chips behind
	StreetBet   int64 // chips put in on the current street
	Contributed int64 // chips put in during the whole hand
	Folded      bool
	AllIn       bool
	Acted       bool  // acted since the bet last increased
	LastActBet  int64 // current bet right after this player's last action this street, -1 if none
}

// Betting is the no-limit betting state of one hand. Players are indexed from
// the small blind (heads-up: index 0 is the button and small blind).
type Betting struct {
	Players    []*Player
	SmallBlind int64
	BigBlind   int64
	Street     int
	CurrentBet int64 // highest street bet
	MinRaise   int64 // size of the last full bet or raise on this street
	Turn       int   // index to act, -1 when the street needs no more action
}

// NewBetting posts the blinds and sets the first player to act preflop.
func NewBetting(stacks []int64, smallBlind, bigBlind int64) *Betting {
	n := len(stacks)
	if n < 2 {
		panic("need at least 2 players")
	}
	if smallBlind <= 0 || bigBlind < smallBlind {
		panic("invalid blinds")
	}
	b := &Betting{SmallBlind: smallBlind, BigBlind: bigBlind, Street: Preflop, MinRaise: bigBlind}
	for _, s := range stacks {
		if s <= 0 {
			panic("player without chips")
		}
		b.Players = append(b.Players, &Player{Stack: s, LastActBet: -1})
	}
	b.post(0, smallBlind)
	b.post(1, bigBlind)
	b.CurrentBet = b.Players[0].StreetBet
	if b.Players[1].StreetBet > b.CurrentBet {
		b.CurrentBet = b.Players[1].StreetBet
	}
	if b.CurrentBet < bigBlind {
		b.CurrentBet = bigBlind
	}
	first := 2 % n
	if n == 2 {
		first = 0
	}
	b.Turn = b.nextToAct(first)
	return b
}

func (b *Betting) post(i int, amount int64) {
	p := b.Players[i]
	if amount > p.Stack {
		amount = p.Stack
	}
	p.Stack -= amount
	p.StreetBet += amount
	p.Contributed += amount
	if p.Stack == 0 {
		p.AllIn = true
	}
}

// Live returns the number of players who have not folded.
func (b *Betting) Live() int {
	n := 0
	for _, p := range b.Players {
		if !p.Folded {
			n++
		}
	}
	return n
}

func (b *Betting) canAct(p *Player) bool {
	return !p.Folded && !p.AllIn
}

func (b *Betting) needsAction(p *Player) bool {
	return b.canAct(p) && (!p.Acted || p.StreetBet < b.CurrentBet)
}

// nextToAct returns the first player from index `from` (inclusive, clockwise)
// who still has to act, or -1 when the street is complete.
func (b *Betting) nextToAct(from int) int {
	if b.Live() <= 1 {
		return -1
	}
	actors := 0
	for _, p := range b.Players {
		if b.canAct(p) {
			actors++
		}
	}
	n := len(b.Players)
	for k := 0; k < n; k++ {
		i := (from + k) % n
		p := b.Players[i]
		if !b.needsAction(p) {
			continue
		}
		// A lone player who can still act and has matched the bet has nobody
		// to bet against.
		if actors == 1 && p.StreetBet >= b.CurrentBet {
			continue
		}
		return i
	}
	return -1
}

// StreetComplete reports whether nobody has to act on this street.
func (b *Betting) StreetComplete() bool {
	return b.Turn < 0
}

// Closed reports whether no further betting is possible in the hand: one live
// player left, or the street is complete and at most one live player still
// has chips.
func (b *Betting) Closed() bool {
	if b.Live() <= 1 {
		return true
	}
	if b.Turn >= 0 {
		return false
	}
	actors := 0
	for _, p := range b.Players {
		if b.canAct(p) {
			actors++
		}
	}
	return actors <= 1
}

// CanCheck reports whether player i may check.
func (b *Betting) CanCheck(i int) bool {
	return b.Players[i].StreetBet == b.CurrentBet
}

// CanRaise reports whether player i may bet or raise: they have chips beyond a
// call, and either have not acted on this street or face at least a full
// raise since they last acted (a short all-in does not reopen the betting).
func (b *Betting) CanRaise(i int) bool {
	p := b.Players[i]
	if p.StreetBet+p.Stack <= b.CurrentBet {
		return false
	}
	return p.LastActBet < 0 || b.CurrentBet-p.LastActBet >= b.MinRaise
}

// MinRaiseTo returns the smallest legal total street bet for a non all-in
// bet or raise.
func (b *Betting) MinRaiseTo() int64 {
	return b.CurrentBet + b.MinRaise
}

// Act applies an action by player i. For "raise", amount is the player's total
// street bet after the action; it also opens the betting when nobody has bet.
func (b *Betting) Act(i int, action string, amount int64) error {
	if b.Turn < 0 || i != b.Turn {
		return errors.New("not this player's turn")
	}
	p := b.Players[i]
	raised := false
	switch action {
	case "fold":
		p.Folded = true
	case "check":
		if !b.CanCheck(i) {
			return errors.New("cannot check facing a bet")
		}
	case "call":
		if p.StreetBet >= b.CurrentBet {
			return errors.New("nothing to call")
		}
		b.post(i, b.CurrentBet-p.StreetBet)
	case "raise":
		if amount <= b.CurrentBet {
			return errors.New("raise must exceed the current bet")
		}
		max := p.StreetBet + p.Stack
		if amount > max {
			return errors.New("raise exceeds stack")
		}
		if !b.CanRaise(i) {
			return errors.New("betting is not reopened for this player")
		}
		allIn := amount == max
		if !allIn && amount < b.CurrentBet+b.MinRaise {
			return errors.New("raise below minimum")
		}
		if amount-b.CurrentBet >= b.MinRaise {
			b.MinRaise = amount - b.CurrentBet
		}
		b.post(i, amount-p.StreetBet)
		b.CurrentBet = amount
		raised = true
	default:
		return errors.New("unknown action")
	}
	p.Acted = true
	p.LastActBet = b.CurrentBet
	if raised {
		for k, q := range b.Players {
			if k != i && b.canAct(q) {
				q.Acted = false
			}
		}
	}
	b.Turn = b.nextToAct((i + 1) % len(b.Players))
	return nil
}

// NextStreet resets street state and sets the first player to act. It must
// only be called when the current street is complete and betting not closed.
func (b *Betting) NextStreet() {
	if b.Street >= River {
		panic("no street after the river")
	}
	b.Street++
	b.CurrentBet = 0
	b.MinRaise = b.BigBlind
	for _, p := range b.Players {
		p.StreetBet = 0
		p.Acted = false
		p.LastActBet = -1
	}
	first := 0
	if len(b.Players) == 2 {
		first = 1
	}
	b.Turn = b.nextToAct(first)
}

// Pot returns the total contributed by all players.
func (b *Betting) Pot() int64 {
	t := int64(0)
	for _, p := range b.Players {
		t += p.Contributed
	}
	return t
}

eval.gno

// Package holdem implements the chain-independent rules of no-limit Texas
// Hold'em: hand evaluation, side pots and the betting state machine of one
// hand. Cards are indices 0..51 with rank = c % 13 (0 = Two .. 12 = Ace) and
// suit = c / 13.
package holdem

// Hand categories, the high bits of a score.
const (
	HighCard = iota
	OnePair
	TwoPair
	Trips
	Straight
	Flush
	FullHouse
	Quads
	StraightFlush
)

var categoryNames = []string{
	"high card", "pair", "two pair", "three of a kind", "straight",
	"flush", "full house", "four of a kind", "straight flush",
}

// CategoryName names the category of a score.
func CategoryName(score int) string {
	c := Category(score)
	if c < 0 || c >= len(categoryNames) {
		return "?"
	}
	return categoryNames[c]
}

// Category returns the hand category of a score.
func Category(score int) int {
	return score >> 20
}

func makeScore(cat int, ranks ...int) int {
	s := cat << 20
	for i := 0; i < 5; i++ {
		r := 0
		if i < len(ranks) {
			r = ranks[i]
		}
		s |= r << uint(16-4*i)
	}
	return s
}

// straightHigh returns the top rank of the best straight in a rank bitmask,
// 3 for the wheel (A-2-3-4-5), or -1.
func straightHigh(mask int) int {
	for hi := 12; hi >= 4; hi-- {
		m := 0x1f << uint(hi-4)
		if mask&m == m {
			return hi
		}
	}
	wheel := 0xf | 1<<12
	if mask&wheel == wheel {
		return 3
	}
	return -1
}

// topRanks returns up to n highest ranks set in mask, skipping excluded ranks.
func topRanks(mask int, n int, exclude ...int) []int {
	out := []int{}
	for r := 12; r >= 0 && len(out) < n; r-- {
		if mask&(1<<uint(r)) == 0 {
			continue
		}
		skip := false
		for _, e := range exclude {
			if e == r {
				skip = true
			}
		}
		if !skip {
			out = append(out, r)
		}
	}
	return out
}

// Evaluate scores the best five-card hand among 5 to 7 cards. Higher is better;
// equal scores tie.
func Evaluate(cards []int) int {
	if len(cards) < 5 || len(cards) > 7 {
		panic("evaluate needs 5 to 7 cards")
	}
	var counts [13]int
	var suitCount [4]int
	var suitMask [4]int
	rankMask := 0
	for _, c := range cards {
		if c < 0 || c >= 52 {
			panic("invalid card")
		}
		r, s := c%13, c/13
		counts[r]++
		suitCount[s]++
		suitMask[s] |= 1 << uint(r)
		rankMask |= 1 << uint(r)
	}
	flushSuit := -1
	for s := 0; s < 4; s++ {
		if suitCount[s] >= 5 {
			flushSuit = s
		}
	}
	if flushSuit >= 0 {
		if hi := straightHigh(suitMask[flushSuit]); hi >= 0 {
			return makeScore(StraightFlush, hi)
		}
	}
	quad, trip, trip2 := -1, -1, -1
	pairs := []int{}
	for r := 12; r >= 0; r-- {
		switch counts[r] {
		case 4:
			if quad < 0 {
				quad = r
			}
		case 3:
			if trip < 0 {
				trip = r
			} else if trip2 < 0 {
				trip2 = r
			}
		case 2:
			pairs = append(pairs, r)
		}
	}
	if quad >= 0 {
		return makeScore(Quads, append([]int{quad}, topRanks(rankMask, 1, quad)...)...)
	}
	if trip >= 0 {
		pairRank := -1
		if trip2 >= 0 {
			pairRank = trip2
		}
		if len(pairs) > 0 && pairs[0] > pairRank {
			pairRank = pairs[0]
		}
		if pairRank >= 0 {
			return makeScore(FullHouse, trip, pairRank)
		}
	}
	if flushSuit >= 0 {
		return makeScore(Flush, topRanks(suitMask[flushSuit], 5)...)
	}
	if hi := straightHigh(rankMask); hi >= 0 {
		return makeScore(Straight, hi)
	}
	if trip >= 0 {
		return makeScore(Trips, append([]int{trip}, topRanks(rankMask, 2, trip)...)...)
	}
	if len(pairs) >= 2 {
		return makeScore(TwoPair, pairs[0], pairs[1], topRanks(rankMask, 1, pairs[0], pairs[1])[0])
	}
	if len(pairs) == 1 {
		return makeScore(OnePair, append([]int{pairs[0]}, topRanks(rankMask, 3, pairs[0])...)...)
	}
	return makeScore(HighCard, topRanks(rankMask, 5)...)
}

gnomod.toml

module = "gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/holdem"
gno = "0.9"

[addpkg]
  creator = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm"
  height = 1089714
  max_deposit = "50000000ugnot"

pots.gno

package holdem

// MaxPlayers is the largest number of players in one hand.
const MaxPlayers = 6

// Pot is one main or side pot.
type Pot struct {
	Amount   int64
	Eligible []int // player indices that can win this pot
}

// BuildPots splits contributions into a main pot and side pots. Folded
// players' chips go into the pots but they are never eligible. Chips above the
// largest contribution of any live player form a last pot that only the live
// players with that contribution can win (an uncalled bet returns to its
// owner this way).
func BuildPots(contrib []int64, folded []bool) []Pot {
	levels := []int64{}
	for i, c := range contrib {
		if folded[i] {
			continue
		}
		pos := len(levels)
		dup := false
		for k, l := range levels {
			if l == c {
				dup = true
				break
			}
			if l > c {
				pos = k
				break
			}
		}
		if dup {
			continue
		}
		levels = append(levels, 0)
		copy(levels[pos+1:], levels[pos:])
		levels[pos] = c
	}
	if len(levels) == 0 {
		panic("no live players")
	}
	pots := []Pot{}
	prev := int64(0)
	for li, lvl := range levels {
		last := li == len(levels)-1
		amount := int64(0)
		for _, c := range contrib {
			hi := c
			if !last && hi > lvl {
				hi = lvl
			}
			if hi > prev {
				amount += hi - prev
			}
		}
		eligible := []int{}
		for i, c := range contrib {
			if !folded[i] && c >= lvl {
				eligible = append(eligible, i)
			}
		}
		prev = lvl
		if amount == 0 {
			continue
		}
		if n := len(pots); n > 0 && sameInts(pots[n-1].Eligible, eligible) {
			pots[n-1].Amount += amount
			continue
		}
		pots = append(pots, Pot{Amount: amount, Eligible: eligible})
	}
	return pots
}

func sameInts(a, b []int) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

// Distribute awards each pot to its best eligible scores, splitting ties
// equally. The odd chips of a split pot all go to the winner that comes first
// in oddOrder (player indices clockwise from the button). It returns the
// amount won per player; the sum always equals the sum of the pots. It panics
// for more than MaxPlayers scores.
func Distribute(pots []Pot, scores []int, oddOrder []int) []int64 {
	if len(scores) > MaxPlayers {
		panic("too many players")
	}
	var buf [MaxPlayers]int64
	won := buf[:len(scores):len(scores)]
	for _, p := range pots {
		best := -1
		for _, i := range p.Eligible {
			if scores[i] > best {
				best = scores[i]
			}
		}
		winners := []int{}
		for _, i := range p.Eligible {
			if scores[i] == best {
				winners = append(winners, i)
			}
		}
		share := p.Amount / int64(len(winners))
		for _, i := range winners {
			won[i] += share
		}
		rem := p.Amount - share*int64(len(winners))
		if rem > 0 {
			for _, i := range oddOrder {
				if scores[i] == best && contains(winners, i) {
					won[i] += rem
					rem = 0
					break
				}
			}
			if rem > 0 {
				panic("odd chip order misses a winner")
			}
		}
	}
	return won
}

func contains(xs []int, x int) bool {
	for _, v := range xs {
		if v == x {
			return true
		}
	}
	return false
}

// OddChipOrder returns player indices clockwise starting left of the button,
// for hand players indexed from the small blind (heads-up: index 0 is the
// button). It panics unless 0 <= n <= MaxPlayers.
func OddChipOrder(n int) []int {
	if n < 0 || n > MaxPlayers {
		panic("bad player count")
	}
	var buf [MaxPlayers]int
	out := buf[:n:n]
	if n == 2 {
		out[0], out[1] = 1, 0
		return out
	}
	for i := range out {
		out[i] = i
	}
	return out
}