Repository navigation
Expand file tree
/
Copy pathuniversal_craps_engine.py
More file actions
executable file
·3836 lines (3482 loc) · 137 KB
/
Copy pathuniversal_craps_engine.py
File metadata and controls
executable file
·3836 lines (3482 loc) · 137 KB
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
#!/usr/bin/env python3
"""A rules-first, YAML-driven, object-oriented craps simulation engine.
Created by Greg M. Krsak (greg.krsak@gmail.com) and the GPT-5.5 High setting
in ChatGPT Plus.
Licensed under the MIT open-source license. A copy of the license is available
in the LICENSE file, or via the web from: https://opensource.org/license/mit
The engine is kept in one file so it is easy to audit, copy, archive, and run
without installing a package. Its internal design follows a Model-View-
Controller architecture:
* MODEL
Immutable dice rolls, table rules, wagers, settlements, a cash ledger, and
the complete state of the table live here. The model knows what the game
*is*, but it does not decide when a player should make a wager.
* VIEW
Views translate model events into human-readable output. A NullView makes
Monte Carlo runs silent; ConsoleView produces an audit trail suitable for
debugging a strategy one roll at a time.
* CONTROLLER
The controller is the only layer allowed to change table state. It accepts
wager instructions, requests dice, resolves every active wager against an
immutable pre-roll snapshot, advances the puck, and emits events. A YAML
strategy controller subscribes to those events and performs declarative
actions.
Money is represented with Decimal rather than float. A wager is removed from
cash when it is placed and remains part of equity while active. A persistent
wager such as a Place 6 receives only its profit after a win because its stake
remains on the layout. A one-roll wager receives its surviving stake and its
profit, then leaves the layout. These accounting rules keep the ledger
consistent and prevent duplicate, missing, or incorrectly returned funds.
The implementation covers the principal casino-craps wager families:
* Pass Line, Don't Pass, Come, and Don't Come
* Taking and laying odds, including configurable 3-4-5x limits
* Place, Buy, Lay, Big 6, Big 8, and Hardway wagers
* Field, Any Seven, Any Craps, Aces, Ace-Deuce, Yo, and Boxcars
* Horn, C & E, World/Whirl, and exact unordered Hop combinations
Casino practices differ. The companion YAML file therefore exposes field
payouts, the Don't bar number, vig timing and basis, odds limits, working-on-
come-out defaults, chip rounding, minimums, and legal wager increments.
Run modes:
python universal_craps_engine.py strategy.yaml --simulate
python universal_craps_engine.py strategy.yaml --run-scenarios
python universal_craps_engine.py strategy.yaml --audit
python universal_craps_engine.py --run-tests
The embedded unittest suite ships with the engine. It uses deterministic
rolls, exhaustive 36-combination checks, ledger invariants, YAML validation,
and end-to-end scenario tests.
"""
from __future__ import annotations
import argparse
import copy
import random
import statistics
import sys
import unittest
from abc import ABC, abstractmethod
from collections import Counter
from dataclasses import dataclass, field, replace
from decimal import Decimal, ROUND_DOWN, ROUND_HALF_UP
from enum import Enum
from pathlib import Path
from typing import Any, Iterable, Iterator, Mapping, Optional, Sequence
from unittest import mock
import yaml
# ---------------------------------------------------------------------------
# MODEL: SMALL, PURE VALUE TYPES
# ---------------------------------------------------------------------------
Money = Decimal
POINT_NUMBERS = (4, 5, 6, 8, 9, 10)
CRAPS_NUMBERS = (2, 3, 12)
NATURALS = (7, 11)
def as_money(value: Any) -> Money:
"""Convert a YAML/Python numeric value to an exact Decimal amount."""
if isinstance(value, Decimal):
return value
return Decimal(str(value))
def money_text(value: Money) -> str:
"""Return a stable, pleasant dollar representation for reports."""
return f"${value.quantize(Decimal('0.01')):,.2f}"
class CrapsError(Exception):
"""Base exception for all intentional engine failures."""
class ConfigurationError(CrapsError):
"""Raised when YAML is unknown, contradictory, or incomplete."""
class BetError(CrapsError):
"""Raised when a wager is illegal in the current table state."""
class InsufficientFunds(BetError):
"""Raised when cash cannot cover a stake, increase, or commission."""
class Phase(str, Enum):
"""The puck has only two meaningful states in traditional craps."""
COME_OUT = "come_out"
POINT_ON = "point_on"
class BetKind(str, Enum):
"""Every wager family understood by the settlement engine."""
PASS_LINE = "pass_line"
DONT_PASS = "dont_pass"
COME = "come"
DONT_COME = "dont_come"
TAKE_ODDS = "take_odds"
LAY_ODDS = "lay_odds"
PLACE = "place"
BUY = "buy"
LAY = "lay"
FIELD = "field"
BIG_6 = "big_6"
BIG_8 = "big_8"
HARDWAY = "hardway"
ANY_SEVEN = "any_seven"
ANY_CRAPS = "any_craps"
ACES = "aces"
ACE_DEUCE = "ace_deuce"
YO = "yo"
BOXCARS = "boxcars"
HORN = "horn"
C_AND_E = "c_and_e"
WORLD = "world"
HOP = "hop"
class BetStatus(str, Enum):
"""Lifecycle states for a wager stored in the table model."""
ACTIVE = "active"
RESOLVED = "resolved"
REMOVED = "removed"
class Outcome(str, Enum):
"""A settlement vocabulary designed for both people and tests."""
WIN = "win"
LOSS = "loss"
PUSH = "push"
TRAVEL = "travel"
NO_ACTION = "no_action"
RETURNED_OFF = "returned_off"
REMOVED = "removed"
@dataclass(frozen=True)
class DiceRoll:
"""An immutable pair of fair-die faces with useful derived properties."""
die_1: int
die_2: int
def __post_init__(self) -> None:
"""Validate both die faces after dataclass initialization."""
for face in (self.die_1, self.die_2):
if face not in range(1, 7):
raise ValueError("Each die face must be between 1 and 6.")
@property
def total(self) -> int:
"""Return the sum called by the stickperson."""
return self.die_1 + self.die_2
@property
def is_pair(self) -> bool:
"""Return True for doubles, the defining feature of a hardway."""
return self.die_1 == self.die_2
@property
def unordered_pair(self) -> tuple[int, int]:
"""Normalize a Hop combination so 3-4 and 4-3 are identical."""
return tuple(sorted((self.die_1, self.die_2)))
class DiceSource(ABC):
"""Dependency-injection seam for random and deterministic dice."""
@abstractmethod
def roll(self) -> DiceRoll:
"""Return the next two-die result."""
class RandomDice(DiceSource):
"""Two independent discrete uniform draws from one seeded generator."""
def __init__(self, seed: Optional[int] = None) -> None:
"""Create a private random generator with an optional seed."""
self._random = random.Random(seed)
def roll(self) -> DiceRoll:
"""Return one independent two-die result from the generator."""
return DiceRoll(
self._random.randint(1, 6),
self._random.randint(1, 6),
)
class ScriptedDice(DiceSource):
"""A finite deterministic source used by audits and unit tests."""
def __init__(self, rolls: Iterable[Sequence[int]]) -> None:
"""Store an iterator over a finite sequence of predetermined rolls."""
self._rolls: Iterator[Sequence[int]] = iter(rolls)
def roll(self) -> DiceRoll:
"""Return the next scripted roll.
Raise CrapsError when the configured sequence is exhausted.
"""
try:
pair = next(self._rolls)
except StopIteration as exc:
raise CrapsError(
"The scripted dice sequence is exhausted."
) from exc
if len(pair) != 2:
raise ValueError("Every scripted roll must contain two die faces.")
return DiceRoll(int(pair[0]), int(pair[1]))
@dataclass(frozen=True)
class OddsSchedule:
"""Maximum odds stakes, expressed as multiples of the flat wager.
A familiar 3-4-5x table permits a Pass/Come odds stake of three times the
flat wager on 4/10, four times on 5/9, and five times on 6/8. The matching
Don't schedule usually permits a six-times lay on every point; those lays
win three, four, or five times the flat wager respectively.
"""
take: Mapping[int, Money]
lay: Mapping[int, Money]
@classmethod
def standard_345x(cls) -> "OddsSchedule":
"""Build the conventional 3-4-5x take and six-times lay schedule."""
return cls(
take={
4: Decimal("3"),
5: Decimal("4"),
6: Decimal("5"),
8: Decimal("5"),
9: Decimal("4"),
10: Decimal("3"),
},
lay={number: Decimal("6") for number in POINT_NUMBERS},
)
@dataclass(frozen=True)
class TableRules:
"""Casino-specific rules that must never be hidden in settlement code."""
dont_bar: int = 12
field_2_profit: Money = Decimal("2")
field_12_profit: Money = Decimal("3")
buy_vig_rate: Money = Decimal("0.05")
buy_vig_timing: str = "on_win"
buy_vig_basis: str = "wager"
lay_vig_rate: Money = Decimal("0.05")
lay_vig_timing: str = "on_win"
lay_vig_basis: str = "win"
chip_unit: Money = Decimal("0.01")
payout_rounding: str = "floor"
enforce_increments: bool = True
place_working_on_comeout: bool = False
buy_working_on_comeout: bool = False
lay_working_on_comeout: bool = False
hardways_working_on_comeout: bool = False
big_6_8_working_on_comeout: bool = False
come_odds_working_on_comeout: bool = False
dont_come_odds_working_on_comeout: bool = True
odds: OddsSchedule = field(default_factory=OddsSchedule.standard_345x)
minimums: Mapping[str, Any] = field(default_factory=dict)
increments: Mapping[str, Any] = field(default_factory=dict)
def __post_init__(self) -> None:
"""Validate rule values that have a fixed set of legal choices."""
if self.dont_bar not in (2, 12):
raise ConfigurationError("dont_bar must be either 2 or 12.")
for timing in (self.buy_vig_timing, self.lay_vig_timing):
if timing not in ("upfront", "on_win"):
raise ConfigurationError(
"Vig timing must be 'upfront' or 'on_win'."
)
for basis in (self.buy_vig_basis, self.lay_vig_basis):
if basis not in ("wager", "win"):
raise ConfigurationError(
"Vig basis must be 'wager' or 'win'."
)
if self.payout_rounding not in ("floor", "nearest", "exact"):
raise ConfigurationError(
"payout_rounding must be floor, nearest, or exact."
)
if self.chip_unit <= 0:
raise ConfigurationError("chip_unit must be positive.")
def round_money(self, value: Money) -> Money:
"""Apply the configured chip policy to a profit or commission."""
if self.payout_rounding == "exact":
return value
units = value / self.chip_unit
rounding = (
ROUND_DOWN
if self.payout_rounding == "floor"
else ROUND_HALF_UP
)
return units.quantize(Decimal("1"), rounding=rounding) * self.chip_unit
def minimum_for(self, kind: BetKind, number: Optional[int]) -> Money:
"""Return the configured minimum for a wager and optional number."""
return self._numbered_rule(self.minimums, kind, number, Decimal("1"))
def increment_for(self, kind: BetKind, number: Optional[int]) -> Money:
"""Return the legal chip increment for a wager and optional number."""
return self._numbered_rule(
self.increments,
kind,
number,
self.chip_unit,
)
@staticmethod
def _numbered_rule(
rules: Mapping[str, Any],
kind: BetKind,
number: Optional[int],
default: Money,
) -> Money:
"""Resolve a scalar or point-specific minimum or increment rule."""
raw = rules.get(kind.value, default)
if isinstance(raw, Mapping):
if number is None:
raw = raw.get("default", default)
else:
raw = raw.get(number, raw.get(str(number), default))
return as_money(raw)
@dataclass
class Bet:
"""One reserved stake and all information needed to settle it."""
bet_id: int
kind: BetKind
amount: Money
number: Optional[int] = None
parent_id: Optional[int] = None
hop_pair: Optional[tuple[int, int]] = None
working: Optional[bool] = None
status: BetStatus = BetStatus.ACTIVE
created_roll: int = 0
metadata: dict[str, Any] = field(default_factory=dict)
@property
def is_active(self) -> bool:
"""Report whether the wager remains available for settlement.
Active wagers may also be selected by strategy actions.
"""
return self.status == BetStatus.ACTIVE
@property
def is_persistent(self) -> bool:
"""Return True when a win normally leaves the stake on the layout."""
return self.kind in {
BetKind.PLACE,
BetKind.BUY,
BetKind.LAY,
BetKind.BIG_6,
BetKind.BIG_8,
BetKind.HARDWAY,
}
@dataclass(frozen=True)
class BetSnapshot:
"""Immutable copy used to make resolution independent of loop order."""
bet_id: int
kind: BetKind
amount: Money
number: Optional[int]
parent_id: Optional[int]
hop_pair: Optional[tuple[int, int]]
working: Optional[bool]
status: BetStatus
@classmethod
def from_bet(cls, bet: Bet) -> "BetSnapshot":
"""Create an immutable settlement snapshot from a mutable wager."""
return cls(
bet_id=bet.bet_id,
kind=bet.kind,
amount=bet.amount,
number=bet.number,
parent_id=bet.parent_id,
hop_pair=bet.hop_pair,
working=bet.working,
status=bet.status,
)
@dataclass(frozen=True)
class TableSnapshot:
"""The entire game state as it existed before the dice landed."""
phase: Phase
point: Optional[int]
roll_number: int
hand_number: int
bets: Mapping[int, BetSnapshot]
@dataclass(frozen=True)
class Settlement:
"""A complete, auditable instruction for one wager after one roll."""
bet_id: int
outcome: Outcome
credit: Money = Decimal("0")
profit: Money = Decimal("0")
commission: Money = Decimal("0")
keep_active: bool = True
travel_to: Optional[int] = None
note: str = ""
@dataclass(frozen=True)
class LedgerEntry:
"""One immutable cash movement in chronological order."""
roll_number: int
amount: Money
balance: Money
memo: str
class BankrollLedger:
"""Cash accounting with no implicit or reversible side effects."""
def __init__(self, opening_cash: Money) -> None:
"""Initialize the ledger with nonnegative opening cash."""
if opening_cash < 0:
raise ValueError("Opening cash cannot be negative.")
self.opening_cash = opening_cash
self.cash = opening_cash
self.entries: list[LedgerEntry] = []
def debit(self, amount: Money, roll_number: int, memo: str) -> None:
"""Reserve cash and append an auditable negative ledger entry."""
if amount < 0:
raise ValueError("A debit amount cannot be negative.")
if amount > self.cash:
raise InsufficientFunds(
f"Need {money_text(amount)} but only "
f"{money_text(self.cash)} is available."
)
self.cash -= amount
self.entries.append(
LedgerEntry(roll_number, -amount, self.cash, memo)
)
def credit(self, amount: Money, roll_number: int, memo: str) -> None:
"""Return cash and append an auditable positive ledger entry."""
if amount < 0:
raise ValueError("A credit amount cannot be negative.")
self.cash += amount
self.entries.append(
LedgerEntry(roll_number, amount, self.cash, memo)
)
@dataclass
class TableModel:
"""The complete mutable model; only CrapsController may mutate it."""
ledger: BankrollLedger
rules: TableRules
point: Optional[int] = None
hand_number: int = 1
roll_number: int = 0
hand_roll_number: int = 0
bets: dict[int, Bet] = field(default_factory=dict)
next_bet_id: int = 1
session_stopped: bool = False
stop_reason: str = ""
@property
def phase(self) -> Phase:
"""Derive the table phase from whether a point is established."""
return Phase.COME_OUT if self.point is None else Phase.POINT_ON
@property
def active_stake(self) -> Money:
"""Return the total stake currently reserved on active wagers."""
return sum(
(bet.amount for bet in self.bets.values() if bet.is_active),
Decimal("0"),
)
@property
def equity(self) -> Money:
"""Return rack cash plus every active wagered stake."""
return self.ledger.cash + self.active_stake
def active_bets(
self,
kind: Optional[BetKind] = None,
number: Optional[int] = None,
parent_id: Optional[int] = None,
) -> list[Bet]:
"""Filter active wagers by kind, number, and parent contract."""
result = [bet for bet in self.bets.values() if bet.is_active]
if kind is not None:
result = [bet for bet in result if bet.kind == kind]
if number is not None:
result = [bet for bet in result if bet.number == number]
if parent_id is not None:
result = [bet for bet in result if bet.parent_id == parent_id]
return result
def snapshot(self) -> TableSnapshot:
"""Freeze the pre-roll table state used by the settlement engine."""
return TableSnapshot(
phase=self.phase,
point=self.point,
roll_number=self.roll_number,
hand_number=self.hand_number,
bets={
bet_id: BetSnapshot.from_bet(bet)
for bet_id, bet in self.bets.items()
if bet.is_active
},
)
@dataclass(frozen=True)
class RollEvent:
"""The public record produced by a single controller roll."""
roll: DiceRoll
phase_before: Phase
point_before: Optional[int]
phase_after: Phase
point_after: Optional[int]
settlements: tuple[Settlement, ...]
point_established: bool = False
point_made: bool = False
seven_out: bool = False
@dataclass(frozen=True)
class SessionResult:
"""A compact result suitable for reports and Monte Carlo aggregation."""
opening_cash: Money
closing_cash: Money
closing_equity: Money
rolls: int
hands: int
target_reached: bool
stop_reason: str
@property
def net(self) -> Money:
"""Return the session gain or loss measured by closing equity."""
return self.closing_equity - self.opening_cash
# ---------------------------------------------------------------------------
# MODEL: PAYOUT MATH AND PURE SETTLEMENT RULES
# ---------------------------------------------------------------------------
class PayoutMath:
"""Central home for payout ratios, splits, and commission arithmetic."""
PLACE_PROFIT = {
4: Decimal("1.8"),
5: Decimal("1.4"),
6: (Decimal("7"), Decimal("6")),
8: (Decimal("7"), Decimal("6")),
9: Decimal("1.4"),
10: Decimal("1.8"),
}
TRUE_WIN_PROFIT = {
4: Decimal("2"),
5: Decimal("1.5"),
6: Decimal("1.2"),
8: Decimal("1.2"),
9: Decimal("1.5"),
10: Decimal("2"),
}
TRUE_LAY_PROFIT = {
4: Decimal("0.5"),
5: (Decimal("2"), Decimal("3")),
6: (Decimal("5"), Decimal("6")),
8: (Decimal("5"), Decimal("6")),
9: (Decimal("2"), Decimal("3")),
10: Decimal("0.5"),
}
HARDWAY_PROFIT = {
4: Decimal("7"),
6: Decimal("9"),
8: Decimal("9"),
10: Decimal("7"),
}
PROPOSITION_PROFIT = {
BetKind.ANY_SEVEN: Decimal("4"),
BetKind.ANY_CRAPS: Decimal("7"),
BetKind.ACES: Decimal("30"),
BetKind.ACE_DEUCE: Decimal("15"),
BetKind.YO: Decimal("15"),
BetKind.BOXCARS: Decimal("30"),
}
@staticmethod
def gross_profit(
amount: Money,
ratio: Money | tuple[Money, Money],
rules: TableRules,
) -> Money:
"""Calculate and round gross profit under the table chip policy."""
if isinstance(ratio, tuple):
numerator, denominator = ratio
return rules.round_money(amount * numerator / denominator)
return rules.round_money(amount * ratio)
@staticmethod
def vig(
amount: Money,
gross_win: Money,
rate: Money,
basis: str,
rules: TableRules,
) -> Money:
"""Calculate commission from the configured basis and rate.
Apply the table's chip-rounding policy before returning the result.
"""
base = amount if basis == "wager" else gross_win
return rules.round_money(base * rate)
class BetResolver:
"""Pure rules engine: snapshot plus roll in, settlement instruction out."""
@classmethod
def resolve_all(
cls,
snapshot: TableSnapshot,
roll: DiceRoll,
rules: TableRules,
) -> list[Settlement]:
"""Resolve every active wager against the same pre-roll snapshot.
Each settlement is calculated independently from loop order.
"""
return [
cls.resolve(bet, snapshot, roll, rules)
for bet in snapshot.bets.values()
]
@classmethod
def resolve(
cls,
bet: BetSnapshot,
snapshot: TableSnapshot,
roll: DiceRoll,
rules: TableRules,
) -> Settlement:
"""Dispatch a wager snapshot to its wager-specific settlement rule."""
dispatch = {
BetKind.PASS_LINE: cls._pass_line,
BetKind.DONT_PASS: cls._dont_pass,
BetKind.COME: cls._come,
BetKind.DONT_COME: cls._dont_come,
BetKind.TAKE_ODDS: cls._take_odds,
BetKind.LAY_ODDS: cls._lay_odds,
BetKind.PLACE: cls._place,
BetKind.BUY: cls._buy,
BetKind.LAY: cls._lay,
BetKind.FIELD: cls._field,
BetKind.BIG_6: cls._big_6,
BetKind.BIG_8: cls._big_8,
BetKind.HARDWAY: cls._hardway,
BetKind.ANY_SEVEN: cls._proposition,
BetKind.ANY_CRAPS: cls._proposition,
BetKind.ACES: cls._proposition,
BetKind.ACE_DEUCE: cls._proposition,
BetKind.YO: cls._proposition,
BetKind.BOXCARS: cls._proposition,
BetKind.HORN: cls._horn,
BetKind.C_AND_E: cls._c_and_e,
BetKind.WORLD: cls._world,
BetKind.HOP: cls._hop,
}
return dispatch[bet.kind](bet, snapshot, roll, rules)
@staticmethod
def _no_action(bet: BetSnapshot, note: str = "") -> Settlement:
"""Create a settlement that leaves the wager unchanged."""
return Settlement(bet.bet_id, Outcome.NO_ACTION, note=note)
@staticmethod
def _loss(bet: BetSnapshot, note: str = "") -> Settlement:
"""Create a losing settlement that removes the wagered stake."""
return Settlement(
bet.bet_id,
Outcome.LOSS,
keep_active=False,
note=note,
)
@staticmethod
def _push(bet: BetSnapshot, note: str = "") -> Settlement:
"""Create a push settlement that leaves the contract active."""
return Settlement(bet.bet_id, Outcome.PUSH, note=note)
@staticmethod
def _travel(
bet: BetSnapshot,
number: int,
note: str,
) -> Settlement:
"""Move a Come-family contract from its box to a number."""
return Settlement(
bet.bet_id,
Outcome.TRAVEL,
travel_to=number,
note=note,
)
@staticmethod
def _contract_win(
bet: BetSnapshot,
profit: Money,
note: str,
commission: Money = Decimal("0"),
) -> Settlement:
"""Settle a winning contract or one-roll wager.
Return its stake and net profit, then remove it from the layout.
"""
net_profit = profit - commission
return Settlement(
bet_id=bet.bet_id,
outcome=Outcome.WIN,
credit=bet.amount + net_profit,
profit=net_profit,
commission=commission,
keep_active=False,
note=note,
)
@staticmethod
def _persistent_win(
bet: BetSnapshot,
profit: Money,
note: str,
commission: Money = Decimal("0"),
) -> Settlement:
"""Credit profit while leaving a persistent wager on the layout."""
net_profit = profit - commission
return Settlement(
bet_id=bet.bet_id,
outcome=Outcome.WIN,
credit=net_profit,
profit=net_profit,
commission=commission,
keep_active=True,
note=note,
)
@classmethod
def _pass_line(
cls,
bet: BetSnapshot,
snapshot: TableSnapshot,
roll: DiceRoll,
rules: TableRules,
) -> Settlement:
"""Resolve Pass Line behavior for come-out and point-on phases."""
del rules
if snapshot.phase == Phase.COME_OUT:
if roll.total in NATURALS:
return cls._contract_win(
bet,
bet.amount,
"Pass Line wins on the come-out natural.",
)
if roll.total in CRAPS_NUMBERS:
return cls._loss(
bet,
"Pass Line loses on come-out craps.",
)
return cls._no_action(
bet,
"The Pass Line contract follows the new table point.",
)
if roll.total == snapshot.point:
return cls._contract_win(
bet,
bet.amount,
"Pass Line wins when the table point repeats.",
)
if roll.total == 7:
return cls._loss(bet, "Pass Line loses on the seven-out.")
return cls._no_action(bet)
@classmethod
def _dont_pass(
cls,
bet: BetSnapshot,
snapshot: TableSnapshot,
roll: DiceRoll,
rules: TableRules,
) -> Settlement:
"""Resolve Don’t Pass behavior.
Honor the table's configured bar number on the come-out roll.
"""
if snapshot.phase == Phase.COME_OUT:
if roll.total == rules.dont_bar:
return cls._push(
bet,
"The configured Don't bar number is a standoff.",
)
if roll.total in CRAPS_NUMBERS:
return cls._contract_win(
bet,
bet.amount,
"Don't Pass wins on a non-bar craps total.",
)
if roll.total in NATURALS:
return cls._loss(
bet,
"Don't Pass loses on 7 or 11.",
)
return cls._no_action(
bet,
"The Don't Pass contract follows the table point.",
)
if roll.total == 7:
return cls._contract_win(
bet,
bet.amount,
"Don't Pass wins on the seven-out.",
)
if roll.total == snapshot.point:
return cls._loss(
bet,
"Don't Pass loses when the table point repeats.",
)
return cls._no_action(bet)
@classmethod
def _come(
cls,
bet: BetSnapshot,
snapshot: TableSnapshot,
roll: DiceRoll,
rules: TableRules,
) -> Settlement:
"""Resolve a Come wager in the Come box or on its traveled number."""
del snapshot, rules
if bet.number is None:
if roll.total in NATURALS:
return cls._contract_win(
bet,
bet.amount,
"Come wins on its personal natural.",
)
if roll.total in CRAPS_NUMBERS:
return cls._loss(
bet,
"Come loses on its personal come-out craps.",
)
return cls._travel(
bet,
roll.total,
"Come travels from the Come box to a number.",
)
if roll.total == bet.number:
return cls._contract_win(
bet,
bet.amount,
"Come wins when its number repeats.",
)
if roll.total == 7:
return cls._loss(bet, "Come loses when seven precedes its number.")
return cls._no_action(bet)
@classmethod
def _dont_come(
cls,
bet: BetSnapshot,
snapshot: TableSnapshot,
roll: DiceRoll,
rules: TableRules,
) -> Settlement:
"""Resolve a Don’t Come wager before or after it travels."""
del snapshot
if bet.number is None:
if roll.total == rules.dont_bar:
return cls._push(
bet,
"Don't Come pushes on the configured bar number.",
)
if roll.total in CRAPS_NUMBERS:
return cls._contract_win(
bet,
bet.amount,
"Don't Come wins on a non-bar craps total.",
)
if roll.total in NATURALS:
return cls._loss(bet, "Don't Come loses on 7 or 11.")
return cls._travel(
bet,
roll.total,
"Don't Come travels behind its number.",
)
if roll.total == 7:
return cls._contract_win(
bet,
bet.amount,
"Don't Come wins when seven precedes its number.",
)
if roll.total == bet.number:
return cls._loss(
bet,
"Don't Come loses when its number repeats.",
)
return cls._no_action(bet)
@classmethod
def _take_odds(
cls,
bet: BetSnapshot,
snapshot: TableSnapshot,
roll: DiceRoll,
rules: TableRules,
) -> Settlement:
"""Resolve positive odds attached to Pass Line or Come contracts."""
parent = snapshot.bets.get(bet.parent_id or -1)
if parent is None or bet.number is None:
return Settlement(
bet.bet_id,
Outcome.RETURNED_OFF,
credit=bet.amount,
keep_active=False,
note="Orphaned odds are safely returned.",
)
working = True
if (
snapshot.phase == Phase.COME_OUT
and parent.kind == BetKind.COME
):
working = rules.come_odds_working_on_comeout
parent_resolves = roll.total in (7, bet.number)
if not working:
if parent_resolves:
return Settlement(
bet.bet_id,
Outcome.RETURNED_OFF,
credit=bet.amount,
keep_active=False,
note="Come odds were off and are returned.",
)