1 package ru
.deadsoftware
.cavecraft
.game
;
3 import com
.badlogic
.gdx
.Gdx
;
4 import com
.badlogic
.gdx
.files
.FileHandle
;
5 import ru
.deadsoftware
.cavecraft
.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
<map
[0].length
; y
++) {
29 for (int x
=0; x
<map
.length
; x
++) {
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(gameProc
);
82 gameProc
.resetRenderer();
83 } catch (Exception e
) {
84 Gdx
.app
.error("GameSaver",e
.getMessage(),e
);
90 public static void save(GameProc gameProc
) {
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
);
97 out
.writeObject(gameProc
);
99 saveMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+"/saves/foremap.sav"), gameProc
.world
.getFullForeMap());
100 saveMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+"/saves/backmap.sav"), gameProc
.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());