diff --git a/core/src/com/unciv/UnCivGame.kt b/core/src/com/unciv/UnCivGame.kt index 971f3f36c2..a84c9f87ec 100644 --- a/core/src/com/unciv/UnCivGame.kt +++ b/core/src/com/unciv/UnCivGame.kt @@ -84,6 +84,10 @@ class UnCivGame(val version: String) : Game() { resume() } + override fun dispose() { + GameSaver().autoSave(gameInfo) + } + companion object { lateinit var Current: UnCivGame } diff --git a/core/src/com/unciv/logic/GameSaver.kt b/core/src/com/unciv/logic/GameSaver.kt index f444c4f7e1..cd684e82e5 100644 --- a/core/src/com/unciv/logic/GameSaver.kt +++ b/core/src/com/unciv/logic/GameSaver.kt @@ -7,6 +7,7 @@ import com.unciv.GameSettings import com.unciv.logic.map.TileMap import com.unciv.ui.saves.Gzip import com.unciv.ui.utils.ImageGetter +import java.io.File class GameSaver { private val saveFilesFolder = "SaveFiles" @@ -66,4 +67,24 @@ class GameSaver { fun setGeneralSettings(gameSettings: GameSettings){ getGeneralSettingsFile().writeString(json().toJson(gameSettings), false) } + + fun autoSave(gameInfo: GameInfo, postRunnable: () -> Unit = {}) { + val gameInfoClone = gameInfo.clone() + kotlin.concurrent.thread { + // the save takes a long time (up to a second!) and we can do it while the player continues his game. + // On the other hand if we alter the game data while it's being serialized we could get a concurrent modification exception. + // So what we do is we clone all the game data and serialize the clone. + saveGame(gameInfoClone, "Autosave") + + // keep auto-saves for the last 10 turns for debugging purposes + // eg turn 238 is saved as "Autosave-8" + getSave("Autosave").copyTo(Gdx.files.local(saveFilesFolder + File.separator + "Autosave-${gameInfoClone.turns%10}")) + + // do this on main thread + Gdx.app.postRunnable { + postRunnable() + } + } + + } } diff --git a/core/src/com/unciv/ui/worldscreen/WorldScreen.kt b/core/src/com/unciv/ui/worldscreen/WorldScreen.kt index 693f1201af..5e69d56717 100644 --- a/core/src/com/unciv/ui/worldscreen/WorldScreen.kt +++ b/core/src/com/unciv/ui/worldscreen/WorldScreen.kt @@ -262,20 +262,11 @@ class WorldScreen : CameraStageBaseScreen() { throw ex } - val gameInfoClone = gameInfo.clone() - kotlin.concurrent.thread { - // the save takes a long time (up to a second!) and we can do it while the player continues his game. - // On the other hand if we alter the game data while it's being serialized we could get a concurrent modification exception. - // So what we do is we clone all the game data and serialize the clone. - if(gameInfo.turns % game.settings.turnsBetweenAutosaves == 0) - GameSaver().saveGame(gameInfoClone, "Autosave") - - // do this on main thread - Gdx.app.postRunnable { + if(gameInfo.turns % game.settings.turnsBetweenAutosaves == 0) { + GameSaver().autoSave(gameInfo) { nextTurnButton.enable() // only enable the user to next turn once we've saved the current one updateNextTurnButton() } - } // If we put this BEFORE the save game, then we try to save the game...