GameStore.swift 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import Foundation
  2. import Combine
  3. struct BoardSnapshot: Codable {
  4. var values: [Int]
  5. var notes: [[Int]]
  6. }
  7. struct GameSession: Codable, Identifiable {
  8. let id: String
  9. let difficulty: Difficulty
  10. let dayKey: String?
  11. let givens: [Int]
  12. let solution: [Int]
  13. var values: [Int]
  14. var notes: [[Int]] = Array(repeating: [], count: 81)
  15. var history: [BoardSnapshot] = []
  16. var mistakes = 0
  17. var elapsed = 0
  18. var hintsRemaining = 3
  19. var completed = false
  20. var lastPlayed = Date()
  21. var failed: Bool { mistakes >= 3 && !completed }
  22. var inProgress: Bool { !completed && !failed }
  23. var filledCount: Int { values.indices.filter { values[$0] != 0 && values[$0] == solution[$0] }.count }
  24. var progress: Double {
  25. let emptyCount = givens.filter { $0 == 0 }.count
  26. return Double(filledCount - givens.filter { $0 != 0 }.count) / Double(max(1, emptyCount))
  27. }
  28. var score: Int {
  29. let filled = values.indices.filter { givens[$0] == 0 && values[$0] == solution[$0] }.count
  30. return max(0, filled * 100 * difficulty.multiplier - mistakes * 50 - (3 - hintsRemaining) * 100)
  31. }
  32. var timeText: String { Self.formatTime(elapsed) }
  33. static func formatTime(_ seconds: Int) -> String {
  34. if seconds >= 3600 { return String(format: "%d:%02d:%02d", seconds / 3600, seconds / 60 % 60, seconds % 60) }
  35. return String(format: "%02d:%02d", seconds / 60, seconds % 60)
  36. }
  37. mutating func checkpoint() {
  38. history.append(BoardSnapshot(values: values, notes: notes))
  39. if history.count > 100 { history.removeFirst() }
  40. }
  41. }
  42. struct PlayerStatistics: Codable {
  43. var started = 0
  44. var won = 0
  45. var bestScore = 0
  46. var totalSeconds = 0
  47. var bestTimes: [String: Int] = [:]
  48. var winsByDifficulty: [String: Int] = [:]
  49. }
  50. struct PlayerSettings: Codable {
  51. var highlightPeers = true
  52. var highlightSameNumbers = true
  53. var removeNotes = true
  54. var haptics = true
  55. }
  56. private struct SavedLibrary: Codable {
  57. var version = 1
  58. var sessions: [String: GameSession] = [:]
  59. var statistics = PlayerStatistics()
  60. var settings = PlayerSettings()
  61. }
  62. @MainActor final class GameStore: ObservableObject {
  63. @Published private var library: SavedLibrary
  64. private let defaults: UserDefaults
  65. private let saveKey = "JokerSudoku.library.v1"
  66. @Published var currentGameID: String?
  67. @Published var isGenerating = false
  68. @Published var storageWarning: String?
  69. init(defaults: UserDefaults = .standard) {
  70. self.defaults = defaults
  71. if let data = defaults.data(forKey: saveKey) {
  72. do { library = try JSONDecoder().decode(SavedLibrary.self, from: data) }
  73. catch {
  74. // Keep the original data available for recovery instead of overwriting it silently.
  75. defaults.set(data, forKey: "JokerSudoku.library.recovery")
  76. library = SavedLibrary()
  77. storageWarning = "Your previous save could not be read. A recovery backup has been kept. You can start a new game."
  78. }
  79. } else { library = SavedLibrary() }
  80. }
  81. var statistics: PlayerStatistics { library.statistics }
  82. var settings: PlayerSettings {
  83. get { library.settings }
  84. set { library.settings = newValue; save() }
  85. }
  86. var currentGame: GameSession? { currentGameID.flatMap { library.sessions[$0] } }
  87. var resumableGame: GameSession? {
  88. library.sessions.values.filter(\.inProgress).max { $0.lastPlayed < $1.lastPlayed }
  89. }
  90. var completedDailyCount: Int { library.sessions.values.filter { $0.dayKey != nil && $0.completed }.count }
  91. func dailySession(for date: Date) -> GameSession? { library.sessions["daily-" + SudokuEngine.dateKey(date)] }
  92. func completedDays(in month: Date) -> Int {
  93. let prefix = String(SudokuEngine.dateKey(month).prefix(7))
  94. return library.sessions.values.filter { $0.completed && ($0.dayKey?.hasPrefix(prefix) ?? false) }.count
  95. }
  96. func startGame(difficulty: Difficulty, day: Date? = nil) async {
  97. guard !isGenerating else { return }
  98. isGenerating = true
  99. defer { isGenerating = false }
  100. let key = day.map { SudokuEngine.dateKey($0) }
  101. let seed = key.map(SudokuEngine.dailySeed) ?? UInt64.random(in: 0...UInt64.max)
  102. let puzzle = await Task.detached(priority: .userInitiated) {
  103. SudokuEngine.generate(difficulty: difficulty, seed: seed)
  104. }.value
  105. let id = key.map { "daily-" + $0 } ?? "classic"
  106. library.sessions[id] = GameSession(id: id, difficulty: difficulty, dayKey: key,
  107. givens: puzzle.givens, solution: puzzle.solution, values: puzzle.givens)
  108. library.statistics.started += 1
  109. currentGameID = id
  110. save()
  111. }
  112. func resume(_ game: GameSession) {
  113. guard game.inProgress else { return }
  114. currentGameID = game.id
  115. library.sessions[game.id]?.lastPlayed = Date()
  116. save()
  117. }
  118. func leaveGame() { save(); currentGameID = nil }
  119. func tick() {
  120. guard let id = currentGameID, library.sessions[id]?.inProgress == true else { return }
  121. library.sessions[id]?.elapsed += 1
  122. library.sessions[id]?.lastPlayed = Date()
  123. save()
  124. }
  125. func enter(_ digit: Int, at index: Int, notesMode: Bool) {
  126. guard (0..<81).contains(index), (1...9).contains(digit) else { return }
  127. update { game in
  128. guard game.givens[index] == 0 else { return }
  129. if notesMode {
  130. guard game.values[index] == 0 else { return }
  131. game.checkpoint()
  132. if game.notes[index].contains(digit) { game.notes[index].removeAll { $0 == digit } }
  133. else { game.notes[index].append(digit); game.notes[index].sort() }
  134. } else {
  135. guard game.values[index] != digit else { return }
  136. game.checkpoint()
  137. game.values[index] = digit
  138. game.notes[index] = []
  139. if digit != game.solution[index] { game.mistakes += 1 }
  140. else if self.settings.removeNotes {
  141. for peer in 0..<81 where SudokuEngine.arePeers(index, peer) { game.notes[peer].removeAll { $0 == digit } }
  142. }
  143. }
  144. }
  145. }
  146. func erase(at index: Int) {
  147. guard (0..<81).contains(index) else { return }
  148. update { game in
  149. guard game.givens[index] == 0, game.values[index] != 0 || !game.notes[index].isEmpty else { return }
  150. game.checkpoint(); game.values[index] = 0; game.notes[index] = []
  151. }
  152. }
  153. func undo() {
  154. update { game in
  155. guard let snapshot = game.history.popLast() else { return }
  156. game.values = snapshot.values; game.notes = snapshot.notes
  157. }
  158. }
  159. @discardableResult func hint(at selected: Int?) -> Int? {
  160. guard let game = currentGame, game.inProgress, game.hintsRemaining > 0 else { return nil }
  161. let index = selected.flatMap { (0..<81).contains($0) && game.values[$0] != game.solution[$0] ? $0 : nil }
  162. ?? game.values.indices.first { game.values[$0] != game.solution[$0] }
  163. guard let index else { return nil }
  164. update { game in
  165. game.checkpoint()
  166. game.values[index] = game.solution[index]
  167. game.notes[index] = []
  168. game.hintsRemaining -= 1
  169. if self.settings.removeNotes {
  170. let digit = game.solution[index]
  171. for peer in 0..<81 where SudokuEngine.arePeers(index, peer) {
  172. game.notes[peer].removeAll { $0 == digit }
  173. }
  174. }
  175. }
  176. return index
  177. }
  178. func restart() async {
  179. guard let game = currentGame else { return }
  180. if let dayKey = game.dayKey {
  181. // Daily restarts always retain that day's puzzle, regardless of timezone changes.
  182. var fresh = GameSession(id: game.id, difficulty: game.difficulty, dayKey: dayKey,
  183. givens: game.givens, solution: game.solution, values: game.givens)
  184. fresh.lastPlayed = Date()
  185. library.sessions[game.id] = fresh
  186. library.statistics.started += 1
  187. save()
  188. } else { await startGame(difficulty: game.difficulty) }
  189. }
  190. private func update(_ action: (inout GameSession) -> Void) {
  191. guard let id = currentGameID, var game = library.sessions[id], game.inProgress else { return }
  192. action(&game)
  193. game.lastPlayed = Date()
  194. if game.values == game.solution {
  195. game.completed = true
  196. library.statistics.won += 1
  197. library.statistics.bestScore = max(library.statistics.bestScore, game.score)
  198. library.statistics.totalSeconds += game.elapsed
  199. let key = game.difficulty.rawValue
  200. library.statistics.bestTimes[key] = min(library.statistics.bestTimes[key] ?? Int.max, game.elapsed)
  201. library.statistics.winsByDifficulty[key, default: 0] += 1
  202. }
  203. library.sessions[id] = game
  204. save()
  205. }
  206. func save() {
  207. do { defaults.set(try JSONEncoder().encode(library), forKey: saveKey) }
  208. catch { storageWarning = "There was a problem saving your progress. Please try again." }
  209. }
  210. }