Skip to content

Commit

Permalink
Added save/restore state
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Apr 25, 2020
1 parent de28dd9 commit 4322168
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
22 changes: 22 additions & 0 deletions Source/Engine/Game.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ public enum GameState {
case playing
}

public struct SavedGame: Codable {
let world: World?
}

public struct Game {
public weak var delegate: GameDelegate?
public let levels: [Tilemap]
Expand All @@ -39,6 +43,24 @@ public extension Game {
return HUD(player: world.player, font: font)
}

func save() -> SavedGame {
switch state {
case .playing:
return SavedGame(world: world)
default:
return SavedGame(world: nil)
}
}

mutating func load(_ savedGame: SavedGame) {
guard let world = savedGame.world else {
self.state = .title
return
}
self.state = .playing
self.world = world
}

mutating func update(timeStep: Double, input: Input) {
guard let delegate = delegate else {
return
Expand Down
18 changes: 11 additions & 7 deletions Source/Rampage/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ import Renderer
private let joystickRadius: Double = 40
private let maximumTimeStep: Double = 1 / 20
private let worldTimeStep: Double = 1 / 120
private let savePath = "~/Documents/quicksave.json"

private let savedGameURL: URL = {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
return documentsURL.appendingPathComponent("quicksave.plist")
}()

public func loadLevels() -> [Tilemap] {
let jsonURL = Bundle.main.url(forResource: "Levels", withExtension: "json")!
Expand Down Expand Up @@ -160,15 +164,15 @@ class ViewController: UIViewController {
}

func saveState() throws {
let data = try JSONEncoder().encode(world)
let url = URL(fileURLWithPath: (savePath as NSString).expandingTildeInPath)
try data.write(to: url, options: .atomic)
let savedGame = game.save()
let data = try PropertyListEncoder().encode(savedGame)
try data.write(to: savedGameURL, options: .atomic)
}

func restoreState() throws {
let url = URL(fileURLWithPath: (savePath as NSString).expandingTildeInPath)
let data = try Data(contentsOf: url)
world = try JSONDecoder().decode(World.self, from: data)
let data = try Data(contentsOf: savedGameURL)
let savedGame = try PropertyListDecoder().decode(SavedGame.self, from: data)
game.load(savedGame)
}
}

Expand Down

0 comments on commit 4322168

Please sign in to comment.