| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224 |
- import Foundation
- import Combine
- struct BoardSnapshot: Codable {
- var values: [Int]
- var notes: [[Int]]
- }
- struct GameSession: Codable, Identifiable {
- let id: String
- let difficulty: Difficulty
- let dayKey: String?
- let givens: [Int]
- let solution: [Int]
- var values: [Int]
- var notes: [[Int]] = Array(repeating: [], count: 81)
- var history: [BoardSnapshot] = []
- var mistakes = 0
- var elapsed = 0
- var hintsRemaining = 3
- var completed = false
- var lastPlayed = Date()
- var failed: Bool { mistakes >= 3 && !completed }
- var inProgress: Bool { !completed && !failed }
- var filledCount: Int { values.indices.filter { values[$0] != 0 && values[$0] == solution[$0] }.count }
- var progress: Double {
- let emptyCount = givens.filter { $0 == 0 }.count
- return Double(filledCount - givens.filter { $0 != 0 }.count) / Double(max(1, emptyCount))
- }
- var score: Int {
- let filled = values.indices.filter { givens[$0] == 0 && values[$0] == solution[$0] }.count
- return max(0, filled * 100 * difficulty.multiplier - mistakes * 50 - (3 - hintsRemaining) * 100)
- }
- var timeText: String { Self.formatTime(elapsed) }
- static func formatTime(_ seconds: Int) -> String {
- if seconds >= 3600 { return String(format: "%d:%02d:%02d", seconds / 3600, seconds / 60 % 60, seconds % 60) }
- return String(format: "%02d:%02d", seconds / 60, seconds % 60)
- }
- mutating func checkpoint() {
- history.append(BoardSnapshot(values: values, notes: notes))
- if history.count > 100 { history.removeFirst() }
- }
- }
- struct PlayerStatistics: Codable {
- var started = 0
- var won = 0
- var bestScore = 0
- var totalSeconds = 0
- var bestTimes: [String: Int] = [:]
- var winsByDifficulty: [String: Int] = [:]
- }
- struct PlayerSettings: Codable {
- var highlightPeers = true
- var highlightSameNumbers = true
- var removeNotes = true
- var haptics = true
- }
- private struct SavedLibrary: Codable {
- var version = 1
- var sessions: [String: GameSession] = [:]
- var statistics = PlayerStatistics()
- var settings = PlayerSettings()
- }
- @MainActor final class GameStore: ObservableObject {
- @Published private var library: SavedLibrary
- private let defaults: UserDefaults
- private let saveKey = "JokerSudoku.library.v1"
- @Published var currentGameID: String?
- @Published var isGenerating = false
- @Published var storageWarning: String?
- init(defaults: UserDefaults = .standard) {
- self.defaults = defaults
- if let data = defaults.data(forKey: saveKey) {
- do { library = try JSONDecoder().decode(SavedLibrary.self, from: data) }
- catch {
- // Keep the original data available for recovery instead of overwriting it silently.
- defaults.set(data, forKey: "JokerSudoku.library.recovery")
- library = SavedLibrary()
- storageWarning = "Your previous save could not be read. A recovery backup has been kept. You can start a new game."
- }
- } else { library = SavedLibrary() }
- }
- var statistics: PlayerStatistics { library.statistics }
- var settings: PlayerSettings {
- get { library.settings }
- set { library.settings = newValue; save() }
- }
- var currentGame: GameSession? { currentGameID.flatMap { library.sessions[$0] } }
- var resumableGame: GameSession? {
- library.sessions.values.filter(\.inProgress).max { $0.lastPlayed < $1.lastPlayed }
- }
- var completedDailyCount: Int { library.sessions.values.filter { $0.dayKey != nil && $0.completed }.count }
- func dailySession(for date: Date) -> GameSession? { library.sessions["daily-" + SudokuEngine.dateKey(date)] }
- func completedDays(in month: Date) -> Int {
- let prefix = String(SudokuEngine.dateKey(month).prefix(7))
- return library.sessions.values.filter { $0.completed && ($0.dayKey?.hasPrefix(prefix) ?? false) }.count
- }
- func startGame(difficulty: Difficulty, day: Date? = nil) async {
- guard !isGenerating else { return }
- isGenerating = true
- defer { isGenerating = false }
- let key = day.map { SudokuEngine.dateKey($0) }
- let seed = key.map(SudokuEngine.dailySeed) ?? UInt64.random(in: 0...UInt64.max)
- let puzzle = await Task.detached(priority: .userInitiated) {
- SudokuEngine.generate(difficulty: difficulty, seed: seed)
- }.value
- let id = key.map { "daily-" + $0 } ?? "classic"
- library.sessions[id] = GameSession(id: id, difficulty: difficulty, dayKey: key,
- givens: puzzle.givens, solution: puzzle.solution, values: puzzle.givens)
- library.statistics.started += 1
- currentGameID = id
- save()
- }
- func resume(_ game: GameSession) {
- guard game.inProgress else { return }
- currentGameID = game.id
- library.sessions[game.id]?.lastPlayed = Date()
- save()
- }
- func leaveGame() { save(); currentGameID = nil }
- func tick() {
- guard let id = currentGameID, library.sessions[id]?.inProgress == true else { return }
- library.sessions[id]?.elapsed += 1
- library.sessions[id]?.lastPlayed = Date()
- save()
- }
- func enter(_ digit: Int, at index: Int, notesMode: Bool) {
- guard (0..<81).contains(index), (1...9).contains(digit) else { return }
- update { game in
- guard game.givens[index] == 0 else { return }
- if notesMode {
- guard game.values[index] == 0 else { return }
- game.checkpoint()
- if game.notes[index].contains(digit) { game.notes[index].removeAll { $0 == digit } }
- else { game.notes[index].append(digit); game.notes[index].sort() }
- } else {
- guard game.values[index] != digit else { return }
- game.checkpoint()
- game.values[index] = digit
- game.notes[index] = []
- if digit != game.solution[index] { game.mistakes += 1 }
- else if self.settings.removeNotes {
- for peer in 0..<81 where SudokuEngine.arePeers(index, peer) { game.notes[peer].removeAll { $0 == digit } }
- }
- }
- }
- }
- func erase(at index: Int) {
- guard (0..<81).contains(index) else { return }
- update { game in
- guard game.givens[index] == 0, game.values[index] != 0 || !game.notes[index].isEmpty else { return }
- game.checkpoint(); game.values[index] = 0; game.notes[index] = []
- }
- }
- func undo() {
- update { game in
- guard let snapshot = game.history.popLast() else { return }
- game.values = snapshot.values; game.notes = snapshot.notes
- }
- }
- @discardableResult func hint(at selected: Int?) -> Int? {
- guard let game = currentGame, game.inProgress, game.hintsRemaining > 0 else { return nil }
- let index = selected.flatMap { (0..<81).contains($0) && game.values[$0] != game.solution[$0] ? $0 : nil }
- ?? game.values.indices.first { game.values[$0] != game.solution[$0] }
- guard let index else { return nil }
- update { game in
- game.checkpoint()
- game.values[index] = game.solution[index]
- game.notes[index] = []
- game.hintsRemaining -= 1
- if self.settings.removeNotes {
- let digit = game.solution[index]
- for peer in 0..<81 where SudokuEngine.arePeers(index, peer) {
- game.notes[peer].removeAll { $0 == digit }
- }
- }
- }
- return index
- }
- func restart() async {
- guard let game = currentGame else { return }
- if let dayKey = game.dayKey {
- // Daily restarts always retain that day's puzzle, regardless of timezone changes.
- var fresh = GameSession(id: game.id, difficulty: game.difficulty, dayKey: dayKey,
- givens: game.givens, solution: game.solution, values: game.givens)
- fresh.lastPlayed = Date()
- library.sessions[game.id] = fresh
- library.statistics.started += 1
- save()
- } else { await startGame(difficulty: game.difficulty) }
- }
- private func update(_ action: (inout GameSession) -> Void) {
- guard let id = currentGameID, var game = library.sessions[id], game.inProgress else { return }
- action(&game)
- game.lastPlayed = Date()
- if game.values == game.solution {
- game.completed = true
- library.statistics.won += 1
- library.statistics.bestScore = max(library.statistics.bestScore, game.score)
- library.statistics.totalSeconds += game.elapsed
- let key = game.difficulty.rawValue
- library.statistics.bestTimes[key] = min(library.statistics.bestTimes[key] ?? Int.max, game.elapsed)
- library.statistics.winsByDifficulty[key, default: 0] += 1
- }
- library.sessions[id] = game
- save()
- }
- func save() {
- do { defaults.set(try JSONEncoder().encode(library), forKey: saveKey) }
- catch { storageWarning = "There was a problem saving your progress. Please try again." }
- }
- }
|