1 package ru
.deadsoftware
.cavedroid
.game
;
3 import com
.badlogic
.gdx
.Gdx
;
4 import com
.badlogic
.gdx
.files
.FileHandle
;
5 import ru
.deadsoftware
.cavedroid
.CaveGame
;
8 import java
.nio
.ByteBuffer
;
10 public class GameSaver
{
12 private static final int VERSION
= 0;
14 private static byte[] intToBytes(int i
) {
15 return ByteBuffer
.allocate(4).putInt(i
).array();
18 private static void saveMap(FileHandle file
, int[][] map
) throws IOException
{
20 int width
= map
.length
;
21 int height
= map
[0].length
;
22 BufferedOutputStream out
= new BufferedOutputStream(file
.write(false));
23 out
.write(intToBytes(VERSION
));
24 out
.write(intToBytes(width
));
25 out
.write(intToBytes(height
));
26 for (int y
= 0; y
< height
; y
++) {
29 for (int x
= 0; x
< width
; x
++) {
30 if (map
[x
][y
] != bl
) {
31 out
.write(intToBytes(rl
));
32 out
.write(intToBytes(bl
));
38 out
.write(intToBytes(rl
));
39 out
.write(intToBytes(bl
));
45 private static int[][] loadMap(FileHandle file
) throws Exception
{
47 int ver
, width
, height
;
49 DataInputStream in
= new DataInputStream(file
.read());
53 height
= in
.readInt();
54 map
= new int[width
][height
];
55 for (int y
= 0; y
< height
; y
++) {
56 for (int x
= 0; x
< width
; x
+= rl
) {
59 for (int i
= x
; i
< x
+ rl
; i
++) map
[i
][y
] = bl
;
63 } else throw new Exception("version mismatch");
67 public static GameProc
load() {
68 FileHandle file
= Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/game.sav");
69 GameProc gameProc
= null;
71 ObjectInputStream in
= new ObjectInputStream(file
.read());
72 int ver
= in
.readInt();
73 if (VERSION
== ver
) gameProc
= (GameProc
) in
.readObject();
74 else throw new Exception("version mismatch");
76 gameProc
.world
= new GameWorld();
77 gameProc
.world
.setMaps(
78 loadMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/foremap.sav")),
79 loadMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/backmap.sav"))
81 gameProc
.physics
= new GamePhysics();
82 gameProc
.resetRenderer();
83 } catch (Exception e
) {
84 Gdx
.app
.error("GameSaver", e
.getMessage(), e
);
90 public static void save(GameProc gp
) {
91 FileHandle file
= Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/");
93 file
= Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/game.sav");
95 ObjectOutputStream out
= new ObjectOutputStream(file
.write(false));
96 out
.writeInt(VERSION
);
99 saveMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/foremap.sav"), gp
.world
.getFullForeMap());
100 saveMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/backmap.sav"), gp
.world
.getFullBackMap());
101 } catch (Exception e
) {
106 public static boolean exists() {
107 return (Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/game.sav").exists() &&
108 Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/foremap.sav").exists() &&
109 Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/backmap.sav").exists());