“Two bets cost about 13%, the rest 18 to 20%.”
That line came from the design spec for two new Table Ready lessons. It sounds fine. It’s wrong twice.
At six decks, Pair costs 17.68%, so it’s not in that band at all. And in a lesson full of payouts like “25 to 1” and “200 to 1,” the phrase “18 to 20” reads like a payout. A player could fairly read it as odds. My test suite reads it that way too, and it won’t let that sentence ship.
Lesson copy is a claim about the engine. If the engine can compute a number, the copy should have to agree with it, in English and in every translation, on every build. There are two halves to that: computing an exact house edge by counting every deal, and then using Swift Testing to tie the lesson text to those numbers.
Nine Bets on One Machine
Table Ready is my casino table-game trainer, the same app whose felt and roulette wheel got the shader treatment. On a trip to Las Vegas I photographed the help screens and pay tables on an electronic blackjack machine that offers nine side bets: Pair, KK, QQ, JJ, 7’s, Poker 3, 19+, Match and A-2. You place them before the deal. Each one settles on your first two cards and, for some, the dealer’s up card. Only the highest winning line pays.
Standing at the machine, I wanted three answers for each bet. How does it win? What does it pay? Is it worth it?
The answer to the third question is no, for all nine. But how much no is the useful part, and that’s a number the engine should own. Table Ready has a hard rule about this: game rules live in CasinoCore, one engine per game, and the engine owns every payout, edge and frequency. Views don’t compute them. Lessons don’t type them.
The bets themselves are plain value types. A pay table is an ordered list of lines, highest first, each with an outcome and what it pays “to 1”:
public struct MachineSideBetPayLine: Codable, Hashable, Sendable {
public let outcome: MachineSideBetOutcome
public let pays: Int
}
public struct MachineSideBetPayTable: Codable, Hashable, Sendable {
public init(_ bet: MachineSideBet) {
self.bet = bet
lines = Self.lines(for: bet)
}
public let bet: MachineSideBet
public let lines: [MachineSideBetPayLine]
private static func lines(for bet: MachineSideBet) -> [MachineSideBetPayLine] {
let rows: [(MachineSideBetOutcome, Int)] = switch bet {
case .pair:
[(.suitedPair, 25), (.nonSuitedPair, 6)]
case .jacks, .kings, .queens:
[(.diamondPair, 200), (.matchedTwenty, 25), (.anyTwenty, 3), (.oneOfRank, 1)]
case .pokerThree:
[(.straightFlush, 30), (.threeOfAKind, 20), (.straight, 10), (.flush, 5)]
default:
[]
}
return rows.map { row in MachineSideBetPayLine(outcome: row.0, pays: row.1) }
}
}
The real switch covers all nine bets. I trimmed it here. The settler takes a MachineSideBetDeal (first card, second card, dealer up card) and returns the winning line, or nil for a loss. Pair is the simplest one:
public enum MachineSideBetSettler {
public static func outcome(of bet: MachineSideBet, in deal: MachineSideBetDeal) -> MachineSideBetOutcome? {
switch bet {
case .pair:
pair(deal)
default:
nil
}
}
private static func pair(_ deal: MachineSideBetDeal) -> MachineSideBetOutcome? {
guard deal.first.rank == deal.second.rank else {
return nil
}
return deal.first.suit == deal.second.suit ? .suitedPair : .nonSuitedPair
}
}
That’s the whole surface the odds code needs. Give it a deal, get back a line or nothing.
Count Every Deal. Don’t Sample.
The tempting move is Monte Carlo. Deal ten million hands, average the results, call it done. The problem is that a simulated edge comes with error bars. You can’t write #expect(edge == "12.57") against a sample without pinning a seed and hoping nobody changes the shuffle. You can write it against a count.
And the space here is small. Three cards drawn from 52 card types is 52³ = 140,608 triples. A six-deck shoe has 312 physical cards, so there are 312 × 311 × 310 = 30,079,920 ordered deals. But you don’t loop over 30 million deals. You loop over the 140,608 card-type triples and weight each one by how many physical deals look like it.
Ordered matters here. It’s easy to think of this as every two-card-plus-upcard combination, but 7’s loses unless your first card is a 7. A 4 and then a 7 loses. A 7 and then a 4 pays 5 to 1. Order is part of the bet, so the loop counts permutations, not combinations.
public struct MachineSideBetOdds: Hashable, Sendable {
public let bet: MachineSideBet
public let deckCount: Int
public let houseEdge: Double
public let hitRate: Double
public let lineProbabilities: [MachineSideBetOutcome: Double]
public static func compute(_ bet: MachineSideBet, deckCount: Int) -> MachineSideBetOdds {
let decks = max(1, deckCount)
let cards = Rank.allCases.flatMap { rank in Suit.allCases.map { suit in Card(rank, suit) } }
let lines = MachineSideBetPayTable(bet).lines
let pays = Dictionary(uniqueKeysWithValues: lines.map { line in (line.outcome, line.pays) })
var total = 0
var net = 0
var weights = Dictionary(uniqueKeysWithValues: lines.map { line in (line.outcome, 0) })
for first in cards {
for second in cards {
let secondCopies = decks - (second == first ? 1 : 0)
guard secondCopies > 0 else {
continue
}
for dealer in cards {
let dealerCopies = decks - (dealer == first ? 1 : 0) - (dealer == second ? 1 : 0)
guard dealerCopies > 0 else {
continue
}
let weight = decks * secondCopies * dealerCopies
total += weight
let deal = MachineSideBetDeal(first: first, second: second, dealerUpcard: dealer)
if let outcome = MachineSideBetSettler.outcome(of: bet, in: deal), let pay = pays[outcome] {
weights[outcome, default: 0] += weight
net += weight * pay
} else {
net -= weight
}
}
}
}
let denominator = Double(total)
let probabilities = weights.mapValues { weight in Double(weight) / denominator }
return MachineSideBetOdds(
bet: bet,
deckCount: decks,
houseEdge: -Double(net) / denominator,
hitRate: Double(weights.values.reduce(0, +)) / denominator,
lineProbabilities: probabilities
)
}
}
The weight is where drawing without replacement lives. Every card type starts with decks copies. The first card can be any of them. The second card has one fewer copy available if it’s the same card type as the first. The dealer’s card loses one copy for each earlier card it matches. Multiply those together and you get the number of physical deals in the shoe that produce this exact triple. Sum them all and total comes out to 52d × (52d − 1) × (52d − 2), which is the 30,079,920 above for six decks.
The guards matter at one deck. There’s only one king of diamonds, so a deal with two of them has zero copies and gets skipped. That’s how “a suited pair needs two decks or more” falls out of the loop without a special case.
Everything stays in Int until the last three lines. A win adds weight * pay, a loss subtracts weight, and none of these bets push. So net is the exact total return, in betting units, across every deal in the shoe. The house edge is the negative of the expected net return per unit bet, -net / total, and that one division is the only place floating point shows up. Overflow isn’t a concern either. Eight decks give 71,472,960 deals, and the top line pays 200, so net stays nowhere near Int.max.
The weights dictionary starts with every pay line at zero. A later commit added that, after I noticed a line that can never hit (that same one-deck suited pair) went missing from lineProbabilities instead of reporting 0. Missing and zero mean different things to anyone reading the result, so every line is always there.
Each bet is about 140,000 calls to the settler. That’s fast enough for a debug test, but nothing in the app calls compute yet. When something does, it’ll run off the main actor, the way the app’s other exact enumerations already do through @concurrent functions. MachineSideBetOdds is a Sendable value type, so handing it back across that boundary costs nothing.
Check One by Hand
Before I trust a loop like this, I check one bet I can do on paper. Pair is the easy one because it only looks at your two cards. The dealer’s card has no effect on the result.
At six decks, after your first card there are 311 cards left. Five are identical to it (same rank, same suit). Eighteen are the same rank in other suits. The other 288 lose.
Expected return per unit = (25 × 5 + 6 × 18 − 288) / 311 = −55/311 ≈ −0.1768
That’s a house edge of 17.68%, and a hit rate of 23/311, or 7.40%. At eight decks it’s (25 × 7 + 6 × 24 − 384) / 415 = −65/415, or 15.66%. At one deck there’s no identical card to draw, so it’s (6 × 3 − 48) / 51 = −30/51, or 58.82%.
The engine gives all four of those numbers. When the closed form and the loop agree on the easy bet, I trust the loop a lot more on the hard ones.
Pin the Engine First
The figures didn’t start in Swift. During design I ran the same exact enumeration in a scratch script, written separately, and those results became the acceptance table. The engine has to reproduce them to two decimals:
@Suite("Machine side bet odds")
struct MachineSideBetOddsTests {
struct Figure: Sendable, CustomTestStringConvertible {
let bet: MachineSideBet
let hit: String
let edgeSixDecks: String
let edgeEightDecks: String
var testDescription: String {
bet.rawValue
}
}
static let figures = [
Figure(bet: .nineteenPlus, hit: "23.75", edgeSixDecks: "12.57", edgeEightDecks: "12.54"),
Figure(bet: .pokerThree, hit: "9.68", edgeSixDecks: "13.39", edgeEightDecks: "12.89"),
Figure(bet: .pair, hit: "7.40", edgeSixDecks: "17.68", edgeEightDecks: "15.66"),
Figure(bet: .aceToTwo, hit: "26.81", edgeSixDecks: "19.20", edgeEightDecks: "18.66"),
Figure(bet: .sevens, hit: "7.69", edgeSixDecks: "19.35", edgeEightDecks: "18.71"),
Figure(bet: .match, hit: "14.27", edgeSixDecks: "19.91", edgeEightDecks: "18.19"),
Figure(bet: .kings, hit: "21.27", edgeSixDecks: "19.99", edgeEightDecks: "19.14")
]
@Test(arguments: figures)
func theFiguresMatchTheSpec(figure: Figure) {
let six = MachineSideBetOdds.compute(figure.bet, deckCount: 6)
let eight = MachineSideBetOdds.compute(figure.bet, deckCount: 8)
#expect(String(format: "%.2f", six.hitRate * 100) == figure.hit)
#expect(String(format: "%.2f", six.houseEdge * 100) == figure.edgeSixDecks)
#expect(String(format: "%.2f", eight.houseEdge * 100) == figure.edgeEightDecks)
}
}
Comparing formatted strings is on purpose. Two decimals is the precision the lessons quote, so that’s the precision the contract is about. It also means I don’t have to pick a float tolerance. CustomTestStringConvertible makes each case show up in the test navigator as pair or nineteenPlus instead of a dump of the struct.
KK, QQ and JJ are one bet in three ranks, so they should cost exactly the same. Here exact == on Double is safe, because both sides come from identical integer counts divided by the same denominator:
@Test
func theRoyalBetsAgree() {
let kings = MachineSideBetOdds.compute(.kings, deckCount: 6)
let queens = MachineSideBetOdds.compute(.queens, deckCount: 6)
let jacks = MachineSideBetOdds.compute(.jacks, deckCount: 6)
#expect(kings.houseEdge == queens.houseEdge)
#expect(kings.houseEdge == jacks.houseEdge)
#expect(kings.hitRate == queens.hitRate)
#expect(kings.hitRate == jacks.hitRate)
}
If this ever fails, the settler treats one rank differently from the others, and that’s a real bug, not a rounding problem.
The structural checks use parameterized arguments. Passing two collections gives you every combination, so this one runs all nine bets at one deck and at six decks, eighteen cases from four lines:
@Test(arguments: MachineSideBet.allCases, [1, 6])
func everyPayTableLineHasAProbability(bet: MachineSideBet, deckCount: Int) {
let odds = MachineSideBetOdds.compute(bet, deckCount: deckCount)
let keys = Set(odds.lineProbabilities.keys)
let outcomes = Set(MachineSideBetPayTable(bet).lines.map { line in line.outcome })
#expect(keys == outcomes)
}
A companion test checks that the line probabilities add up to the hit rate, within 1e-12 because that sum really is floating point. Another pins the one-deck case: suited pair, diamond pair, matched twenty and every suited-sevens line must have probability exactly 0, and Pair’s edge must be 58.82%. That’s the hand calculation from earlier, now written down where it can’t drift.
Make the Copy Answer to the Engine
The lessons are JSON files with a title, a summary, sections and a quiz. Before any check runs, the suite flattens a lesson into the text a player actually reads as true:
private static func checkedText(of lesson: Lesson) -> String {
let sections = lesson.sections.map { "\($0.heading) \($0.body)" }
let quiz = lesson.quiz.map { question in
[question.prompt, question.choices[question.answerIndex], question.explanation].joined(separator: " ")
}
return ([lesson.title, lesson.summary] + sections + quiz).joined(separator: " ")
}
Notice what’s missing. The wrong quiz choices are left out on purpose. A distractor like “About twice as much” is supposed to be wrong. Checking it against the engine would either fail for no reason or push you into writing weaker distractors.
From there the suite gets stricter in layers, and each layer exists because the one before it had a gap.
Every percent is a real figure
The first check pulls every percent out of the text and requires it to be something the engine computed:
private static func percents(in text: String) -> [String] {
text.matches(of: #/(\d+(?:\.\d+)?)%/#).map { String($0.output.1) }
}
private static func percentText(_ value: Double) -> String {
var text = String(format: "%.2f", value * 100)
while text.contains("."), text.hasSuffix("0") || text.hasSuffix(".") {
text.removeLast()
}
return text
}
@Test
func everyQuotedPercentIsASourcedFigure() throws {
for lesson in try LessonCatalog.load(for: .blackjack) {
let known = Self.knownPercents(for: lesson)
for percent in Self.percents(in: Self.checkedText(of: lesson)) {
#expect(known.contains(percent), "\(lesson.id) quotes \(percent)%")
}
}
}
percentText trims trailing zeros because the lessons do. The copy says “19.2%” and “7.4%”, not “19.20%”. One formatter in the tests means the copy’s number style is part of the contract too.
For the two machine lessons, the known set is small on purpose: every bet’s edge and hit rate at six and eight decks, plus one yardstick, the 1.39% it costs to move from a 3 to 2 table to a 6 to 5 table. That comes from a sourced constant, BlackjackVariantFacts.sixToFiveCost. Nothing else gets in. No main-game edge, no rounded “about 20%.”
A sibling test does the same for every “N to M” in the text, against the nine pay tables. That’s the test that rejects “18 to 20%.”
Each section quotes only its own numbers
Set membership has an obvious hole. Swap the Match and A-2 edges in the copy and every percent is still a real figure. So each bet’s section has to quote exactly its own edge and hit rate, and exactly its own pay lines:
@Test
func eachMachineBetSectionQuotesOnlyItsOwnFigures() throws {
let lessons = try LessonCatalog.load(for: .blackjack)
let sections = lessons.filter { lesson in Self.machineLessonBets.keys.contains(lesson.id) }
.flatMap { lesson in lesson.sections }
for (heading, bet) in Self.machineSectionBets {
let section = try #require(sections.first { section in section.heading == heading })
let odds = try Self.sixDeckOdds(bet)
let percents = Set(Self.percents(in: section.body))
let expectedPercents: Set = [Self.percentText(odds.houseEdge), Self.percentText(odds.hitRate)]
#expect(percents == expectedPercents, "\(heading) quotes \(percents.sorted())")
let ratios = Set(Self.ratios(in: section.body))
let expectedRatios = Set(MachineSideBetPayTable(bet).lines.map { line in "\(line.pays) to 1" })
#expect(ratios == expectedRatios, "\(heading) quotes \(ratios.sorted())")
}
}
The ratio side catches a dropped line as well as a wrong one. If the 19+ section forgets to mention that a 19 pays 1 to 1, the sets don’t match.
The ranking comes from the engine
This is the part that matters most to a player. The second lesson ends with all nine bets, cheapest first. The order is not typed by hand. The test sorts the engine’s six-deck edges and requires the ranking section to quote them in that order:
@Test
func theRankingListsEveryEdgeCheapestFirst() throws {
let lessons = try LessonCatalog.load(for: .blackjack)
let lesson = try #require(lessons.first { lesson in lesson.id == "machine-side-bets-three-card" })
let ranking = try #require(lesson.sections.last)
let sixDecks = Self.machineOdds.filter { odds in odds.deckCount == 6 }
let cheapestFirst = sixDecks.sorted { lhs, rhs in lhs.houseEdge < rhs.houseEdge }
let expected = cheapestFirst.map { odds in Self.percentText(odds.houseEdge) }
.reduce(into: [String]()) { edges, edge in
if edges.last != edge {
edges.append(edge)
}
}
#expect(sixDecks.count == MachineSideBet.allCases.count)
#expect(expected.count == 7)
let edges = Set(expected)
let quoted = Self.percents(in: ranking.body).filter { percent in edges.contains(percent) }
#expect(quoted == expected)
}
Nine bets, seven distinct edges, because KK, QQ and JJ tie at 19.99%. The reduce drops the duplicates, and the copy names those three together. Filtering the quoted percents down to the edge set drops the 1.39% yardstick, which sits in the same paragraph.
Why derive the order instead of just reviewing it once? Because the order depends on the deck count. At six decks it’s 19+, Poker 3, Pair, A-2, 7’s, Match, then KK, QQ and JJ. At eight decks Pair drops to 15.66% and Match drops to 18.19%, which puts Match ahead of A-2 (18.66%) and 7’s (18.71%). A ranking typed from one table is right for one shoe. The lessons quote six decks because it’s the app’s default and the machine doesn’t post its deck count, and the lesson says so. If that default ever changes, this test tells me which sentences have to move.
A correct list of edges with the names shuffled would still pass that test, so one more pins each name to its number. The first percent after “Match” has to be Match’s edge:
@Test
func theRankingGivesEachBetItsOwnEdge() throws {
let lessons = try LessonCatalog.load(for: .blackjack)
let lesson = try #require(lessons.first { lesson in lesson.id == "machine-side-bets-three-card" })
let ranking = try #require(lesson.sections.last).body
for (name, bet) in Self.machineBetsByName {
let nameRange = try #require(ranking.range(of: name), "the ranking does not name \(name)")
let following = String(ranking[nameRange.upperBound...])
let quoted = Self.percents(in: following).first
let edge = try Self.percentText(Self.sixDeckOdds(bet).houseEdge)
#expect(quoted == edge, "the ranking gives \(name) \(quoted ?? "no edge"), not \(edge)")
}
}
The last claim in that paragraph is a comparison: even the cheapest bet, 19+, “costs about nine times as much” as the 6 to 5 penalty. That’s a number too, just spelled out. So the test computes it, 12.57 divided by 1.39 and rounded, requires it to be 9, and requires the copy to say “about nine times.” If an engine change moves 19+ to 11%, the multiple becomes 8 and the sentence fails, even though no digit in it changed.
Copy That Reads Two Ways
Back to “18 to 20%.”
I caught that one while planning, before a word of lesson text existed. Laying out which tests the lessons would need, I could see the ratio test was going to read “18 to 20” as a payout. So my plan for the feature picked up a writing rule: never write a range or a count as “N to M.” Write ranges as “between 18% and 20%” instead.
That rewrite would have failed too. “Between 18% and 20%” isn’t ambiguous anymore, but the percent test only accepts engine figures, and 18% and 20% aren’t engine figures. Nothing computed them. The plan’s own fix would have tripped the sibling test, and Pair still sits outside that range anyway.
So the lessons don’t quote ranges at all. Every number gets named. The ranking paragraph now reads:
Here are all nine at six decks, cheapest first: 19+ 12.57%, Poker 3 13.39%, Pair 17.68%, A-2 19.2%, 7’s 19.35%, Match 19.91%, and KK, QQ and JJ 19.99% each.
It’s less elegant than “the rest 18 to 20%.” It’s also true, and every number in it is checked.
The same pressure showed up in the rules text. The machine’s help screen doesn’t say how an ace and a 9 count on KK, so the engine treats them as “any 20” and the lesson says that plainly: “The help screen does not say how an ace and a 9 count, so here they count as any 20.” When the tests force the copy to be specific about numbers, the vague spots in the prose get much easier to see.
Seven Translations, Same Numbers
Table Ready ships in English plus seven translations: Spanish, Traditional Chinese, French, Japanese, Korean, German and Brazilian Portuguese. The lessons don’t go through the String Catalog. Each one has a JSON twin with the same filename in every *.lproj folder.
One app-wide decision makes these numbers testable across languages: figures are casino style, en_US, everywhere. The German ranking reads “19+ 12.57%, Poker 3 13.39%, Pair 17.68%,” not “12,57 %.” Bet names stay in English too, because that’s what’s printed on the machine. So a German player and an English player are looking at the same digits and the same names, and the test can compare them directly:
@Test(arguments: BlackjackLessonCatalogTests.translatedLanguages)
func theMachineLessonTwinsKeepEveryFigureAndName(language: String) throws {
let english = LessonCatalog.lessonURLs(for: .blackjack, in: .main, localization: nil)
let translated = LessonCatalog.lessonURLs(for: .blackjack, in: .main, localization: language)
for id in Self.machineLessonBets.keys.sorted() {
let name = "lesson-\(id).json"
let source = try #require(english[name], "\(name) has no English file")
let twinURL = try #require(translated[name], "\(language) has no twin of \(name)")
let englishText = try Self.checkedText(of: Self.decode(source))
let twinText = try Self.checkedText(of: Self.decode(twinURL))
let twinCounts = Self.digitRunCounts(in: twinText)
for (run, count) in Self.digitRunCounts(in: englishText) {
let twinCount = twinCounts[run, default: 0]
#expect(twinCount >= count, "\(language) \(id) has \(run) \(twinCount) times, English \(count)")
}
for bet in Self.machineBetNames where englishText.contains(bet) {
#expect(twinText.contains(bet), "\(language) \(id) does not name \(bet)")
}
}
}
The English lesson is already pinned to the engine, so a twin only has to match the English. Every digit run in the English text (“12.57”, “200”, “6”) has to show up in the twin at least as many times. Counting digit runs instead of parsing ratios matters here, because “6 to 5” becomes “6 zu 5” in German and something else again in Japanese and Korean. The digits survive every translation, even when the words around them don’t.
There’s one Swift 6 detail in how the suite is declared. The app target defaults to main-actor isolation, so the suite is @MainActor. The arguments: expression is read outside that isolation, so the two language lists used as arguments are declared nonisolated:
@Suite("Blackjack lessons")
@MainActor
struct BlackjackLessonCatalogTests {
nonisolated static let chartLanguages = ["en", "es", "zh-Hant", "fr", "ja", "ko", "de", "pt-BR"]
nonisolated static let translatedLanguages = chartLanguages.filter { language in language != "en" }
}
Everything else in the suite can stay main-actor isolated. Only what feeds arguments: has to come out.
What the Tests Can’t See
This setup proves the copy agrees with the engine. It doesn’t prove the engine agrees with the machine. The ace-and-9 reading on KK and the ace counting as 1 or 11 on 19+ are my assumptions, because the help screens don’t say. The lessons state both. If the machine settles them differently, the engine is wrong, the lesson is wrong in exactly the same way, and every test passes. Pay tables also differ from machine to machine, which is why the first lesson opens by telling you to read the help screen on yours.
Spelled-out numbers slip past the twin check. English “about nine times” is guarded, but the German “etwa neunmal” has no digits for the counter to find. A translator who wrote “etwa zehnmal” would pass. That one is still a reviewer’s job.
The >= in the digit-run comparison is loose on purpose, since some languages repeat a figure where English doesn’t. It also means a twin can add a number the English never had.
And the eight-deck order isn’t pinned in any copy, because no lesson quotes a ranking at eight decks. The tests only cover claims the lessons actually make. That’s the right scope. It just means the coverage stops where the copy does.
The Lesson Doesn’t Know the Numbers Anymore
None of this is specific to casino games. If your app quotes a price, a rate, a limit or a ranking in its copy, that sentence is a claim about some piece of code. Somewhere a test can hold the two together.
The lessons in Table Ready don’t know the numbers anymore. They just have to agree with something that does. And when they stop agreeing, I hear about it from a test run, not from a player standing at a machine in Las Vegas.
Thanks for reading.