49822863f876b074fe28f25e10aab9a376951aab
1 package ru
.deadsoftware
.cavedroid
.game
;
3 import com
.badlogic
.gdx
.Gdx
;
4 import com
.badlogic
.gdx
.files
.FileHandle
;
5 import org
.jetbrains
.annotations
.NotNull
;
6 import ru
.deadsoftware
.cavedroid
.CaveGame
;
9 import java
.nio
.ByteBuffer
;
11 public class GameSaver
{
13 private static final int VERSION
= 0;
16 private static byte[] intToBytes(int i
) {
17 return ByteBuffer
.allocate(4).putInt(i
).array();
20 private static void saveMap(@NotNull FileHandle file
, @NotNull int[][] map
) throws IOException
{
22 int width
= map
.length
;
23 int height
= map
[0].length
;
24 BufferedOutputStream out
= new BufferedOutputStream(file
.write(false));
25 out
.write(intToBytes(VERSION
));
26 out
.write(intToBytes(width
));
27 out
.write(intToBytes(height
));
28 for (int y
= 0; y
< height
; y
++) {
31 for (int[] ints
: map
) {
33 out
.write(intToBytes(rl
));
34 out
.write(intToBytes(bl
));
40 out
.write(intToBytes(rl
));
41 out
.write(intToBytes(bl
));
48 private static int[][] loadMap(@NotNull FileHandle file
) throws Exception
{
50 int ver
, width
, height
;
52 DataInputStream in
= new DataInputStream(file
.read());
56 height
= in
.readInt();
57 map
= new int[width
][height
];
58 for (int y
= 0; y
< height
; y
++) {
59 for (int x
= 0; x
< width
; x
+= rl
) {
62 for (int i
= x
; i
< x
+ rl
; i
++) map
[i
][y
] = bl
;
66 } else throw new Exception("version mismatch");
70 public static GameProc
load() {
71 FileHandle file
= Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/game.sav");
72 GameProc gameProc
= null;
74 ObjectInputStream in
= new ObjectInputStream(file
.read());
75 int ver
= in
.readInt();
76 if (VERSION
== ver
) gameProc
= (GameProc
) in
.readObject();
77 else throw new Exception("version mismatch");
79 gameProc
.world
= new GameWorld(
80 loadMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/foremap.sav")),
81 loadMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/backmap.sav"))
83 gameProc
.physics
= new GamePhysics();
84 gameProc
.input
= new GameInput();
85 } catch (Exception e
) {
86 Gdx
.app
.error("GameSaver", e
.getMessage(), e
);
92 public static void save(GameProc gp
) {
93 FileHandle file
= Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/");
95 file
= Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/game.sav");
97 ObjectOutputStream out
= new ObjectOutputStream(file
.write(false));
98 out
.writeInt(VERSION
);
101 saveMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/foremap.sav"), gp
.world
.getFullForeMap());
102 saveMap(Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/backmap.sav"), gp
.world
.getFullBackMap());
103 } catch (Exception e
) {
108 public static boolean exists() {
109 return (Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/game.sav").exists() &&
110 Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/foremap.sav").exists() &&
111 Gdx
.files
.absolute(CaveGame
.GAME_FOLDER
+ "/saves/backmap.sav").exists());