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.

hand.gno

14.22 Kb · 606 lines
  1package poker
  2
  3import (
  4	"strconv"
  5
  6	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/cards"
  7	"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/holdem"
  8)
  9
 10// Hand phases.
 11const (
 12	phShuffle = iota
 13	phRekey
 14	phDealHole
 15	phPreflop
 16	phDealFlop
 17	phFlop
 18	phDealTurn
 19	phTurn
 20	phDealRiver
 21	phRiver
 22	phReveal
 23	phChallenge
 24	phDone
 25)
 26
 27var phaseNames = []string{
 28	"shuffle", "rekey", "deal_hole", "preflop", "deal_flop", "flop",
 29	"deal_turn", "turn", "deal_river", "river", "reveal", "challenge", "done",
 30}
 31
 32// HandPlayer is a seat's participation in one hand.
 33type HandPlayer struct {
 34	Seat     int
 35	Owner    address
 36	Commit   string         // hex
 37	Seed     string         // hex, after reveal
 38	Keys     map[int]string // position -> hex card key
 39	Revealed bool
 40	Accepted bool
 41}
 42
 43// ChallengeRecord is one resolved challenge.
 44type ChallengeRecord struct {
 45	Challenger int
 46	Accused    int
 47	Kind       string
 48	Index      int
 49	Guilty     bool
 50}
 51
 52// Result is the outcome of a hand. Credits are what settlement adds to each
 53// hand player's stack (winnings, or refund plus penalty share on abort).
 54type Result struct {
 55	Aborted    bool
 56	Convicted  []int
 57	Stallers   []int
 58	Credits    []int64
 59	Scores     []int
 60	Challenges []ChallengeRecord
 61}
 62
 63// Hand is the state of the current or last hand of a table.
 64type Hand struct {
 65	No       uint64
 66	Phase    int
 67	Players  []*HandPlayer
 68	Bet      *holdem.Betting
 69	Roots    []string // hex root per accepted deck pass
 70	Owing    []bool   // per player, for deal steps
 71	Deadline int64
 72	Cards    []int // official card per position, after reveal
 73	Result   *Result
 74	Settled  bool // contributions have been paid out or refunded
 75}
 76
 77// maxSeats is the largest table; per-player buffers are sized by it.
 78const maxSeats = holdem.MaxPlayers
 79
 80// n is the number of players in the hand, at most maxSeats.
 81func (h *Hand) n() int { return len(h.Players) }
 82
 83func (h *Hand) playerIndex(seat int) int {
 84	for j, p := range h.Players {
 85		if p.Seat == seat {
 86			return j
 87		}
 88	}
 89	return -1
 90}
 91
 92func isBettingPhase(ph int) bool {
 93	return ph == phPreflop || ph == phFlop || ph == phTurn || ph == phRiver
 94}
 95
 96func isDealPhase(ph int) bool {
 97	return ph == phDealHole || ph == phDealFlop || ph == phDealTurn || ph == phDealRiver
 98}
 99
100// turnIndex is the player expected to act in an in-turn phase, else -1.
101func (h *Hand) turnIndex() int {
102	switch {
103	case h.Phase == phShuffle:
104		return len(h.Roots)
105	case h.Phase == phRekey:
106		return len(h.Roots) - h.n()
107	case isBettingPhase(h.Phase):
108		return h.Bet.Turn
109	}
110	return -1
111}
112
113// owedPositions lists the positions player j must share keys for in the
114// current deal step, ascending.
115func (h *Hand) owedPositions(j int) []int {
116	n := h.n()
117	out := []int{}
118	switch h.Phase {
119	case phDealHole:
120		for i := 0; i < 2*n; i++ {
121			if i/2 != j {
122				out = append(out, i)
123			}
124		}
125	case phDealFlop:
126		out = append(out, 2*n, 2*n+1, 2*n+2)
127	case phDealTurn:
128		out = append(out, 2*n+3)
129	case phDealRiver:
130		out = append(out, 2*n+4)
131	}
132	return out
133}
134
135func (t *Table) eligible(i int) bool {
136	s := t.Seats[i]
137	return s != nil && !s.SittingOut && !s.Leaving && s.Stack >= t.BigBlind
138}
139
140// StartHand moves the button, posts blinds and opens the shuffle.
141func StartHand(cur realm, tableID uint64) {
142	assertNoSend(cur)
143	ctx := newCtx(cur)
144	t := getTable(tableID)
145	t.authSeat(ctx.caller)
146	if t.Hand != nil && t.Hand.Phase != phDone {
147		panic("a hand is in progress")
148	}
149	m := t.MaxPlayers
150	seats := []int{}
151	for k := 1; k <= m; k++ {
152		i := (t.Button + k + m) % m
153		if t.eligible(i) {
154			seats = append(seats, i)
155		}
156	}
157	if len(seats) < 2 {
158		panic("need at least 2 active players with a stack of at least the big blind")
159	}
160	// seats starts with the new button.
161	button := seats[0]
162	order := []int{}
163	if len(seats) == 2 {
164		order = append(order, seats[0], seats[1])
165	} else {
166		order = append(order, seats[1:]...)
167		order = append(order, button)
168	}
169	t.Button = button
170	t.HandNo++
171	for _, s := range t.Seats {
172		if s != nil {
173			s.Waiting = false
174		}
175	}
176	if len(order) > maxSeats {
177		panic("too many players")
178	}
179	var stackBuf [maxSeats]int64
180	stacks := stackBuf[:len(order):len(order)]
181	players := make([]*HandPlayer, len(order))
182	for j, si := range order {
183		stacks[j] = t.Seats[si].Stack
184		players[j] = &HandPlayer{Seat: si, Owner: t.Seats[si].Owner, Keys: map[int]string{}}
185	}
186	h := &Hand{
187		No:       t.HandNo,
188		Phase:    phShuffle,
189		Players:  players,
190		Bet:      holdem.NewBetting(stacks, t.SmallBlind, t.BigBlind),
191		Deadline: ctx.height + t.ActionTimeout,
192	}
193	t.Hand = h
194	t.syncStacks()
195}
196
197func (t *Table) syncStacks() {
198	for j, p := range t.Hand.Players {
199		t.Seats[p.Seat].Stack = t.Hand.Bet.Players[j].Stack
200	}
201}
202
203// handFor validates the table, hand number and caller, and returns the hand
204// and the caller's hand index.
205func handFor(cur realm, tableID, handNo uint64) (*Table, *Hand, int) {
206	t := getTable(tableID)
207	h := t.Hand
208	if h == nil || h.No != handNo || handNo != t.HandNo {
209		panic("stale or unknown hand number")
210	}
211	if h.Phase == phDone {
212		panic("hand is over")
213	}
214	seat := t.authSeat(cur.Previous().Address())
215	j := h.playerIndex(seat)
216	if j < 0 {
217		panic("caller is not in this hand")
218	}
219	return t, h, j
220}
221
222// SubmitShuffle records the caller's commitment and shuffled deck.
223func SubmitShuffle(cur realm, tableID, handNo uint64, commitHex, deckB64 string) {
224	assertNoSend(cur)
225	ctx := newCtx(cur)
226	t, h, j := handFor(cur, tableID, handNo)
227	if h.Phase != phShuffle {
228		panic("not in shuffle phase")
229	}
230	if j != h.turnIndex() {
231		panic("not this player's turn to shuffle")
232	}
233	if _, err := cards.DecodeHex(commitHex, 32); err != nil {
234		panic("commit: " + err.Error())
235	}
236	t.acceptDeck(h, deckB64)
237	h.Players[j].Commit = commitHex
238	h.Deadline = ctx.height + t.ActionTimeout
239	if len(h.Roots) == h.n() {
240		h.Phase = phRekey
241	}
242}
243
244// SubmitRekey records the caller's re-keyed deck.
245func SubmitRekey(cur realm, tableID, handNo uint64, deckB64 string) {
246	assertNoSend(cur)
247	ctx := newCtx(cur)
248	t, h, j := handFor(cur, tableID, handNo)
249	if h.Phase != phRekey {
250		panic("not in rekey phase")
251	}
252	if j != h.turnIndex() {
253		panic("not this player's turn to rekey")
254	}
255	t.acceptDeck(h, deckB64)
256	h.Deadline = ctx.height + t.ActionTimeout
257	if len(h.Roots) == 2*h.n() {
258		h.startDeal(ctx, t, phDealHole)
259	}
260}
261
262func (t *Table) acceptDeck(h *Hand, deckB64 string) {
263	deck, root, err := cards.ParseDeck(deckB64)
264	if err != nil {
265		panic("deck: " + err.Error())
266	}
267	h.Roots = append(h.Roots, cards.EncodeHex(root))
268	t.Deck = string(deck)
269	t.DeckHand = h.No
270}
271
272func (h *Hand) startDeal(ctx *txCtx, t *Table, phase int) {
273	h.Phase = phase
274	var owing [maxSeats]bool
275	h.Owing = owing[:h.n():h.n()]
276	for j := range h.Owing {
277		h.Owing[j] = true
278	}
279	h.Deadline = ctx.height + t.ActionTimeout
280}
281
282// ShareKeys publishes the caller's card keys for the current deal step.
283func ShareKeys(cur realm, tableID, handNo uint64, keysHex string) {
284	assertNoSend(cur)
285	ctx := newCtx(cur)
286	t, h, j := handFor(cur, tableID, handNo)
287	if !isDealPhase(h.Phase) {
288		panic("not in a deal phase")
289	}
290	if !h.Owing[j] {
291		panic("keys already shared")
292	}
293	pos := h.owedPositions(j)
294	if len(keysHex) != 64*len(pos) {
295		panic("expected " + strconv.Itoa(len(pos)) + " keys")
296	}
297	if _, err := cards.DecodeHex(keysHex, 32*len(pos)); err != nil {
298		panic("keys: " + err.Error())
299	}
300	p := h.Players[j]
301	for k, i := range pos {
302		p.Keys[i] = keysHex[64*k : 64*(k+1)]
303	}
304	h.Owing[j] = false
305	for _, o := range h.Owing {
306		if o {
307			return
308		}
309	}
310	h.Owing = nil
311	switch h.Phase {
312	case phDealHole:
313		h.Phase = phPreflop
314	case phDealFlop:
315		h.Bet.NextStreet()
316		h.Phase = phFlop
317	case phDealTurn:
318		h.Bet.NextStreet()
319		h.Phase = phTurn
320	case phDealRiver:
321		h.Bet.NextStreet()
322		h.Phase = phRiver
323	}
324	h.Deadline = ctx.height + t.ActionTimeout
325	t.afterBetting(ctx)
326}
327
328// Act applies a betting action by the player to act.
329func Act(cur realm, tableID, handNo uint64, action string, amount int64) {
330	assertNoSend(cur)
331	ctx := newCtx(cur)
332	t, h, j := handFor(cur, tableID, handNo)
333	if !isBettingPhase(h.Phase) {
334		panic("not in a betting phase")
335	}
336	t.applyAction(ctx, j, action, amount)
337}
338
339func (t *Table) applyAction(ctx *txCtx, j int, action string, amount int64) {
340	h := t.Hand
341	if err := h.Bet.Act(j, action, amount); err != nil {
342		panic(err.Error())
343	}
344	t.syncStacks()
345	h.Deadline = ctx.height + t.ActionTimeout
346	t.afterBetting(ctx)
347}
348
349// afterBetting moves on once the street needs no more action.
350func (t *Table) afterBetting(ctx *txCtx) {
351	h := t.Hand
352	if !isBettingPhase(h.Phase) || !h.Bet.StreetComplete() {
353		return
354	}
355	if h.Bet.Closed() || h.Phase == phRiver {
356		h.Phase = phReveal
357		h.Deadline = ctx.height + t.ActionTimeout
358		return
359	}
360	switch h.Phase {
361	case phPreflop:
362		h.startDeal(ctx, t, phDealFlop)
363	case phFlop:
364		h.startDeal(ctx, t, phDealTurn)
365	case phTurn:
366		h.startDeal(ctx, t, phDealRiver)
367	}
368}
369
370// RevealSeed opens the caller's seed; published card keys are checked at once.
371func RevealSeed(cur realm, tableID, handNo uint64, seedHex string) {
372	assertNoSend(cur)
373	ctx := newCtx(cur)
374	t, h, j := handFor(cur, tableID, handNo)
375	if h.Phase != phReveal {
376		panic("not in reveal phase")
377	}
378	p := h.Players[j]
379	if p.Revealed {
380		panic("seed already revealed")
381	}
382	seed, err := cards.DecodeHex(seedHex, 32)
383	if err != nil {
384		panic("seed: " + err.Error())
385	}
386	if cards.EncodeHex(cards.Commit(seed)) != p.Commit {
387		panic("seed does not match commitment")
388	}
389	p.Seed = seedHex
390	p.Revealed = true
391	for pos, key := range p.Keys {
392		if cards.EncodeHex(cards.CardKey(seed, pos)) != key {
393			t.abort(ctx, []int{j}, true)
394			return
395		}
396	}
397	for _, q := range h.Players {
398		if !q.Revealed {
399			return
400		}
401	}
402	t.showdown(ctx)
403}
404
405func seedBytes(p *HandPlayer) []byte {
406	b, err := cards.DecodeHex(p.Seed, 32)
407	if err != nil {
408		panic("seed missing")
409	}
410	return b
411}
412
413// showdown derives all cards from the seeds and computes the payouts.
414func (t *Table) showdown(ctx *txCtx) {
415	h := t.Hand
416	n := h.n()
417	perms := make([][]int, n)
418	for j, p := range h.Players {
419		perms[j] = cards.Permutation(seedBytes(p))
420	}
421	h.Cards = cards.OfficialCards(perms)
422	board := h.Cards[2*n : 2*n+5]
423	var contribBuf [maxSeats]int64
424	var foldedBuf [maxSeats]bool
425	var scoreBuf [maxSeats]int
426	contrib, folded, scores := contribBuf[:n:n], foldedBuf[:n:n], scoreBuf[:n:n]
427	for j, bp := range h.Bet.Players {
428		contrib[j] = bp.Contributed
429		folded[j] = bp.Folded
430		if !bp.Folded {
431			seven := []int{h.Cards[2*j], h.Cards[2*j+1]}
432			seven = append(seven, board...)
433			scores[j] = holdem.Evaluate(seven)
434		} else {
435			scores[j] = -1
436		}
437	}
438	pots := holdem.BuildPots(contrib, folded)
439	won := holdem.Distribute(pots, scores, holdem.OddChipOrder(n))
440	h.Result = &Result{Credits: won, Scores: scores}
441	if !challengesEnabled {
442		t.finalize(ctx)
443		return
444	}
445	h.Phase = phChallenge
446	h.Deadline = ctx.height + t.ChallengeWindow
447}
448
449// finalize pays the recorded result and ends the hand.
450func (t *Table) finalize(ctx *txCtx) {
451	h := t.Hand
452	for j, p := range h.Players {
453		t.Seats[p.Seat].Stack += h.Result.Credits[j]
454	}
455	h.Settled = true
456	h.Phase = phDone
457	t.cleanupSeats(ctx)
458}
459
460// cleanupSeats pays out and frees seats marked leaving.
461func (t *Table) cleanupSeats(ctx *txCtx) {
462	for i, s := range t.Seats {
463		if s != nil && s.Leaving {
464			t.removeSeat(ctx, i)
465		}
466	}
467}
468
469// abort ends the hand without a showdown: all contributions are refunded and
470// each penalized player's whole stack is split equally among the other hand
471// players (remainder to the lowest hand index), then the penalized players
472// are removed from the table.
473func (t *Table) abort(ctx *txCtx, penalized []int, convicted bool) {
474	h := t.Hand
475	n := h.n()
476	var creditBuf [maxSeats]int64
477	credits := creditBuf[:n:n]
478	if !h.Settled {
479		for j, p := range h.Players {
480			c := h.Bet.Players[j].Contributed
481			t.Seats[p.Seat].Stack += c
482			credits[j] = c
483		}
484	}
485	var penBuf [maxSeats]bool
486	isPen := penBuf[:n:n]
487	for _, j := range penalized {
488		isPen[j] = true
489	}
490	recipients := []int{}
491	for j := 0; j < n; j++ {
492		if !isPen[j] {
493			recipients = append(recipients, j)
494		}
495	}
496	if len(recipients) > 0 {
497		for _, j := range penalized {
498			s := t.Seats[h.Players[j].Seat]
499			amount := s.Stack
500			s.Stack = 0
501			credits[j] = 0
502			share := amount / int64(len(recipients))
503			rem := amount - share*int64(len(recipients))
504			for k, r := range recipients {
505				add := share
506				if k == 0 {
507					add += rem
508				}
509				t.Seats[h.Players[r].Seat].Stack += add
510				credits[r] += add
511			}
512		}
513	}
514	res := &Result{Aborted: true, Credits: credits}
515	if h.Result != nil {
516		res.Challenges = h.Result.Challenges
517	}
518	if convicted {
519		res.Convicted = penalized
520	} else {
521		res.Stallers = penalized
522	}
523	h.Result = res
524	h.Settled = true
525	h.Phase = phDone
526	for _, j := range penalized {
527		t.removeSeat(ctx, h.Players[j].Seat)
528	}
529	t.cleanupSeats(ctx)
530}
531
532// Accept agrees with the result; when all hand players accept, the hand is
533// finalized without waiting for the window.
534func Accept(cur realm, tableID, handNo uint64) {
535	assertNoSend(cur)
536	ctx := newCtx(cur)
537	t, h, j := handFor(cur, tableID, handNo)
538	if h.Phase != phChallenge {
539		panic("not in challenge window")
540	}
541	h.Players[j].Accepted = true
542	for _, p := range h.Players {
543		if !p.Accepted {
544			return
545		}
546	}
547	t.finalize(ctx)
548}
549
550// Finalize settles the hand once the challenge window has passed.
551func Finalize(cur realm, tableID uint64) {
552	assertNoSend(cur)
553	ctx := newCtx(cur)
554	t := getTable(tableID)
555	h := t.Hand
556	if h == nil || h.Phase != phChallenge {
557		panic("no hand in challenge window")
558	}
559	if ctx.height <= h.Deadline {
560		panic("challenge window still open")
561	}
562	t.finalize(ctx)
563}
564
565// Timeout applies the stall rules once the current deadline has passed.
566func Timeout(cur realm, tableID uint64) {
567	assertNoSend(cur)
568	ctx := newCtx(cur)
569	t := getTable(tableID)
570	h := t.Hand
571	if h == nil || h.Phase == phDone {
572		panic("no hand in progress")
573	}
574	if ctx.height <= h.Deadline {
575		panic("deadline not reached")
576	}
577	switch {
578	case isBettingPhase(h.Phase):
579		j := h.Bet.Turn
580		if h.Bet.CanCheck(j) {
581			t.applyAction(ctx, j, "check", 0)
582		} else {
583			t.applyAction(ctx, j, "fold", 0)
584		}
585	case h.Phase == phShuffle || h.Phase == phRekey:
586		t.abort(ctx, []int{h.turnIndex()}, false)
587	case isDealPhase(h.Phase):
588		stallers := []int{}
589		for j, o := range h.Owing {
590			if o {
591				stallers = append(stallers, j)
592			}
593		}
594		t.abort(ctx, stallers, false)
595	case h.Phase == phReveal:
596		stallers := []int{}
597		for j, p := range h.Players {
598			if !p.Revealed {
599				stallers = append(stallers, j)
600			}
601		}
602		t.abort(ctx, stallers, false)
603	case h.Phase == phChallenge:
604		t.finalize(ctx)
605	}
606}