GameStore.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import Foundation
  2. import Combine
  3. enum BoardTheme: String, CaseIterable {
  4. case blue = "清新蓝", paper = "暖纸", night = "夜色"
  5. }
  6. enum PlayerPreferenceKeys {
  7. static let theme = "JokerSudoku.boardTheme"
  8. static let sound = "JokerSudoku.soundEffects"
  9. }
  10. struct BoardSnapshot: Codable {
  11. var values: [Int]
  12. var notes: [[Int]]
  13. }
  14. struct GameSession: Codable, Identifiable {
  15. let id: String
  16. let difficulty: Difficulty
  17. let dayKey: String?
  18. let givens: [Int]
  19. let solution: [Int]
  20. var values: [Int]
  21. var notes: [[Int]] = Array(repeating: [], count: 81)
  22. var history: [BoardSnapshot] = []
  23. var mistakes = 0
  24. var elapsed = 0
  25. var hintsRemaining = 3
  26. var completed = false
  27. var lastPlayed = Date()
  28. var failed: Bool { mistakes >= 3 && !completed }
  29. var inProgress: Bool { !completed && !failed }
  30. var filledCount: Int { values.indices.filter { values[$0] != 0 && values[$0] == solution[$0] }.count }
  31. var progress: Double {
  32. let emptyCount = givens.filter { $0 == 0 }.count
  33. return Double(filledCount - givens.filter { $0 != 0 }.count) / Double(max(1, emptyCount))
  34. }
  35. var score: Int {
  36. let filled = values.indices.filter { givens[$0] == 0 && values[$0] == solution[$0] }.count
  37. return max(0, filled * 100 * difficulty.multiplier - mistakes * 50 - (3 - hintsRemaining) * 100)
  38. }
  39. var timeText: String { Self.formatTime(elapsed) }
  40. static func formatTime(_ seconds: Int) -> String {
  41. if seconds >= 3600 { return String(format: "%d:%02d:%02d", seconds / 3600, seconds / 60 % 60, seconds % 60) }
  42. return String(format: "%02d:%02d", seconds / 60, seconds % 60)
  43. }
  44. mutating func checkpoint() {
  45. history.append(BoardSnapshot(values: values, notes: notes))
  46. if history.count > 100 { history.removeFirst() }
  47. }
  48. }
  49. struct PlayerStatistics: Codable {
  50. var started = 0
  51. var won = 0
  52. var bestScore = 0
  53. var totalSeconds = 0
  54. var bestTimes: [String: Int] = [:]
  55. var winsByDifficulty: [String: Int] = [:]
  56. }
  57. struct PlayerSettings: Codable {
  58. var highlightPeers = true
  59. var highlightSameNumbers = true
  60. var removeNotes = true
  61. var haptics = true
  62. }
  63. private struct SavedLibrary: Codable {
  64. var version = 1
  65. var sessions: [String: GameSession] = [:]
  66. var statistics = PlayerStatistics()
  67. var settings = PlayerSettings()
  68. var recoveredInvalidData = false
  69. private enum CodingKeys: String, CodingKey { case version, sessions, statistics, settings }
  70. private struct SessionKey: CodingKey {
  71. let stringValue: String
  72. var intValue: Int? { nil }
  73. init?(stringValue: String) { self.stringValue = stringValue }
  74. init?(intValue: Int) { return nil }
  75. }
  76. init() { }
  77. init(from decoder: Decoder) throws {
  78. let container = try decoder.container(keyedBy: CodingKeys.self)
  79. version = try container.decode(Int.self, forKey: .version)
  80. guard version == 1 else {
  81. throw DecodingError.dataCorruptedError(forKey: .version, in: container, debugDescription: "Unsupported save version")
  82. }
  83. if let records = try? container.nestedContainer(keyedBy: SessionKey.self, forKey: .sessions) {
  84. for key in records.allKeys {
  85. if let game = try? records.decode(GameSession.self, forKey: key), SaveValidation.valid(game, key: key.stringValue) {
  86. sessions[key.stringValue] = game
  87. } else { recoveredInvalidData = true }
  88. }
  89. } else { recoveredInvalidData = true }
  90. if let value = try? container.decode(PlayerStatistics.self, forKey: .statistics), SaveValidation.valid(value),
  91. value.started >= sessions.count, value.won >= sessions.values.filter(\.completed).count {
  92. statistics = value
  93. } else {
  94. recoveredInvalidData = true
  95. statistics.started = sessions.count
  96. for game in sessions.values where game.completed {
  97. statistics.won += 1
  98. statistics.bestScore = max(statistics.bestScore, game.score)
  99. statistics.totalSeconds += min(Int(Int32.max) - statistics.totalSeconds, game.elapsed)
  100. let level = game.difficulty.rawValue
  101. statistics.bestTimes[level] = min(statistics.bestTimes[level] ?? Int.max, game.elapsed)
  102. statistics.winsByDifficulty[level, default: 0] += 1
  103. }
  104. }
  105. if let value = try? container.decode(PlayerSettings.self, forKey: .settings) { settings = value }
  106. else { recoveredInvalidData = true }
  107. }
  108. }
  109. private enum SaveValidation {
  110. static func valid(_ game: GameSession, key: String) -> Bool {
  111. guard key == game.id, game.givens.count == 81, game.solution.count == 81,
  112. game.solution.allSatisfy({ (1...9).contains($0) }), SudokuEngine.solutionCount(game.solution) == 1,
  113. game.givens.allSatisfy({ (0...9).contains($0) }),
  114. game.givens.indices.allSatisfy({ game.givens[$0] == 0 || game.givens[$0] == game.solution[$0] }),
  115. valid(game.values, notes: game.notes, givens: game.givens),
  116. game.history.count <= 100, game.history.allSatisfy({ valid($0.values, notes: $0.notes, givens: game.givens) }),
  117. (0...3).contains(game.mistakes), (0...3).contains(game.hintsRemaining),
  118. (0...Int(Int32.max)).contains(game.elapsed), game.lastPlayed.timeIntervalSince1970.isFinite,
  119. game.completed == (game.values == game.solution) else { return false }
  120. guard let day = game.dayKey else { return key == "classic" }
  121. let parts = day.split(separator: "-", omittingEmptySubsequences: false)
  122. guard parts.count == 3, parts[0].count == 4, parts[1].count == 2, parts[2].count == 2,
  123. let year = Int(parts[0]), (1...9999).contains(year), let month = Int(parts[1]), let date = Int(parts[2]) else { return false }
  124. var calendar = Calendar(identifier: .gregorian)
  125. calendar.timeZone = TimeZone(secondsFromGMT: 0)!
  126. guard let value = calendar.date(from: DateComponents(year: year, month: month, day: date)),
  127. SudokuEngine.dateKey(value, calendar: calendar) == day else { return false }
  128. return key == "daily-" + day
  129. }
  130. private static func valid(_ values: [Int], notes: [[Int]], givens: [Int]) -> Bool {
  131. values.count == 81 && notes.count == 81 && values.allSatisfy({ (0...9).contains($0) }) &&
  132. notes.allSatisfy({ $0.count <= 9 && Set($0).count == $0.count && $0.allSatisfy({ (1...9).contains($0) }) }) &&
  133. givens.indices.allSatisfy({ givens[$0] == 0 || values[$0] == givens[$0] })
  134. }
  135. static func valid(_ stats: PlayerStatistics) -> Bool {
  136. let numbers = [stats.started, stats.won, stats.bestScore, stats.totalSeconds] + Array(stats.bestTimes.values) + Array(stats.winsByDifficulty.values)
  137. let difficulties = Set(Difficulty.allCases.map(\.rawValue))
  138. return stats.won <= stats.started && numbers.allSatisfy({ (0...Int(Int32.max)).contains($0) }) &&
  139. Set(stats.bestTimes.keys).isSubset(of: difficulties) && Set(stats.winsByDifficulty.keys).isSubset(of: difficulties)
  140. }
  141. }
  142. @MainActor final class GameStore: ObservableObject {
  143. @Published private var library: SavedLibrary
  144. private let defaults: UserDefaults
  145. private let saveKey = "JokerSudoku.library.v1"
  146. @Published var currentGameID: String?
  147. @Published var isGenerating = false
  148. @Published var storageWarning: String?
  149. init(defaults: UserDefaults = .standard) {
  150. self.defaults = defaults
  151. if let data = defaults.data(forKey: saveKey) {
  152. do {
  153. let restored = try JSONDecoder().decode(SavedLibrary.self, from: data)
  154. if restored.recoveredInvalidData {
  155. defaults.set(data, forKey: "JokerSudoku.library.recovery")
  156. defaults.set(try JSONEncoder().encode(restored), forKey: saveKey)
  157. storageWarning = "Your previous save could not be read. A recovery backup has been kept. You can start a new game."
  158. }
  159. library = restored
  160. }
  161. catch {
  162. // Keep the original data available for recovery instead of overwriting it silently.
  163. defaults.set(data, forKey: "JokerSudoku.library.recovery")
  164. library = SavedLibrary()
  165. storageWarning = "Your previous save could not be read. A recovery backup has been kept. You can start a new game."
  166. }
  167. } else { library = SavedLibrary() }
  168. }
  169. var statistics: PlayerStatistics { library.statistics }
  170. var settings: PlayerSettings {
  171. get { library.settings }
  172. set { library.settings = newValue; save() }
  173. }
  174. var currentGame: GameSession? { currentGameID.flatMap { library.sessions[$0] } }
  175. var resumableGame: GameSession? {
  176. library.sessions.values.filter(\.inProgress).max { $0.lastPlayed < $1.lastPlayed }
  177. }
  178. var completedDailyCount: Int { library.sessions.values.filter { $0.dayKey != nil && $0.completed }.count }
  179. func dailySession(for date: Date) -> GameSession? { library.sessions["daily-" + SudokuEngine.dateKey(date)] }
  180. func completedDays(in month: Date) -> Int {
  181. let prefix = String(SudokuEngine.dateKey(month).prefix(7))
  182. return library.sessions.values.filter { $0.completed && ($0.dayKey?.hasPrefix(prefix) ?? false) }.count
  183. }
  184. func startGame(difficulty: Difficulty, day: Date? = nil) async {
  185. guard !isGenerating else { return }
  186. isGenerating = true
  187. defer { isGenerating = false }
  188. let key = day.map { SudokuEngine.dateKey($0) }
  189. let seed = key.map(SudokuEngine.dailySeed) ?? UInt64.random(in: 0...UInt64.max)
  190. let puzzle = await Task.detached(priority: .userInitiated) {
  191. SudokuEngine.generate(difficulty: difficulty, seed: seed)
  192. }.value
  193. let id = key.map { "daily-" + $0 } ?? "classic"
  194. library.sessions[id] = GameSession(id: id, difficulty: difficulty, dayKey: key,
  195. givens: puzzle.givens, solution: puzzle.solution, values: puzzle.givens)
  196. library.statistics.started += 1
  197. currentGameID = id
  198. save()
  199. }
  200. func resume(_ game: GameSession) {
  201. guard game.inProgress else { return }
  202. currentGameID = game.id
  203. library.sessions[game.id]?.lastPlayed = Date()
  204. save()
  205. }
  206. func leaveGame() { save(); currentGameID = nil }
  207. func tick() {
  208. guard let id = currentGameID, library.sessions[id]?.inProgress == true else { return }
  209. library.sessions[id]?.elapsed += 1
  210. library.sessions[id]?.lastPlayed = Date()
  211. save()
  212. }
  213. func enter(_ digit: Int, at index: Int, notesMode: Bool) {
  214. guard (0..<81).contains(index), (1...9).contains(digit) else { return }
  215. update { game in
  216. guard game.givens[index] == 0 else { return }
  217. if notesMode {
  218. guard game.values[index] == 0 else { return }
  219. game.checkpoint()
  220. if game.notes[index].contains(digit) { game.notes[index].removeAll { $0 == digit } }
  221. else { game.notes[index].append(digit); game.notes[index].sort() }
  222. } else {
  223. guard game.values[index] != digit else { return }
  224. game.checkpoint()
  225. game.values[index] = digit
  226. game.notes[index] = []
  227. if digit != game.solution[index] { game.mistakes += 1 }
  228. else if self.settings.removeNotes {
  229. for peer in 0..<81 where SudokuEngine.arePeers(index, peer) { game.notes[peer].removeAll { $0 == digit } }
  230. }
  231. }
  232. }
  233. }
  234. func erase(at index: Int) {
  235. guard (0..<81).contains(index) else { return }
  236. update { game in
  237. guard game.givens[index] == 0, game.values[index] != 0 || !game.notes[index].isEmpty else { return }
  238. game.checkpoint(); game.values[index] = 0; game.notes[index] = []
  239. }
  240. }
  241. func undo() {
  242. update { game in
  243. guard let snapshot = game.history.popLast() else { return }
  244. game.values = snapshot.values; game.notes = snapshot.notes
  245. }
  246. }
  247. @discardableResult func hint(at selected: Int?) -> Int? {
  248. guard let game = currentGame, game.inProgress, game.hintsRemaining > 0 else { return nil }
  249. let index = selected.flatMap { (0..<81).contains($0) && game.values[$0] != game.solution[$0] ? $0 : nil }
  250. ?? game.values.indices.first { game.values[$0] != game.solution[$0] }
  251. guard let index else { return nil }
  252. update { game in
  253. game.checkpoint()
  254. game.values[index] = game.solution[index]
  255. game.notes[index] = []
  256. game.hintsRemaining -= 1
  257. if self.settings.removeNotes {
  258. let digit = game.solution[index]
  259. for peer in 0..<81 where SudokuEngine.arePeers(index, peer) {
  260. game.notes[peer].removeAll { $0 == digit }
  261. }
  262. }
  263. }
  264. return index
  265. }
  266. func restart() async {
  267. guard let game = currentGame else { return }
  268. if let dayKey = game.dayKey {
  269. // Daily restarts always retain that day's puzzle, regardless of timezone changes.
  270. var fresh = GameSession(id: game.id, difficulty: game.difficulty, dayKey: dayKey,
  271. givens: game.givens, solution: game.solution, values: game.givens)
  272. fresh.lastPlayed = Date()
  273. library.sessions[game.id] = fresh
  274. library.statistics.started += 1
  275. save()
  276. } else { await startGame(difficulty: game.difficulty) }
  277. }
  278. private func update(_ action: (inout GameSession) -> Void) {
  279. guard let id = currentGameID, var game = library.sessions[id], game.inProgress else { return }
  280. action(&game)
  281. game.lastPlayed = Date()
  282. if game.values == game.solution {
  283. game.completed = true
  284. library.statistics.won += 1
  285. library.statistics.bestScore = max(library.statistics.bestScore, game.score)
  286. library.statistics.totalSeconds += game.elapsed
  287. let key = game.difficulty.rawValue
  288. library.statistics.bestTimes[key] = min(library.statistics.bestTimes[key] ?? Int.max, game.elapsed)
  289. library.statistics.winsByDifficulty[key, default: 0] += 1
  290. }
  291. library.sessions[id] = game
  292. save()
  293. }
  294. func save() {
  295. do { defaults.set(try JSONEncoder().encode(library), forKey: saveKey) }
  296. catch { storageWarning = "There was a problem saving your progress. Please try again." }
  297. }
  298. }