summaryrefslogtreecommitdiffstats
path: root/src/MapLoader.java
blob: b55f2acbdbc4b4b67da8a8a7aee868ed9cac1a37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.lang.String;

import java.io.File;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.awt.Dimension;

import com.google.gson.Gson;

// TODO: this class loads AND saves classes, refractor name
class MapLoader {
	File path;

	public MapLoader(Object path) {
		if (path instanceof java.io.File) {
			this.path = (File) path;
		} else {
			this.path = new File((String) path);
		}
	}

	public Map getMap() {
		String mapText = "";
		String line = null;
		FileReader fr = null;
		BufferedReader bf = null;

		try {
			fr = new FileReader(this.path);
			bf = new BufferedReader(fr);
			// TODO: read all
			while ((line = bf.readLine()) != null) {
				mapText = mapText + line;	
			}
			bf.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		Gson gson = new Gson();
		Map importMap = gson.fromJson(mapText, Map.class);

		//update map with new classes
		Map map = new Map(new Dimension(importMap.getSize(), importMap.getSize()));
		map.update(importMap.getActors(), importMap.getGrid());
		return map;
	}

	public void saveMap(Map map) {
		Gson gson = new Gson();
		String mapText = gson.toJson(map);
		PrintWriter out = null;
		try {
			out = new PrintWriter(this.path + ".json");
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		}
		out.println(mapText);
		out.close();
	}
}