SPB Git

Repository Public License

DominoViews.swift 20.1 KB 421 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/DominoCity/DominoViews.swift10// Description      : Domino City — SwiftUI flow: level select, play screen with11//                    HUD, tutorial coach, results, progress saving and autoplay12//                    sequencing.13// Module           : Games14// Repository       : https://git.spboucher.ai/orix-arcade15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI9293struct DominoRootView: View {94    let onExit: () -> Void95    @Environment(ArcadeServices.self) private var services96    @State private var playing: DominoLevel?97    @State private var started = false9899    var body: some View {100        ZStack {101            if let level = playing {102                DominoPlayView(level: level, onSelect: { next in withAnimation(OrixMotion.decorative(OrixMotion.snappy)) { playing = next } }, onExit: onExit)103                    .id(level.id)104                    .transition(.opacity)105            } else {106                DominoLevelSelect(onPlay: { level in withAnimation(OrixMotion.decorative(OrixMotion.snappy)) { playing = level } }, onExit: onExit)107                    .transition(.opacity)108            }109        }110        .onAppear {111            guard !started else { return }112            started = true113            if let requested = LaunchOptions.int("Level"), let level = DominoLevels.level(requested) {114                playing = level115            } else if LaunchOptions.autoplay {116                playing = DominoLevels.all.first117            }118        }119    }120}121122// MARK: - Level select123124struct DominoLevelSelect: View {125    let onPlay: (DominoLevel) -> Void126    let onExit: () -> Void127    @Environment(ArcadeServices.self) private var services128129    var body: some View {130        let save = services.save.domino131        ZStack {132            AuroraBackground(theme: .domino)133            ScrollView {134                VStack(alignment: .leading, spacing: OrixSpace.md) {135                    HStack(spacing: OrixSpace.sm) {136                        OrixIconButton(systemImage: "chevron.left", label: "Back to arcade", action: onExit)137                            .accessibilityIdentifier("domino-back")138                        VStack(alignment: .leading, spacing: 0) {139                            Text("DOMINO CITY").font(OrixFont.overline).tracking(2).foregroundStyle(GameTheme.domino.primary)140                            Text("Choose a block").font(OrixFont.title).foregroundStyle(OrixColor.textPrimary)141                        }142                        Spacer()143                        OrixChip(text: "\(save.totalStars)/\(DominoSave.levelCount * 3)", systemImage: "star.fill", tint: OrixColor.gold)144                            .accessibilityLabel("\(save.totalStars) of \(DominoSave.levelCount * 3) stars")145                    }146                    HStack(spacing: OrixSpace.sm) {147                        Image(systemName: "hand.draw.fill").font(.system(size: 20, weight: .bold)).foregroundStyle(GameTheme.domino.primary)148                        Text("Drag back to aim, release to launch. Light every golden target — longer chains and spare impulses earn more stars.")149                            .font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary)150                    }151                    .frame(maxWidth: .infinity, alignment: .leading)152                    .glassPanel(radius: OrixRadius.md, tint: GameTheme.domino.primary, padding: OrixSpace.sm)153154                    LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: OrixSpace.xs), count: 3), spacing: OrixSpace.xs) {155                        ForEach(DominoLevels.all) { level in156                            DominoLevelTile(level: level, stars: save.bestStars(level.id), score: save.bestScore(level.id),157                                            unlocked: save.isUnlocked(level.id), isCurrent: level.id == save.highestUnlocked) {158                                onPlay(level)159                            }160                        }161                    }162                }163                .padding(.horizontal, OrixSpace.md)164                .padding(.top, OrixSpace.xs)165                .padding(.bottom, OrixSpace.xl)166            }167            .scrollIndicators(.hidden)168        }169    }170}171172struct DominoLevelTile: View {173    let level: DominoLevel174    let stars: Int175    let score: Int176    let unlocked: Bool177    let isCurrent: Bool178    let action: () -> Void179    @Environment(ArcadeServices.self) private var services180181    var body: some View {182        Button {183            services.feedbackTap()184            action()185        } label: {186            VStack(spacing: 5) {187                if unlocked {188                    Text("\(level.id)")189                        .font(.system(size: 30, weight: .black, design: .rounded))190                        .foregroundStyle(stars > 0 ? AnyShapeStyle(GameTheme.domino.gradient) : AnyShapeStyle(OrixColor.textPrimary))191                } else {192                    Image(systemName: "lock.fill").font(.system(size: 22, weight: .bold)).foregroundStyle(OrixColor.textTertiary).frame(height: 36)193                }194                Text(level.name).font(OrixFont.caption).foregroundStyle(unlocked ? OrixColor.textSecondary : OrixColor.textTertiary)195                    .lineLimit(1).minimumScaleFactor(0.7)196                HStack(spacing: 3) {197                    ForEach(0..<3, id: \.self) { index in198                        Image(systemName: "star.fill").font(.system(size: 12, weight: .black))199                            .foregroundStyle(index < stars ? OrixColor.gold : Color.white.opacity(0.14))200                    }201                }202                Text(score > 0 ? score.formatted() : " ").font(OrixFont.overline.monospacedDigit()).foregroundStyle(OrixColor.textTertiary)203            }204            .frame(maxWidth: .infinity, minHeight: 112)205            .glassPanel(radius: OrixRadius.md, tint: unlocked ? GameTheme.domino.primary : .white, padding: OrixSpace.xs)206            .overlay(207                RoundedRectangle(cornerRadius: OrixRadius.md, style: .continuous)208                    .strokeBorder(GameTheme.domino.primary.opacity(isCurrent && unlocked ? 0.9 : 0), lineWidth: 1.5)209            )210            .opacity(unlocked ? 1 : 0.6)211        }212        .buttonStyle(OrixPressStyle())213        .disabled(!unlocked)214        .accessibilityLabel(unlocked ? "Level \(level.id), \(level.name), \(stars) of 3 stars" : "Level \(level.id), locked")215        .accessibilityHint(unlocked ? "Plays this level" : "Clear the previous level to unlock")216        .accessibilityIdentifier("domino-level-\(level.id)")217    }218}219220// MARK: - Play221222struct DominoPlayView: View {223    let level: DominoLevel224    /// `nil` returns to the level list.225    let onSelect: (DominoLevel?) -> Void226    let onExit: () -> Void227228    @Environment(ArcadeServices.self) private var services229    @State private var session: DominoSession230    @State private var scene: DominoScene?231    @State private var isPaused = false232    @State private var showResults = false233    @State private var outcome: DominoSave.RecordOutcome?234    @State private var previousBest = 0235    @State private var attemptStart = Date()236237    init(level: DominoLevel, onSelect: @escaping (DominoLevel?) -> Void, onExit: @escaping () -> Void) {238        self.level = level239        self.onSelect = onSelect240        self.onExit = onExit241        _session = State(initialValue: DominoSession(level: level))242    }243244    private var nextLevel: DominoLevel? { DominoLevels.level(level.id + 1) }245246    var body: some View {247        GameChrome(theme: .domino, title: "Domino City", isPaused: $isPaused, canPause: session.result == nil,248                   pauseDetail: "Level \(level.id) · \(level.name)", onRestart: restart, onExit: quit) {249            ZStack {250                if let scene { GameSceneView(scene: scene, isPaused: isPaused) } else { Color(hex: DominoArt.night).ignoresSafeArea() }251                hud252                if showResults, let result = session.result { results(result) }253            }254        }255        .onAppear(perform: start)256        .onChange(of: session.result) { _, result in257            guard let result else { return }258            commit(result)259        }260        .onChange(of: session.hasLaunched) { _, launched in261            if launched, level.id == 1, !services.save.domino.tutorialDone { services.store.update { $0.domino.tutorialDone = true } }262        }263    }264265    // MARK: HUD266267    private var hud: some View {268        let leftHanded = services.settings.leftHanded269        return VStack(spacing: 0) {270            VStack(alignment: .leading, spacing: 6) {271                VStack(alignment: .leading, spacing: 0) {272                    Text("LEVEL \(level.id)").font(OrixFont.overline).tracking(2).foregroundStyle(GameTheme.domino.primary)273                    Text(level.name).font(OrixFont.hud(20)).foregroundStyle(OrixColor.textPrimary)274                }275                HStack(spacing: 6) {276                    HUDPill(systemImage: "star.fill", text: "\(session.targetsHit)/\(level.targets.count)", tint: OrixColor.gold, label: "Targets")277                    HUDPill(systemImage: "link", text: "\(session.chain)", tint: Color(hex: 0x7FD8FF), label: "Chain")278                    if !level.gems.isEmpty {279                        HUDPill(systemImage: "diamond.fill", text: "\(session.gems)/\(level.gems.count)", tint: OrixColor.cyan, label: "Gems")280                    }281                }282            }283            .frame(maxWidth: .infinity, alignment: leftHanded ? .trailing : .leading)284            .padding(leftHanded ? .leading : .trailing, 60)285            .padding(.horizontal, OrixSpace.md)286            .padding(.top, 6)287288            Spacer()289290            if session.result == nil {291                if !session.hasLaunched {292                    if level.id == 1, !services.save.domino.tutorialDone {293                        CoachMark(text: session.isAiming ? "Now let go to launch!" : "Drag back anywhere on the screen to aim, then release.",294                                  systemImage: session.isAiming ? "hand.raised.fill" : "hand.draw.fill", theme: .domino)295                            .padding(.bottom, OrixSpace.sm)296                            .accessibilityIdentifier("domino-coach")297                    } else {298                        Text(level.hint)299                            .font(OrixFont.caption).foregroundStyle(OrixColor.textPrimary)300                            .multilineTextAlignment(.center)301                            .padding(.horizontal, OrixSpace.sm).padding(.vertical, 7)302                            .background(Color.black.opacity(0.55), in: Capsule())303                            .padding(.horizontal, OrixSpace.lg)304                            .padding(.bottom, OrixSpace.sm)305                            .transition(.opacity)306                            .allowsHitTesting(false)307                    }308                }309                HStack(spacing: OrixSpace.sm) {310                    if leftHanded { restartButton }311                    impulses312                    Spacer()313                    if !leftHanded { restartButton }314                }315                .padding(.horizontal, OrixSpace.md)316                .padding(.bottom, 4)317            }318        }319        .animation(OrixMotion.decorative(OrixMotion.snappy), value: session.hasLaunched)320    }321322    private var restartButton: some View {323        OrixIconButton(systemImage: "arrow.counterclockwise", label: "Restart level", tint: GameTheme.domino.primary, action: restart)324            .accessibilityIdentifier("domino-restart")325    }326327    private var impulses: some View {328        HStack(spacing: 7) {329            Text("IMPULSES").font(OrixFont.overline).tracking(1.2).foregroundStyle(OrixColor.textSecondary)330            ForEach(0..<level.impulses, id: \.self) { index in331                Circle()332                    .fill(index < session.impulsesLeft ? AnyShapeStyle(GameTheme.domino.gradient) : AnyShapeStyle(Color.white.opacity(0.14)))333                    .frame(width: 16, height: 16)334                    .overlay(Circle().strokeBorder(Color.white.opacity(0.35), lineWidth: 1))335            }336        }337        .padding(.horizontal, 14)338        .frame(minHeight: OrixSpace.hit)339        .background(Color.black.opacity(0.5), in: Capsule())340        .accessibilityElement(children: .ignore)341        .accessibilityLabel("Impulses left")342        .accessibilityValue("\(session.impulsesLeft) of \(level.impulses)")343    }344345    private func results(_ result: DominoResult) -> some View {346        let stats = result.stats347        let rows = [348            ResultRow(label: "Targets", value: "\(stats.targetsHit)/\(stats.targetsTotal)", systemImage: "star.fill", highlight: result.cleared),349            ResultRow(label: "Chain", value: "\(stats.chain) pieces", systemImage: "link"),350            ResultRow(label: "Impulses left", value: "\(stats.impulsesLeft)", systemImage: "circle.circle.fill"),351        ] + (level.gems.isEmpty ? [] : [ResultRow(label: "Gems", value: "\(stats.gems)/\(level.gems.count)", systemImage: "diamond.fill")])352        let record = result.cleared && (outcome?.isNewBestScore ?? false) && previousBest > 0353        let subtitle: String = {354            if !result.cleared { return "\(stats.targetsTotal - stats.targetsHit) golden target\(stats.targetsTotal - stats.targetsHit == 1 ? "" : "s") still standing." }355            if let unlocked = outcome?.unlockedLevel, let next = DominoLevels.level(unlocked) { return "Level \(unlocked) unlocked: \(next.name)" }356            if result.stars < 3 { return "3 stars at \(level.threeStarScore.formatted()) points." }357            return "Flawless demolition."358        }()359        let canAdvance = result.cleared && nextLevel != nil360        return ResultsCard(theme: .domino, title: result.cleared ? "Block Cleared!" : "So Close", subtitle: subtitle,361                           stars: result.stars, score: result.score, isNewRecord: record, success: result.cleared, rows: rows,362                           primaryTitle: canAdvance ? "Next Level" : "Retry", primaryIcon: canAdvance ? "arrow.right" : "arrow.counterclockwise",363                           onPrimary: { if canAdvance { onSelect(nextLevel) } else { restart() } },364                           secondaryTitle: canAdvance ? "Retry" : "Levels", secondaryIcon: canAdvance ? "arrow.counterclockwise" : "square.grid.3x3.fill",365                           onSecondary: { if canAdvance { restart() } else { onSelect(nil) } },366                           onExit: onExit)367            .transition(.opacity)368    }369370    // MARK: Flow371372    private func start() {373        guard scene == nil else { return }374        let created = DominoScene(services: services, level: level, session: session)375        if LaunchOptions.autoplay { created.botShots = level.solution }376        scene = created377        attemptStart = Date()378        services.setResumeNote("Level \(level.id) · \(level.name)")379        services.store.update { $0.domino.lastLevel = level.id }380    }381382    private func restart() {383        services.audio.play(.whoosh)384        // An abandoned attempt still counts as play time.385        if session.result == nil { services.addPlayTime(game: .dominoCity, duration: Date().timeIntervalSince(attemptStart)) }386        showResults = false387        outcome = nil388        attemptStart = Date()389        scene?.restart()390    }391392    private func quit() {393        if session.result == nil { services.addPlayTime(game: .dominoCity, duration: Date().timeIntervalSince(attemptStart)) }394        onExit()395    }396397    private func commit(_ result: DominoResult) {398        previousBest = services.save.domino.bestScore(level.id)399        var recorded: DominoSave.RecordOutcome?400        services.store.update { recorded = $0.domino.record(result) }401        outcome = recorded402        let stars = String(repeating: "★", count: result.stars) + String(repeating: "☆", count: 3 - result.stars)403        services.recordSession(game: .dominoCity, score: result.score, duration: max(result.duration, Date().timeIntervalSince(attemptStart)),404                               headline: result.cleared ? "Level \(level.id) · \(stars)" : "Level \(level.id) · not cleared",405                               isRecord: result.cleared && (recorded?.isNewBestScore ?? false) && previousBest > 0)406        DominoCityGame.awardAchievements(for: result, save: services.save.domino, services: services)407        if LaunchOptions.autoplay { DominoAutoplayLog.append(result) }408        Task {409            try? await Task.sleep(for: .milliseconds(650))410            guard session.result == result else { return }411            withAnimation(OrixMotion.decorative(OrixMotion.snappy)) { showResults = true }412            if LaunchOptions.autoplay {413                try? await Task.sleep(for: .milliseconds(1800))414                guard session.result == result else { return }415                // The bot stops after the last level unless `-ORIXDominoLoop YES` asks for an endless soak run.416                if let next = nextLevel { onSelect(next) } else if LaunchOptions.flag("DominoLoop") { onSelect(DominoLevels.all.first) }417            }418        }419    }420}421
Files main
Menu

Theme