aboutsummaryrefslogtreecommitdiff
path: root/internal/casino
diff options
context:
space:
mode:
Diffstat (limited to 'internal/casino')
-rw-r--r--internal/casino/machine.go364
-rw-r--r--internal/casino/manager.go238
-rw-r--r--internal/casino/manager_test.go103
-rw-r--r--internal/casino/slots.go278
-rw-r--r--internal/casino/slots_test.go44
-rw-r--r--internal/casino/table.go217
-rw-r--r--internal/casino/types.go121
7 files changed, 1365 insertions, 0 deletions
diff --git a/internal/casino/machine.go b/internal/casino/machine.go
new file mode 100644
index 0000000..d9fa590
--- /dev/null
+++ b/internal/casino/machine.go
@@ -0,0 +1,364 @@
+package casino
+
+import (
+ "fmt"
+ "math/rand"
+ "sync"
+)
+
+type machinePhase string
+
+const (
+ machineReady machinePhase = "ready"
+ machineSpinning machinePhase = "spinning"
+ machinePayout machinePhase = "payout"
+ payoutDelay = 2
+)
+
+type Machine struct {
+ mu sync.Mutex
+ RoomID int
+ Config MachineConfig
+ player *Participant
+ bet int
+ phase machinePhase
+ spin *SlotSpin
+ reel int
+ clock int
+ freeSpins int
+ spinBet int
+ payoutRemainder float64
+ profile SlotProfile
+ rng *rand.Rand
+ suspense bool
+ autoBet bool
+ autoCountdown int
+}
+
+func newMachine(roomID int, cfg MachineConfig, rng *rand.Rand) *Machine {
+ profile := DefaultHuffAndPuffProfile()
+ if cfg.Payout > 0 {
+ profile = ScaleToRTP(profile, cfg.Payout)
+ }
+ return &Machine{RoomID: roomID, Config: cfg, phase: machineReady, profile: profile, rng: rng}
+}
+
+func (m *Machine) join(name string) []Event {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.player != nil && m.player.Name != name {
+ return []Event{{RoomID: m.RoomID, TableID: m.Config.ID, Type: EventResult, PrivateTo: name, Message: "That slot machine is occupied."}}
+ }
+ if m.player == nil {
+ m.player = &Participant{Name: name, Connected: true}
+ events := []Event{{RoomID: m.RoomID, TableID: m.Config.ID, Type: EventJoined, Player: name,
+ Message: fmt.Sprintf("%s sits down at the slots machine.", name),
+ PrivateMessage: "You sit down at the slot machine.", PrivateTo: name, Color: "casino_action", Public: true}}
+ return append(events, m.privateMenu("You sit down at the slot machine.")...)
+ }
+ m.player.Connected = true
+ if m.autoBet {
+ return m.private("Autobet is active. Type \"stop\" to stop playing.")
+ }
+ return m.menuEvents("You resume your place at the slot machine.")
+}
+
+func (m *Machine) setBet(name string, amount int) []Event {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.owns(name) {
+ return m.private("You aren't playing at a slot machine.")
+ }
+ if m.autoBet {
+ return m.private("Autobet is active. Type \"stop\" to stop playing.")
+ }
+ if m.phase != machineReady {
+ return m.private("You're in the middle of a spin!")
+ }
+ if amount < m.Config.MinBet || amount > m.Config.MaxBet {
+ return m.private(fmt.Sprintf("Slot machine bets must be between %d and %d.", m.Config.MinBet, m.Config.MaxBet))
+ }
+ m.bet = amount
+ return m.menuEvents(fmt.Sprintf("Your slot machine bet is set to %d.", amount))
+}
+
+func (m *Machine) start(name string, wallet Wallet) []Event {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.owns(name) {
+ return m.private("You aren't playing at a slot machine.")
+ }
+ if m.autoBet {
+ return m.private("Autobet is active. Type \"stop\" to stop playing.")
+ }
+ if m.phase != machineReady {
+ return m.private("You're in the middle of a spin!")
+ }
+ if m.bet <= 0 {
+ return m.private("Set a wager first with 'bet <amount>'.")
+ }
+ wager := m.bet
+ if m.freeSpins > 0 {
+ m.spinBet = wager
+ } else {
+ if _, ok := wallet.Wager(wager); !ok {
+ return m.private("You don't have enough chips and credits for that bet.")
+ }
+ m.spinBet = wager
+ }
+ m.player.Wallet = wallet
+ m.spin = generateSlotSpinWithProfile(m.rng, m.spinBet, m.profile)
+ m.reel, m.clock, m.suspense = 0, 0, false
+ m.phase = machineSpinning
+ if m.freeSpins > 0 {
+ m.freeSpins--
+ return m.playerAction(fmt.Sprintf("%s begins a free spin.", name), "You begin a free spin.")
+ }
+ return m.playerAction(fmt.Sprintf("%s pulls the lever on the slots machine.", name), "You pull the lever on the slots machine.")
+}
+
+func (m *Machine) enableAutoBet(name string, wallet Wallet) []Event {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.owns(name) {
+ return m.private("You aren't playing at a slot machine.")
+ }
+ if m.autoBet {
+ return m.private("Autobet is already active.")
+ }
+ if m.phase != machineReady {
+ return m.private("You're in the middle of a spin!")
+ }
+ if m.bet <= 0 {
+ return m.private("Set a wager first with 'bet <amount>'.")
+ }
+ m.player.Wallet = wallet
+ m.autoBet = true
+ m.autoCountdown = 0
+ return nil
+}
+
+func (m *Machine) stopAutoBet(name string) ([]Event, bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.owns(name) || !m.autoBet {
+ return nil, false
+ }
+ m.autoBet = false
+ m.autoCountdown = 0
+ return m.private("Autobet stopped. You remain at the slot machine."), true
+}
+
+func (m *Machine) tick() []Event {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.phase == machineReady && m.autoBet {
+ return m.autoBetTick()
+ }
+ if (m.phase != machineSpinning && m.phase != machinePayout) || m.spin == nil {
+ return nil
+ }
+ if m.phase == machinePayout {
+ m.clock++
+ if m.clock < payoutDelay {
+ return nil
+ }
+ m.clock = 0
+ m.phase = machineReady
+ return m.finishSpin()
+ }
+ m.clock++
+ delay := m.Config.SpinTicks
+ if m.suspense && delay < 4 {
+ delay = 4
+ }
+ if m.clock < delay {
+ return nil
+ }
+ m.clock = 0
+ m.reel++
+ message := fmt.Sprintf("Reel %d stops...", m.reel)
+ events := m.publicSlot(message, m.reel)
+ if m.reel < 5 && stoppedScatters(m.spin.Grid, m.reel) >= 2 && !m.suspense {
+ m.suspense = true
+ events = append(events, m.public("Two scatters! The remaining reels slow down...")...)
+ }
+ if m.reel < 5 {
+ return events
+ }
+ m.phase = machinePayout
+ m.clock = 0
+ return events
+}
+
+func (m *Machine) autoBetTick() []Event {
+ m.autoCountdown++
+ switch m.autoCountdown {
+ case 1:
+ return m.private("Autobet enabled!")
+ case 2:
+ return m.private(`Type "stop" to stop playing`)
+ case 3:
+ m.autoCountdown = 0
+ if m.bet <= 0 || m.player.Wallet == nil {
+ m.autoBet = false
+ return m.private("Autobet stopped: no wager is set.")
+ }
+ if _, ok := m.player.Wallet.Wager(m.bet); !ok {
+ m.autoBet = false
+ return m.private("Autobet stopped: you don't have enough chips and credits for that bet.")
+ }
+ m.spinBet = m.bet
+ m.spin = generateSlotSpinWithProfile(m.rng, m.spinBet, m.profile)
+ m.reel, m.clock, m.suspense = 0, 0, false
+ m.phase = machineSpinning
+ return m.playerAction(fmt.Sprintf("%s starts an automatic spin.", m.player.Name), fmt.Sprintf("Betting... %d credits.", m.bet))
+ default:
+ return nil
+ }
+}
+
+func (m *Machine) finishSpin() []Event {
+ events := []Event{}
+ result := m.spin.Payout + m.payoutRemainder
+ credits := int(result)
+ m.payoutRemainder = result - float64(credits)
+ if credits > 0 && m.player.Wallet != nil {
+ m.player.Wallet.PayCredits(credits)
+ }
+ if credits > 0 {
+ winEvents := m.private(fmt.Sprintf("\nYou win %d credits.", credits))
+ winEvents[0].Color = "casino_payout"
+ if credits > m.spinBet {
+ winEvents[0].Color = "casino_big_win"
+ }
+ if credits >= 2*m.spinBet {
+ winEvents[0].Color = "casino_jackpot_win"
+ }
+ events = append(events, winEvents...)
+ }
+ if len(m.spin.Wins) > 0 {
+ winEvents := m.private(formatWins(m.spin.Wins))
+ winEvents[0].Color = "casino_win"
+ events = append(events, winEvents...)
+ }
+ if m.spin.ScatterCount >= 3 && m.freeSpins == 0 {
+ m.freeSpins = 8
+ events = append(events, m.public("Three scatter symbols trigger 8 free spins!")...)
+ }
+ if m.freeSpins > 0 {
+ m.freeSpins--
+ m.phase = machineSpinning
+ m.spin = generateSlotSpinWithProfile(m.rng, m.spinBet, m.profile)
+ m.reel, m.clock, m.suspense = 0, 0, false
+ events = append(events, m.public(fmt.Sprintf("%d free spins remain.", m.freeSpins))...)
+ } else if !m.autoBet {
+ events = append(events, m.menuEvents("")...)
+ }
+ return events
+}
+
+func (m *Machine) leave(name string) []Event {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.owns(name) {
+ return nil
+ }
+ if m.phase != machineReady {
+ return m.private("You're in the middle of a spin!")
+ }
+ m.player = nil
+ m.bet = 0
+ return []Event{{RoomID: m.RoomID, TableID: m.Config.ID, Type: EventLeft, Player: name,
+ Message: fmt.Sprintf("%s stands up from the slots machine.", name), PrivateMessage: "You stand up from the slot machine.", PrivateTo: name, Color: "casino_action", Public: true}}
+}
+
+func (m *Machine) markDisconnected(name string) []Event {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.owns(name) {
+ m.player.Connected = false
+ }
+ return nil
+}
+
+func (m *Machine) markConnected(name string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.owns(name) {
+ m.player.Connected = true
+ }
+}
+
+func (m *Machine) hasParticipant(name string) bool {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.owns(name)
+}
+
+func (m *Machine) isBusy(name string) bool {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.owns(name) && (m.autoBet || m.phase == machineSpinning || m.phase == machinePayout)
+}
+
+func (m *Machine) owns(name string) bool { return m.player != nil && m.player.Name == name }
+
+func (m *Machine) private(message string) []Event {
+ return []Event{{RoomID: m.RoomID, TableID: m.Config.ID, Type: EventResult, PrivateTo: m.player.Name, Message: message, Color: "casino_action"}}
+}
+
+func (m *Machine) public(message string) []Event {
+ return []Event{{RoomID: m.RoomID, TableID: m.Config.ID, Type: EventResult, Player: m.player.Name, Message: message, Color: "casino_action", Public: true}}
+}
+
+func (m *Machine) playerAction(publicMessage, privateMessage string) []Event {
+ return []Event{{RoomID: m.RoomID, TableID: m.Config.ID, Type: EventResult, Player: m.player.Name,
+ Message: publicMessage, PrivateMessage: privateMessage, PrivateTo: m.player.Name, Color: "casino_action", Public: true}}
+}
+
+func (m *Machine) publicSlot(message string, stopped int) []Event {
+ return []Event{{RoomID: m.RoomID, TableID: m.Config.ID, Type: EventResult, Player: m.player.Name,
+ Message: message, Color: "casino_action", Public: true, Slot: &SlotSnapshot{Grid: m.spin.Grid, StoppedReels: stopped}}}
+}
+
+func stoppedScatters(grid [3][5]string, reels int) int {
+ count := 0
+ for row := 0; row < 3; row++ {
+ for reel := 0; reel < reels && reel < 5; reel++ {
+ if grid[row][reel] == "scatter" {
+ count++
+ }
+ }
+ }
+ return count
+}
+
+func formatWins(wins []SlotWin) string {
+ message := "Winning lines/ways (243-way evaluation):\n"
+ for _, win := range wins {
+ message += fmt.Sprintf(" %s x%d: %d ways x %.4gx bet / 243 = %.4f credits\n", win.Symbol, win.Length, win.Ways, win.Multiplier, win.Payout)
+ }
+ return message[:len(message)-1]
+}
+
+func (m *Machine) privateMenu(prefix string) []Event {
+ if m.phase != machineReady {
+ events := m.private(prefix)
+ events[0].Color = "casino_menu"
+ return events
+ }
+ menu := "Slot machine commands:\n bet <amount> Set your wager\n bet max Set the maximum wager\n spin Spin using your current wager\n autospin Start automatic betting\n stop Leave the slot machine"
+ if prefix == "" {
+ prefix = "\n" + menu
+ } else {
+ prefix += "\n\n" + menu
+ }
+ events := m.private(prefix)
+ events[0].Color = "casino_menu"
+ return events
+}
+
+func (m *Machine) menuEvents(prefix string) []Event {
+ return m.privateMenu(prefix)
+}
diff --git a/internal/casino/manager.go b/internal/casino/manager.go
new file mode 100644
index 0000000..d6a3825
--- /dev/null
+++ b/internal/casino/manager.go
@@ -0,0 +1,238 @@
+package casino
+
+import (
+ "fmt"
+ "math/rand"
+ "sort"
+ "sync"
+)
+
+type Manager struct {
+ mu sync.Mutex
+ tables map[string]*Table
+ machines map[string]*Machine
+ rng *rand.Rand
+}
+
+func NewManager(seed int64) *Manager {
+ return &Manager{
+ tables: make(map[string]*Table),
+ machines: make(map[string]*Machine),
+ rng: rand.New(rand.NewSource(seed)),
+ }
+}
+
+func (m *Manager) EnsureMachine(roomID int, cfg MachineConfig) *Machine {
+ cfg = cfg.Normalize()
+ key := tableKey(roomID, cfg.ID)
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if machine := m.machines[key]; machine != nil {
+ return machine
+ }
+ machine := newMachine(roomID, cfg, m.rng)
+ m.machines[key] = machine
+ return machine
+}
+
+func tableKey(roomID int, tableID string) string {
+ return fmt.Sprintf("%d:%s", roomID, tableID)
+}
+
+func (m *Manager) EnsureTable(roomID int, cfg TableConfig) *Table {
+ cfg = cfg.Normalize()
+ key := tableKey(roomID, cfg.ID)
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if table := m.tables[key]; table != nil {
+ return table
+ }
+ table := newTable(roomID, cfg, m.rng)
+ m.tables[key] = table
+ return table
+}
+
+func (m *Manager) Table(roomID int, tableID string) *Table {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.tables[tableKey(roomID, tableID)]
+}
+
+func (m *Manager) Tick() []Event {
+ m.mu.Lock()
+ tables := make([]*Table, 0, len(m.tables))
+ for _, table := range m.tables {
+ tables = append(tables, table)
+ }
+ m.mu.Unlock()
+ sort.Slice(tables, func(i, j int) bool {
+ if tables[i].RoomID != tables[j].RoomID {
+ return tables[i].RoomID < tables[j].RoomID
+ }
+ return tables[i].Config.ID < tables[j].Config.ID
+ })
+ var events []Event
+ for _, table := range tables {
+ events = append(events, table.tick()...)
+ }
+ m.mu.Lock()
+ machines := make([]*Machine, 0, len(m.machines))
+ for _, machine := range m.machines {
+ machines = append(machines, machine)
+ }
+ m.mu.Unlock()
+ sort.Slice(machines, func(i, j int) bool {
+ if machines[i].RoomID != machines[j].RoomID {
+ return machines[i].RoomID < machines[j].RoomID
+ }
+ return machines[i].Config.ID < machines[j].Config.ID
+ })
+ for _, machine := range machines {
+ events = append(events, machine.tick()...)
+ }
+ return events
+}
+
+func (m *Manager) JoinMachine(roomID int, cfg MachineConfig, name string) []Event {
+ return m.EnsureMachine(roomID, cfg).join(name)
+}
+
+func (m *Manager) SetMachineBet(roomID int, machineID, name string, amount int) []Event {
+ m.mu.Lock()
+ machine := m.machines[tableKey(roomID, machineID)]
+ m.mu.Unlock()
+ if machine == nil {
+ return nil
+ }
+ return machine.setBet(name, amount)
+}
+
+func (m *Manager) StartMachine(roomID int, machineID, name string, wallet Wallet) []Event {
+ m.mu.Lock()
+ machine := m.machines[tableKey(roomID, machineID)]
+ m.mu.Unlock()
+ if machine == nil {
+ return nil
+ }
+ return machine.start(name, wallet)
+}
+
+func (m *Manager) EnableMachineAutoBet(roomID int, machineID, name string, wallet Wallet) []Event {
+ m.mu.Lock()
+ machine := m.machines[tableKey(roomID, machineID)]
+ m.mu.Unlock()
+ if machine == nil {
+ return nil
+ }
+ return machine.enableAutoBet(name, wallet)
+}
+
+func (m *Manager) StopMachineAutoBet(roomID int, machineID, name string) ([]Event, bool) {
+ m.mu.Lock()
+ machine := m.machines[tableKey(roomID, machineID)]
+ m.mu.Unlock()
+ if machine == nil {
+ return nil, false
+ }
+ return machine.stopAutoBet(name)
+}
+
+func (m *Manager) LeaveMachine(roomID int, machineID, name string) []Event {
+ m.mu.Lock()
+ machine := m.machines[tableKey(roomID, machineID)]
+ m.mu.Unlock()
+ if machine == nil {
+ return nil
+ }
+ return machine.leave(name)
+}
+
+func (m *Manager) Join(roomID int, cfg TableConfig, name string) []Event {
+ return m.EnsureTable(roomID, cfg).join(name)
+}
+
+func (m *Manager) Leave(roomID int, tableID, name string) []Event {
+ if table := m.Table(roomID, tableID); table != nil {
+ return table.leave(name)
+ }
+ return nil
+}
+
+func (m *Manager) Bet(roomID int, tableID, name string, amount int, wallet Wallet) []Event {
+ if table := m.Table(roomID, tableID); table != nil {
+ return table.bet(name, amount, wallet)
+ }
+ return []Event{{RoomID: roomID, TableID: tableID, Type: EventResult, Player: name, PrivateTo: name, Message: "That game is not available here."}}
+}
+
+func (m *Manager) MarkDisconnected(name string) []Event {
+ m.mu.Lock()
+ tables := make([]*Table, 0, len(m.tables))
+ for _, table := range m.tables {
+ tables = append(tables, table)
+ }
+ m.mu.Unlock()
+ var events []Event
+ for _, table := range tables {
+ events = append(events, table.markDisconnected(name)...)
+ }
+ m.mu.Lock()
+ machines := make([]*Machine, 0, len(m.machines))
+ for _, machine := range m.machines {
+ machines = append(machines, machine)
+ }
+ m.mu.Unlock()
+ for _, machine := range machines {
+ events = append(events, machine.markDisconnected(name)...)
+ }
+ return events
+}
+
+func (m *Manager) MarkConnected(name string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, table := range m.tables {
+ table.markConnected(name)
+ }
+ for _, machine := range m.machines {
+ machine.markConnected(name)
+ }
+}
+
+func (m *Manager) Participation(name string) (*Table, bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, table := range m.tables {
+ if table.hasParticipant(name) {
+ return table, true
+ }
+ }
+ for _, machine := range m.machines {
+ if machine.hasParticipant(name) {
+ return nil, true
+ }
+ }
+ return nil, false
+}
+
+func (m *Manager) MachineFor(name string) (*Machine, bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, machine := range m.machines {
+ if machine.hasParticipant(name) {
+ return machine, true
+ }
+ }
+ return nil, false
+}
+
+func (m *Manager) MachineBusy(name string) bool {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, machine := range m.machines {
+ if machine.isBusy(name) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/casino/manager_test.go b/internal/casino/manager_test.go
new file mode 100644
index 0000000..245133d
--- /dev/null
+++ b/internal/casino/manager_test.go
@@ -0,0 +1,103 @@
+package casino
+
+import "testing"
+
+type testWallet struct {
+ chips, credits, paid int
+}
+
+func (w *testWallet) Wager(amount int) (Wager, bool) {
+ if w.chips+w.credits < amount {
+ return Wager{}, false
+ }
+ chips := amount
+ if chips > w.chips {
+ chips = w.chips
+ }
+ w.chips -= chips
+ credits := amount - chips
+ w.credits -= credits
+ return Wager{Total: amount, Chips: chips, Credits: credits}, true
+}
+
+func (w *testWallet) PayCredits(amount int) {
+ w.paid += amount
+}
+
+func TestMixedWagerUsesChipsFirst(t *testing.T) {
+ w := &testWallet{chips: 7, credits: 50}
+ wager, ok := w.Wager(12)
+ if !ok || wager.Chips != 7 || wager.Credits != 5 || w.chips != 0 || w.credits != 45 {
+ t.Fatalf("unexpected wager: %+v wallet=%+v", wager, w)
+ }
+}
+
+func TestSoloBetResolvesImmediately(t *testing.T) {
+ m := NewManager(1)
+ cfg := TableConfig{ID: "slots", Game: GameSlots}
+ m.Join(1, cfg, "alice")
+ w := &testWallet{credits: 100}
+ events := m.Bet(1, "slots", "alice", 10, w)
+ found := false
+ for _, event := range events {
+ if event.Type == EventRoundStarted {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("solo bet did not resolve immediately")
+ }
+}
+
+func TestMultiplePlayersWaitForBets(t *testing.T) {
+ m := NewManager(1)
+ cfg := TableConfig{ID: "slots", Game: GameSlots, BettingTicks: 2}
+ m.Join(1, cfg, "alice")
+ m.Join(1, cfg, "bob")
+ wa, wb := &testWallet{credits: 100}, &testWallet{credits: 100}
+ events := m.Bet(1, "slots", "alice", 10, wa)
+ for _, event := range events {
+ if event.Type == EventRoundStarted {
+ t.Fatal("round started before all players bet or timeout")
+ }
+ }
+ m.Bet(1, "slots", "bob", 10, wb)
+}
+
+func TestMachineAutobetCountdownAndStop(t *testing.T) {
+ m := NewManager(1)
+ cfg := MachineConfig{ID: "slots", Game: GameSlots, SpinTicks: 1}
+ m.JoinMachine(1, cfg, "alice")
+ m.SetMachineBet(1, "slots", "alice", 10)
+ w := &testWallet{credits: 100}
+ if events := m.EnableMachineAutoBet(1, "slots", "alice", w); len(events) != 0 {
+ t.Fatalf("enabling autobet emitted events before countdown: %+v", events)
+ }
+ for i, want := range []string{"Autobet enabled!", `Type "stop" to stop playing`, "Betting... 10 credits."} {
+ events := m.Tick()
+ if len(events) == 0 || eventText(events) != want {
+ t.Fatalf("tick %d message=%q events=%+v, want %q", i+1, eventText(events), events, want)
+ }
+ }
+ if !m.MachineBusy("alice") {
+ t.Fatal("autobet did not start a spin after countdown")
+ }
+ if events, stopped := m.StopMachineAutoBet(1, "slots", "alice"); !stopped || len(events) != 1 {
+ t.Fatalf("stop autobet events=%+v stopped=%v", events, stopped)
+ }
+ if _, playing := m.MachineFor("alice"); !playing {
+ t.Fatal("stopping autobet removed the player from the machine")
+ }
+}
+
+func eventText(events []Event) string {
+ for _, event := range events {
+ if event.PrivateMessage != "" {
+ return event.PrivateMessage
+ }
+ if event.Message != "" {
+ return event.Message
+ }
+ }
+ return ""
+}
diff --git a/internal/casino/slots.go b/internal/casino/slots.go
new file mode 100644
index 0000000..9d53bb1
--- /dev/null
+++ b/internal/casino/slots.go
@@ -0,0 +1,278 @@
+package casino
+
+import (
+ "fmt"
+ "math"
+ "math/rand"
+)
+
+type SlotSymbol struct {
+ ID string `yaml:"id"`
+ Weight int `yaml:"weight"`
+ Payout map[int]float64 `yaml:"payout"`
+}
+
+type SlotProfile struct {
+ Symbols []SlotSymbol `yaml:"symbols"`
+ Rows int `yaml:"rows"`
+ Reels int `yaml:"reels"`
+ FreeSpinTrigger string `yaml:"free_spin_trigger"`
+ FreeSpinCount int `yaml:"free_spin_count"`
+ Ways int `yaml:"ways"`
+ TargetRTP float64 `yaml:"payout"`
+}
+
+type SlotSpin struct {
+ Grid [3][5]string
+ Payout float64
+ ScatterCount int
+ Wins []SlotWin
+}
+
+type SlotWin struct {
+ Symbol string
+ Length int
+ Ways int
+ Multiplier float64
+ Payout float64
+}
+
+// slotResult preserves the small rules-engine hook used by the unfinished
+// generic table implementation while slots move onto SlotMachine.
+type slotSpin struct {
+ Display string
+ Payout int
+}
+
+func slotResult(rng *rand.Rand, bet int) slotSpin {
+ spin := generateSlotSpin(rng, bet)
+ return slotSpin{Display: spin.render(5), Payout: int(math.Floor(spin.Payout + 0.5))}
+}
+
+func DefaultHuffAndPuffProfile() SlotProfile {
+ return SlotProfile{
+ Rows: 3, Reels: 5, Ways: 243,
+ FreeSpinTrigger: "scatter", FreeSpinCount: 8,
+ Symbols: []SlotSymbol{
+ {ID: "straw", Weight: 22, Payout: map[int]float64{3: .5, 4: 1, 5: 2}},
+ {ID: "stick", Weight: 12, Payout: map[int]float64{3: 1, 4: 2, 5: 5}},
+ {ID: "brick", Weight: 7, Payout: map[int]float64{3: 2, 4: 5, 5: 15}},
+ {ID: "hat", Weight: 4, Payout: map[int]float64{3: 5, 4: 15, 5: 50}},
+ {ID: "wolf", Weight: 2, Payout: map[int]float64{3: 10, 4: 50, 5: 250}},
+ {ID: "scatter", Weight: 3},
+ },
+ }
+}
+
+func (p SlotProfile) Normalize() SlotProfile {
+ if p.Rows <= 0 {
+ p.Rows = 3
+ }
+ if p.Reels <= 0 {
+ p.Reels = 5
+ }
+ if p.Ways <= 0 {
+ p.Ways = 243
+ }
+ if p.FreeSpinCount <= 0 {
+ p.FreeSpinCount = 8
+ }
+ if len(p.Symbols) == 0 {
+ return DefaultHuffAndPuffProfile()
+ }
+ return p
+}
+
+func (p SlotProfile) symbol(id string) *SlotSymbol {
+ for i := range p.Symbols {
+ if p.Symbols[i].ID == id {
+ return &p.Symbols[i]
+ }
+ }
+ return nil
+}
+
+func generateSlotSpin(rng *rand.Rand, bet int) *SlotSpin {
+ return generateSlotSpinWithProfile(rng, bet, DefaultHuffAndPuffProfile())
+}
+
+func generateSlotSpinWithProfile(rng *rand.Rand, bet int, profile SlotProfile) *SlotSpin {
+ p := profile.Normalize()
+ spin := &SlotSpin{}
+ for reel := 0; reel < p.Reels && reel < 5; reel++ {
+ for row := 0; row < p.Rows && row < 3; row++ {
+ symbol := weightedSymbol(rng, p.Symbols)
+ spin.Grid[row][reel] = symbol
+ if symbol == p.FreeSpinTrigger {
+ spin.ScatterCount++
+ }
+ }
+ }
+ spin.Payout, spin.Wins = evaluateSlot(spin.Grid, bet, p)
+ return spin
+}
+
+func weightedSymbol(rng *rand.Rand, symbols []SlotSymbol) string {
+ total := 0
+ for _, symbol := range symbols {
+ if symbol.Weight > 0 {
+ total += symbol.Weight
+ }
+ }
+ if total <= 0 {
+ return ""
+ }
+ n := rng.Intn(total)
+ for _, symbol := range symbols {
+ if symbol.Weight <= 0 {
+ continue
+ }
+ if n < symbol.Weight {
+ return symbol.ID
+ }
+ n -= symbol.Weight
+ }
+ return symbols[len(symbols)-1].ID
+}
+
+func evaluateSlot(grid [3][5]string, bet int, profile SlotProfile) (float64, []SlotWin) {
+ p := profile.Normalize()
+ if bet <= 0 {
+ return 0, nil
+ }
+ total := 0.0
+ var wins []SlotWin
+ for _, symbol := range p.Symbols {
+ length, ways := matchingLength(grid, symbol.ID)
+ if length >= 3 && symbol.Payout[length] > 0 {
+ payout := float64(bet) * symbol.Payout[length] * float64(ways) / 243.0
+ total += payout
+ wins = append(wins, SlotWin{Symbol: symbol.ID, Length: length, Ways: ways, Multiplier: symbol.Payout[length], Payout: payout})
+ }
+ }
+ return total, wins
+}
+
+func matchingLength(grid [3][5]string, symbol string) (int, int) {
+ ways := 1
+ length := 0
+ for reel := 0; reel < 5; reel++ {
+ count := 0
+ for row := 0; row < 3; row++ {
+ if grid[row][reel] == symbol {
+ count++
+ }
+ }
+ if count == 0 {
+ break
+ }
+ ways *= count
+ length = reel + 1
+ }
+ if length < 3 {
+ return length, 0
+ }
+ return length, ways
+}
+
+func (s *SlotSpin) render(stoppedReels int) string {
+ var out string
+ out += "+---------+---------+---------+---------+---------+\n"
+ for row := 0; row < 3; row++ {
+ out += "|"
+ for reel := 0; reel < 5; reel++ {
+ value := "..."
+ if reel < stoppedReels {
+ value = s.Grid[row][reel]
+ }
+ out += fmt.Sprintf(" %-7s |", value)
+ }
+ out += "\n"
+ }
+ out += "+---------+---------+---------+---------+---------+"
+ return out
+}
+
+// CalculateRTP returns the exact mathematical RTP for the independent-cell
+// model used by the baseline machine, before integer-credit rounding.
+func CalculateRTP(profile SlotProfile) float64 {
+ p := profile.Normalize()
+ totalWeight := 0
+ for _, symbol := range p.Symbols {
+ if symbol.Weight > 0 {
+ totalWeight += symbol.Weight
+ }
+ }
+ if totalWeight == 0 {
+ return 0
+ }
+ baseRTP := 0.0
+ scatterProbability := 0.0
+ for _, symbol := range p.Symbols {
+ probability := float64(symbol.Weight) / float64(totalWeight)
+ if symbol.ID == p.FreeSpinTrigger {
+ scatterProbability = probability
+ }
+ if symbol.ID == p.FreeSpinTrigger {
+ continue
+ }
+ for length := 3; length <= 5; length++ {
+ ways := math.Pow(float64(p.Rows), float64(length))
+ nextReelNoMatch := 1.0
+ if length < 5 {
+ nextReelNoMatch = math.Pow(1-probability, float64(p.Rows))
+ }
+ baseRTP += symbol.Payout[length] * ways * math.Pow(probability, float64(length)) * nextReelNoMatch / float64(p.Ways)
+ }
+ }
+ // The baseline feature awards a fixed number of automatic spins and does
+ // not retrigger during those spins. Its expected value is therefore the
+ // trigger probability multiplied by the free-spin count and base RTP.
+ triggerProbability := 0.0
+ for scatters := 3; scatters <= p.Rows*p.Reels; scatters++ {
+ triggerProbability += binomial(p.Rows*p.Reels, scatters) * math.Pow(scatterProbability, float64(scatters)) * math.Pow(1-scatterProbability, float64(p.Rows*p.Reels-scatters))
+ }
+ return baseRTP * (1 + triggerProbability*float64(p.FreeSpinCount))
+}
+
+func binomial(n, k int) float64 {
+ if k < 0 || k > n {
+ return 0
+ }
+ result := 1.0
+ for i := 1; i <= k; i++ {
+ result *= float64(n-k+i) / float64(i)
+ }
+ return result
+}
+
+func ValidateRTP(profile SlotProfile, tolerance float64) error {
+ if profile.TargetRTP <= 0 {
+ return nil
+ }
+ actual := CalculateRTP(profile)
+ if math.Abs(actual-profile.TargetRTP) > tolerance {
+ return fmt.Errorf("slot profile RTP %.6f does not match target %.6f", actual, profile.TargetRTP)
+ }
+ return nil
+}
+
+// ScaleToRTP adjusts the configured paytable, without changing reel weights or
+// feature probabilities, so the profile's exact mathematical RTP reaches the
+// requested target. Runtime payouts retain fractional credits internally until
+// they can be paid as whole credits.
+func ScaleToRTP(profile SlotProfile, target float64) SlotProfile {
+ profile = profile.Normalize()
+ actual := CalculateRTP(profile)
+ if actual <= 0 || target <= 0 {
+ return profile
+ }
+ scale := target / actual
+ for i := range profile.Symbols {
+ for length, payout := range profile.Symbols[i].Payout {
+ profile.Symbols[i].Payout[length] = payout * scale
+ }
+ }
+ profile.TargetRTP = target
+ return profile
+}
diff --git a/internal/casino/slots_test.go b/internal/casino/slots_test.go
new file mode 100644
index 0000000..22e39bf
--- /dev/null
+++ b/internal/casino/slots_test.go
@@ -0,0 +1,44 @@
+package casino
+
+import "testing"
+
+func TestCalculateRTPUsesLongestWayOnly(t *testing.T) {
+ profile := SlotProfile{
+ Rows: 3, Reels: 5, Ways: 243,
+ Symbols: []SlotSymbol{{ID: "x", Weight: 1, Payout: map[int]float64{3: 1, 4: 2, 5: 3}}},
+ FreeSpinTrigger: "scatter", FreeSpinCount: 8,
+ }
+ if got := CalculateRTP(profile); got != 3 {
+ t.Fatalf("RTP = %v, want 3", got)
+ }
+}
+
+func TestValidateRTP(t *testing.T) {
+ profile := SlotProfile{Rows: 3, Reels: 5, Ways: 243, TargetRTP: 3,
+ Symbols: []SlotSymbol{{ID: "x", Weight: 1, Payout: map[int]float64{5: 3}}}}
+ if err := ValidateRTP(profile, 0.000001); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestScaleToRTP(t *testing.T) {
+ profile := ScaleToRTP(DefaultHuffAndPuffProfile(), 0.97)
+ if err := ValidateRTP(profile, 0.000000001); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestEvaluateSlotReportsWinningWays(t *testing.T) {
+ profile := SlotProfile{Rows: 3, Reels: 5, Ways: 243,
+ Symbols: []SlotSymbol{{ID: "x", Weight: 1, Payout: map[int]float64{5: 2}}}}
+ grid := [3][5]string{}
+ for row := range grid {
+ for reel := range grid[row] {
+ grid[row][reel] = "x"
+ }
+ }
+ payout, wins := evaluateSlot(grid, 10, profile)
+ if payout != 20 || len(wins) != 1 || wins[0].Ways != 243 || wins[0].Length != 5 {
+ t.Fatalf("payout=%v wins=%+v", payout, wins)
+ }
+}
diff --git a/internal/casino/table.go b/internal/casino/table.go
new file mode 100644
index 0000000..1b9d0b5
--- /dev/null
+++ b/internal/casino/table.go
@@ -0,0 +1,217 @@
+package casino
+
+import (
+ "fmt"
+ "math/rand"
+ "sync"
+)
+
+type tablePhase string
+
+const (
+ phaseWaiting tablePhase = "waiting"
+ phaseBetting tablePhase = "betting"
+)
+
+type Table struct {
+ mu sync.Mutex
+ RoomID int
+ Config TableConfig
+
+ participants map[string]*Participant
+ order []string
+ phase tablePhase
+ deadline int
+ clock int
+ rng *rand.Rand
+}
+
+func newTable(roomID int, cfg TableConfig, rng *rand.Rand) *Table {
+ return &Table{
+ RoomID: roomID,
+ Config: cfg,
+ phase: phaseWaiting,
+ participants: make(map[string]*Participant),
+ rng: rng,
+ }
+}
+
+func (t *Table) join(name string) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if p := t.participants[name]; p != nil {
+ p.Connected = true
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventJoined, Player: name, PrivateTo: name, Message: fmt.Sprintf("You resume your place at the %s table.", t.Config.ID)}}
+ }
+ if len(t.participants) >= t.Config.MaxPlayers {
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventResult, Player: name, PrivateTo: name, Message: "That table is full."}}
+ }
+ t.participants[name] = &Participant{Name: name, Connected: true}
+ t.order = append(t.order, name)
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventJoined, Player: name, Message: fmt.Sprintf("%s joins the %s table.", name, t.Config.ID), Public: true}}
+}
+
+func (t *Table) leave(name string) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p := t.participants[name]
+ if p == nil {
+ return nil
+ }
+ if t.phase != phaseWaiting {
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventResult, Player: name, PrivateTo: name, Message: "You're in the middle of a game!"}}
+ }
+ delete(t.participants, name)
+ for i, n := range t.order {
+ if n == name {
+ t.order = append(t.order[:i], t.order[i+1:]...)
+ break
+ }
+ }
+ events := []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventLeft, Player: name, Message: fmt.Sprintf("%s stops playing at the %s table.", name, t.Config.ID), Public: true}}
+ if len(t.participants) == 0 {
+ events = append(events, Event{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventClosed, Message: fmt.Sprintf("The %s table closes.", t.Config.ID), Public: true})
+ }
+ return events
+}
+
+func (t *Table) bet(name string, amount int, wallet Wallet) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p := t.participants[name]
+ if p == nil {
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventResult, Player: name, PrivateTo: name, Message: "You aren't playing at that table."}}
+ }
+ if t.phase != phaseWaiting && t.phase != phaseBetting {
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventResult, Player: name, PrivateTo: name, Message: "That table isn't accepting bets."}}
+ }
+ if amount < t.Config.MinBet || amount > t.Config.MaxBet {
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventResult, Player: name, PrivateTo: name, Message: fmt.Sprintf("Bets must be between %d and %d.", t.Config.MinBet, t.Config.MaxBet)}}
+ }
+ if p.HasBet {
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventResult, Player: name, PrivateTo: name, Message: "You have already bet this round."}}
+ }
+ wager, ok := wallet.Wager(amount)
+ if !ok {
+ return []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventResult, Player: name, PrivateTo: name, Message: "You don't have enough chips and credits for that bet."}}
+ }
+ p.HasBet = true
+ p.Wager = wager
+ p.Wallet = wallet
+ if t.phase == phaseWaiting && len(t.participants) > 1 {
+ t.phase = phaseBetting
+ t.clock = 0
+ t.deadline = t.Config.BettingTicks
+ }
+ events := []Event{{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventBetPlaced, Player: name, Message: fmt.Sprintf("%s bets %d credits at the %s table.", name, amount, t.Config.ID), Public: true}}
+ if t.phase == phaseBetting && t.clock == 0 {
+ events = append(events, Event{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventBetting, Message: fmt.Sprintf("Betting is open at the %s table for %d ticks.", t.Config.ID, t.deadline), Public: true})
+ }
+ if len(t.participants) == 1 || t.allBet() {
+ events = append(events, t.resolveRound()...)
+ }
+ return events
+}
+
+func (t *Table) tick() []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.phase != phaseBetting {
+ return nil
+ }
+ t.clock++
+ if t.allBet() {
+ return t.resolveRound()
+ }
+ if t.clock < t.deadline {
+ return nil
+ }
+ var events []Event
+ for _, name := range t.order {
+ p := t.participants[name]
+ if p != nil && !p.HasBet {
+ events = append(events, Event{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventTimedOut, Player: name, Message: fmt.Sprintf("%s sits out this round.", name), Public: true})
+ }
+ }
+ if t.anyBet() {
+ events = append(events, t.resolveRound()...)
+ } else {
+ t.resetRound()
+ }
+ return events
+}
+
+func (t *Table) resolveRound() []Event {
+ var events []Event
+ for _, name := range t.order {
+ p := t.participants[name]
+ if p == nil || !p.HasBet {
+ continue
+ }
+ result := slotResult(t.rng, p.Wager.Total)
+ message := fmt.Sprintf("%s spins: %s", name, result.Display)
+ events = append(events, Event{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventRoundStarted, Player: name, Message: message, Public: true})
+ if result.Payout > 0 {
+ if p.Wallet != nil {
+ p.Wallet.PayCredits(result.Payout)
+ }
+ events = append(events, Event{RoomID: t.RoomID, TableID: t.Config.ID, Type: EventPayout, Player: name, PrivateTo: name, Message: fmt.Sprintf("You win %d credits!", result.Payout)})
+ }
+ }
+ t.resetRound()
+ return events
+}
+
+func (t *Table) resetRound() {
+ t.phase = phaseWaiting
+ t.clock = 0
+ t.deadline = 0
+ for _, p := range t.participants {
+ p.HasBet = false
+ p.Wager = Wager{}
+ }
+}
+
+func (t *Table) allBet() bool {
+ if len(t.participants) == 0 {
+ return false
+ }
+ for _, p := range t.participants {
+ if !p.HasBet {
+ return false
+ }
+ }
+ return true
+}
+
+func (t *Table) anyBet() bool {
+ for _, p := range t.participants {
+ if p.HasBet {
+ return true
+ }
+ }
+ return false
+}
+
+func (t *Table) markDisconnected(name string) []Event {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if p := t.participants[name]; p != nil {
+ p.Connected = false
+ }
+ return nil
+}
+
+func (t *Table) markConnected(name string) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if p := t.participants[name]; p != nil {
+ p.Connected = true
+ }
+}
+
+func (t *Table) hasParticipant(name string) bool {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return t.participants[name] != nil
+}
diff --git a/internal/casino/types.go b/internal/casino/types.go
new file mode 100644
index 0000000..f284869
--- /dev/null
+++ b/internal/casino/types.go
@@ -0,0 +1,121 @@
+package casino
+
+import "fmt"
+
+type GameName string
+
+const (
+ GameSlots GameName = "slots"
+)
+
+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"`
+}
+
+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"`
+}
+
+func (c MachineConfig) Normalize() MachineConfig {
+ if c.MinBet <= 0 {
+ c.MinBet = 1
+ }
+ if c.MaxBet <= 0 {
+ c.MaxBet = int(^uint(0) >> 1)
+ }
+ 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 = int(^uint(0) >> 1)
+ }
+ return c
+}
+
+type Wager struct {
+ Total int
+ Chips int
+ Credits int
+}
+
+type Wallet interface {
+ Wager(amount int) (Wager, bool)
+ PayCredits(amount int)
+}
+
+type EventType string
+
+const (
+ EventJoined EventType = "joined"
+ EventBetting EventType = "betting"
+ EventBetPlaced EventType = "bet_placed"
+ EventRoundStarted EventType = "round_started"
+ EventResult EventType = "result"
+ EventPayout EventType = "payout"
+ EventTimedOut EventType = "timed_out"
+ EventLeft EventType = "left"
+ EventClosed EventType = "closed"
+)
+
+type Event struct {
+ RoomID int
+ TableID string
+ Type EventType
+ Player string
+ Message string
+ PrivateMessage string
+ PrivateTo string
+ Color string
+ Public bool
+ Slot *SlotSnapshot
+}
+
+type SlotSnapshot struct {
+ Grid [3][5]string
+ StoppedReels int
+}
+
+func (e Event) String() string {
+ if e.Message != "" {
+ return e.Message
+ }
+ return fmt.Sprintf("%s at %s", e.Type, e.TableID)
+}
+
+type Participant struct {
+ Name string
+ Connected bool
+ HasBet bool
+ Wager Wager
+ Wallet Wallet
+}