aboutsummaryrefslogtreecommitdiff
path: root/internal/game/casino_test.go
blob: 2f72d07b9bf4b80a43ffff8f0b9b23cc0835c444 (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
package game

import (
	"regexp"
	"strings"
	"testing"
	"time"

	"thehouseoficarus/internal/casino"
	"thehouseoficarus/internal/color"
	"thehouseoficarus/internal/net"
	"thehouseoficarus/internal/player"
)

type casinoTestConn struct {
	data []byte
}

func (c *casinoTestConn) ReadMessage() (string, error) { return "", nil }
func (c *casinoTestConn) Write(b []byte) (int, error) {
	c.data = append(c.data, b...)
	return len(b), nil
}
func (c *casinoTestConn) SetWriteDeadline(time.Time) error { return nil }

func (c *casinoTestConn) Close() error       { return nil }
func (c *casinoTestConn) SetEcho(bool) error { return nil }

func TestCasinoDisplayDefaultsToDetailedAndDoesNotOverrideCardSize(t *testing.T) {
	snapshot := &casino.BlackjackSnapshot{
		Dealer:  []casino.CardView{{Rank: "K", Suit: "hearts"}},
		Players: []casino.BlackjackPlayerView{{Name: "alice", Score: "10", Cards: []casino.CardView{{Rank: "10", Suit: "clubs"}}}},
	}
	if got := player.New("alice").OptionString("casino_display"); got != "detailed" {
		t.Fatalf("casino_display default=%q, want detailed", got)
	}
	for _, display := range []string{"", "detailed", "compact"} {
		p := player.New("alice")
		p.Options = map[string]any{"color": "none"}
		if display != "" {
			p.Options["casino_display"] = display
		}
		sess := &net.Session{Player: p}
		g := &Game{}
		got := g.renderCasinoSnapshot(sess, snapshot)
		want := renderBlackjackSnapshotFor(snapshot, g.colorMode(sess), p.OptionBool("unicode"), p.OptionInt("card_size"), p.OptionString("card_style"), nil, p.Name)
		if got != want {
			t.Fatalf("display=%q: card_size ignored\n got %q\nwant %q", display, got, want)
		}
		if !strings.Contains(got, "┌") {
			t.Fatalf("display=%q: expected card art, got %q", display, got)
		}
	}
}

func TestExecuteBetRejectsInvalidMachineArgs(t *testing.T) {
	g := &Game{Casino: casino.NewManager(1)}
	cfg := casino.MachineConfig{ID: "slots", Game: casino.GameSlots}
	g.Casino.JoinMachine(1, cfg, "alice")
	conn := &casinoTestConn{}
	sess := &net.Session{Player: player.New("alice"), Conn: conn}
	g.loggedInChars = map[string]*net.Session{"alice": sess}
	for _, args := range [][]string{{"banana"}, {"-5"}, {"10", "extra"}} {
		conn.data = nil
		g.executeBet(sess, args, "bet "+strings.Join(args, " "))
		if !strings.Contains(string(conn.data), "Use bet, bet <amount>, or bet max.") {
			t.Fatalf("bet %v: expected usage error, got %q", args, string(conn.data))
		}
	}
	// A bet amount at a machine sets the wager and immediately spins.
	conn.data = nil
	g.executeBet(sess, []string{"10"}, "bet 10")
	if !strings.Contains(string(conn.data), "You don't have enough chips and credits") {
		t.Fatalf("bet 10 should attempt an auto-spin and fail at the empty wallet, got %q", string(conn.data))
	}
	// Bet max with an empty wallet is rejected before any wager is attempted.
	conn.data = nil
	g.executeBet(sess, []string{"max"}, "bet max")
	if !strings.Contains(string(conn.data), "You don't have any chips or credits to bet.") {
		t.Fatalf("bet max with empty wallet: expected no-funds message, got %q", string(conn.data))
	}
}

func TestExecuteBetParsesBaccaratSpots(t *testing.T) {
	g := &Game{Casino: casino.NewManager(1)}
	cfg := casino.TableConfig{ID: "baccarat", Game: casino.GameBaccarat}
	g.Casino.Join(1, cfg, "alice")
	conn := &casinoTestConn{}
	sess := &net.Session{Player: player.New("alice"), Conn: conn}
	g.loggedInChars = map[string]*net.Session{"alice": sess}
	// Valid spot syntaxes reach the table and fail only at the (empty) wallet.
	for _, args := range [][]string{{"tie", "100"}, {"100", "tie"}, {"100", "on", "banker"}, {"banker", "100"}} {
		conn.data = nil
		g.executeBet(sess, args, "bet "+strings.Join(args, " "))
		if !strings.Contains(string(conn.data), "You don't have enough chips and credits") {
			t.Fatalf("bet %v: expected wallet failure, got %q", args, string(conn.data))
		}
	}
	// Invalid spots are rejected by the table.
	conn.data = nil
	g.executeBet(sess, []string{"red", "100"}, "bet red 100")
	if !strings.Contains(string(conn.data), "must be on player, banker, or tie") {
		t.Fatalf("bet red 100: expected spot rejection, got %q", string(conn.data))
	}
	// A numeric token AFTER "on" is the target, not a second amount, so
	// numeric spots (roulette numbers, craps hard ways) reach the table.
	// Baccarat rejects the value, which proves the parser forwarded it.
	conn.data = nil
	g.executeBet(sess, []string{"5", "on", "17"}, "bet 5 on 17")
	if !strings.Contains(string(conn.data), "must be on player, banker, or tie") {
		t.Fatalf("bet 5 on 17: expected the table to receive the numeric spot, got %q", string(conn.data))
	}
	// Two amounts or two spots are usage errors.
	for _, args := range [][]string{{"10", "20"}, {"player", "banker"}} {
		conn.data = nil
		g.executeBet(sess, args, "bet "+strings.Join(args, " "))
		if !strings.Contains(string(conn.data), "Use bet,") {
			t.Fatalf("bet %v: expected usage error, got %q", args, string(conn.data))
		}
	}
	// A bare first bet asks for a target (via the rebet path).
	conn.data = nil
	g.executeBet(sess, nil, "bet")
	if !strings.Contains(string(conn.data), "Bet on what?") {
		t.Fatalf("bare bet: expected target guidance, got %q", string(conn.data))
	}
}

func TestCasinoMenuRendersAlignedColoredCommands(t *testing.T) {
	g := &Game{Casino: casino.NewManager(1)}
	conn := &casinoTestConn{}
	sess := &net.Session{Player: player.New("alice"), Conn: conn}
	g.loggedInChars = map[string]*net.Session{"alice": sess}
	menu := &casino.MenuView{Heading: "Your slot machine bet is set to 10.", ShowBalance: true, Commands: []casino.MenuCommand{
		{Command: "bet <amount>", Desc: "Set your wager"},
		{Command: "spin", Desc: "Spin using your current wager"},
	}}
	msg := g.casinoPrivateMessage(sess, "casino_menu", menu, "Your slot machine bet is set to 10.")
	if !strings.Contains(regexp.MustCompile(`\x1b\[[0-9;]*m`).ReplaceAllString(msg, ""), "Available 0 (0 chips + 0 credits)") {
		t.Fatalf("missing balance line: %q", msg)
	}
	// Commands are painted with the "command" color (0A bold).
	if !strings.Contains(msg, "\033[1m\033[38;5;10mbet <amount>\033[0m") {
		t.Fatalf("command not colored: %q", msg)
	}
	// Shorter commands are right-padded to align the descriptions.
	if !strings.Contains(msg, "\033[1m\033[38;5;10mspin        \033[0m  Spin using your current wager") {
		t.Fatalf("commands not aligned: %q", msg)
	}
}

func TestRenderBaccaratSnapshot(t *testing.T) {
	snapshot := &casino.BaccaratSnapshot{
		Player:      []casino.CardView{{Rank: "5", Suit: "clubs"}, {Rank: "4", Suit: "hearts"}},
		Banker:      []casino.CardView{{Rank: "2", Suit: "spades"}, {Rank: "3", Suit: "diamonds"}},
		PlayerScore: "9",
		BankerScore: "5",
		Bets:        []casino.BaccaratBetView{{Name: "alice", Spot: "player", Amount: 100}},
	}
	plain := renderBaccaratSnapshot(snapshot, "none", false, 5, "dark", nil)
	if !strings.Contains(plain, "Player (9):") || !strings.Contains(plain, "Banker (5):") || !strings.Contains(plain, "alice bets 100 on player.") {
		t.Fatalf("unexpected baccarat render: %q", plain)
	}
	output := renderBaccaratSnapshot(snapshot, "xterm256", true, 7, "dark", nil)
	if !strings.Contains(output, "\033[38;5;") {
		t.Fatalf("expected colored baccarat art: %q", output)
	}
	// The light card style applies to baccarat hands too, with the half-block
	// edges oriented to touch the white body (▄ top, ▀ bottom).
	light := renderBaccaratSnapshot(snapshot, "none", true, 7, "light", nil)
	lightLines := strings.Split(light, "\n")
	if !strings.Contains(lightLines[1], "▄▄▄▄▄▄▄") || !strings.Contains(lightLines[7], "▀▀▀▀▀▀▀") {
		t.Fatalf("baccarat light card edges flipped: top=%q bottom=%q", lightLines[1], lightLines[7])
	}
	for _, line := range strings.Split(output, "\n") {
		if color.VisibleLen(line) > 80 {
			t.Fatalf("baccarat line exceeds console width: %d", color.VisibleLen(line))
		}
	}
}

func TestRenderSlotSnapshotColorsWordSymbols(t *testing.T) {
	snapshot := &casino.SlotSnapshot{StoppedReels: 1}
	snapshot.Grid[0][0] = "scatter"
	if !strings.Contains(renderSlotSnapshot(snapshot, "none", false), "scatter") {
		t.Fatal("expected word-based slot symbols")
	}
	output := renderSlotSnapshot(snapshot, "xterm256", true)
	if !strings.Contains(output, "\033[38;5;") {
		t.Fatalf("expected colored slot symbols, got %q", output)
	}
	for _, line := range strings.Split(output, "\n") {
		if color.VisibleLen(line) != 51 {
			t.Fatalf("line visible width = %d, want 51: %q", color.VisibleLen(line), line)
		}
	}
	if !strings.Contains(output, "┌") || !strings.Contains(output, "└") {
		t.Fatalf("slot output lacks the Unicode frame: %q", output)
	}
}

func TestRenderBlackjackSnapshotUsesCompactASCIIArt(t *testing.T) {
	snapshot := &casino.BlackjackSnapshot{
		Dealer:  []casino.CardView{{Rank: "?", Hidden: true}, {Rank: "K", Suit: "hearts"}},
		Players: []casino.BlackjackPlayerView{{Name: "alice", Score: "20", Cards: []casino.CardView{{Rank: "5", Suit: "clubs"}, {Rank: "Q", Suit: "spades"}}}},
	}
	plain := renderBlackjackSnapshotFor(snapshot, "none", false, 5, "dark", nil, "")
	if !strings.Contains(plain, "+---+") || !strings.Contains(plain, "Dealer:") || !strings.Contains(plain, "alice (20):") {
		t.Fatalf("unexpected blackjack art: %q", plain)
	}
	output := renderBlackjackSnapshotFor(snapshot, "xterm256", false, 5, "dark", nil, "")
	if !strings.Contains(output, "\033[38;5;") {
		t.Fatalf("expected colored blackjack art: %q", output)
	}
	if strings.ContainsAny(output, "│─┌┐└┘") {
		t.Fatalf("blackjack art contains Unicode borders: %q", output)
	}
	for _, line := range strings.Split(output, "\n") {
		if color.VisibleLen(line) > 80 {
			t.Fatalf("blackjack line exceeds console width: %d", color.VisibleLen(line))
		}
	}
	unicodeOutput := renderBlackjackSnapshotFor(snapshot, "none", true, 7, "dark", nil, "")
	if !strings.Contains(unicodeOutput, "│5    │") || !strings.Contains(unicodeOutput, "│    5│") || !strings.Contains(unicodeOutput, "│  ♣  │") {
		t.Fatalf("unexpected Unicode card alignment: %q", unicodeOutput)
	}
	coloredUnicode := renderBlackjackSnapshotFor(snapshot, "xterm256", true, 7, "dark", nil, "")
	if !strings.Contains(coloredUnicode, "\033[38;5;15m") || !strings.Contains(coloredUnicode, "\033[38;5;27m") {
		t.Fatalf("expected white borders and blue card art: %q", coloredUnicode)
	}
	light := renderBlackjackSnapshotFor(snapshot, "xterm256", true, 7, "light", nil, "")
	if !strings.Contains(light, "\033[48;5;15m") {
		t.Fatalf("expected white card background in light style: %q", light)
	}
	lightLines := strings.Split(light, "\n")
	if strings.Contains(lightLines[1], "\033[48;5;15m") || strings.Contains(lightLines[7], "\033[48;5;15m") {
		t.Fatalf("card edges should not have a background: %q", light)
	}
	lightPlain := renderBlackjackSnapshotFor(snapshot, "none", true, 7, "light", nil, "")
	if !strings.Contains(lightPlain, "▀▀▀▀▀▀▀") || !strings.Contains(lightPlain, "▄▄▄▄▄▄▄") {
		t.Fatalf("expected half-height light card edges: %q", lightPlain)
	}
	// The card edges must touch the white body: ▄ blocks on top, ▀ on bottom.
	plainLines := strings.Split(lightPlain, "\n")
	if !strings.Contains(plainLines[1], "▄▄▄▄▄▄▄") || !strings.Contains(plainLines[7], "▀▀▀▀▀▀▀") {
		t.Fatalf("light card edges flipped: top=%q bottom=%q", plainLines[1], plainLines[7])
	}
}

// Casino settlements carry inline color tags for the outcome and each bet.
// The presentation layer must expand them per recipient (white prose, green
// win, red loss) rather than leaking the raw tags.
func TestCasinoProseExpandsSettlementTags(t *testing.T) {
	g := &Game{}
	p := player.New("alice")
	p.Options = map[string]any{"color": "xterm256"}
	sess := &net.Session{Player: p}
	got := g.casinoProse(sess, "casino_result_loss",
		"{casino_result_loss}LOSS{/} {casino_payout}-1 credit{/}\n  {casino_action}red:{/} {casino_result_loss}-1 credit{/}")
	if strings.Contains(got, "{") {
		t.Fatalf("raw tag leaked into rendered text: %q", got)
	}
	for _, want := range []string{"LOSS", "-1 credit", "red:"} {
		if !strings.Contains(got, want) {
			t.Fatalf("missing %q in %q", want, got)
		}
	}
	// White label, red loss, and the payout color on the headline total.
	if !strings.Contains(got, color.FgCode("xterm256", 255)) {
		t.Fatalf("bet label is not white: %q", got)
	}
	if !strings.Contains(got, color.FgCode("xterm256", 196)) {
		t.Fatalf("loss is not bold red: %q", got)
	}
	if !strings.Contains(got, color.StyleCode("bold")) {
		t.Fatalf("loss/amount is not bold: %q", got)
	}
}

// The landing pocket is the only bolded part of the spin announcement.
func TestCasinoProseBoldsLandingPocket(t *testing.T) {
	g := &Game{}
	p := player.New("alice")
	p.Options = map[string]any{"color": "xterm256"}
	sess := &net.Session{Player: p}
	got := g.casinoProse(sess, "casino_action", "The ball lands in {casino_emphasis}20{/}!")
	if !strings.Contains(got, color.StyleCode("bold")+color.FgCode("xterm256", 255)+"20") {
		t.Fatalf("landing pocket is not bold white: %q", got)
	}
}