package jrummikub.control; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import jrummikub.model.GameSettings; import jrummikub.model.GameState; import jrummikub.model.IRoundState; import jrummikub.util.Event; import jrummikub.util.Event3; import jrummikub.util.IEvent3; import jrummikub.util.IListener1; import jrummikub.view.IView; /** * The save control is responsible for loading and saving game and round states */ public class SaveControl { private GameSettings gameSettings; private GameState gameState; private IRoundState roundState; private Event3 loadEvent = new Event3(); private Event loadErrorEvent = new Event(); /** * Creates a new SaveControl * * @param view * the view to use */ public SaveControl(final IView view) { view.getSaveEvent().add(new IListener1() { @Override public void handle(File file) { save(file); } }); view.getLoadFileEvent().add(new IListener1() { @Override public void handle(final File file) { load(file); } }); } /** * Getter for loadEvent * * @return loadEvent */ public IEvent3 getLoadEvent() { return loadEvent; } /** * Sets the current game settings * * @param gameSettings * the game settings */ public void setGameSettings(GameSettings gameSettings) { this.gameSettings = gameSettings; } /** * Sets the current game state * * @param gameState * the game state */ public void setGameState(GameState gameState) { this.gameState = gameState; } /** * Sets the current round state * * @param roundState * the round state */ public void setRoundState(IRoundState roundState) { this.roundState = roundState; } /** * Loads the specified file and sets game state and round state. If the file * selected cannot be handled, an error will occur and show * * @param file * to be loaded */ private void load(File file) { try { ObjectInputStream stream = new ObjectInputStream( new FileInputStream(file)); gameSettings = (GameSettings) stream.readObject(); gameState = (GameState) stream.readObject(); roundState = (IRoundState) stream.readObject(); stream.close(); if (gameState == null || gameSettings == null) { loadErrorEvent.emit(); return; } loadEvent.emit(gameSettings, gameState, roundState); } catch (Exception e) { loadErrorEvent.emit(); } } /** * The load error event is emitted when the file selected for loading is not * a rum file * * @return the event */ public Event getLoadErrorEvent() { return loadErrorEvent; } /** * Saves the current game state and round state to a file with the specified * file name * * @param file * file to save game in */ private void save(File file) { if (gameState == null || gameSettings == null) { return; } try { ObjectOutputStream stream = new ObjectOutputStream( new FileOutputStream(file)); stream.writeObject(gameSettings); stream.writeObject(gameState); stream.writeObject(roundState); stream.flush(); stream.close(); } catch (Exception e) { e.printStackTrace(); } } }