Compare commits

...

10 Commits

37 changed files with 7033 additions and 6457 deletions

View File

@ -159,11 +159,9 @@ final class GameState {
/// Handles data received from iCloud (e.g., after fresh install or from another device).
private func handleCloudDataReceived(_ cloudData: BaccaratGameData) {
print("GameState: Received cloud data with \(cloudData.roundsPlayed) rounds")
// Only update if cloud has more progress than current state
guard cloudData.roundsPlayed > roundHistory.count else {
print("GameState: Local data is newer, ignoring cloud data")
return
}
@ -181,8 +179,6 @@ final class GameState {
bankerPair: saved.bankerPair
)
}
print("GameState: Restored from cloud - \(cloudData.roundsPlayed) rounds, balance: \(cloudData.balance)")
}
// MARK: - Persistence
@ -208,8 +204,6 @@ final class GameState {
bankerPair: saved.bankerPair
)
}
print("GameState: Restored \(savedData.roundsPlayed) rounds, balance: \(savedData.balance)")
}
/// Saves current game state to iCloud/local storage.

View File

@ -295,8 +295,6 @@ final class GameSettings {
if let volume = iCloudStore.object(forKey: Keys.soundVolume) as? Double {
self.soundVolume = Float(volume)
}
print("GameSettings: Loaded from iCloud")
}
/// Saves settings to UserDefaults and iCloud.
@ -327,7 +325,6 @@ final class GameSettings {
iCloudStore.set(hapticsEnabled, forKey: Keys.hapticsEnabled)
iCloudStore.set(Double(soundVolume), forKey: Keys.soundVolume)
iCloudStore.synchronize()
print("GameSettings: Saved to iCloud")
}
}

View File

@ -1532,6 +1532,7 @@
},
"Game Over" : {
"comment" : "The title of the game over screen.",
"extractionState" : "stale",
"localizations" : {
"en" : {
"stringUnit" : {
@ -1555,6 +1556,7 @@
},
"GAME OVER" : {
"comment" : "The title of the game over screen.",
"extractionState" : "stale",
"localizations" : {
"en" : {
"stringUnit" : {
@ -2900,6 +2902,7 @@
},
"Rounds Played" : {
"comment" : "A label displayed next to the number of rounds played in the game over screen.",
"extractionState" : "stale",
"localizations" : {
"en" : {
"stringUnit" : {

View File

@ -145,18 +145,19 @@ struct GameTableView: View {
// Main content area with optional sidebar
HStack(spacing: 0) {
// Left side: Road map history grid
if settings.showHistory && !state.roundHistory.isEmpty {
if settings.showHistory {
VStack(alignment: .leading, spacing: Design.Spacing.xSmall) {
// Header with reading instructions
VStack(alignment: .leading, spacing: 2) {
VStack(alignment: .leading, spacing: 5) {
Text("HISTORY")
.font(.system(size: Design.BaseFontSize.small, weight: .bold, design: .rounded))
.font(.system(size: Design.BaseFontSize.xLarge, weight: .bold, design: .rounded))
.foregroundStyle(.white.opacity(Design.Opacity.strong))
Text("↓ then →")
.font(.system(size: Design.BaseFontSize.xSmall, design: .rounded))
.font(.system(size: Design.BaseFontSize.large, design: .rounded))
.foregroundStyle(.white.opacity(Design.Opacity.medium))
}
.padding(.leading, Design.Spacing.small)
.padding(.horizontal, Design.Spacing.small)
.padding(.top, Design.Spacing.small)
@ -285,7 +286,7 @@ struct GameTableView: View {
.debugBorder(showDebugBorders, color: .yellow, label: "Spacer2")
// Road map history
if settings.showHistory && !state.roundHistory.isEmpty {
if settings.showHistory {
RoadMapView(results: state.recentResults)
.frame(maxWidth: isLargeScreen ? maxContentWidth : .infinity)
.padding(.horizontal, Design.Spacing.medium)

View File

@ -1,189 +0,0 @@
//
// GameOverView.swift
// Baccarat
//
// Game over screen shown when player runs out of money.
//
import SwiftUI
import CasinoKit
/// Game over screen shown when player runs out of money.
struct GameOverView: View {
let roundsPlayed: Int
let onPlayAgain: () -> Void
@State private var showContent = false
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
/// Maximum width for the modal card on iPad
private var maxModalWidth: CGFloat {
horizontalSizeClass == .regular ? CasinoDesign.Size.maxModalWidth : .infinity
}
// MARK: - Scaled Font Sizes (Dynamic Type)
@ScaledMetric(relativeTo: .largeTitle) private var iconSize: CGFloat = Design.BaseFontSize.display
@ScaledMetric(relativeTo: .largeTitle) private var titleFontSize: CGFloat = Design.BaseFontSize.largeTitle
@ScaledMetric(relativeTo: .body) private var messageFontSize: CGFloat = Design.BaseFontSize.xLarge
@ScaledMetric(relativeTo: .body) private var statsFontSize: CGFloat = 17
@ScaledMetric(relativeTo: .headline) private var buttonFontSize: CGFloat = Design.BaseFontSize.xLarge
// MARK: - Layout Constants
private let modalCornerRadius = Design.CornerRadius.xxxLarge
private let statsCornerRadius = Design.CornerRadius.large
private let cardPadding = Design.Spacing.xxxLarge
private let contentSpacing: CGFloat = 28
private let buttonHorizontalPadding: CGFloat = 48
private let buttonVerticalPadding: CGFloat = 18
// MARK: - Body
var body: some View {
ZStack {
// Solid dark backdrop - fully opaque
Color.black
.ignoresSafeArea()
// Modal card
modalContent
}
.onAppear {
withAnimation(.spring(duration: Design.Animation.springDuration, bounce: Design.Animation.springBounce)) {
showContent = true
}
}
.accessibilityElement(children: .contain)
.accessibilityLabel(String(localized: "Game Over"))
.accessibilityAddTraits(.isModal)
}
// MARK: - Private Views
private var modalContent: some View {
VStack(spacing: contentSpacing) {
// Broke icon
Image(systemName: "creditcard.trianglebadge.exclamationmark")
.font(.system(size: iconSize))
.foregroundStyle(.red)
.symbolEffect(.pulse, options: .repeating)
// Title
Text("GAME OVER")
.font(.system(size: titleFontSize, weight: .black, design: .rounded))
.foregroundStyle(.white)
// Message
Text("You've run out of chips!")
.font(.system(size: messageFontSize, weight: .medium))
.foregroundStyle(.white.opacity(Design.Opacity.strong))
// Stats card
statsCard
// Play Again button
playAgainButton
}
.padding(cardPadding)
.background(modalBackground)
.shadow(color: .red.opacity(Design.Opacity.hint), radius: Design.Shadow.radiusXXLarge)
.frame(maxWidth: maxModalWidth)
.padding(.horizontal, Design.Spacing.xxLarge)
.scaleEffect(showContent ? Design.Scale.normal : Design.Scale.slightShrink)
.opacity(showContent ? 1.0 : 0)
}
private var statsCard: some View {
VStack(spacing: Design.Spacing.medium) {
HStack {
Text("Rounds Played")
.foregroundStyle(.white.opacity(Design.Opacity.medium))
Spacer()
Text("\(roundsPlayed)")
.bold()
.foregroundStyle(.white)
}
}
.font(.system(size: statsFontSize))
.padding()
.background(
RoundedRectangle(cornerRadius: statsCornerRadius)
.fill(Color.white.opacity(Design.Opacity.subtle))
.overlay(
RoundedRectangle(cornerRadius: statsCornerRadius)
.strokeBorder(Color.white.opacity(Design.Opacity.subtle), lineWidth: Design.LineWidth.thin)
)
)
.padding(.horizontal, Design.Spacing.xLarge)
}
private var playAgainButton: some View {
Button {
onPlayAgain()
} label: {
HStack(spacing: Design.Spacing.small) {
Image(systemName: "arrow.counterclockwise")
Text("Play Again")
}
.font(.system(size: buttonFontSize, weight: .bold))
.foregroundStyle(.black)
.padding(.horizontal, buttonHorizontalPadding)
.padding(.vertical, buttonVerticalPadding)
.background(
Capsule()
.fill(
LinearGradient(
colors: [Color.CasinoButton.goldLight, Color.CasinoButton.goldDark],
startPoint: .top,
endPoint: .bottom
)
)
)
.shadow(color: .yellow.opacity(Design.Opacity.light), radius: Design.Shadow.radiusXLarge)
}
.padding(.top, Design.Spacing.medium)
}
private var modalBackground: some View {
RoundedRectangle(cornerRadius: modalCornerRadius)
.fill(
LinearGradient(
colors: [Color.CasinoModal.backgroundLight, Color.CasinoModal.backgroundDark],
startPoint: .top,
endPoint: .bottom
)
)
.overlay(
RoundedRectangle(cornerRadius: modalCornerRadius)
.strokeBorder(
LinearGradient(
colors: [
Color.red.opacity(Design.Opacity.medium),
Color.red.opacity(Design.Opacity.hint)
],
startPoint: .topLeading,
endPoint: .bottomTrailing
),
lineWidth: Design.LineWidth.medium
)
)
}
}
// MARK: - Previews
#Preview("Game Over") {
GameOverView(
roundsPlayed: 42,
onPlayAgain: {}
)
}
#Preview("Few Rounds") {
GameOverView(
roundsPlayed: 3,
onPlayAgain: {}
)
}

View File

@ -111,10 +111,10 @@ struct CardsDisplayArea: View {
GeometryReader { geometry in
Color.clear
.onAppear {
containerWidth = geometry.size.width
containerWidth = geometry.size.width * 0.95
}
.onChange(of: geometry.size.width) { _, newWidth in
containerWidth = newWidth
containerWidth = newWidth * 0.95
}
}
)

View File

@ -82,6 +82,7 @@ struct RoadMapGridView: View {
}
.padding(spacing)
}
.padding(.leading, spacing)
}
}
}

View File

@ -411,91 +411,91 @@ final class BlackjackEngine {
// 16 vs 10: Stand when TC 0 (basic strategy says Hit)
if playerValue == 16 && !isSoft && dealerValue == 10 {
if tc >= 0 {
return String(localized: "Stand instead of Hit (TC \(tcDisplay), deck is neutral/rich)")
return String(localized: "Stand, not Hit (TC \(tcDisplay))")
}
}
// 15 vs 10: Stand when TC +4 (basic strategy says Hit/Surrender)
if playerValue == 15 && !isSoft && dealerValue == 10 {
if tc >= 4 {
return String(localized: "Stand instead of Hit (TC \(tcDisplay), deck is very rich)")
return String(localized: "Stand, not Hit (TC \(tcDisplay))")
}
}
// 12 vs 2: Stand when TC +3 (basic strategy says Hit)
if playerValue == 12 && !isSoft && dealerValue == 2 {
if tc >= 3 {
return String(localized: "Stand instead of Hit (TC \(tcDisplay), dealer likely to bust)")
return String(localized: "Stand, not Hit (TC \(tcDisplay))")
}
}
// 12 vs 3: Stand when TC +2 (basic strategy says Hit)
if playerValue == 12 && !isSoft && dealerValue == 3 {
if tc >= 2 {
return String(localized: "Stand instead of Hit (TC \(tcDisplay), dealer likely to bust)")
return String(localized: "Stand, not Hit (TC \(tcDisplay))")
}
}
// 12 vs 4: Hit when TC < 0 (basic strategy says Stand)
if playerValue == 12 && !isSoft && dealerValue == 4 {
if tc < 0 {
return String(localized: "Hit instead of Stand (TC \(tcDisplay), deck is poor)")
return String(localized: "Hit, not Stand (TC \(tcDisplay))")
}
}
// 13 vs 2: Hit when TC < -1 (basic strategy says Stand)
if playerValue == 13 && !isSoft && dealerValue == 2 {
if tc < -1 {
return String(localized: "Hit instead of Stand (TC \(tcDisplay), deck is very poor)")
return String(localized: "Hit, not Stand (TC \(tcDisplay))")
}
}
// 16 vs 9: Stand when TC +5 (basic strategy says Hit)
if playerValue == 16 && !isSoft && dealerValue == 9 {
if tc >= 5 {
return String(localized: "Stand instead of Hit (TC \(tcDisplay), deck is extremely rich)")
return String(localized: "Stand, not Hit (TC \(tcDisplay))")
}
}
// 10 vs 10: Double when TC +4 (basic strategy says Hit)
if playerValue == 10 && !isSoft && playerHand.cards.count == 2 && dealerValue == 10 {
if tc >= 4 {
return String(localized: "Double instead of Hit (TC \(tcDisplay), high cards favor you)")
return String(localized: "Double, not Hit (TC \(tcDisplay))")
}
}
// 10 vs Ace: Double when TC +4 (basic strategy says Hit)
if playerValue == 10 && !isSoft && playerHand.cards.count == 2 && dealerValue == 1 {
if tc >= 4 {
return String(localized: "Double instead of Hit (TC \(tcDisplay), high cards favor you)")
return String(localized: "Double, not Hit (TC \(tcDisplay))")
}
}
// 9 vs 2: Double when TC +1 (basic strategy says Hit)
if playerValue == 9 && !isSoft && playerHand.cards.count == 2 && dealerValue == 2 {
if tc >= 1 {
return String(localized: "Double instead of Hit (TC \(tcDisplay), slight edge to double)")
return String(localized: "Double, not Hit (TC \(tcDisplay))")
}
}
// 9 vs 7: Double when TC +3 (basic strategy says Hit)
if playerValue == 9 && !isSoft && playerHand.cards.count == 2 && dealerValue == 7 {
if tc >= 3 {
return String(localized: "Double instead of Hit (TC \(tcDisplay), deck favors doubling)")
return String(localized: "Double, not Hit (TC \(tcDisplay))")
}
}
// Pair of 10s vs 5: Split when TC +5 (basic strategy says Stand)
if playerHand.canSplit && playerHand.cards[0].blackjackValue == 10 && dealerValue == 5 {
if tc >= 5 {
return String(localized: "Split instead of Stand (TC \(tcDisplay), dealer very likely to bust)")
return String(localized: "Split, not Stand (TC \(tcDisplay))")
}
}
// Pair of 10s vs 6: Split when TC +4 (basic strategy says Stand)
if playerHand.canSplit && playerHand.cards[0].blackjackValue == 10 && dealerValue == 6 {
if tc >= 4 {
return String(localized: "Split instead of Stand (TC \(tcDisplay), dealer very likely to bust)")
return String(localized: "Split, not Stand (TC \(tcDisplay))")
}
}

View File

@ -36,6 +36,23 @@ final class GameState {
/// Insurance bet amount.
var insuranceBet: Int = 0
// MARK: - Side Bets
/// Perfect Pairs side bet amount.
var perfectPairsBet: Int = 0
/// 21+3 side bet amount.
var twentyOnePlusThreeBet: Int = 0
/// Result of Perfect Pairs bet (set after deal).
var perfectPairsResult: PerfectPairsResult?
/// Result of 21+3 bet (set after deal).
var twentyOnePlusThreeResult: TwentyOnePlusThreeResult?
/// Whether to show side bet toast notifications.
var showSideBetToasts: Bool = false
/// Whether a reshuffle notification should be shown.
var showReshuffleNotification: Bool = false
@ -105,8 +122,57 @@ final class GameState {
/// Whether player can place a bet.
/// True if in betting phase, have balance, and haven't hit max bet.
var canBet: Bool {
currentPhase == .betting && balance > 0 && currentBet < settings.maxBet
/// Whether in betting phase (matches Baccarat's canPlaceBet).
var canPlaceBet: Bool {
currentPhase == .betting
}
/// Whether the main bet can accept more chips of the given amount.
/// Matches Baccarat's canAddToBet pattern.
func canAddToMainBet(amount: Int) -> Bool {
currentBet + amount <= settings.maxBet
}
/// Whether a specific side bet can accept more chips of the given amount.
/// Matches Baccarat's canAddToBet pattern.
func canAddToSideBet(type: SideBetType, amount: Int) -> Bool {
guard settings.sideBetsEnabled else { return false }
let currentAmount: Int
switch type {
case .perfectPairs:
currentAmount = perfectPairsBet
case .twentyOnePlusThree:
currentAmount = twentyOnePlusThreeBet
}
return currentAmount + amount <= settings.maxBet
}
/// Whether a bet type is at max.
func isAtMax(main: Bool = false, sideType: SideBetType? = nil) -> Bool {
if main {
return currentBet >= settings.maxBet
}
if let type = sideType {
switch type {
case .perfectPairs:
return perfectPairsBet >= settings.maxBet
case .twentyOnePlusThree:
return twentyOnePlusThreeBet >= settings.maxBet
}
}
return false
}
/// The minimum bet level across all active bet types.
/// Used by chip selector to determine if chips should be enabled.
/// Returns the smallest bet so chips stay enabled if ANY bet type can accept more.
var minBetForChipSelector: Int {
if settings.sideBetsEnabled {
// Return the minimum of all bet types so chips stay enabled if any can be increased
return min(currentBet, perfectPairsBet, twentyOnePlusThreeBet)
} else {
return currentBet
}
}
/// Whether the current hand can hit.
@ -315,24 +381,49 @@ final class GameState {
// MARK: - Betting
/// Places a bet.
/// Places a main bet.
/// Places a main bet. Matches Baccarat's placeBet pattern.
func placeBet(amount: Int) {
guard canBet else { return }
guard currentBet + amount <= settings.maxBet else { return }
guard canPlaceBet else { return }
guard balance >= amount else { return }
guard canAddToMainBet(amount: amount) else { return }
currentBet += amount
balance -= amount
sound.play(.chipPlace)
}
/// Clears the current bet.
func clearBet() {
balance += currentBet
currentBet = 0
/// Places a side bet (Perfect Pairs or 21+3).
/// Matches Baccarat's placeBet pattern for side bets.
func placeSideBet(type: SideBetType, amount: Int) {
guard canPlaceBet else { return }
guard balance >= amount else { return }
guard canAddToSideBet(type: type, amount: amount) else { return }
switch type {
case .perfectPairs:
perfectPairsBet += amount
case .twentyOnePlusThree:
twentyOnePlusThreeBet += amount
}
balance -= amount
sound.play(.chipPlace)
}
/// Clears all bets (main and side bets).
func clearBet() {
balance += currentBet + perfectPairsBet + twentyOnePlusThreeBet
currentBet = 0
perfectPairsBet = 0
twentyOnePlusThreeBet = 0
sound.play(.chipPlace)
}
/// Total amount bet (main + side bets).
var totalBetAmount: Int {
currentBet + perfectPairsBet + twentyOnePlusThreeBet
}
// MARK: - Dealing
/// Whether the player can deal (betting phase with valid bet).
@ -360,6 +451,8 @@ final class GameState {
dealerHand = BlackjackHand()
activeHandIndex = 0
insuranceBet = 0
perfectPairsResult = nil
twentyOnePlusThreeResult = nil
let delay = settings.showAnimations ? 0.3 * settings.dealingSpeed : 0
@ -381,6 +474,9 @@ final class GameState {
}
}
// Evaluate side bets after initial cards are dealt
evaluateSideBets()
// Check for insurance offer (only in American style with hole card)
if !settings.noHoleCard, let upCard = dealerUpCard, engine.shouldOfferInsurance(dealerUpCard: upCard) {
currentPhase = .insurance
@ -652,6 +748,66 @@ final class GameState {
await completeRound()
}
// MARK: - Side Bets
/// Evaluates side bets based on the initial deal.
private func evaluateSideBets() {
guard settings.sideBetsEnabled else { return }
let playerCards = playerHands[0].cards
guard playerCards.count >= 2 else { return }
// Evaluate Perfect Pairs
if perfectPairsBet > 0 {
perfectPairsResult = SideBetEvaluator.evaluatePerfectPairs(
card1: playerCards[0],
card2: playerCards[1]
)
}
// Evaluate 21+3 (requires dealer upcard)
if twentyOnePlusThreeBet > 0, let dealerUpCard = dealerUpCard {
twentyOnePlusThreeResult = SideBetEvaluator.evaluateTwentyOnePlusThree(
playerCard1: playerCards[0],
playerCard2: playerCards[1],
dealerUpcard: dealerUpCard
)
}
// Show toast notifications if any side bets were placed
if perfectPairsBet > 0 || twentyOnePlusThreeBet > 0 {
showSideBetToasts = true
// Play sound for side bet result
let ppWon = perfectPairsResult?.isWin ?? false
let topWon = twentyOnePlusThreeResult?.isWin ?? false
if ppWon || topWon {
sound.play(.win)
}
// Auto-hide toasts after delay
Task {
try? await Task.sleep(for: .seconds(3))
showSideBetToasts = false
}
}
}
/// Calculates winnings from side bets.
var sideBetWinnings: Int {
var winnings = 0
if let ppResult = perfectPairsResult, ppResult.isWin {
winnings += perfectPairsBet * ppResult.payout
}
if let topResult = twentyOnePlusThreeResult, topResult.isWin {
winnings += twentyOnePlusThreeBet * topResult.payout
}
return winnings
}
// MARK: - Round Completion
/// Completes the round and calculates payouts.
@ -712,6 +868,17 @@ final class GameState {
}
}
// Calculate side bet results
let sideBetsTotal = perfectPairsBet + twentyOnePlusThreeBet
let sideBetsWon = sideBetWinnings
if sideBetsWon > 0 {
balance += sideBetsWon + sideBetsTotal // Return bet + winnings
roundWinnings += sideBetsWon
} else if sideBetsTotal > 0 {
// Side bets lost - account for the loss in round winnings
roundWinnings -= sideBetsTotal
}
// Update statistics
totalWinnings += roundWinnings
if roundWinnings > biggestWin {
@ -727,13 +894,33 @@ final class GameState {
bustCount += 1
}
// Create round result with all hand results and per-hand winnings
// Create round result with all hand results, per-hand winnings, and side bets
let allHandResults = playerHands.map { $0.result ?? .lose }
// Calculate individual side bet winnings
let ppWinnings: Int
if let ppResult = perfectPairsResult, perfectPairsBet > 0 {
ppWinnings = ppResult.isWin ? perfectPairsBet * ppResult.payout : -perfectPairsBet
} else {
ppWinnings = 0
}
let topWinnings: Int
if let topResult = twentyOnePlusThreeResult, twentyOnePlusThreeBet > 0 {
topWinnings = topResult.isWin ? twentyOnePlusThreeBet * topResult.payout : -twentyOnePlusThreeBet
} else {
topWinnings = 0
}
lastRoundResult = RoundResult(
handResults: allHandResults,
handWinnings: perHandWinnings,
insuranceResult: insResult,
insuranceWinnings: insWinnings,
perfectPairsResult: perfectPairsBet > 0 ? perfectPairsResult : nil,
perfectPairsWinnings: ppWinnings,
twentyOnePlusThreeResult: twentyOnePlusThreeBet > 0 ? twentyOnePlusThreeResult : nil,
twentyOnePlusThreeWinnings: topWinnings,
totalWinnings: roundWinnings,
wasBlackjack: wasBlackjack
)
@ -782,6 +969,13 @@ final class GameState {
// Reset bets
currentBet = 0
insuranceBet = 0
perfectPairsBet = 0
twentyOnePlusThreeBet = 0
// Reset side bet results
perfectPairsResult = nil
twentyOnePlusThreeResult = nil
showSideBetToasts = false
// Reset UI state
showResultBanner = false

View File

@ -76,6 +76,17 @@ struct RoundResult: Equatable {
let totalWinnings: Int
let wasBlackjack: Bool
// MARK: - Side Bets
/// Perfect Pairs result (nil if no bet placed)
let perfectPairsResult: PerfectPairsResult?
/// Perfect Pairs winnings (positive if won, negative if lost)
let perfectPairsWinnings: Int
/// 21+3 result (nil if no bet placed)
let twentyOnePlusThreeResult: TwentyOnePlusThreeResult?
/// 21+3 winnings (positive if won, negative if lost)
let twentyOnePlusThreeWinnings: Int
/// Convenience initializer without per-hand winnings (backwards compatibility)
init(handResults: [HandResult], insuranceResult: HandResult?, totalWinnings: Int, wasBlackjack: Bool) {
self.handResults = handResults
@ -84,6 +95,10 @@ struct RoundResult: Equatable {
self.insuranceWinnings = 0
self.totalWinnings = totalWinnings
self.wasBlackjack = wasBlackjack
self.perfectPairsResult = nil
self.perfectPairsWinnings = 0
self.twentyOnePlusThreeResult = nil
self.twentyOnePlusThreeWinnings = 0
}
/// Full initializer with per-hand winnings
@ -94,6 +109,35 @@ struct RoundResult: Equatable {
self.insuranceWinnings = insuranceWinnings
self.totalWinnings = totalWinnings
self.wasBlackjack = wasBlackjack
self.perfectPairsResult = nil
self.perfectPairsWinnings = 0
self.twentyOnePlusThreeResult = nil
self.twentyOnePlusThreeWinnings = 0
}
/// Full initializer with side bets
init(
handResults: [HandResult],
handWinnings: [Int],
insuranceResult: HandResult?,
insuranceWinnings: Int,
perfectPairsResult: PerfectPairsResult?,
perfectPairsWinnings: Int,
twentyOnePlusThreeResult: TwentyOnePlusThreeResult?,
twentyOnePlusThreeWinnings: Int,
totalWinnings: Int,
wasBlackjack: Bool
) {
self.handResults = handResults
self.handWinnings = handWinnings
self.insuranceResult = insuranceResult
self.insuranceWinnings = insuranceWinnings
self.perfectPairsResult = perfectPairsResult
self.perfectPairsWinnings = perfectPairsWinnings
self.twentyOnePlusThreeResult = twentyOnePlusThreeResult
self.twentyOnePlusThreeWinnings = twentyOnePlusThreeWinnings
self.totalWinnings = totalWinnings
self.wasBlackjack = wasBlackjack
}
/// The main/best result for display purposes (first hand, or best if split)
@ -112,6 +156,11 @@ struct RoundResult: Equatable {
handResults.count > 1
}
/// Whether this round had any side bets
var hadSideBets: Bool {
perfectPairsResult != nil || twentyOnePlusThreeResult != nil
}
/// Legacy accessor for backwards compatibility
var splitHandResult: HandResult? {
handResults.count > 1 ? handResults[1] : nil

View File

@ -132,6 +132,11 @@ final class GameSettings {
/// Speed of card dealing (1.0 = normal)
var dealingSpeed: Double = 1.0 { didSet { save() } }
// MARK: - Side Bets
/// Whether side bets (Perfect Pairs, 21+3) are enabled.
var sideBetsEnabled: Bool = false { didSet { save() } }
// MARK: - Display Settings
/// Whether to show the cards remaining indicator.
@ -232,6 +237,7 @@ final class GameSettings {
self.noHoleCard = data.noHoleCard
self.blackjackPayout = data.blackjackPayout
self.insuranceAllowed = data.insuranceAllowed
self.sideBetsEnabled = data.sideBetsEnabled
self.showAnimations = data.showAnimations
self.dealingSpeed = data.dealingSpeed
self.showCardsRemaining = data.showCardsRemaining
@ -257,6 +263,7 @@ final class GameSettings {
noHoleCard: noHoleCard,
blackjackPayout: blackjackPayout,
insuranceAllowed: insuranceAllowed,
sideBetsEnabled: sideBetsEnabled,
showAnimations: showAnimations,
dealingSpeed: dealingSpeed,
showCardsRemaining: showCardsRemaining,
@ -283,6 +290,7 @@ final class GameSettings {
noHoleCard = false
blackjackPayout = 1.5
insuranceAllowed = true
sideBetsEnabled = false
showAnimations = true
dealingSpeed = 1.0
showCardsRemaining = true

View File

@ -117,10 +117,11 @@ struct BlackjackHand: Identifiable, Equatable {
// MARK: - Card Value Extension
extension Card {
/// The blackjack value of this card (Ace = 1 or 11, face cards = 10).
/// The blackjack value of this card for display purposes (Ace = 11, face cards = 10).
/// Note: Hand calculation handles ace flexibility (1 or 11).
var blackjackValue: Int {
switch rank {
case .ace: return 1 // Or 11, handled by hand calculation
case .ace: return 11 // Show as 11 for display; hand calculation handles soft/hard
case .two: return 2
case .three: return 3
case .four: return 4

View File

@ -0,0 +1,229 @@
//
// SideBet.swift
// Blackjack
//
// Side bet types and evaluation for Perfect Pairs and 21+3.
//
import Foundation
import CasinoKit
// MARK: - Side Bet Types
/// Available side bet types in Blackjack.
enum SideBetType: String, CaseIterable, Identifiable {
case perfectPairs = "perfectPairs"
case twentyOnePlusThree = "21+3"
var id: String { rawValue }
var displayName: String {
switch self {
case .perfectPairs: return String(localized: "Perfect Pairs")
case .twentyOnePlusThree: return String(localized: "21+3")
}
}
var shortName: String {
switch self {
case .perfectPairs: return "PP"
case .twentyOnePlusThree: return "21+3"
}
}
var description: String {
switch self {
case .perfectPairs:
return String(localized: "Bet on your first two cards forming a pair")
case .twentyOnePlusThree:
return String(localized: "Poker hand from your first two cards + dealer's upcard")
}
}
}
// MARK: - Perfect Pairs Results
/// Perfect Pairs side bet outcomes.
enum PerfectPairsResult: CaseIterable {
case perfectPair // Same rank AND same suit (e.g., K K)
case coloredPair // Same rank, same color, different suit (e.g., K K)
case mixedPair // Same rank, different color (e.g., K K)
case noPair // No pair
var displayName: String {
switch self {
case .perfectPair: return String(localized: "Perfect Pair")
case .coloredPair: return String(localized: "Colored Pair")
case .mixedPair: return String(localized: "Mixed Pair")
case .noPair: return String(localized: "No Pair")
}
}
/// Payout multiplier (e.g., 25 means 25:1)
var payout: Int {
switch self {
case .perfectPair: return 25
case .coloredPair: return 12
case .mixedPair: return 6
case .noPair: return 0
}
}
var isWin: Bool {
self != .noPair
}
}
// MARK: - 21+3 Results
/// 21+3 side bet outcomes (poker hands).
enum TwentyOnePlusThreeResult: CaseIterable {
case suitedTrips // Three of a kind, same suit (e.g., 7 7 7)
case straightFlush // Straight + Flush (e.g., 5 6 7)
case threeOfAKind // Three of a kind, different suits (e.g., 7 7 7)
case straight // Three consecutive ranks (e.g., 5 6 7)
case flush // Three cards of same suit (e.g., 2 7 K)
case nothing // No qualifying hand
var displayName: String {
switch self {
case .suitedTrips: return String(localized: "Suited Trips")
case .straightFlush: return String(localized: "Straight Flush")
case .threeOfAKind: return String(localized: "Three of a Kind")
case .straight: return String(localized: "Straight")
case .flush: return String(localized: "Flush")
case .nothing: return String(localized: "No Hand")
}
}
/// Payout multiplier (e.g., 100 means 100:1)
var payout: Int {
switch self {
case .suitedTrips: return 100
case .straightFlush: return 40
case .threeOfAKind: return 30
case .straight: return 10
case .flush: return 5
case .nothing: return 0
}
}
var isWin: Bool {
self != .nothing
}
}
// MARK: - Side Bet Evaluation
/// Evaluates side bet outcomes.
enum SideBetEvaluator {
/// Evaluates Perfect Pairs bet from player's first two cards.
static func evaluatePerfectPairs(card1: Card, card2: Card) -> PerfectPairsResult {
// Must be same rank for any pair
guard card1.rank == card2.rank else {
return .noPair
}
// Perfect Pair: same suit
if card1.suit == card2.suit {
return .perfectPair
}
// Colored Pair: same color (both red or both black), different suit
if card1.suit.isRed == card2.suit.isRed {
return .coloredPair
}
// Mixed Pair: different color
return .mixedPair
}
/// Evaluates 21+3 bet from player's first two cards + dealer's upcard.
static func evaluateTwentyOnePlusThree(playerCard1: Card, playerCard2: Card, dealerUpcard: Card) -> TwentyOnePlusThreeResult {
let cards = [playerCard1, playerCard2, dealerUpcard]
let ranks = cards.map { $0.rank }
let suits = cards.map { $0.suit }
let isFlush = suits.allSatisfy { $0 == suits[0] }
let isStraight = checkStraight(ranks: ranks)
let isThreeOfAKind = ranks.allSatisfy { $0 == ranks[0] }
// Check from highest payout to lowest
if isThreeOfAKind && isFlush {
return .suitedTrips
}
if isStraight && isFlush {
return .straightFlush
}
if isThreeOfAKind {
return .threeOfAKind
}
if isStraight {
return .straight
}
if isFlush {
return .flush
}
return .nothing
}
/// Checks if three ranks form a straight (consecutive values).
/// Handles A-2-3 and Q-K-A straights.
private static func checkStraight(ranks: [Rank]) -> Bool {
// Convert to numeric values (Ace can be 1 or 14)
let values = ranks.map { rankValue($0) }.sorted()
// Check normal straight (consecutive)
if values[2] - values[1] == 1 && values[1] - values[0] == 1 {
return true
}
// Check A-2-3 (values would be [1, 2, 3] after converting Ace to 1)
// But our rankValue gives Ace = 14, so check [2, 3, 14]
let sortedRanks = ranks.sorted { rankValue($0) < rankValue($1) }
let hasAce = sortedRanks.contains(.ace)
let hasTwo = sortedRanks.contains(.two)
let hasThree = sortedRanks.contains(.three)
if hasAce && hasTwo && hasThree {
return true
}
return false
}
/// Converts rank to numeric value for straight checking.
private static func rankValue(_ rank: Rank) -> Int {
switch rank {
case .ace: return 14 // High ace for Q-K-A
case .two: return 2
case .three: return 3
case .four: return 4
case .five: return 5
case .six: return 6
case .seven: return 7
case .eight: return 8
case .nine: return 9
case .ten: return 10
case .jack: return 11
case .queen: return 12
case .king: return 13
}
}
}
// MARK: - Suit Extension for Color
extension Suit {
/// Whether this suit is red (hearts, diamonds).
var isRed: Bool {
self == .hearts || self == .diamonds
}
}

View File

@ -47,6 +47,30 @@
}
}
},
"%@ bet, pays up to %@" : {
"comment" : "An accessibility label describing the side bet type, the payout, and the current bet amount (if any).",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "%1$@ bet, pays up to %2$@"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Apuesta %1$@, paga hasta %2$@"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Pari %1$@, paie jusqu'à %2$@"
}
}
}
},
"%lld" : {
"comment" : "A label displaying the amount wagered in the current hand. The argument is the amount wagered in the current hand.",
"isCommentAutoGenerated" : true,
@ -618,6 +642,33 @@
}
}
}
},
"21+3" : {
"comment" : "Description of the 21+3 side bet type.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "21+3"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "21+3"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "21+3"
}
}
}
},
"21+3: Poker hand from your cards + dealer's upcard." : {
},
"A 'soft' hand has an Ace counting as 11." : {
"comment" : "Explanation of how an Ace can be counted as either 1 or 11 in a hand.",
@ -666,6 +717,9 @@
}
}
}
},
"Aces can be high or low in straights (A-2-3 or Q-K-A)." : {
},
"Actions" : {
"localizations" : {
@ -1270,6 +1324,13 @@
}
}
}
},
"Bet on your first two cards forming a pair" : {
"comment" : "Description of the Perfect Pairs side bet.",
"isCommentAutoGenerated" : true
},
"Bet on your first two cards forming a pair." : {
},
"Betting Hint" : {
"comment" : "A label describing the view that shows betting recommendations.",
@ -1782,6 +1843,33 @@
}
}
}
},
"Colored Pair" : {
"comment" : "Description of a Perfect Pairs side bet result when the first two cards form a pair of the same rank but different suit.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Colored Pair"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Par de Color"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Paire Colorée"
}
}
}
},
"Colored Pair (same color): 12:1" : {
},
"Common shoe game" : {
"comment" : "Description of a deck count option when the user selects 4 decks.",
@ -1899,6 +1987,10 @@
}
}
},
"Current bet $%lld" : {
"comment" : "A hint that appears when a user taps on a side bet zone. The text varies depending on whether a bet is currently placed or not.",
"isCommentAutoGenerated" : true
},
"Custom" : {
"localizations" : {
"en" : {
@ -2595,78 +2687,6 @@
}
}
},
"Double instead of Hit (TC %@, deck favors doubling)": {
"comment": "Text explaining a Blackjack strategy recommendation to double down when the true count is favorable. The argument is the formatted true count.",
"isCommentAutoGenerated": true,
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Double instead of Hit (TC %@, deck favors doubling)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Doblar en vez de Pedir (TC %@, la baraja favorece doblar)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Doubler au lieu de Tirer (TC %@, le jeu favorise le double)"
}
}
}
},
"Double instead of Hit (TC %@, high cards favor you)": {
"comment": "A hint to double down when the true count and the dealer's upcard favor it. The argument is the formatted true count.",
"isCommentAutoGenerated": true,
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Double instead of Hit (TC %@, high cards favor you)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Doblar en vez de Pedir (TC %@, las cartas altas te favorecen)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Doubler au lieu de Tirer (TC %@, les cartes hautes vous favorisent)"
}
}
}
},
"Double instead of Hit (TC %@, slight edge to double)": {
"comment": "Text explaining a situation where doubling is recommended in Blackjack, based on the true count and the dealer's upcard. The argument is the formatted true count.",
"isCommentAutoGenerated": true,
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Double instead of Hit (TC %@, slight edge to double)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Doblar en vez de Pedir (TC %@, ligera ventaja para doblar)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Doubler au lieu de Tirer (TC %@, léger avantage à doubler)"
}
}
}
},
"Double on 9, 10, or 11 only (some venues)." : {
"localizations" : {
"en" : {
@ -2757,6 +2777,10 @@
}
}
},
"Double tap to place bet" : {
"comment" : "A hint text that describes the action to take to place a side bet.",
"isCommentAutoGenerated" : true
},
"Enable 'Card Count' in Settings to practice." : {
"localizations" : {
"en" : {
@ -2779,6 +2803,31 @@
}
}
},
"Enable in Settings to play side bets." : {
},
"Enable Side Bets" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Enable Side Bets"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Activar Apuestas Laterales"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Activer les Paris Annexes"
}
}
}
},
"European" : {
"localizations" : {
"en" : {
@ -2800,6 +2849,15 @@
}
}
}
},
"Example: K♠ K♠ = Perfect Pair" : {
},
"Example: K♠ K♣ = Colored Pair (both black)" : {
},
"Example: K♠ K♥ = Mixed Pair (red/black)" : {
},
"Fewer decks = easier to count accurately." : {
"localizations" : {
@ -2844,6 +2902,36 @@
}
}
}
},
"Flush" : {
"comment" : "Description of a 21+3 side bet outcome when the user has a flush.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Flush"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Color"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Couleur"
}
}
}
},
"Flush (same suit): 5:1" : {
},
"Forms a poker hand: your 2 cards + dealer upcard." : {
},
"GAME STYLE" : {
"localizations" : {
@ -3141,52 +3229,6 @@
}
}
},
"Hit instead of Stand (TC %@, deck is poor)": {
"comment": "A hint to the player based on the true count, suggesting they should hit instead of stand. The argument is the true count, displayed with a plus sign if positive.",
"isCommentAutoGenerated": true,
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Hit instead of Stand (TC %@, deck is poor)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Pedir en vez de Plantarse (TC %@, la baraja es pobre)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Tirer au lieu de Rester (TC %@, le jeu est pauvre)"
}
}
}
},
"Hit instead of Stand (TC %@, deck is very poor)": {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Hit instead of Stand (TC %@, deck is very poor)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Pedir en vez de Plantarse (TC %@, la baraja es muy pobre)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Tirer au lieu de Rester (TC %@, le jeu est très pauvre)"
}
}
}
},
"Hit on soft 17 or less." : {
"localizations" : {
"en" : {
@ -3847,6 +3889,30 @@
}
}
},
"MAX" : {
"comment" : "The text displayed in the center of the chip badge when it represents the maximum bet.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "MAX"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "MÁX"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "MAX"
}
}
}
},
"Max: $%@" : {
"comment" : "A label displaying the maximum bet amount. The argument is the maximum bet amount.",
"isCommentAutoGenerated" : true,
@ -3916,6 +3982,33 @@
}
}
}
},
"Mixed Pair" : {
"comment" : "Description of a Perfect Pairs side bet outcome when the first two cards have the same rank but different color.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Mixed Pair"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Par Mixto"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Paire Mixte"
}
}
}
},
"Mixed Pair (diff. color): 6:1" : {
},
"More decks = harder to count cards." : {
"localizations" : {
@ -4049,6 +4142,30 @@
}
}
},
"No Hand" : {
"comment" : "Description of a 21+3 side bet outcome when there is no qualifying hand.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "No Hand"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Sin Mano"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Pas de Main"
}
}
}
},
"No hole card, dealer stands on soft 17, no surrender" : {
"localizations" : {
"en" : {
@ -4093,6 +4210,29 @@
}
}
},
"No Pair" : {
"comment" : "Description of a Perfect Pairs side bet outcome when there is no pair.",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "No Pair"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Sin Par"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Pas de Paire"
}
}
}
},
"No surrender option." : {
"localizations" : {
"en" : {
@ -4230,6 +4370,9 @@
}
}
}
},
"Optional bets placed before the deal." : {
},
"Other Game Icons" : {
"comment" : "A label displayed above a section of the BrandingPreviewView that shows icons for other games.",
@ -4346,6 +4489,63 @@
}
}
}
},
"Perfect Pair" : {
"comment" : "Name of the side bet outcome where the first two cards form a perfect pair.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Perfect Pair"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Par Perfecto"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Paire Parfaite"
}
}
}
},
"Perfect Pair (same suit): 25:1" : {
},
"Perfect Pairs" : {
"comment" : "Name of the Perfect Pairs side bet type.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Perfect Pairs"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Pares Perfectos"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Paires Parfaites"
}
}
}
},
"Perfect Pairs (25:1) and 21+3 (100:1)" : {
},
"Perfect Pairs: Bet on your first two cards being a pair." : {
},
"Play Again" : {
"localizations" : {
@ -4415,6 +4615,10 @@
}
}
},
"Poker hand from your first two cards + dealer's upcard" : {
"comment" : "Description of the 21+3 side bet type.",
"isCommentAutoGenerated" : true
},
"Positive count = more high cards remain = player advantage." : {
"localizations" : {
"en" : {
@ -5022,6 +5226,34 @@
}
}
}
},
"Side Bets" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Side Bets"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Apuestas Laterales"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Paris Annexes"
}
}
}
},
"SIDE BETS" : {
},
"Side bets have higher house edge than main game." : {
},
"Sign in to iCloud to sync progress" : {
"localizations" : {
@ -5159,6 +5391,98 @@
}
}
},
"Split, not Stand (TC %@)" : {
"comment" : "Short hint to split instead of stand based on true count.",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Split, not Stand (TC %@)"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Dividir, no Plantarse (TC %@)"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Séparer, pas Rester (TC %@)"
}
}
}
},
"Stand, not Hit (TC %@)" : {
"comment" : "Short hint to stand instead of hit based on true count.",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Stand, not Hit (TC %@)"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Plantarse, no Pedir (TC %@)"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Rester, pas Tirer (TC %@)"
}
}
}
},
"Hit, not Stand (TC %@)" : {
"comment" : "Short hint to hit instead of stand based on true count.",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Hit, not Stand (TC %@)"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Pedir, no Plantarse (TC %@)"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Tirer, pas Rester (TC %@)"
}
}
}
},
"Double, not Hit (TC %@)" : {
"comment" : "Short hint to double instead of hit based on true count.",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Double, not Hit (TC %@)"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Doblar, no Pedir (TC %@)"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Doubler, pas Tirer (TC %@)"
}
}
}
},
"Split instead of Stand (TC %@, dealer very likely to bust)" : {
"comment" : "A hint to split a pair of 10s when the true count is high enough.",
"isCommentAutoGenerated" : true,
@ -5251,100 +5575,6 @@
}
}
},
"Stand instead of Hit (TC %@, dealer likely to bust)": {
"comment": "Text explaining a Blackjack strategy recommendation based on the true count. The argument is the formatted true count.",
"isCommentAutoGenerated": true,
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Stand instead of Hit (TC %@, dealer likely to bust)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Plantarse en vez de Pedir (TC %@, el crupier probablemente se pase)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Rester au lieu de Tirer (TC %@, le croupier va probablement sauter)"
}
}
}
},
"Stand instead of Hit (TC %@, deck is extremely rich)": {
"comment": "Text provided in the \"Count Adjusted\" hint section of the Blackjack game UI, explaining a recommended action based on the true count and the current game state. The argument is the formatted true count.",
"isCommentAutoGenerated": true,
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Stand instead of Hit (TC %@, deck is extremely rich)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Plantarse en vez de Pedir (TC %@, la baraja es extremadamente rica)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Rester au lieu de Tirer (TC %@, le jeu est extrêmement riche)"
}
}
}
},
"Stand instead of Hit (TC %@, deck is neutral/rich)": {
"comment": "Explanation of a count-based deviation from the basic strategy, including the true count and a description of the deck situation.",
"isCommentAutoGenerated": true,
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Stand instead of Hit (TC %@, deck is neutral/rich)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Plantarse en vez de Pedir (TC %@, la baraja es neutral/rica)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Rester au lieu de Tirer (TC %@, le jeu est neutre/riche)"
}
}
}
},
"Stand instead of Hit (TC %@, deck is very rich)": {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Stand instead of Hit (TC %@, deck is very rich)"
}
},
"es-MX": {
"stringUnit": {
"state": "translated",
"value": "Plantarse en vez de Pedir (TC %@, la baraja es muy rica)"
}
},
"fr-CA": {
"stringUnit": {
"state": "translated",
"value": "Rester au lieu de Tirer (TC %@, le jeu est très riche)"
}
}
}
},
"Stand on 17+ always." : {
"localizations" : {
"en" : {
@ -5480,6 +5710,87 @@
}
}
}
},
"Straight" : {
"comment" : "Name of a 21+3 result when the user has three consecutive ranks.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Straight"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Escalera"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Suite"
}
}
}
},
"Straight (consecutive): 10:1" : {
},
"Straight Flush" : {
"comment" : "Description of a 21+3 side bet outcome when the player has a straight flush.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Straight Flush"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Escalera de Color"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Quinte Flush"
}
}
}
},
"Straight Flush: 40:1" : {
},
"Suited Trips" : {
"comment" : "Name of a 21+3 side bet outcome when the user has three cards of the same rank and suit.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Suited Trips"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Trío del Mismo Palo"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Brelan Assorti"
}
}
}
},
"Suited Trips (same rank & suit): 100:1" : {
},
"Surrender" : {
"localizations" : {
@ -5772,6 +6083,33 @@
}
}
}
},
"Three of a Kind" : {
"comment" : "Description of a 21+3 side bet outcome when they have three of a kind.",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Three of a Kind"
}
},
"es-MX" : {
"stringUnit" : {
"state" : "translated",
"value" : "Trío"
}
},
"fr-CA" : {
"stringUnit" : {
"state" : "translated",
"value" : "Brelan"
}
}
}
},
"Three of a Kind: 30:1" : {
},
"Total Winnings" : {
"localizations" : {

View File

@ -66,6 +66,7 @@ struct BlackjackSettingsData: PersistableGameData {
noHoleCard: false,
blackjackPayout: 1.5,
insuranceAllowed: true,
sideBetsEnabled: false,
showAnimations: true,
dealingSpeed: 1.0,
showCardsRemaining: true,
@ -89,6 +90,7 @@ struct BlackjackSettingsData: PersistableGameData {
var noHoleCard: Bool
var blackjackPayout: Double
var insuranceAllowed: Bool
var sideBetsEnabled: Bool
var showAnimations: Bool
var dealingSpeed: Double
var showCardsRemaining: Bool

View File

@ -17,7 +17,7 @@ enum Design {
// MARK: - Debug
/// Set to true to show layout debug borders on views
static let showDebugBorders = true
static let showDebugBorders = false
// MARK: - Shared Constants (from CasinoKit)
@ -50,8 +50,8 @@ enum Design {
// Hints
static let hintFontSize: CGFloat = 15
static let hintIconSize: CGFloat = 24
static let hintPaddingH: CGFloat = 18
static let hintPaddingV: CGFloat = 12
static let hintPaddingH: CGFloat = 10
static let hintPaddingV: CGFloat = 10
// Hand icons
static let handIconSize: CGFloat = 18
@ -126,4 +126,13 @@ extension Color {
enum TopBar {
static let balance = Color(red: 0.95, green: 0.85, blue: 0.4)
}
// MARK: - Side Bet Colors
enum SideBet {
/// Perfect Pairs - purple theme
static let perfectPairs = Color(red: 0.4, green: 0.2, blue: 0.5)
/// 21+3 - teal/cyan theme
static let twentyOnePlusThree = Color(red: 0.1, green: 0.4, blue: 0.5)
}
}

View File

@ -1,108 +0,0 @@
//
// ActionButton.swift
// Blackjack
//
// Reusable styled button for game actions.
//
import SwiftUI
import CasinoKit
struct ActionButton: View {
let title: String
let icon: String?
let style: ButtonStyle
let action: () -> Void
enum ButtonStyle {
case primary // Gold gradient (Deal, New Round)
case destructive // Red (Clear)
case secondary // Subtle white
case custom(Color) // Game-specific colors (Hit, Stand, etc.)
var foregroundColor: Color {
switch self {
case .primary: return .black
case .destructive, .secondary, .custom: return .white
}
}
}
init(_ title: String, icon: String? = nil, style: ButtonStyle = .primary, action: @escaping () -> Void) {
self.title = title
self.icon = icon
self.style = style
self.action = action
}
var body: some View {
Button(action: action) {
HStack(spacing: Design.Spacing.small) {
if let icon = icon {
Image(systemName: icon)
}
Text(title)
.lineLimit(1)
.minimumScaleFactor(CasinoDesign.MinScaleFactor.relaxed)
}
.font(.system(size: Design.BaseFontSize.large, weight: .semibold))
.foregroundStyle(style.foregroundColor)
.padding(.horizontal, Design.Spacing.large)
.padding(.vertical, Design.Spacing.medium)
.background(backgroundView)
}
.accessibilityLabel(title)
}
@ViewBuilder
private var backgroundView: some View {
switch style {
case .primary:
Capsule()
.fill(
LinearGradient(
colors: [Color.CasinoButton.goldLight, Color.CasinoButton.goldDark],
startPoint: .top,
endPoint: .bottom
)
)
case .destructive:
Capsule()
.fill(Color.red.opacity(Design.Opacity.heavy))
case .secondary:
Capsule()
.fill(Color.white.opacity(Design.Opacity.hint))
case .custom(let color):
Capsule()
.fill(color)
}
}
}
// MARK: - Previews
#Preview("Primary") {
ZStack {
Color.Table.felt.ignoresSafeArea()
ActionButton("Deal", icon: "play.fill", style: .primary) {}
}
}
#Preview("Destructive") {
ZStack {
Color.Table.felt.ignoresSafeArea()
ActionButton("Clear", icon: "xmark.circle", style: .destructive) {}
}
}
#Preview("Custom Colors") {
ZStack {
Color.Table.felt.ignoresSafeArea()
HStack(spacing: Design.Spacing.medium) {
ActionButton("Hit", style: .custom(Color.Button.hit)) {}
ActionButton("Stand", style: .custom(Color.Button.stand)) {}
ActionButton("Double", style: .custom(Color.Button.doubleDown)) {}
}
}
}

View File

@ -19,6 +19,9 @@ struct GameTableView: View {
@State private var showRules = false
@State private var showStats = false
/// Full screen size (measured from TableBackgroundView - stable, doesn't change with content)
@State private var fullScreenSize: CGSize = CGSize(width: 375, height: 667)
// MARK: - Environment
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
@ -73,8 +76,13 @@ struct GameTableView: View {
@ViewBuilder
private func mainGameView(state: GameState) -> some View {
ZStack {
// Background
// Background - measures full screen size (stable)
TableBackgroundView()
.onGeometryChange(for: CGSize.self) { proxy in
proxy.size
} action: { size in
fullScreenSize = size
}
mainContent(state: state)
}
@ -117,7 +125,8 @@ struct GameTableView: View {
// Table layout - fills available space
BlackjackTableView(
state: state,
onPlaceBet: { placeBet(state: state) }
selectedChip: selectedChip,
fullScreenSize: fullScreenSize
)
.frame(maxWidth: maxContentWidth)
@ -129,7 +138,7 @@ struct GameTableView: View {
ChipSelectorView(
selectedChip: $selectedChip,
balance: state.balance,
currentBet: state.currentBet,
currentBet: state.minBetForChipSelector, // Use min bet so chips stay enabled if any bet type can accept more
maxBet: state.settings.maxBet
)
.frame(maxWidth: maxContentWidth)
@ -182,11 +191,6 @@ struct GameTableView: View {
}
}
// MARK: - Betting
private func placeBet(state: GameState) {
state.placeBet(amount: selectedChip.rawValue)
}
}
// MARK: - Preview

View File

@ -94,6 +94,25 @@ struct ResultBannerView: View {
amount: showInsAmount ? result.insuranceWinnings : nil
)
}
// Side bet results
if let ppResult = result.perfectPairsResult {
SideBetResultRow(
label: String(localized: "Perfect Pairs"),
resultText: ppResult.displayName,
isWin: ppResult.isWin,
amount: result.perfectPairsWinnings
)
}
if let topResult = result.twentyOnePlusThreeResult {
SideBetResultRow(
label: String(localized: "21+3"),
resultText: topResult.displayName,
isWin: topResult.isWin,
amount: result.twentyOnePlusThreeWinnings
)
}
}
.padding(Design.Spacing.medium)
.background(
@ -245,6 +264,57 @@ struct ResultRow: View {
}
}
// MARK: - Side Bet Result Row
struct SideBetResultRow: View {
let label: String
let resultText: String
let isWin: Bool
let amount: Int
private var amountText: String {
if amount > 0 {
return "+$\(amount)"
} else if amount < 0 {
return "-$\(abs(amount))"
} else {
return "$0"
}
}
private var amountColor: Color {
if amount > 0 { return .green }
if amount < 0 { return .red }
return .blue
}
private var resultColor: Color {
isWin ? .green : .red
}
var body: some View {
HStack {
Text(label)
.font(.system(size: Design.BaseFontSize.body))
.foregroundStyle(.white.opacity(Design.Opacity.strong))
Spacer()
Text(amountText)
.font(.system(size: Design.BaseFontSize.body, weight: .semibold, design: .rounded))
.foregroundStyle(amountColor)
.frame(width: 70, alignment: .trailing)
Text(resultText)
.font(.system(size: Design.BaseFontSize.body, weight: .bold))
.foregroundStyle(resultColor)
.frame(width: 100, alignment: .trailing)
.lineLimit(1)
.minimumScaleFactor(Design.MinScaleFactor.comfortable)
}
}
}
#Preview("Single Hand") {
ResultBannerView(
result: RoundResult(
@ -296,3 +366,24 @@ struct ResultRow: View {
)
}
#Preview("With Side Bets") {
ResultBannerView(
result: RoundResult(
handResults: [.win],
handWinnings: [100],
insuranceResult: nil,
insuranceWinnings: 0,
perfectPairsResult: .coloredPair,
perfectPairsWinnings: 300,
twentyOnePlusThreeResult: .nothing,
twentyOnePlusThreeWinnings: -25,
totalWinnings: 375,
wasBlackjack: false
),
currentBalance: 1375,
minBet: 10,
onNewRound: {},
onPlayAgain: {}
)
}

View File

@ -82,6 +82,43 @@ struct RulesHelpView: View {
String(localized: "Surrender: Half bet returned")
]
),
RulePage(
title: String(localized: "Side Bets"),
icon: "plus.circle.fill",
content: [
String(localized: "Optional bets placed before the deal."),
String(localized: "Perfect Pairs: Bet on your first two cards being a pair."),
String(localized: "21+3: Poker hand from your cards + dealer's upcard."),
String(localized: "Side bets have higher house edge than main game."),
String(localized: "Enable in Settings to play side bets.")
]
),
RulePage(
title: String(localized: "Perfect Pairs"),
icon: "suit.heart.fill",
content: [
String(localized: "Bet on your first two cards forming a pair."),
String(localized: "Mixed Pair (diff. color): 6:1"),
String(localized: "Colored Pair (same color): 12:1"),
String(localized: "Perfect Pair (same suit): 25:1"),
String(localized: "Example: K♠ K♠ = Perfect Pair"),
String(localized: "Example: K♠ K♣ = Colored Pair (both black)"),
String(localized: "Example: K♠ K♥ = Mixed Pair (red/black)")
]
),
RulePage(
title: String(localized: "21+3"),
icon: "dice.fill",
content: [
String(localized: "Forms a poker hand: your 2 cards + dealer upcard."),
String(localized: "Flush (same suit): 5:1"),
String(localized: "Straight (consecutive): 10:1"),
String(localized: "Three of a Kind: 30:1"),
String(localized: "Straight Flush: 40:1"),
String(localized: "Suited Trips (same rank & suit): 100:1"),
String(localized: "Aces can be high or low in straights (A-2-3 or Q-K-A).")
]
),
RulePage(
title: String(localized: "Vegas Strip"),
icon: "sparkles",

View File

@ -81,6 +81,16 @@ struct SettingsView: View {
TableLimitsPicker(selection: $settings.tableLimits)
}
// 3.5. Side Bets
SheetSection(title: String(localized: "SIDE BETS"), icon: "dollarsign.arrow.trianglehead.counterclockwise.rotate.90") {
SettingsToggle(
title: String(localized: "Enable Side Bets"),
subtitle: String(localized: "Perfect Pairs (25:1) and 21+3 (100:1)"),
isOn: $settings.sideBetsEnabled,
accentColor: accent
)
}
// 4. Deck Settings
SheetSection(title: String(localized: "DECK SETTINGS"), icon: "rectangle.portrait.on.rectangle.portrait") {
DeckCountPicker(selection: $settings.deckCount)

View File

@ -8,23 +8,93 @@
import SwiftUI
import CasinoKit
/// Main betting zone view - adapts layout based on whether side bets are enabled.
/// Follows Baccarat's betting pattern exactly.
struct BettingZoneView: View {
let betAmount: Int
let minBet: Int
let maxBet: Int
let onTap: () -> Void
@Bindable var state: GameState
let selectedChip: ChipDenomination
@ScaledMetric(relativeTo: .headline) private var labelFontSize: CGFloat = Design.Size.handLabelFontSize
@ScaledMetric(relativeTo: .caption) private var detailFontSize: CGFloat = Design.Size.handNumberFontSize
@ScaledMetric(relativeTo: .body) private var chipSize: CGFloat = Design.Size.bettingChipSize
@ScaledMetric(relativeTo: .body) private var zoneHeight: CGFloat = CasinoDesign.Size.bettingZoneHeight
private var isAtMax: Bool {
betAmount >= maxBet
// MARK: - Computed Properties (matches Baccarat's pattern)
/// Whether a bet can be added to main bet (matches Baccarat's canAddBet)
private var canAddMainBet: Bool {
state.canPlaceBet &&
state.balance >= selectedChip.rawValue &&
state.canAddToMainBet(amount: selectedChip.rawValue)
}
/// Whether a bet can be added to Perfect Pairs
private var canAddPerfectPairs: Bool {
state.canPlaceBet &&
state.balance >= selectedChip.rawValue &&
state.canAddToSideBet(type: .perfectPairs, amount: selectedChip.rawValue)
}
/// Whether a bet can be added to 21+3
private var canAddTwentyOnePlusThree: Bool {
state.canPlaceBet &&
state.balance >= selectedChip.rawValue &&
state.canAddToSideBet(type: .twentyOnePlusThree, amount: selectedChip.rawValue)
}
private var isMainAtMax: Bool {
state.currentBet >= state.settings.maxBet
}
private var isPPAtMax: Bool {
state.perfectPairsBet >= state.settings.maxBet
}
private var is21PlusThreeAtMax: Bool {
state.twentyOnePlusThreeBet >= state.settings.maxBet
}
var body: some View {
Button(action: onTap) {
if state.settings.sideBetsEnabled {
// Horizontal layout: PP | Main Bet | 21+3
HStack(spacing: Design.Spacing.small) {
// Perfect Pairs
SideBetZoneView(
betType: .perfectPairs,
betAmount: state.perfectPairsBet,
isEnabled: canAddPerfectPairs,
isAtMax: isPPAtMax,
onTap: { state.placeSideBet(type: .perfectPairs, amount: selectedChip.rawValue) }
)
.frame(width: Design.Size.sideBetZoneWidth)
// Main bet (center, takes remaining space)
mainBetZone
// 21+3
SideBetZoneView(
betType: .twentyOnePlusThree,
betAmount: state.twentyOnePlusThreeBet,
isEnabled: canAddTwentyOnePlusThree,
isAtMax: is21PlusThreeAtMax,
onTap: { state.placeSideBet(type: .twentyOnePlusThree, amount: selectedChip.rawValue) }
)
.frame(width: Design.Size.sideBetZoneWidth)
}
.frame(height: zoneHeight)
} else {
// Simple layout: just main bet
mainBetZone
.frame(height: zoneHeight)
}
}
private var mainBetZone: some View {
Button {
if canAddMainBet {
state.placeBet(amount: selectedChip.rawValue)
}
} label: {
ZStack {
// Background
RoundedRectangle(cornerRadius: Design.CornerRadius.large)
@ -35,9 +105,9 @@ struct BettingZoneView: View {
)
// Content
if betAmount > 0 {
if state.currentBet > 0 {
// Show chip with amount (scaled)
ChipOnTableView(amount: betAmount, showMax: isAtMax, size: chipSize)
ChipOnTableView(amount: state.currentBet, showMax: isMainAtMax, size: chipSize)
} else {
// Empty state
VStack(spacing: Design.Spacing.small) {
@ -46,11 +116,11 @@ struct BettingZoneView: View {
.foregroundStyle(.white.opacity(Design.Opacity.medium))
HStack(spacing: Design.Spacing.medium) {
Text(String(localized: "Min: $\(minBet)"))
Text(String(localized: "Min: $\(state.settings.minBet)"))
.font(.system(size: detailFontSize, weight: .medium))
.foregroundStyle(.white.opacity(Design.Opacity.light))
Text(String(localized: "Max: $\(maxBet.formatted())"))
Text(String(localized: "Max: $\(state.settings.maxBet.formatted())"))
.font(.system(size: detailFontSize, weight: .medium))
.foregroundStyle(.white.opacity(Design.Opacity.light))
}
@ -58,50 +128,64 @@ struct BettingZoneView: View {
}
}
.frame(maxWidth: .infinity)
.frame(height: zoneHeight)
}
.buttonStyle(.plain)
.accessibilityLabel(betAmount > 0 ? "$\(betAmount) bet" + (isAtMax ? ", maximum" : "") : "Place bet")
.accessibilityLabel(state.currentBet > 0 ? "$\(state.currentBet) bet" + (isMainAtMax ? ", maximum" : "") : "Place bet")
.accessibilityHint("Double tap to add chips")
}
}
// MARK: - Design Constants Extension
extension Design.Size {
/// Width of side bet zones
static let sideBetZoneWidth: CGFloat = 70
}
// MARK: - Previews
#Preview("Empty") {
#Preview("Empty - No Side Bets") {
ZStack {
Color.Table.felt.ignoresSafeArea()
BettingZoneView(
betAmount: 0,
minBet: 10,
maxBet: 1000,
onTap: {}
state: GameState(settings: GameSettings()),
selectedChip: .hundred
)
.padding()
}
}
#Preview("With Bet") {
#Preview("With Side Bets") {
ZStack {
Color.Table.felt.ignoresSafeArea()
BettingZoneView(
betAmount: 250,
minBet: 10,
maxBet: 1000,
onTap: {}
state: {
let settings = GameSettings()
settings.sideBetsEnabled = true
let state = GameState(settings: settings)
state.placeBet(amount: 100)
return state
}(),
selectedChip: .twentyFive
)
.padding()
}
}
#Preview("Max Bet") {
#Preview("All Bets Placed") {
ZStack {
Color.Table.felt.ignoresSafeArea()
BettingZoneView(
betAmount: 1000,
minBet: 10,
maxBet: 1000,
onTap: {}
state: {
let settings = GameSettings()
settings.sideBetsEnabled = true
let state = GameState(settings: settings)
state.placeBet(amount: 250)
state.placeSideBet(type: .perfectPairs, amount: 25)
state.placeSideBet(type: .twentyOnePlusThree, amount: 50)
return state
}(),
selectedChip: .hundred
)
.padding()
}

View File

@ -10,17 +10,19 @@ import CasinoKit
struct BlackjackTableView: View {
@Bindable var state: GameState
let onPlaceBet: () -> Void
let selectedChip: ChipDenomination
/// Full screen size passed from parent (stable - measured from TableBackgroundView)
let fullScreenSize: CGSize
// MARK: - Environment
@Environment(\.verticalSizeClass) private var verticalSizeClass
// MARK: - State
// MARK: - Computed from stable screen size
/// Screen dimensions measured from container for responsive sizing
@State private var screenHeight: CGFloat = 800
@State private var screenWidth: CGFloat = 375
private var screenWidth: CGFloat { fullScreenSize.width }
private var screenHeight: CGFloat { fullScreenSize.height }
/// Whether to show Hi-Lo card count values on cards.
var showCardCount: Bool { state.settings.showCardCount }
@ -43,13 +45,11 @@ struct BlackjackTableView: View {
return verticalSizeClass == .compact
}
/// Card width derived from screen height percentage and card aspect ratio
/// cardHeight = maxHeight × percentage, then cardWidth = cardHeight / aspectRatio
/// Card width based on full screen height (stable - doesn't change with content)
private var cardWidth: CGFloat {
let maxHeight = max(screenWidth, screenHeight)
let heightPercentage: CGFloat = 0.19 // Card takes 12% of screen height
let cardHeight = maxHeight * heightPercentage
return cardHeight
let maxDimension = screenHeight
let percentage: CGFloat = 0.13 // ~10% of screen
return maxDimension * percentage
}
/// Card overlap scales proportionally with card width
@ -73,8 +73,8 @@ struct BlackjackTableView: View {
/// - iPad Pro 12.9" (~1366pt): ~150pt (capped)
private var dealerPlayerSpacing: CGFloat {
let baseline: CGFloat = 550 // Below this, use minimum
let scale: CGFloat = 0.2 // 20% of height above baseline
let minSpacing: CGFloat = 20 // Floor for smallest screens
let scale: CGFloat = 0.18 // 20% of height above baseline
let minSpacing: CGFloat = 10 // Floor for smallest screens
let maxSpacing: CGFloat = 150 // Ceiling for largest screens
let calculated = (screenHeight - baseline) * scale
@ -99,6 +99,7 @@ struct BlackjackTableView: View {
// Player hands area - only show when there are cards dealt
if state.playerHands.first?.cards.isEmpty == false {
ZStack {
PlayerHandsView(
hands: state.playerHands,
activeHandIndex: state.activeHandIndex,
@ -107,6 +108,38 @@ struct BlackjackTableView: View {
cardWidth: cardWidth,
cardSpacing: cardSpacing
)
// Side bet toasts (positioned on left/right sides to not cover cards)
if state.settings.sideBetsEnabled && state.showSideBetToasts {
HStack {
// PP on left
if state.perfectPairsBet > 0, let ppResult = state.perfectPairsResult {
SideBetToastView(
title: "PP",
result: ppResult.displayName,
isWin: ppResult.isWin,
amount: ppResult.isWin ? state.perfectPairsBet * ppResult.payout : -state.perfectPairsBet,
showOnLeft: true
)
}
Spacer()
// 21+3 on right
if state.twentyOnePlusThreeBet > 0, let topResult = state.twentyOnePlusThreeResult {
SideBetToastView(
title: "21+3",
result: topResult.displayName,
isWin: topResult.isWin,
amount: topResult.isWin ? state.twentyOnePlusThreeBet * topResult.payout : -state.twentyOnePlusThreeBet,
showOnLeft: false
)
}
}
.padding(.horizontal, Design.Spacing.small)
}
}
.padding(.bottom, 5)
.transition(.opacity)
.debugBorder(showDebugBorders, color: .green, label: "Player")
}
@ -117,10 +150,8 @@ struct BlackjackTableView: View {
.debugBorder(showDebugBorders, color: .yellow, label: "Spacer2")
BettingZoneView(
betAmount: state.currentBet,
minBet: state.settings.minBet,
maxBet: state.settings.maxBet,
onTap: onPlaceBet
state: state,
selectedChip: selectedChip
)
.transition(.scale.combined(with: .opacity))
.debugBorder(showDebugBorders, color: .blue, label: "BetZone")
@ -145,12 +176,6 @@ struct BlackjackTableView: View {
}
.padding(.horizontal, Design.Spacing.large)
.padding(.vertical, Design.Spacing.medium)
.onGeometryChange(for: CGSize.self) { proxy in
proxy.size
} action: { size in
screenWidth = size.width
screenHeight = size.height
}
.debugBorder(showDebugBorders, color: .white, label: "TableView")
.animation(.spring(duration: Design.Animation.springDuration), value: state.currentPhase)
}

View File

@ -18,6 +18,7 @@ struct DealerHandView: View {
@ScaledMetric(relativeTo: .headline) private var labelFontSize: CGFloat = Design.Size.handLabelFontSize
var body: some View {
VStack(spacing: Design.Spacing.small) {
// Label and value
HStack(spacing: Design.Spacing.small) {
@ -25,17 +26,17 @@ struct DealerHandView: View {
.font(.system(size: labelFontSize, weight: .bold, design: .rounded))
.foregroundStyle(.white)
// Show value: always show if hole card visible, or show single card value in European mode
// Show value: full value when hole card visible, otherwise just the face-up card's value
if !hand.cards.isEmpty {
if showHoleCard {
// All cards visible - show total hand value
ValueBadge(value: hand.value, color: Color.Hand.dealer)
} else if hand.cards.count == 1 {
// European mode: show single visible card value
} else {
// Hole card hidden - show only the first (face-up) card's value
ValueBadge(value: hand.cards[0].blackjackValue, color: Color.Hand.dealer)
}
}
}
// Cards
HStack(spacing: hand.cards.isEmpty ? Design.Spacing.small : cardSpacing) {
if hand.cards.isEmpty {

View File

@ -27,6 +27,8 @@ struct HintView: View {
Text(String(localized: "Hint: \(hint)"))
.font(.system(size: fontSize, weight: .medium))
.foregroundStyle(.white.opacity(Design.Opacity.strong))
.lineLimit(1)
.minimumScaleFactor(Design.MinScaleFactor.comfortable)
}
.padding(.horizontal, paddingH)
.padding(.vertical, paddingV)
@ -82,6 +84,8 @@ struct BettingHintView: View {
Text(hint)
.font(.system(size: fontSize, weight: .medium))
.foregroundStyle(.white.opacity(Design.Opacity.strong))
.lineLimit(1)
.minimumScaleFactor(Design.MinScaleFactor.comfortable)
}
.padding(.horizontal, paddingH)
.padding(.vertical, paddingV)

View File

@ -30,17 +30,17 @@ struct InsurancePopupView: View {
// Title
Text(String(localized: "INSURANCE?"))
.font(.system(size: Design.BaseFontSize.xLarge, weight: .bold))
.font(.system(size: Design.BaseFontSize.largeTitle, weight: .black, design: .rounded))
.foregroundStyle(.white)
// Subtitle
Text(String(localized: "Dealer showing Ace"))
.font(.system(size: Design.BaseFontSize.medium))
.font(.system(size: Design.BaseFontSize.xxLarge))
.foregroundStyle(.white.opacity(Design.Opacity.strong))
// Cost info
Text(String(localized: "Cost: $\(betAmount) (half your bet)"))
.font(.system(size: Design.BaseFontSize.small))
.font(.system(size: Design.BaseFontSize.xxLarge))
.foregroundStyle(.white.opacity(Design.Opacity.medium))
.padding(.bottom, Design.Spacing.small)

View File

@ -44,13 +44,11 @@ struct PlayerHandsView: View {
.id(index)
}
}
.padding(.horizontal, Design.Spacing.large)
.containerRelativeFrame(.horizontal) { length, _ in
length // Ensures content fills container width for centering
}
.padding(.horizontal, Design.Spacing.xxLarge) // More padding for scrolling
}
.scrollClipDisabled()
.scrollBounceBehavior(.basedOnSize)
.scrollBounceBehavior(.always) // Always allow bouncing for better scroll feel
.defaultScrollAnchor(.center) // Center the content by default
.onChange(of: activeHandIndex) { _, newIndex in
scrollToHand(proxy: proxy, index: newIndex)
}
@ -66,6 +64,7 @@ struct PlayerHandsView: View {
scrollToHand(proxy: proxy, index: activeHandIndex)
}
}
.frame(maxWidth: .infinity)
}
private func scrollToHand(proxy: ScrollViewProxy, index: Int) {

View File

@ -0,0 +1,144 @@
//
// SideBetToastView.swift
// Blackjack
//
// Animated toast notifications for side bet results that appear after dealing.
//
import SwiftUI
import CasinoKit
/// Toast notification for a single side bet result with built-in animation.
struct SideBetToastView: View {
let title: String
let result: String
let isWin: Bool
let amount: Int
let showOnLeft: Bool
@State private var isShowing = false
@ScaledMetric(relativeTo: .caption) private var titleFontSize: CGFloat = 10
@ScaledMetric(relativeTo: .caption2) private var resultFontSize: CGFloat = 11
@ScaledMetric(relativeTo: .caption2) private var amountFontSize: CGFloat = 13
private var backgroundColor: Color {
isWin ? Color.green.opacity(Design.Opacity.heavy) : Color.red.opacity(Design.Opacity.heavy)
}
private var borderColor: Color {
isWin ? Color.green : Color.red
}
private var amountText: String {
if amount > 0 {
return "+$\(amount)"
} else {
return "-$\(abs(amount))"
}
}
var body: some View {
VStack(spacing: Design.Spacing.xxSmall) {
// Title (PP or 21+3)
Text(title)
.font(.system(size: titleFontSize, weight: .bold, design: .rounded))
.foregroundStyle(.white.opacity(Design.Opacity.strong))
// Result
Text(result)
.font(.system(size: resultFontSize, weight: .semibold, design: .rounded))
.foregroundStyle(.white)
.lineLimit(1)
.minimumScaleFactor(Design.MinScaleFactor.comfortable)
// Amount
Text(amountText)
.font(.system(size: amountFontSize, weight: .black, design: .rounded))
.foregroundStyle(isWin ? .yellow : .white)
}
.padding(.horizontal, Design.Spacing.small)
.padding(.vertical, Design.Spacing.xSmall)
.background(
RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
.fill(backgroundColor)
.overlay(
RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
.strokeBorder(borderColor, lineWidth: Design.LineWidth.medium)
)
)
.shadow(color: borderColor.opacity(Design.Opacity.medium), radius: Design.Shadow.radiusMedium)
.scaleEffect(isShowing ? 1.0 : 0.5)
.opacity(isShowing ? 1.0 : 0)
.offset(x: isShowing ? 0 : (showOnLeft ? -Design.Spacing.toastSlide : Design.Spacing.toastSlide))
.accessibilityElement(children: .combine)
.accessibilityLabel("\(title): \(result)")
.accessibilityValue(amountText)
.onAppear {
withAnimation(.spring(duration: Design.Animation.springDuration, bounce: 0.4).delay(showOnLeft ? 0 : Design.Animation.staggerDelay1)) {
isShowing = true
}
}
}
}
// MARK: - Previews
#Preview("Win Toast Left") {
ZStack {
Color.Table.felt.ignoresSafeArea()
HStack {
SideBetToastView(
title: "PP",
result: "Perfect Pair",
isWin: true,
amount: 625,
showOnLeft: true
)
Spacer()
}
.padding()
}
}
#Preview("Lose Toast Right") {
ZStack {
Color.Table.felt.ignoresSafeArea()
HStack {
Spacer()
SideBetToastView(
title: "21+3",
result: "No Hand",
isWin: false,
amount: -25,
showOnLeft: false
)
}
.padding()
}
}
#Preview("Both Toasts") {
ZStack {
Color.Table.felt.ignoresSafeArea()
HStack {
SideBetToastView(
title: "PP",
result: "Colored Pair",
isWin: true,
amount: 300,
showOnLeft: true
)
Spacer()
SideBetToastView(
title: "21+3",
result: "Flush",
isWin: true,
amount: 125,
showOnLeft: false
)
}
.padding()
}
}

View File

@ -0,0 +1,152 @@
//
// SideBetZoneView.swift
// Blackjack
//
// Side bet zone for Perfect Pairs and 21+3.
//
import SwiftUI
import CasinoKit
/// A tappable zone for placing side bets.
struct SideBetZoneView: View {
let betType: SideBetType
let betAmount: Int
let isEnabled: Bool
let isAtMax: Bool
let onTap: () -> Void
@ScaledMetric(relativeTo: .caption) private var labelFontSize: CGFloat = 11
@ScaledMetric(relativeTo: .caption2) private var payoutFontSize: CGFloat = 9
private var backgroundColor: Color {
switch betType {
case .perfectPairs:
return Color.SideBet.perfectPairs
case .twentyOnePlusThree:
return Color.SideBet.twentyOnePlusThree
}
}
private var payoutText: String {
switch betType {
case .perfectPairs:
return "25:1" // Best payout shown
case .twentyOnePlusThree:
return "100:1" // Best payout shown
}
}
var body: some View {
Button {
if isEnabled { onTap() }
} label: {
ZStack {
// Background
RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
.fill(backgroundColor)
.overlay(
RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
.strokeBorder(
Color.white.opacity(Design.Opacity.hint),
lineWidth: Design.LineWidth.thin
)
)
// Content
VStack(spacing: Design.Spacing.xxSmall) {
Text(betType.shortName)
.font(.system(size: labelFontSize, weight: .black, design: .rounded))
.foregroundStyle(.yellow)
Text(payoutText)
.font(.system(size: payoutFontSize, weight: .medium, design: .rounded))
.foregroundStyle(.white.opacity(Design.Opacity.strong))
}
// Chip indicator - top right
if betAmount > 0 {
VStack {
HStack {
Spacer()
ChipBadgeView(amount: betAmount, isMax: isAtMax)
.padding(Design.Spacing.xSmall)
}
Spacer()
}
}
}
}
.buttonStyle(.plain)
.opacity(isEnabled ? 1.0 : Design.Opacity.medium)
.accessibilityLabel("\(betType.displayName) bet, pays up to \(payoutText)")
.accessibilityHint(betAmount > 0 ? "Current bet $\(betAmount)" : "Double tap to place bet")
}
}
/// Small chip badge for side bet indicators.
struct ChipBadgeView: View {
let amount: Int
let isMax: Bool
var body: some View {
ZStack {
Circle()
.fill(isMax ? Color.gray : Color.yellow)
.frame(width: CasinoDesign.Size.chipBadge, height: CasinoDesign.Size.chipBadge)
Circle()
.strokeBorder(Color.white.opacity(Design.Opacity.almostFull), lineWidth: Design.LineWidth.thin)
.frame(width: CasinoDesign.Size.chipBadgeInner, height: CasinoDesign.Size.chipBadgeInner)
if isMax {
Text(String(localized: "MAX"))
.font(.system(size: Design.BaseFontSize.xxSmall, weight: .black))
.foregroundStyle(.white)
} else {
Text(formatCompact(amount))
.font(.system(size: Design.BaseFontSize.small, weight: .bold, design: .rounded))
.foregroundStyle(.black)
}
}
.shadow(color: .black.opacity(Design.Opacity.light), radius: Design.Shadow.radiusSmall, y: Design.Shadow.offsetSmall)
}
private func formatCompact(_ value: Int) -> String {
if value >= 1000 {
return "\(value / 1000)K"
}
return "\(value)"
}
}
// MARK: - Previews
#Preview("Perfect Pairs") {
ZStack {
Color.Table.felt.ignoresSafeArea()
SideBetZoneView(
betType: .perfectPairs,
betAmount: 0,
isEnabled: true,
isAtMax: false,
onTap: {}
)
.frame(width: 80, height: 70)
}
}
#Preview("21+3 with Bet") {
ZStack {
Color.Table.felt.ignoresSafeArea()
SideBetZoneView(
betType: .twentyOnePlusThree,
betAmount: 25,
isEnabled: true,
isAtMax: false,
onTap: {}
)
.frame(width: 80, height: 70)
}
}

View File

@ -16,15 +16,9 @@ let package = Package(
targets: ["CasinoKit"]
)
],
dependencies: [
.package(url: "https://github.com/devicekit/DeviceKit.git", from: "5.0.0")
],
targets: [
.target(
name: "CasinoKit",
dependencies: [
.product(name: "DeviceKit", package: "DeviceKit")
],
resources: [
.process("Resources")
]

View File

@ -99,7 +99,7 @@ public final class SoundManager {
}
}
/// Master volume (0.0 to 1.0).
/// Master volume (0.0 to 1.0). This is the linear slider value.
public var volume: Float = 1.0 {
didSet {
UserDefaults.standard.set(volume, forKey: "casinokit.soundVolume")
@ -107,6 +107,15 @@ public final class SoundManager {
}
}
/// Perceived volume using an exponential curve.
/// Human hearing is logarithmic, so linear volume feels wrong.
/// This curve makes 50% on the slider sound like 50% to human ears.
private var perceivedVolume: Float {
// Using a power of 3 gives a natural-feeling curve
// 0.0 -> 0.0, 0.5 -> 0.125, 1.0 -> 1.0
pow(volume, 3)
}
/// The bundle to load sound files from. Defaults to CasinoKit's bundle.
/// Set this to `.main` if sounds are in your app bundle instead.
public var soundBundle: Bundle = .module
@ -166,7 +175,7 @@ public final class SoundManager {
do {
let player = try AVAudioPlayer(contentsOf: url)
player.prepareToPlay()
player.volume = volume
player.volume = perceivedVolume
return player
} catch {
print("CasinoKit: Failed to create audio player for \(sound.rawValue): \(error)")
@ -193,8 +202,8 @@ public final class SoundManager {
/// Plays a system sound by ID.
private func playSystemSound(_ soundID: SystemSoundID) {
// Only play if volume is above threshold
guard volume > 0.1 else { return }
// Only play if volume is above threshold (system sounds can't be volume-adjusted)
guard perceivedVolume > 0.01 else { return }
AudioServicesPlaySystemSound(soundID)
}
@ -223,7 +232,7 @@ public final class SoundManager {
private func updatePlayerVolumes() {
for player in audioPlayers.values {
player.volume = volume
player.volume = perceivedVolume
}
}

View File

@ -215,6 +215,7 @@
},
"$%lld bet" : {
"comment" : "A value describing the bet amount in the accessibility label. The argument is the bet amount.",
"extractionState" : "stale",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
@ -423,6 +424,7 @@
},
"Betting disabled" : {
"comment" : "A hint that appears when a betting zone is disabled.",
"extractionState" : "stale",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
@ -713,6 +715,7 @@
},
"Double tap to place bet" : {
"comment" : "A hint text describing the action to take in the betting zone.",
"extractionState" : "stale",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
@ -1355,6 +1358,7 @@
},
"No bet" : {
"comment" : "A description of a zone with no active bet.",
"extractionState" : "stale",
"isCommentAutoGenerated" : true,
"localizations" : {
"en" : {
@ -2062,6 +2066,7 @@
}
},
"WIN" : {
"extractionState" : "stale",
"localizations" : {
"en" : {
"stringUnit" : {

View File

@ -22,6 +22,9 @@ public enum CasinoDesign {
public static let xLarge: CGFloat = 20
public static let xxLarge: CGFloat = 24
public static let xxxLarge: CGFloat = 32
/// Slide distance for toast animations
public static let toastSlide: CGFloat = 50
}
// MARK: - Corner Radius
@ -149,7 +152,7 @@ public enum CasinoDesign {
public static let actionButtonMinWidth: CGFloat = 80
/// Betting zone height.
public static let bettingZoneHeight: CGFloat = 80
public static let bettingZoneHeight: CGFloat = 70
}
// MARK: - Icon Sizes

View File

@ -1,196 +1,18 @@
////
//// DeviceInfo.swift
//// CasinoKit
////
//// Device detection utilities using DeviceKit.
////
//
// DeviceInfo.swift
// CasinoKit
//
// Device detection utilities using DeviceKit.
//
import Foundation
import UIKit
import SwiftUI
@_exported import DeviceKit
/// Device information utilities for responsive layouts.
///// Device information utilities for responsive layouts.
public enum DeviceInfo {
// MARK: - Current Device
/// The current device.
public static var current: Device {
Device.current
}
// MARK: - Device Size Categories
public static var isSmallDevice: Bool {
isSmallPhone || isPadMini
}
/// Whether the current device is a small iPhone (SE series).
/// Includes iPhone SE (1st, 2nd, 3rd gen) and their simulators.
public static var isSmallPhone: Bool {
let smallPhones: [Device] = [
// iPhone SE series
.iPhoneSE,
.iPhoneSE2,
.iPhoneSE3,
// Simulators
.simulator(.iPhoneSE),
.simulator(.iPhoneSE2),
.simulator(.iPhoneSE3)
]
return current.isOneOf(smallPhones)
}
/// Whether the current device is a standard iPhone (not SE, not Pro Max/Plus).
public static var isStandardPhone: Bool {
current.isPhone && !isSmallPhone && !isLargePhone
}
/// Whether the current device is a large iPhone (Pro Max, Plus models).
public static var isLargePhone: Bool {
let largePhones: [Device] = [
// Plus models
.iPhone6Plus, .iPhone6sPlus, .iPhone7Plus, .iPhone8Plus,
// Max models
.iPhoneXSMax, .iPhone11ProMax, .iPhone12ProMax,
.iPhone13ProMax, .iPhone14Plus, .iPhone14ProMax,
.iPhone15Plus, .iPhone15ProMax, .iPhone16Plus, .iPhone16ProMax,
// Simulators
.simulator(.iPhone6Plus), .simulator(.iPhone6sPlus),
.simulator(.iPhone7Plus), .simulator(.iPhone8Plus),
.simulator(.iPhoneXSMax), .simulator(.iPhone11ProMax),
.simulator(.iPhone12ProMax), .simulator(.iPhone13ProMax),
.simulator(.iPhone14Plus), .simulator(.iPhone14ProMax),
.simulator(.iPhone15Plus), .simulator(.iPhone15ProMax),
.simulator(.iPhone16Plus), .simulator(.iPhone16ProMax)
]
return current.isOneOf(largePhones)
}
/// Whether the current device is an iPhone.
public static var isPhone: Bool {
current.isPhone
}
/// Whether the current device is an iPad.
public static var isPad: Bool {
current.isPad
}
/// Whether the current device is an iPad mini.
/// iPad minis have smaller screens than standard iPads (7.9" or 8.3").
/// Uses screen diagonal as fallback for reliable detection on real devices.
public static var isPadMini: Bool {
// First try exact device match
let minis: [Device] = [
.iPadMini, .iPadMini2, .iPadMini3, .iPadMini4,
.iPadMini5, .iPadMini6, .iPadMiniA17Pro,
.simulator(.iPadMini), .simulator(.iPadMini2), .simulator(.iPadMini3),
.simulator(.iPadMini4), .simulator(.iPadMini5), .simulator(.iPadMini6),
.simulator(.iPadMiniA17Pro)
]
if current.isOneOf(minis) {
return true
}
// Fallback: Check screen diagonal (iPad minis are 7.9" or 8.3")
// Other iPads are 10.2" and larger
if current.isPad {
let diagonal = current.diagonal
return diagonal > 0 && diagonal < 9.0
}
return false
}
/// Whether the current device is a large iPad (Pro 12.9", 13").
public static var isLargePad: Bool {
let largePads: [Device] = [
.iPadPro12Inch, .iPadPro12Inch2, .iPadPro12Inch3,
.iPadPro12Inch4, .iPadPro12Inch5, .iPadPro12Inch6,
.iPadPro13M4,
.simulator(.iPadPro12Inch), .simulator(.iPadPro12Inch2),
.simulator(.iPadPro12Inch3), .simulator(.iPadPro12Inch4),
.simulator(.iPadPro12Inch5), .simulator(.iPadPro12Inch6),
.simulator(.iPadPro13M4)
]
return current.isOneOf(largePads)
}
/// Whether running in a simulator.
public static var isSimulator: Bool {
current.isSimulator
}
// MARK: - Screen Size Helpers
/// The diagonal screen size in inches.
public static var screenDiagonal: Double {
current.diagonal
}
/// The screen's pixels per inch.
public static var screenPPI: Int {
current.ppi ?? 0
}
// MARK: - Device Name
/// A human-readable description of the current device.
public static var deviceName: String {
current.description
}
/// The real device when running in simulator, or the device itself.
public static var realDevice: Device {
current.realDevice
}
/// Debug info about the current device (for troubleshooting).
public static var debugInfo: String {
let diag = String(format: "%.1f", screenDiagonal)
return "Device: \(current), diagonal: \(diag)\", isPadMini: \(isPadMini)"
}
}
// MARK: - SwiftUI Environment
/// Environment key for small phone detection.
private struct IsSmallPhoneKey: EnvironmentKey {
static let defaultValue: Bool = DeviceInfo.isSmallPhone
}
extension EnvironmentValues {
/// Whether the current device is a small phone (iPhone SE series).
public var isSmallPhone: Bool {
get { self[IsSmallPhoneKey.self] }
set { self[IsSmallPhoneKey.self] = newValue }
}
}
// MARK: - View Extension
extension View {
/// Applies different modifiers based on device size.
/// - Parameters:
/// - small: Modifier to apply on small phones (iPhone SE)
/// - standard: Modifier to apply on standard phones
/// - large: Modifier to apply on large phones (Pro Max, Plus)
/// - pad: Modifier to apply on iPads
@ViewBuilder
public func deviceAdaptive<Small: View, Standard: View, Large: View, Pad: View>(
small: (Self) -> Small,
standard: (Self) -> Standard,
large: (Self) -> Large,
pad: (Self) -> Pad
) -> some View {
if DeviceInfo.isPad {
pad(self)
} else if DeviceInfo.isSmallPhone {
small(self)
} else if DeviceInfo.isLargePhone {
large(self)
} else {
standard(self)
}
UIDevice.current.userInterfaceIdiom == .pad
}
}

View File

@ -28,6 +28,9 @@ public struct ActionButton: View {
private let fontSize: CGFloat = 18
private let iconSize: CGFloat = 20
/// Minimum button width to prevent tiny buttons for short words like "Hit"
private let minButtonWidth: CGFloat = 35
/// Creates an action button.
/// - Parameters:
/// - title: The button title.
@ -58,15 +61,19 @@ public struct ActionButton: View {
}
Text(title)
.font(.system(size: fontSize, weight: .bold))
.lineLimit(1)
.minimumScaleFactor(CasinoDesign.MinScaleFactor.relaxed)
}
.foregroundStyle(style.foregroundColor)
.padding(.horizontal, CasinoDesign.Spacing.xxLarge)
.frame(minWidth: minButtonWidth)
.padding(.horizontal, CasinoDesign.Spacing.xLarge)
.padding(.vertical, CasinoDesign.Spacing.medium)
.background(style.background)
.shadow(color: style.shadowColor, radius: CasinoDesign.Shadow.radiusMedium)
}
.disabled(!isEnabled)
.opacity(isEnabled ? 1.0 : CasinoDesign.Opacity.medium)
.accessibilityLabel(title)
}
}
@ -78,12 +85,13 @@ public enum ActionButtonStyle {
case destructive
/// Secondary subtle button
case secondary
/// Custom color button for game-specific actions
case custom(Color)
var foregroundColor: Color {
switch self {
case .primary: return .black
case .destructive: return .white
case .secondary: return .white
case .destructive, .secondary, .custom: return .white
}
}
@ -105,6 +113,9 @@ public enum ActionButtonStyle {
case .secondary:
Capsule()
.fill(Color.white.opacity(CasinoDesign.Opacity.hint))
case .custom(let color):
Capsule()
.fill(color)
}
}
@ -112,7 +123,7 @@ public enum ActionButtonStyle {
switch self {
case .primary: return .yellow.opacity(CasinoDesign.Opacity.light)
case .destructive: return .red.opacity(CasinoDesign.Opacity.light)
case .secondary: return .clear
case .secondary, .custom: return .clear
}
}
}
@ -125,7 +136,21 @@ public enum ActionButtonStyle {
ActionButton("Deal", icon: "play.fill", style: .primary) { }
ActionButton("Clear", icon: "xmark.circle", style: .destructive) { }
ActionButton("Stand", style: .secondary) { }
ActionButton("Hit", style: .primary, isEnabled: false) { }
ActionButton("Hit", style: .custom(.green)) { }
ActionButton("Disabled", style: .primary, isEnabled: false) { }
}
}
}
#Preview("BlackJack Action Buttons") {
ZStack {
Color.CasinoTable.felt.ignoresSafeArea()
HStack(spacing: CasinoDesign.Spacing.medium) {
ActionButton("Hit", style: .custom(.green)) { }
ActionButton("Stand", style: .secondary) { }
ActionButton("Double", style: .custom(Color.purple)) {}
ActionButton("Split", style: .custom(Color.yellow)) {}
}
}
}

View File

@ -1,194 +0,0 @@
//
// HandDisplayView.swift
// CasinoKit
//
// A generic view for displaying a hand of cards with optional overlap.
//
import SwiftUI
/// A view displaying a hand of cards with configurable layout.
public struct HandDisplayView: View {
/// The cards in the hand.
public let cards: [Card]
/// Which cards are face up (by index).
public let cardsFaceUp: [Bool]
/// The width of each card.
public let cardWidth: CGFloat
/// The overlap between cards (negative = overlap, positive = gap).
public let cardSpacing: CGFloat
/// Whether this hand is the winner.
public let isWinner: Bool
/// Optional label to show (e.g., "PLAYER", "DEALER").
public let label: String?
/// Optional value badge to show.
public let value: Int?
/// Badge color for the value.
public let valueColor: Color
/// Maximum number of card slots to reserve space for.
public let maxCards: Int
// Layout
@ScaledMetric(relativeTo: .headline) private var labelFontSize: CGFloat = 14
@ScaledMetric(relativeTo: .caption) private var winBadgeFontSize: CGFloat = 10
/// Creates a hand display view.
/// - Parameters:
/// - cards: The cards to display.
/// - cardsFaceUp: Which cards are face up.
/// - cardWidth: Width of each card.
/// - cardSpacing: Spacing between cards (negative for overlap).
/// - isWinner: Whether to show winner styling.
/// - label: Optional label above cards.
/// - value: Optional value badge to show.
/// - valueColor: Color for value badge.
/// - maxCards: Max cards to reserve space for (default: 3).
public init(
cards: [Card],
cardsFaceUp: [Bool] = [],
cardWidth: CGFloat = 45,
cardSpacing: CGFloat = -12,
isWinner: Bool = false,
label: String? = nil,
value: Int? = nil,
valueColor: Color = .blue,
maxCards: Int = 3
) {
self.cards = cards
self.cardsFaceUp = cardsFaceUp
self.cardWidth = cardWidth
self.cardSpacing = cardSpacing
self.isWinner = isWinner
self.label = label
self.value = value
self.valueColor = valueColor
self.maxCards = maxCards
}
/// Card height based on aspect ratio.
private var cardHeight: CGFloat {
cardWidth * CasinoDesign.Size.cardAspectRatio
}
/// Fixed container width based on max cards.
private var containerWidth: CGFloat {
if maxCards <= 1 {
return cardWidth + CasinoDesign.Spacing.xSmall * 2
}
let cardsWidth = cardWidth + (cardWidth + cardSpacing) * CGFloat(maxCards - 1)
return cardsWidth + CasinoDesign.Spacing.xSmall * 2
}
/// Fixed container height.
private var containerHeight: CGFloat {
cardHeight + CasinoDesign.Spacing.xSmall * 2
}
public var body: some View {
VStack(spacing: CasinoDesign.Spacing.small) {
// Label with optional value badge
if label != nil || value != nil {
HStack(spacing: CasinoDesign.Spacing.small) {
if let label = label {
Text(label)
.font(.system(size: labelFontSize, weight: .bold, design: .rounded))
.foregroundStyle(.white)
}
if let value = value, !cards.isEmpty {
ValueBadge(value: value, color: valueColor)
}
}
.frame(minHeight: CasinoDesign.Spacing.xxxLarge)
}
// Cards container
ZStack {
// Fixed-size container
Color.clear
.frame(width: containerWidth, height: containerHeight)
// Cards
HStack(spacing: cards.isEmpty ? CasinoDesign.Spacing.small : cardSpacing) {
if cards.isEmpty {
// Placeholders
ForEach(0..<min(2, maxCards), id: \.self) { _ in
CardPlaceholderView(width: cardWidth)
}
} else {
ForEach(cards.indices, id: \.self) { index in
let isFaceUp = index < cardsFaceUp.count ? cardsFaceUp[index] : true
CardView(
card: cards[index],
isFaceUp: isFaceUp,
cardWidth: cardWidth
)
.zIndex(Double(index))
}
}
}
}
.background(
RoundedRectangle(cornerRadius: CasinoDesign.CornerRadius.small)
.strokeBorder(
isWinner ? Color.yellow : Color.clear,
lineWidth: CasinoDesign.LineWidth.medium
)
)
.overlay(alignment: .bottom) {
if isWinner {
Text(String(localized: "WIN", bundle: .module))
.font(.system(size: winBadgeFontSize, weight: .black))
.foregroundStyle(.black)
.padding(.horizontal, CasinoDesign.Spacing.small)
.padding(.vertical, CasinoDesign.Spacing.xxSmall)
.background(
Capsule()
.fill(Color.yellow)
)
.offset(y: CasinoDesign.Spacing.small)
}
}
}
}
}
#Preview {
ZStack {
Color.CasinoTable.felt.ignoresSafeArea()
HStack(spacing: 40) {
HandDisplayView(
cards: [
Card(suit: .hearts, rank: .ace),
Card(suit: .spades, rank: .king)
],
cardsFaceUp: [true, true],
isWinner: true,
label: "PLAYER",
value: 21,
valueColor: .blue
)
HandDisplayView(
cards: [
Card(suit: .diamonds, rank: .seven),
Card(suit: .clubs, rank: .ten)
],
cardsFaceUp: [true, false],
label: "DEALER",
value: 17,
valueColor: .red
)
}
}
}

View File

@ -1,168 +0,0 @@
//
// BettingZone.swift
// CasinoKit
//
// A reusable betting zone for casino table layouts.
//
import SwiftUI
/// A tappable betting zone with label and chip display.
public struct BettingZone: View {
/// The zone label (e.g., "PLAYER", "TIE", "INSURANCE").
public let label: String
/// Optional payout info (e.g., "1:1", "8:1").
public let payoutInfo: String?
/// Current bet amount (0 if no bet).
public let betAmount: Int
/// Whether the zone is enabled for betting.
public let isEnabled: Bool
/// Action when the zone is tapped.
public let onTap: () -> Void
/// Background color for the zone.
public let backgroundColor: Color
/// Text color.
public let textColor: Color
// Layout
@ScaledMetric(relativeTo: .headline) private var labelFontSize: CGFloat = 16
@ScaledMetric(relativeTo: .caption) private var payoutFontSize: CGFloat = 12
/// Creates a betting zone.
public init(
label: String,
payoutInfo: String? = nil,
betAmount: Int = 0,
isEnabled: Bool = true,
backgroundColor: Color = .blue.opacity(0.2),
textColor: Color = .white,
onTap: @escaping () -> Void
) {
self.label = label
self.payoutInfo = payoutInfo
self.betAmount = betAmount
self.isEnabled = isEnabled
self.backgroundColor = backgroundColor
self.textColor = textColor
self.onTap = onTap
}
public var body: some View {
Button(action: onTap) {
ZStack {
// Background
RoundedRectangle(cornerRadius: CasinoDesign.CornerRadius.medium)
.fill(backgroundColor)
.overlay(
RoundedRectangle(cornerRadius: CasinoDesign.CornerRadius.medium)
.strokeBorder(
textColor.opacity(CasinoDesign.Opacity.light),
lineWidth: CasinoDesign.LineWidth.thin
)
)
// Content
VStack(spacing: CasinoDesign.Spacing.xxSmall) {
Text(label)
.font(.system(size: labelFontSize, weight: .bold))
.foregroundStyle(textColor)
if let payout = payoutInfo {
Text(payout)
.font(.system(size: payoutFontSize, weight: .medium))
.foregroundStyle(textColor.opacity(CasinoDesign.Opacity.medium))
}
}
// Chip badge for bet amount
if betAmount > 0 {
ChipBadge(amount: betAmount)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)
.padding(CasinoDesign.Spacing.xSmall)
}
}
}
.buttonStyle(.plain)
.disabled(!isEnabled)
.accessibilityLabel(label)
.accessibilityValue(betAmount > 0 ? "$\(betAmount) bet" : "No bet")
.accessibilityHint(isEnabled ? "Double tap to place bet" : "Betting disabled")
}
}
/// A small chip badge showing bet amount.
public struct ChipBadge: View {
public let amount: Int
private let badgeSize: CGFloat = 28
private let fontSize: CGFloat = 10
public init(amount: Int) {
self.amount = amount
}
public var body: some View {
ZStack {
Circle()
.fill(Color.yellow)
.frame(width: badgeSize, height: badgeSize)
Circle()
.strokeBorder(Color.orange, lineWidth: 2)
.frame(width: badgeSize - 4, height: badgeSize - 4)
Text(formattedAmount)
.font(.system(size: fontSize, weight: .bold))
.foregroundStyle(.black)
.minimumScaleFactor(0.5)
}
}
private var formattedAmount: String {
if amount >= 1_000_000 {
return "\(amount / 1_000_000)M"
} else if amount >= 1_000 {
return "\(amount / 1_000)K"
}
return "\(amount)"
}
}
#Preview {
ZStack {
Color.CasinoTable.felt.ignoresSafeArea()
HStack(spacing: 20) {
BettingZone(
label: "PLAYER",
payoutInfo: "1:1",
betAmount: 0,
backgroundColor: .blue.opacity(0.2)
) { }
.frame(width: 120, height: 80)
BettingZone(
label: "TIE",
payoutInfo: "8:1",
betAmount: 500,
backgroundColor: .green.opacity(0.2)
) { }
.frame(width: 80, height: 80)
BettingZone(
label: "BANKER",
payoutInfo: "0.95:1",
betAmount: 2500,
backgroundColor: .red.opacity(0.2)
) { }
.frame(width: 120, height: 80)
}
}
}