import Foundation import Combine enum BoardTheme: String, CaseIterable { case blue = "清新蓝", paper = "暖纸", night = "夜色" } enum PlayerPreferenceKeys { static let theme = "JokerSudoku.boardTheme" static let sound = "JokerSudoku.soundEffects" } 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() var recoveredInvalidData = false private enum CodingKeys: String, CodingKey { case version, sessions, statistics, settings } private struct SessionKey: CodingKey { let stringValue: String var intValue: Int? { nil } init?(stringValue: String) { self.stringValue = stringValue } init?(intValue: Int) { return nil } } init() { } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) version = try container.decode(Int.self, forKey: .version) guard version == 1 else { throw DecodingError.dataCorruptedError(forKey: .version, in: container, debugDescription: "Unsupported save version") } if let records = try? container.nestedContainer(keyedBy: SessionKey.self, forKey: .sessions) { for key in records.allKeys { if let game = try? records.decode(GameSession.self, forKey: key), SaveValidation.valid(game, key: key.stringValue) { sessions[key.stringValue] = game } else { recoveredInvalidData = true } } } else { recoveredInvalidData = true } if let value = try? container.decode(PlayerStatistics.self, forKey: .statistics), SaveValidation.valid(value), value.started >= sessions.count, value.won >= sessions.values.filter(\.completed).count { statistics = value } else { recoveredInvalidData = true statistics.started = sessions.count for game in sessions.values where game.completed { statistics.won += 1 statistics.bestScore = max(statistics.bestScore, game.score) statistics.totalSeconds += min(Int(Int32.max) - statistics.totalSeconds, game.elapsed) let level = game.difficulty.rawValue statistics.bestTimes[level] = min(statistics.bestTimes[level] ?? Int.max, game.elapsed) statistics.winsByDifficulty[level, default: 0] += 1 } } if let value = try? container.decode(PlayerSettings.self, forKey: .settings) { settings = value } else { recoveredInvalidData = true } } } private enum SaveValidation { static func valid(_ game: GameSession, key: String) -> Bool { guard key == game.id, game.givens.count == 81, game.solution.count == 81, game.solution.allSatisfy({ (1...9).contains($0) }), SudokuEngine.solutionCount(game.solution) == 1, game.givens.allSatisfy({ (0...9).contains($0) }), game.givens.indices.allSatisfy({ game.givens[$0] == 0 || game.givens[$0] == game.solution[$0] }), valid(game.values, notes: game.notes, givens: game.givens), game.history.count <= 100, game.history.allSatisfy({ valid($0.values, notes: $0.notes, givens: game.givens) }), (0...3).contains(game.mistakes), (0...3).contains(game.hintsRemaining), (0...Int(Int32.max)).contains(game.elapsed), game.lastPlayed.timeIntervalSince1970.isFinite, game.completed == (game.values == game.solution) else { return false } guard let day = game.dayKey else { return key == "classic" } let parts = day.split(separator: "-", omittingEmptySubsequences: false) guard parts.count == 3, parts[0].count == 4, parts[1].count == 2, parts[2].count == 2, let year = Int(parts[0]), (1...9999).contains(year), let month = Int(parts[1]), let date = Int(parts[2]) else { return false } var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(secondsFromGMT: 0)! guard let value = calendar.date(from: DateComponents(year: year, month: month, day: date)), SudokuEngine.dateKey(value, calendar: calendar) == day else { return false } return key == "daily-" + day } private static func valid(_ values: [Int], notes: [[Int]], givens: [Int]) -> Bool { values.count == 81 && notes.count == 81 && values.allSatisfy({ (0...9).contains($0) }) && notes.allSatisfy({ $0.count <= 9 && Set($0).count == $0.count && $0.allSatisfy({ (1...9).contains($0) }) }) && givens.indices.allSatisfy({ givens[$0] == 0 || values[$0] == givens[$0] }) } static func valid(_ stats: PlayerStatistics) -> Bool { let numbers = [stats.started, stats.won, stats.bestScore, stats.totalSeconds] + Array(stats.bestTimes.values) + Array(stats.winsByDifficulty.values) let difficulties = Set(Difficulty.allCases.map(\.rawValue)) return stats.won <= stats.started && numbers.allSatisfy({ (0...Int(Int32.max)).contains($0) }) && Set(stats.bestTimes.keys).isSubset(of: difficulties) && Set(stats.winsByDifficulty.keys).isSubset(of: difficulties) } } @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 { let restored = try JSONDecoder().decode(SavedLibrary.self, from: data) if restored.recoveredInvalidData { defaults.set(data, forKey: "JokerSudoku.library.recovery") defaults.set(try JSONEncoder().encode(restored), forKey: saveKey) storageWarning = "Your previous save could not be read. A recovery backup has been kept. You can start a new game." } library = restored } 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." } } }