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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
|
package game
import (
"errors"
"fmt"
"os"
"strconv"
"strings"
"unicode/utf8"
"thehouseoficarus/internal/cardart"
"thehouseoficarus/internal/casino"
"thehouseoficarus/internal/color"
"thehouseoficarus/internal/net"
"thehouseoficarus/internal/persistence"
"thehouseoficarus/internal/player"
)
type casinoWallet struct {
g *Game
p *player.Player
}
// Wager debits the stake durably. Order of operations: durable journal
// record FIRST (with balance checkpoints), then the in-memory mutation,
// then the character save, then the record is registered as an OUTSTANDING
// STAKE. It is NOT settled here: it stays open until the round resolves
// (casino.Wallet.ResolveStakes) or is refunded (RefundOutstanding). An open
// record at startup recovery means the round state was lost in a crash and
// the stake is refunded — the documented refund-on-crash policy.
//
// A failed save reverts the in-memory mutation and voids the record: no
// charge is kept in memory, and the error distinguishes persistence failure
// from insufficient funds.
func (w casinoWallet) Wager(amount int) (casino.Wager, error) {
if amount <= 0 {
return casino.Wager{}, casino.ErrInsufficientFunds
}
creditsBefore := w.p.Credits
chipsBefore := countChips(w.p)
chips := chipsBefore
if chips > amount {
chips = amount
}
credits := amount - chips
if creditsBefore < credits {
return casino.Wager{}, casino.ErrInsufficientFunds
}
rec, err := w.g.Economy.start("wager", w.p, chips, credits,
creditsBefore, creditsBefore-credits, chipsBefore, chipsBefore-chips)
if err != nil {
return casino.Wager{}, casino.ErrWalletPersistence
}
if chips > 0 {
w.p.RemoveItem("chips", chips)
}
w.p.Credits -= credits
if err := w.g.AccountStore.SaveCharacter(w.p); err != nil {
if errors.Is(err, persistence.ErrDurabilityUncertain) {
// The character file was replaced but the directory sync failed:
// the debit may be durable. Keep the in-memory debit and the
// journal record OPEN instead of voiding it, so recovery compares
// checkpoints against whatever file survived and either voids or
// refunds consistently. Proceeding is safe: the record stays open
// (refundable) until the round resolves.
fmt.Fprintf(os.Stderr, "casino wager: %s save durability uncertain: %v — record kept open\n", w.p.Name, err)
w.g.Economy.registerStake(rec)
return casino.Wager{Total: amount, Chips: chips, Credits: credits, ID: rec.ID}, nil
}
// Revert the in-memory mutation: the play must not proceed on a
// stake that could not be made durable.
if chips > 0 {
if !w.g.giveChips(w.p, chips) {
// Cannot happen (the debit just freed or reduced the chips
// stack), but surface it instead of silently losing chips.
fmt.Fprintf(os.Stderr, "casino wager revert: no inventory room for %d chips\n", chips)
}
}
w.p.Credits += credits
w.g.Economy.void(rec)
return casino.Wager{}, casino.ErrWalletPersistence
}
// The record stays open as an outstanding stake until the round
// resolves; recovery refunds open stakes after a crash.
w.g.Economy.registerStake(rec)
return casino.Wager{Total: amount, Chips: chips, Credits: credits, ID: rec.ID}, nil
}
// PayCredits applies a payout durably. The journal record is written first;
// if the save fails, the record stays open and startup recovery re-pays it
// (the player is owed the settlement).
func (w casinoWallet) PayCredits(amount int) error {
return w.payCreditsFlagged(amount, false, nil)
}
// PayStakeCover applies a settlement that INCLUDES the return of the listed
// stake wager IDs (a table hand pays its stake back inside the payout). The
// record is journaled with that linkage, so a shutdown refund never returns
// those stakes a second time; recovery re-applies the owed payout instead.
func (w casinoWallet) PayStakeCover(amount int, stakeIDs []string) error {
return w.payCreditsFlagged(amount, false, stakeIDs)
}
// payCreditsFlagged journals and applies a credit payout; a settlement
// payout (refund=false) proves the round resolved during recovery, while a
// refund payout (refund=true) marks a stake RETURNED at shutdown/eviction
// (its chip part returns in chips, not through this credit payout).
// stakeIDs, when non-empty, records WHICH open stakes this settlement
// returns (table hands); empty means the payout resolves the round without
// a linked stake return (slots winnings).
func (w casinoWallet) payCreditsFlagged(amount int, refund bool, stakeIDs []string) error {
if amount <= 0 {
return nil
}
creditsBefore := w.p.Credits
chipsBefore := countChips(w.p)
creditsAfter, capErr := addCreditsChecked(creditsBefore, amount)
// The journal record is written FIRST, even when the economy cap
// blocks the payout: a won settlement must never be silently dropped.
// With the cap blocking, the balance is unchanged and the open record
// keeps the owed amount durable; startup recovery re-applies it once
// the balance has room below the cap.
rec, err := w.g.Economy.startKind("payout", refund, stakeIDs, w.p, 0, amount,
creditsBefore, creditsAfter, chipsBefore, chipsBefore)
if err != nil {
// The journal is unavailable (persistent append failure). Last
// resort: pay through the character file only. The save below is
// the commit point — the money is durable even without a journal
// record, so the settlement may be announced as paid. The stake
// resolution evidence (recordStakeEvidence) recorded in that same
// file keeps recovery from treating the round as unresolved;
// without a payout record, an open wager can no longer be
// distinguished from a lost one, so the balance itself is the only
// record of what happened.
if capErr != nil {
return capErr
}
w.p.Credits = creditsAfter
// The character file is the only durable record, so it must also
// carry the resolution evidence for the stakes this settlement
// resolves: a crash before the games' own ResolveStakes call would
// otherwise leave the wager records open with checkpoint balances
// that no longer match, and recovery would refund chip stakes the
// paid settlement had already consumed. Only the settled stakes are
// recorded (see recordStakeEvidence), so a sibling hand's stake stays
// refundable. The single save below is the commit point for the
// payout AND the resolution.
resolved := w.recordStakeEvidence(stakeIDs)
if serr := w.g.AccountStore.SaveCharacter(w.p); serr != nil {
w.p.Credits = creditsBefore
if resolved > 0 {
w.p.ResolvedStakes = w.p.ResolvedStakes[:len(w.p.ResolvedStakes)-resolved]
}
return casino.ErrWalletPersistence
}
kind := "settlement"
if refund {
kind = "refund"
}
fmt.Fprintf(os.Stderr, "economy: %s payout of %d credits for %s could not be journaled; the character file is the only durable record\n", kind, amount, w.p.Name)
return nil
}
if capErr != nil {
return capErr
}
w.p.Credits = creditsAfter
// Record the payout in the character's open-payout evidence list: the
// save below is the commit point, and the file itself then proves the
// amount is included in the balance. Recovery reads this list instead
// of guessing from balance checkpoints, which unrelated credit changes
// (a shop sale, a bank deposit) can replicate by coincidence.
w.p.OpenPayouts = append(w.p.OpenPayouts, rec.ID)
if err := w.g.AccountStore.SaveCharacter(w.p); err != nil {
w.p.Credits = creditsBefore
removeOpenPayout(w.p, rec.ID)
// Keep the record open: recovery re-pays on next startup, since a
// reported win must be durable.
return casino.ErrWalletPersistence
}
// The evidence entry may only be dropped once the settled marker is
// durable; while the marker is still open, the file's membership is
// what proves durability to recovery.
if w.g.Economy.settleDurable(rec) {
removeOpenPayout(w.p, rec.ID)
}
return nil
}
// ResolveStakes marks every outstanding stake for the player settled: the
// round resolved (won, lost, pushed, or forfeited), so startup recovery
// must no longer refund it. When the journal cannot persist the settled
// markers, the record IDs are recorded in the character file as durable
// resolution evidence (player.Player.ResolvedStakes) so recovery still
// honors the resolution instead of refunding an already-resolved round.
func (w casinoWallet) ResolveStakes() {
unresolved := w.g.Economy.ResolveStakes(economyKey(w.p))
w.recordResolutionEvidence(unresolved)
}
// recordResolutionEvidence persists file-side resolution evidence for stake
// records whose settled markers could not be journaled. The character file
// then proves the round resolved even though the journal could not record
// its marker, so recovery still honors the resolution instead of refunding
// an already-resolved round.
func (w casinoWallet) recordResolutionEvidence(unresolved []*economyRecord) {
if len(unresolved) == 0 {
return
}
changed := false
for _, rec := range unresolved {
if !resolvedStakeRecorded(w.p, rec.ID) {
w.p.ResolvedStakes = append(w.p.ResolvedStakes, rec.ID)
changed = true
}
}
if !changed {
return
}
if err := w.g.AccountStore.SaveCharacter(w.p); err != nil {
fmt.Fprintf(os.Stderr, "casino resolve stakes: evidence save for %s: %v\n", w.p.Name, err)
}
}
// ResolveStake settles ONE outstanding stake by wallet handle: the hand it
// belongs to was paid (its return is inside the settlement) or lost, so it
// must never be refunded. Unresolvable markers fall back to the same file-
// side evidence the bulk ResolveStakes uses.
func (w casinoWallet) ResolveStake(stakeID string) {
if stakeID == "" {
return
}
unresolved := w.g.Economy.ResolveStakeByID(economyKey(w.p), stakeID)
w.recordResolutionEvidence(unresolved)
}
// recordStakeEvidence adds the stakes the current settlement resolves to the
// file-side resolution evidence list and returns how many IDs were newly
// recorded. Used when the economy journal is unavailable: the open wager
// record IDs in the character file prove the round resolved even though no
// settled marker (or payout record) could ever be journaled. The caller
// must persist the character file for the evidence to count.
//
// stakeIDs are the stakes the payout settles (a table hand lists its own
// hand's stakes). Only those are recorded: a sibling hand's stake is settled
// by its own payout, so marking it resolved here would suppress the refund a
// crash before that payout must still produce. An empty list (a slots payout
// links no stake) settles the round that consumed the stake, so every open
// stake of the player is evidence.
func (w casinoWallet) recordStakeEvidence(stakeIDs []string) int {
added := 0
for _, rec := range w.g.Economy.openStakes(economyKey(w.p)) {
if len(stakeIDs) > 0 && !containsString(stakeIDs, rec.ID) {
continue
}
if !resolvedStakeRecorded(w.p, rec.ID) {
w.p.ResolvedStakes = append(w.p.ResolvedStakes, rec.ID)
added++
}
}
return added
}
// RefundOutstanding returns every outstanding stake to the player: chips
// come back as chips, credits through the durable payout path. The stakes
// are resolved only once the return is durable; on failure the chip return
// is rolled back out of memory and the open records drive recovery instead.
//
// Stakes already accounted for by an open settlement payout are NOT
// refunded: a journaled table settlement includes its hand's stake return
// and recovery re-applies that owed payout, so refunding the stake here
// would pay the round twice (the returned credits then arrive on top of
// the stake). The stakes are resolved; their money arrives with the
// re-applied settlement.
func (w casinoWallet) RefundOutstanding() (chips, credits int, err error) {
for _, rec := range w.g.Economy.openStakes(economyKey(w.p)) {
if resolvedStakeRecorded(w.p, rec.ID) {
// Already resolved through file-side evidence: recovery
// settles it, never refunds it.
continue
}
if w.g.Economy.stakeCovered(rec) {
// The covering settlement is journaled and owed: resolving
// the stake defers its return to the payout re-application.
continue
}
chips += rec.Chips
credits += rec.Credit
}
if chips <= 0 && credits <= 0 {
w.ResolveStakes()
return 0, 0, nil
}
if chips > 0 {
if !w.g.giveChips(w.p, chips) {
// No inventory room for the chip return: nothing was refunded.
// The stakes stay open so recovery (or a later attempt once the
// player has inventory space) can complete the refund; callers
// report the stake as recorded rather than refunded, never as
// silently dropped.
return 0, 0, casino.ErrWalletPersistence
}
}
if credits > 0 {
if err := w.payCreditsFlagged(credits, true, nil); err != nil {
if chips > 0 {
// Roll the chip return back out of memory: the durable
// refund will re-apply both amounts from the open records.
w.p.RemoveItem("chips", chips)
}
return chips, credits, err
}
} else if chips > 0 {
// A chips-only refund needs its own durable save.
if err := w.g.AccountStore.SaveCharacter(w.p); err != nil {
w.p.RemoveItem("chips", chips)
return chips, 0, casino.ErrWalletPersistence
}
}
w.ResolveStakes()
return chips, credits, nil
}
// casinoAffordable is the most a player can wager: chips are spent first,
// then credits.
func casinoAffordable(p *player.Player) int { return p.Credits + countChips(p) }
// leaveCasinoGames departs every casino game the player participates in
// using the graceful leave policy each game defines for player-initiated
// exits (the same path the "stop" command takes): a table with a wager
// committed to the round in flight refuses and emits its own refusal
// message, machines stop auto-bet or are left outright. It reports whether
// the player is now clear of all casino games; false means a departure is
// blocked mid-round and the caller (quit) must abort. Nil-safe for test
// scaffolding without a Casino manager.
func (g *Game) leaveCasinoGames(p *player.Player) bool {
if g.Casino == nil {
return true
}
if table, playing := g.Casino.Participation(p.Name); playing {
if table != nil {
g.emitCasinoEvents(g.Casino.Leave(table.RoomID, table.Config.ID, p.Name))
} else if machine, ok := g.Casino.MachineFor(p.Name); ok {
// Stop autobet first, then take the machine's own leave path: a
// machine between spins has no committed stake, so one quit must
// free it (and must not warn about a forfeit that cannot happen).
// A machine mid-spin refuses the leave, the player stays seated,
// and the caller warns about the stake that is really committed.
if events, stopped := g.Casino.StopMachineAutoBet(machine.RoomID, machine.Config.ID, p.Name); stopped {
g.emitCasinoEvents(events)
}
g.emitCasinoEvents(g.Casino.LeaveMachine(machine.RoomID, machine.Config.ID, p.Name))
}
_, stillPlaying := g.Casino.Participation(p.Name)
return !stillPlaying
}
return true
}
// inCasinoGame reports whether the player is currently seated at any casino
// table or machine. Nil-safe for test scaffolding without a Casino manager.
func (g *Game) inCasinoGame(name string) bool {
if g.Casino == nil {
return false
}
_, playing := g.Casino.Participation(name)
return playing
}
// casinoTable returns the room's table for the named game. A room addresses
// at most one table (or machine) per game name — "play blackjack" carries no
// table id — so a second table for the same game would be unreachable
// content; ValidateRoomConfigs rejects that configuration instead of silently
// dropping it.
func (g *Game) casinoTable(roomID int, gameName string) (*casino.Table, bool) {
room, err := g.World.LoadRoom(roomID)
if err != nil {
return nil, false
}
if casino.ValidateRoomConfigs(room.CasinoTables, room.CasinoMachines) != nil {
return nil, false
}
for _, cfg := range room.CasinoTables {
if strings.EqualFold(string(cfg.Game), gameName) {
table := g.Casino.EnsureTable(roomID, cfg)
if table == nil {
return nil, false
}
return table, true
}
}
return nil, false
}
// casinoMachine returns the room's machine for the named game or variant.
// Like casinoTable, only the first match is reachable, which is why
// ValidateRoomConfigs rejects a room with two entries addressing the same
// game name or variant.
func (g *Game) casinoMachine(roomID int, gameName string) (*casino.Machine, bool) {
room, err := g.World.LoadRoom(roomID)
if err != nil {
return nil, false
}
if casino.ValidateRoomConfigs(room.CasinoTables, room.CasinoMachines) != nil {
return nil, false
}
for _, cfg := range room.CasinoMachines {
if strings.EqualFold(string(cfg.Game), gameName) || strings.EqualFold(cfg.Variant, gameName) {
machine := g.Casino.EnsureMachine(roomID, cfg)
return machine, machine != nil
}
}
// Migrate older room definitions that declared slots under casino_tables;
// slots are still always instantiated as one-player machines.
if strings.EqualFold(gameName, "slots") {
for _, cfg := range room.CasinoTables {
if strings.EqualFold(string(cfg.Game), "slots") {
machine := g.Casino.EnsureMachine(roomID, casino.LegacySlotMachine(cfg))
return machine, machine != nil
}
}
}
return nil, false
}
func (g *Game) executePlay(sess *net.Session, args []string, rawInput string) {
p := sess.Player
if p == nil || len(args) == 0 {
sess.WriteLine("Play what?")
return
}
if _, playing := g.Casino.Participation(p.Name); playing {
sess.WriteLine("You're already playing a game. Type \"stop\" between rounds to leave it.")
return
}
g.startCasinoGame(sess, p, args[0])
}
func (g *Game) startCasinoGame(sess *net.Session, p *player.Player, gameName string) {
if p == nil || sess == nil {
return
}
if _, playing := g.Casino.Participation(p.Name); playing {
sess.WriteLine("You're already playing a game. Type \"stop\" between rounds to leave it.")
return
}
if machine, ok := g.casinoMachine(p.RoomID, gameName); ok {
g.emitCasinoEvents(g.Casino.JoinMachine(machine.RoomID, machine.Config, p.Name))
return
}
table, ok := g.casinoTable(p.RoomID, gameName)
if !ok {
sess.WriteLine(fmt.Sprintf("There is no %s table here.", gameName))
return
}
g.emitCasinoEvents(g.Casino.Join(table.RoomID, table.Config, p.Name))
}
func (g *Game) executeBet(sess *net.Session, args []string, rawInput string) {
p := sess.Player
if p == nil {
sess.WriteLine("Bet how much?")
return
}
if machine, ok := g.Casino.MachineFor(p.Name); ok {
if len(args) == 0 {
g.emitCasinoEvents(g.Casino.StartMachine(machine.RoomID, machine.Config.ID, p.Name, casinoWallet{g: g, p: p}))
return
}
if len(args) == 1 {
if args[0] == "max" {
amount := min(machine.Config.MaxBet, casinoAffordable(p))
if amount < 1 {
sess.WriteLine("You don't have any chips or credits to bet.")
return
}
g.emitCasinoEvents(g.Casino.SetMachineBet(machine.RoomID, machine.Config.ID, p.Name, amount, casinoWallet{g: g, p: p}))
return
}
if amount, err := strconv.Atoi(args[0]); err == nil && amount > 0 {
g.emitCasinoEvents(g.Casino.SetMachineBet(machine.RoomID, machine.Config.ID, p.Name, amount, casinoWallet{g: g, p: p}))
return
}
}
sess.WriteLine("Use bet, bet <amount>, or bet max.")
return
}
table, playing := g.Casino.Participation(p.Name)
if !playing || table == nil {
sess.WriteLine("You're not playing a game.")
return
}
// Table bet syntax: bet | bet <amount> [on] <target> | bet min|max [on] <target>.
// BEFORE an "on" keyword, a token that parses as an amount (or min/max)
// sets the wager and any other token is the bet target; AFTER "on", the
// next token is always the target. That makes numeric targets reachable
// ("bet 5 on 17"), which roulette, craps, and keno need.
amount, spot, hasAmount, sawOn := 0, "", false, false
for _, arg := range args {
if strings.EqualFold(arg, "on") {
sawOn = true
continue
}
if !sawOn {
if strings.EqualFold(arg, "min") {
if hasAmount {
sess.WriteLine("Use bet, bet <amount> [on <target>], bet min, or bet max.")
return
}
amount, hasAmount = table.Config.MinBet, true
continue
}
if strings.EqualFold(arg, "max") {
if hasAmount {
sess.WriteLine("Use bet, bet <amount> [on <target>], bet min, or bet max.")
return
}
amount = min(table.Config.MaxBet, casinoAffordable(p))
if amount < 1 {
sess.WriteLine("You don't have any chips or credits to bet.")
return
}
hasAmount = true
continue
}
if value, err := strconv.Atoi(arg); err == nil && value > 0 {
if hasAmount {
sess.WriteLine("Use bet, bet <amount> [on <target>], bet min, or bet max.")
return
}
amount, hasAmount = value, true
continue
}
}
if spot != "" {
sess.WriteLine("Use bet, bet <amount> [on <target>], bet min, or bet max.")
return
}
spot = strings.ToLower(arg)
}
if !hasAmount {
var lastSpot string
lastSpot, amount = g.Casino.Rebet(table.RoomID, table.Config.ID, p.Name)
if spot == "" {
spot = lastSpot
}
if amount <= 0 {
sess.WriteLine("Bet how much?")
return
}
}
g.emitCasinoEvents(g.Casino.Bet(table.RoomID, table.Config.ID, p.Name, spot, amount, casinoWallet{g: g, p: p}))
}
func (g *Game) executeAutoBet(sess *net.Session, args []string, rawInput string) {
p := sess.Player
if p == nil {
return
}
if machine, ok := g.Casino.MachineFor(p.Name); ok {
g.emitCasinoEvents(g.Casino.EnableMachineAutoBet(machine.RoomID, machine.Config.ID, p.Name, casinoWallet{g: g, p: p}))
return
}
sess.WriteLine("Autobet is only available at games without player choices.")
}
func (g *Game) executeTableAction(sess *net.Session, action string) {
p := sess.Player
if p == nil {
return
}
table, playing := g.Casino.Participation(p.Name)
if !playing || table == nil {
sess.WriteLine("You're not playing a multiplayer casino game.")
return
}
g.emitCasinoEvents(g.Casino.Action(table.RoomID, table.Config.ID, p.Name, action))
}
func (g *Game) CasinoTick() {
if g.Casino != nil {
g.emitCasinoEvents(g.Casino.Tick())
}
}
func (g *Game) emitCasinoEvents(events []casino.Event) {
for _, event := range events {
if event.Message == "" && event.PrivateMessage == "" && event.Menu == nil && event.Snapshot == nil {
continue
}
category := event.Color
if category == "" {
category = "casino_action"
}
if event.Public && g.Hub != nil {
for _, sess := range g.Hub.PlayersInRoom(event.RoomID) {
if event.PrivateTo != "" && sess.Player != nil && sess.Player.Name == event.PrivateTo {
continue
}
message := event.Message
if rendered := g.renderCasinoSnapshot(sess, event.Snapshot); rendered != "" {
message += "\n" + rendered
}
sess.WriteLine(g.colorize(sess, category, message))
}
}
if event.PrivateTo == "" {
continue
}
text := event.PrivateMessage
if text == "" {
text = event.Message
}
if text == "" && event.Menu == nil {
continue
}
g.charsMu.Lock()
sess := g.loggedInChars[event.PrivateTo]
g.charsMu.Unlock()
if sess == nil {
continue
}
privateMessage := g.casinoPrivateMessage(sess, category, event.Menu, text)
if rendered := g.renderCasinoSnapshot(sess, event.Snapshot); rendered != "" {
privateMessage += "\n" + rendered
}
sess.WriteLine(g.renderCasinoMessage(sess, category, event.Menu, privateMessage))
if category == "casino_menu" {
g.writePrompt(sess)
}
}
}
// renderCasinoMessage colorizes a casino message unless it is an
// already-composed structured menu.
func (g *Game) renderCasinoMessage(sess *net.Session, category string, menu *casino.MenuView, message string) string {
if category == "casino_menu" && menu != nil {
return message
}
return g.colorize(sess, category, message)
}
func (g *Game) casinoPrivateMessage(sess *net.Session, category string, menu *casino.MenuView, message string) string {
if category != "casino_menu" || menu == nil {
return message
}
balance := ""
if menu.ShowBalance {
chips := g.colorize(sess, "casino_chips", fmt.Sprintf("%d", countChips(sess.Player)))
credits := g.colorize(sess, "casino_credits", fmt.Sprintf("%d", sess.Player.Credits))
balance = fmt.Sprintf("You have %s chips and %s credits.", chips, credits)
}
heading := menu.Heading
if heading == "" {
heading = message
}
return g.renderCasinoCommands(sess, balance, heading, menu.Commands)
}
// renderCasinoSnapshot renders a game's structured view for one session. It is
// the only per-game switch in the presentation layer: adding a game means
// adding its snapshot type here, and the Snapshot interface guarantees the
// event carries it rather than being silently dropped by a field filter.
func (g *Game) renderCasinoSnapshot(sess *net.Session, snapshot casino.Snapshot) string {
if snapshot == nil || sess.Player == nil {
return ""
}
mode := g.colorMode(sess)
unicode := sess.Player.OptionBool("unicode")
switch s := snapshot.(type) {
case *casino.SlotSnapshot:
return renderSlotSnapshot(s, mode, unicode)
case *casino.BlackjackSnapshot:
return renderBlackjackSnapshot(s, mode, unicode, sess.Player.OptionInt("card_size"), sess.Player.OptionString("card_style"), g.CardArt)
case *casino.BaccaratSnapshot:
return renderBaccaratSnapshot(s, mode, unicode, sess.Player.OptionInt("card_size"), sess.Player.OptionString("card_style"), g.CardArt)
}
return ""
}
// renderCasinoCommands lays every casino menu out in the same style: an
// optional balance line, a heading, and an aligned command list with each
// command in the "command" color and its description in plain text.
func (g *Game) renderCasinoCommands(sess *net.Session, balance, heading string, commands []casino.MenuCommand) string {
var sb strings.Builder
if balance != "" {
sb.WriteString(balance)
sb.WriteString("\n\n")
}
if heading != "" {
sb.WriteString(heading)
sb.WriteString("\n\n")
}
width := 0
for _, c := range commands {
if n := utf8.RuneCountInString(c.Command); n > width {
width = n
}
}
for _, c := range commands {
padded := c.Command + strings.Repeat(" ", width-utf8.RuneCountInString(c.Command))
cmd := g.colorize(sess, "command", padded)
if c.Desc != "" {
fmt.Fprintf(&sb, " %s %s\n", cmd, c.Desc)
} else {
fmt.Fprintf(&sb, " %s\n", cmd)
}
}
return strings.TrimRight(sb.String(), "\n")
}
func renderBlackjackSnapshot(snapshot *casino.BlackjackSnapshot, mode string, unicode bool, size int, style string, art *cardart.Store) string {
if snapshot == nil {
return ""
}
size = cardRenderSize(unicode, size)
var lines []string
dealerTitle := "Dealer:"
if snapshot.DealerRevealed {
dealerTitle = "Dealer (" + snapshot.DealerScore + "):"
} else if snapshot.DealerShownScore != "" {
dealerTitle = "Dealer (" + snapshot.DealerShownScore + "):"
}
lines = append(lines, cardLine(mode, dealerTitle))
lines = append(lines, cardsLine(mode, snapshot.Dealer, size, unicode, style, art)...)
for _, player := range snapshot.Players {
lines = append(lines, cardLine(mode, fmt.Sprintf("%s (%s):", player.Name, player.Score)))
lines = append(lines, cardsLine(mode, player.Cards, size, unicode, style, art)...)
}
return strings.Join(lines, "\n")
}
// renderBaccaratSnapshot draws the player and banker hands followed by the
// list of wagers riding on the round.
func renderBaccaratSnapshot(snapshot *casino.BaccaratSnapshot, mode string, unicode bool, size int, style string, art *cardart.Store) string {
if snapshot == nil {
return ""
}
size = cardRenderSize(unicode, size)
var lines []string
lines = append(lines, cardLine(mode, "Player ("+snapshot.PlayerScore+"):"))
lines = append(lines, cardsLine(mode, snapshot.Player, size, unicode, style, art)...)
lines = append(lines, cardLine(mode, "Banker ("+snapshot.BankerScore+"):"))
lines = append(lines, cardsLine(mode, snapshot.Banker, size, unicode, style, art)...)
for _, bet := range snapshot.Bets {
lines = append(lines, cardLine(mode, fmt.Sprintf("%s bets %d on %s.", bet.Name, bet.Amount, bet.Spot)))
}
return strings.Join(lines, "\n")
}
func cardLine(mode, text string) string {
spec := color.NoColor()
spec.Fg = 39
return color.Render(mode, spec, text)
}
func cardsLine(mode string, cards []casino.CardView, size int, unicode bool, style string, art *cardart.Store) []string {
if len(cards) == 0 {
return nil
}
if size == 1 {
parts := make([]string, len(cards))
for i, card := range cards {
parts[i] = colorizeCardSymbol(mode, card)
}
return []string{strings.Join(parts, " ")}
}
artLines := make([][]string, len(cards))
for i, card := range cards {
artLines[i] = cardArtLines(card, size, unicode, style, art)
}
lines := make([]string, size)
for row := 0; row < size; row++ {
var lineParts []string
for i, card := range artLines {
lineParts = append(lineParts, colorizeCardLine(mode, card[row], cards[i], row, size, style))
}
lines[row] = strings.Join(lineParts, " ")
}
return lines
}
func cardRenderSize(unicode bool, size int) int {
if !unicode {
return 5
}
if size == 1 || size == 5 || size == 7 || size == 9 {
return size
}
return 7
}
var suitSymbols = map[string]string{"hearts": "♥", "spades": "♠", "diamonds": "♦", "clubs": "♣"}
func cardSymbol(card casino.CardView) string {
if card.Hidden {
return "?"
}
return card.Rank + suitSymbols[card.Suit]
}
func cardArtLines(card casino.CardView, size int, unicode bool, style string, art *cardart.Store) []string {
if card.Hidden {
return generatedCardArt("?", "", size, unicode, style)
}
key := card.Rank + strings.ToUpper(card.Suit[:1])
if configured := art.Art(key, size); len(configured) == size {
return configured
}
return generatedCardArt(card.Rank, card.Suit, size, unicode, style)
}
func generatedCardArt(rank, suit string, size int, unicode bool, style string) []string {
if size < 5 {
size = 5
}
border := "-"
left, right := "+", "+"
if unicode {
border, left, right = "─", "┌", "┐"
}
bottomLeft, bottomRight := left, right
if unicode {
bottomLeft, bottomRight = "└", "┘"
}
vertical := "|"
if unicode {
vertical = "│"
}
if unicode && style == "light" {
lines := []string{strings.Repeat("▄", size)}
lines = append(lines, generatedCardBody(rank, suit, size, unicode, vertical)...)
return append(lines, strings.Repeat("▀", size))
}
lines := []string{left + strings.Repeat(border, size-2) + right}
lines = append(lines, generatedCardBody(rank, suit, size, unicode, vertical)...)
lines = append(lines, bottomLeft+strings.Repeat(border, size-2)+bottomRight)
return lines
}
func generatedCardBody(rank, suit string, size int, unicode bool, vertical string) []string {
inner := size - 2
lines := make([]string, 0, size-2)
for row := 1; row < size-1; row++ {
content := strings.Repeat(" ", inner)
if row == 1 {
content = rank + strings.Repeat(" ", inner-len(rank))
}
if row == (size-1)/2 {
suitText := ""
if suit != "" {
suitText = suitLetter(suit, unicode)
}
suitWidth := utf8.RuneCountInString(suitText)
leftPadding := (inner - suitWidth) / 2
content = strings.Repeat(" ", leftPadding) + suitText + strings.Repeat(" ", inner-leftPadding-suitWidth)
}
if row == size-2 {
content = strings.Repeat(" ", inner-len(rank)) + rank
}
lines = append(lines, vertical+content+vertical)
}
return lines
}
func suitLetter(suit string, unicode bool) string {
if !unicode {
return strings.ToUpper(suit[:1])
}
return suitSymbols[suit]
}
func colorizeCardLine(mode, line string, card casino.CardView, row, size int, style string) string {
red := card.Suit == "hearts" || card.Suit == "diamonds"
rankColor := 27
if red {
rankColor = 196
}
suitColor := 27
if red {
suitColor = 196
}
rankLine := row == 1 || row == size-2
light := style == "light"
bodyBackground := light && row > 0 && row < size-1
var builder strings.Builder
for _, r := range line {
if strings.ContainsRune("┌─┐└┘│┬┴├┤┼╔╗╚╝═║╦╩╠╣╬▀▄+|-", r) {
spec := color.ColorSpec{Fg: 15}
if bodyBackground {
spec.Bg = 15
}
builder.WriteString(color.Render(mode, spec, string(r)))
} else if r == ' ' {
if bodyBackground {
builder.WriteString(color.Render(mode, color.ColorSpec{Fg: 15, Bg: 15}, " "))
} else {
builder.WriteRune(r)
}
} else {
value := suitColor
if rankLine {
value = rankColor
}
spec := color.ColorSpec{Fg: value}
if bodyBackground {
spec.Bg = 15
}
builder.WriteString(color.Render(mode, spec, string(r)))
}
}
return builder.String()
}
func colorizeCardSymbol(mode string, card casino.CardView) string {
if card.Hidden {
return color.Render(mode, color.ColorSpec{Fg: 15}, "?")
}
rankColor, suitColor := 27, 27
if card.Suit == "hearts" || card.Suit == "diamonds" {
rankColor, suitColor = 196, 196
}
runes := []rune(cardSymbol(card))
rankLength := len([]rune(card.Rank))
return color.Render(mode, color.ColorSpec{Fg: rankColor}, string(runes[:rankLength])) +
color.Render(mode, color.ColorSpec{Fg: suitColor}, string(runes[rankLength:]))
}
func renderSlotSnapshot(snapshot *casino.SlotSnapshot, mode string, unicode bool) string {
if snapshot == nil {
return ""
}
left, junction, right, horizontal, vertical := '+', '+', '+', '-', '|'
bottomLeft, bottomJunction, bottomRight := '+', '+', '+'
if unicode {
left, junction, right, horizontal, vertical = '\u250c', '\u252c', '\u2510', '\u2500', '\u2502'
bottomLeft, bottomJunction, bottomRight = '\u2514', '\u2534', '\u2518'
}
separator := string(left)
for reel := 0; reel < 5; reel++ {
if reel > 0 {
separator += string(junction)
}
separator += strings.Repeat(string(horizontal), 9)
}
separator += string(right)
lines := []string{casinoFrame(mode, separator)}
frameVertical := casinoFrame(mode, string(vertical))
for row := 0; row < 3; row++ {
line := frameVertical
for reel := 0; reel < 5; reel++ {
value := "..."
if reel < snapshot.StoppedReels {
value = snapshot.Grid[row][reel]
}
// Pad to the fixed 7-cell reel width; a malformed profile could
// otherwise make this negative and panic. Validation caps the id
// length, so this is a defence-in-depth backstop.
pad := 7 - len(value)
if pad < 0 {
pad = 0
}
line += " " + colorSlotSymbol(mode, value) + strings.Repeat(" ", pad) + " " + frameVertical
}
lines = append(lines, line)
}
bottom := string(bottomLeft)
for reel := 0; reel < 5; reel++ {
if reel > 0 {
bottom += string(bottomJunction)
}
bottom += strings.Repeat(string(horizontal), 9)
}
bottom += string(bottomRight)
lines = append(lines, casinoFrame(mode, bottom))
return strings.Join(lines, "\n")
}
func casinoFrame(mode, text string) string {
spec := color.NoColor()
spec.Fg = 244
return color.Render(mode, spec, text)
}
func colorSlotSymbol(mode, symbol string) string {
spec := color.NoColor()
spec.Fg = 250
switch symbol {
case "straw":
spec.Fg = 220
case "stick":
spec.Fg = 46
case "brick":
spec.Fg = 196
case "hat":
spec.Fg = 201
case "wolf":
spec.Fg = 39
case "scatter":
spec.Fg = 226
default:
spec.Dim = true
}
return color.Render(mode, spec, symbol)
}
|