DEADSOFTWARE

Rename GameState.java -> AppState.java
[cavedroid.git] / core / src / ru / deadsoftware / cavecraft / game / WorldSaver.java
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;
7 import java.nio.ByteBuffer;
9 public class WorldSaver {
11 private static final int VERSION = 0;
13 private static int[][] fMap, bMap;
14 private static int readIndex;
16 private static int bytesInt(byte[] bytes) {
17 ByteBuffer wrapped = ByteBuffer.wrap(bytes);
18 int res = wrapped.getInt(readIndex);
19 readIndex+=4;
20 return res;
21 }
23 private static void writeInt(FileHandle file, int i, boolean append) {
24 byte[] bytes = ByteBuffer.allocate(4).putInt(i).array();
25 file.writeBytes(bytes, append);
26 }
28 private static void saveMap(FileHandle file, int[][] map) {
29 int width = map.length;
30 int height = map[0].length;
31 writeInt(file, VERSION, false);
32 writeInt(file, width, true);
33 writeInt(file, height, true);
34 for (int y=0; y<map[0].length; y++) {
35 int bl = map[0][y];
36 int rl = 1;
37 for (int x=0; x<map.length; x++) {
38 if (map[x][y]!=bl || x==map.length-1) {
39 writeInt(file, rl, true);
40 writeInt(file, bl, true);
41 rl=1;
42 bl=map[x][y];
43 } else {
44 rl++;
45 }
46 }
47 }
48 }
50 private static int[][] loadMap(FileHandle file) {
51 int[][] map = null;
52 int ver, width, height;
53 int rl,bl;
54 byte[] data = file.readBytes();
55 readIndex = 0;
56 ver = bytesInt(data);
57 if (VERSION <= ver) {
58 width = bytesInt(data);
59 height = bytesInt(data);
60 map = new int[width][height];
61 for (int y=0; y<height; y++) {
62 for (int x=0; x<width; x+=rl) {
63 rl = bytesInt(data);
64 bl = bytesInt(data);
65 for (int i=x; i<x+rl; i++) map[i][y] = bl;
66 }
67 }
68 }
69 return map;
70 }
72 public static int[][] getLoadedForeMap() {
73 return fMap;
74 }
76 public static int[][] getLoadedBackMap() {
77 return bMap;
78 }
80 public static void load() {
81 fMap = loadMap(Gdx.files.absolute(CaveGame.GAME_FOLDER+"/saves/foremap.sav"));
82 bMap = loadMap(Gdx.files.absolute(CaveGame.GAME_FOLDER+"/saves/backmap.sav"));
83 }
85 public static void save(int[][] foreMap, int[][] backMap) {
86 Gdx.files.absolute(CaveGame.GAME_FOLDER+"/saves/").mkdirs();
87 saveMap(Gdx.files.absolute(CaveGame.GAME_FOLDER+"/saves/foremap.sav"), foreMap);
88 saveMap(Gdx.files.absolute(CaveGame.GAME_FOLDER+"/saves/backmap.sav"), backMap);
89 }
91 public static boolean exists() {
92 return (Gdx.files.absolute(CaveGame.GAME_FOLDER+"/saves/foremap.sav").exists() &&
93 Gdx.files.absolute(CaveGame.GAME_FOLDER+"/saves/backmap.sav").exists());
94 }
96 }