aboutsummaryrefslogtreecommitdiff
path: root/internal/casino/types.go
blob: a5e1415623a07950d8a9d50edfd12bb0d5c2faa4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package casino

import "fmt"

// betRangeText describes the accepted wager range; the unlimited sentinel is
// rendered as "no maximum" instead of a machine-sized integer.
func betRangeText(minBet, maxBet int) string {
	if maxBet == maxBetUnlimited {
		return fmt.Sprintf("%d or more (no maximum)", minBet)
	}
	return fmt.Sprintf("between %d and %d", minBet, maxBet)
}

type GameName string

const (
	GameSlots     GameName = "slots"
	GameBlackjack GameName = "blackjack"
	GameBaccarat  GameName = "baccarat"
)

type BlackjackConfig struct {
	Decks                int     `yaml:"decks,omitempty"`
	ShuffleAt            float64 `yaml:"shuffle_at,omitempty"`
	BlackjackPayout      float64 `yaml:"blackjack_payout,omitempty"`
	DealerHitSoft17      *bool   `yaml:"dealer_hit_soft_17,omitempty"`
	MaxSplitHands        int     `yaml:"max_split_hands,omitempty"`
	ResplitAces          *bool   `yaml:"resplit_aces,omitempty"`
	DoubleAfterSplit     *bool   `yaml:"double_after_split,omitempty"`
	DoubleSplitBlackjack *bool   `yaml:"double_split_blackjack,omitempty"`
	InsurancePayout      float64 `yaml:"insurance_payout,omitempty"`
	Surrender            *bool   `yaml:"surrender,omitempty"`
	ActionTicks          int     `yaml:"action_ticks,omitempty"`
	SplitUnlikeTenValues *bool   `yaml:"split_unlike_ten_values,omitempty"`
}

func ruleBool(value *bool, defaultValue bool) bool {
	if value == nil {
		return defaultValue
	}
	return *value
}

func (c BlackjackConfig) DealerHitsSoft17() bool       { return ruleBool(c.DealerHitSoft17, false) }
func (c BlackjackConfig) AllowsResplitAces() bool      { return ruleBool(c.ResplitAces, false) }
func (c BlackjackConfig) AllowsDoubleAfterSplit() bool { return ruleBool(c.DoubleAfterSplit, true) }

// CountsDoubleSplitBlackjack reports whether a 3+ card hand that reaches 21
// after a split and double is paid as a blackjack (3:2). When true (the
// default) this raises the table RTP above the nominal blackjack payout;
// standard play pays 1:1 for any 21 on a split hand, doubled or not.
func (c BlackjackConfig) CountsDoubleSplitBlackjack() bool {
	return ruleBool(c.DoubleSplitBlackjack, true)
}

func (c BlackjackConfig) AllowsSurrender() bool { return ruleBool(c.Surrender, false) }

// AllowsUnlikeTenSplit reports whether any two 10-valued cards may split
// (K+Q, 10+J). Standard casinos split only identical ranks, so a true value
// (the default) is player-favourable.
func (c BlackjackConfig) AllowsUnlikeTenSplit() bool { return ruleBool(c.SplitUnlikeTenValues, true) }

func (c BlackjackConfig) Normalize() BlackjackConfig {
	if c.Decks <= 0 {
		c.Decks = 8
	}
	if c.ShuffleAt <= 0 || c.ShuffleAt >= 1 {
		c.ShuffleAt = 0.25
	}
	if c.BlackjackPayout <= 0 {
		c.BlackjackPayout = 1.5
	}
	if c.MaxSplitHands <= 0 {
		c.MaxSplitHands = 4
	}
	if c.InsurancePayout <= 0 {
		c.InsurancePayout = 2
	}
	if c.ActionTicks <= 0 {
		c.ActionTicks = 20
	}
	return c
}

// BaccaratConfig holds punto banco house rules: shoe composition and payout
// multipliers. Banker wins pay BankerPayout:1 (a 5% commission game is 0.95);
// tie wins pay TiePayout:1.
type BaccaratConfig struct {
	Decks        int     `yaml:"decks,omitempty"`
	ShuffleAt    float64 `yaml:"shuffle_at,omitempty"`
	TiePayout    float64 `yaml:"tie_payout,omitempty"`
	BankerPayout float64 `yaml:"banker_payout,omitempty"`
}

func (c BaccaratConfig) Normalize() BaccaratConfig {
	if c.Decks <= 0 {
		c.Decks = 8
	}
	if c.ShuffleAt <= 0 || c.ShuffleAt >= 1 {
		c.ShuffleAt = 0.25
	}
	if c.TiePayout <= 0 {
		c.TiePayout = 8
	}
	if c.BankerPayout <= 0 {
		c.BankerPayout = 0.95
	}
	return c
}

type TableConfig struct {
	ID           string          `yaml:"id"`
	Game         GameName        `yaml:"game"`
	MaxPlayers   int             `yaml:"max_players,omitempty"`
	BettingTicks int             `yaml:"betting_ticks,omitempty"`
	MinBet       int             `yaml:"min_bet,omitempty"`
	MaxBet       int             `yaml:"max_bet,omitempty"`
	Blackjack    BlackjackConfig `yaml:"blackjack,omitempty"`
	Baccarat     BaccaratConfig  `yaml:"baccarat,omitempty"`
}

type MachineConfig struct {
	ID        string   `yaml:"id"`
	Game      GameName `yaml:"game"`
	Variant   string   `yaml:"variant,omitempty"`
	MinBet    int      `yaml:"min_bet,omitempty"`
	MaxBet    int      `yaml:"max_bet,omitempty"`
	SpinTicks int      `yaml:"spin_ticks,omitempty"`
	Payout    float64  `yaml:"payout,omitempty"`
}

// LegacySlotMachine converts a legacy slots TableConfig (older rooms declared
// slots under casino_tables) into the MachineConfig the room actually
// instantiates. Shared by validation and room lookup so the two cannot drift.
func LegacySlotMachine(c TableConfig) MachineConfig {
	return MachineConfig{ID: c.ID, Game: GameSlots, MinBet: c.MinBet, MaxBet: c.MaxBet}
}

func (c MachineConfig) Normalize() MachineConfig {
	if c.MinBet <= 0 {
		c.MinBet = 1
	}
	// An unset MaxBet defaults to the economy's bounded cap; the explicit
	// unlimited sentinel is still honored for authored configurations.
	if c.MaxBet <= 0 {
		c.MaxBet = DefaultMaxBet
	}
	// Never leave a normalized config self-contradictory: a min_bet above
	// the default cap must widen the effective maximum rather than produce
	// a game every wager is rejected from.
	if c.MaxBet < c.MinBet {
		c.MaxBet = c.MinBet
	}
	if c.SpinTicks <= 0 {
		c.SpinTicks = 2
	}
	if c.Variant == "" {
		c.Variant = "huff_and_even_more_puff"
	}
	if c.Payout <= 0 {
		c.Payout = 0.97
	}
	return c
}

func (c TableConfig) Normalize() TableConfig {
	if c.MaxPlayers <= 0 {
		c.MaxPlayers = 8
	}
	if c.BettingTicks <= 0 {
		c.BettingTicks = 20
	}
	if c.MinBet <= 0 {
		c.MinBet = 1
	}
	if c.MaxBet <= 0 {
		c.MaxBet = DefaultMaxBet
	}
	// Normalize the nested game rule blocks too: a new game that reads
	// t.Config.Blackjack/Baccarat directly (rather than only t.Rules) would
	// otherwise see zero values and build an empty shoe.
	c.Blackjack = c.Blackjack.Normalize()
	c.Baccarat = c.Baccarat.Normalize()
	if c.MaxBet < c.MinBet {
		c.MaxBet = c.MinBet
	}
	return c
}

type Wager struct {
	Total   int
	Chips   int
	Credits int
	// ID is the wallet's opaque handle for the committed stake. Table
	// settlements pass the hand's stake IDs to PayStakeCover so the wallet
	// removes exactly the stakes the payout returns.
	ID string
}

type Wallet interface {
	// Wager debits the stake and records it as pending. ErrInsufficientFunds
	// is a normal rejected bet; ErrWalletPersistence means the debit could
	// not be made durable and the game must not proceed as if it succeeded.
	Wager(amount int) (Wager, error)
	// PayCredits pays winnings durably, returning an error when the credit
	// could not be persisted (the game must not report a win that is not
	// durable). The payout carries no stake linkage: the stake was consumed
	// by playing the round, so the game resolves it separately.
	PayCredits(amount int) error
	// PayStakeCover pays a settlement whose amount INCLUDES the return of
	// the listed stake wager IDs (a table hand pays back its stake inside
	// the payout). The credit and the removal of those stakes are one
	// durable step, so a failed settlement leaves the stakes pending —
	// refunded at the next startup, never paid on top of the refund.
	PayStakeCover(amount int, stakeIDs []string) error
	// ResolveStakes consumes every pending stake for this player: the round
	// resolved as a loss, a forfeit, or an unlinked payout, so the stakes
	// must not be refunded.
	ResolveStakes()
	// ResolveStake consumes ONE pending stake by wallet handle (a single
	// hand paid or lost while a sibling hand's round is still in flight).
	ResolveStake(stakeID string)
	// RefundOutstanding returns every pending stake to the player (chips as
	// chips, credits as credits) and clears the ledger. An error means the
	// refund could not be made durable: nothing was returned and the stakes
	// remain pending for a later attempt or startup recovery.
	RefundOutstanding() (chips, credits int, err error)
}

type EventType string

// Only the event types the games actually construct are defined. Payout and
// win styling travels on Event.Color, so there is no separate payout event
// type to keep in sync.
const (
	EventJoined EventType = "joined"
	EventResult EventType = "result"
	EventLeft   EventType = "left"
)

// MenuView carries a structured menu alongside its plain-text Message so the
// presentation layer can enrich it (balances, command colors) without parsing
// message prefixes. It is deliberately game-agnostic: every game supplies a
// heading and its command list, and the renderer has no per-game switch that
// could silently drop a new game's commands.
type MenuView struct {
	Heading     string // prompt heading shown above the command list
	ShowBalance bool   // prepend the player's chips/credits balance
	Commands    []MenuCommand
}

// MenuCommand is one selectable command shown in a casino menu: the typed
// command text plus a short human-readable description.
type MenuCommand struct {
	Command string
	Desc    string
}

type Event struct {
	RoomID         int
	TableID        string
	Type           EventType
	Player         string
	Message        string
	PrivateMessage string
	PrivateTo      string
	Color          string
	Public         bool
	// Snapshot is the optional per-game view attached to the event. A game
	// implements the Snapshot interface for its view type; the presentation
	// layer type-switches on it. Because the field is typed, a new game's
	// snapshot can never be assigned without implementing the interface, and
	// the event filter can test it with a single nil check instead of
	// enumerating every game's field.
	Snapshot Snapshot
	Menu     *MenuView
}

// Snapshot is the marker interface for a game's structured event view. The
// method is unexported so only types in this package can implement it.
type Snapshot interface{ snapshot() }

type SlotSnapshot struct {
	Grid         [slotGridRows][slotGridReels]string
	StoppedReels int
}

func (*SlotSnapshot) snapshot() {}

// CardView renders one card for any card-based table game.
type CardView struct {
	Rank   string
	Suit   string
	Hidden bool
}

type BlackjackPlayerView struct {
	Name  string
	Cards []CardView
	Score string
}

type BlackjackSnapshot struct {
	Dealer           []CardView
	DealerShownScore string
	DealerScore      string
	DealerRevealed   bool
	Players          []BlackjackPlayerView
}

func (*BlackjackSnapshot) snapshot() {}

// BaccaratBetView lists one participant's wager on a baccarat outcome.
type BaccaratBetView struct {
	Name   string
	Spot   string
	Amount int
}

type BaccaratSnapshot struct {
	Player      []CardView
	Banker      []CardView
	PlayerScore string
	BankerScore string
	Bets        []BaccaratBetView
}

func (*BaccaratSnapshot) snapshot() {}

type Participant struct {
	Name      string
	Connected bool
	HasBet    bool
	Wager     Wager
	Wallet    Wallet
}