Java tutorial
/* * Inmisericordia * Copyright (C) 2014 Ruben Rosado <rrosadoalba@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.rubenrosado.inmisericordia; import java.util.Iterator; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonReader; import com.badlogic.gdx.utils.JsonValue; import eu.rubenrosado.inmisericordia.actors.Hero; import eu.rubenrosado.inmisericordia.actors.Monster; import eu.rubenrosado.inmisericordia.screens.PlayGame; /** * This class saves and loads the game using JSon and preferences * * @author Ruben Rosado * */ public class LSGame { private float autosave; /** * * @return if exists any saved game */ public boolean existsSavedGame() { Preferences pref = Gdx.app.getPreferences(".sav"); if (!pref.getBoolean("savedgame", false)) { return false; } return true; } /** * Save the game in JSon */ public void saveGame() { Json json = new Json(); String hero = json.toJson(PlayGame.hero, Hero.class); String monsters = json.toJson(PlayGame.monsters, Monster.class); FileHandle file = Gdx.files.local("hero.sav"); file.writeString(hero, false); file = Gdx.files.local("monsters.sav"); file.writeString(monsters, false); Preferences pref = Gdx.app.getPreferences(".sav"); if (!pref.getBoolean("savedgame", false)) { pref.putBoolean("savedgame", true); } pref.flush(); } /** * Load the game saved in JSon */ public void loadGame() { Json json = new Json(); FileHandle file = Gdx.files.local("hero.sav"); PlayGame.hero = json.fromJson(Hero.class, file.readString()); file = Gdx.files.local("monsters.sav"); JsonValue root = new JsonReader().parse(file.readString()); @SuppressWarnings("rawtypes") Iterator it = root.iterator(); while (it.hasNext()) { PlayGame.monsters.add(json.fromJson(Monster.class, it.next().toString())); } } /** * Delete saved game */ public void deleteGame() { Preferences pref = Gdx.app.getPreferences(".sav"); pref.putBoolean("savedgame", false); pref.flush(); Gdx.files.local("hero.sav").delete(); Gdx.files.local("monsters.sav").delete(); } /** * Save the game automatically */ public void autosave() { autosave += PlayGame.delta; if (autosave > 60) { saveGame(); autosave = 0; } } }