PIbd-23_Polevoy_S.V._SelfPr.../MapsCollection.java

101 lines
3.0 KiB
Java
Raw Normal View History

import java.io.*;
2022-11-05 16:40:00 +04:00
import java.util.HashMap;
import java.util.Set;
public class MapsCollection {
2022-11-05 19:18:29 +04:00
private final HashMap<String, MapWithSetArtilleriesGeneric<IDrawingObject, AbstractMap>> _mapsStorage;
2022-11-05 16:40:00 +04:00
private final int _pictureWidth;
private final int _pictureHeight;
private final char separatorDict = '|';
private final char separatorData = ';';
2022-11-05 16:40:00 +04:00
public Set<String> getKeys() {
return _mapsStorage.keySet();
}
public MapsCollection(int pictureWidth, int pictureHeight) {
_mapsStorage = new HashMap<>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void addMap(String name, AbstractMap map) {
if (!_mapsStorage.containsKey(name)) {
_mapsStorage.put(name, new MapWithSetArtilleriesGeneric<>(_pictureWidth, _pictureHeight, map));
}
}
public void deleteMap(String name) {
_mapsStorage.remove(name);
}
2022-11-05 19:18:29 +04:00
public MapWithSetArtilleriesGeneric<IDrawingObject, AbstractMap> getMap(String name) {
2022-11-05 16:40:00 +04:00
return _mapsStorage.getOrDefault(name, null);
}
2022-11-08 16:19:52 +04:00
public IDrawingObject getArtillery(String mapName, int index) {
var map = _mapsStorage.getOrDefault(mapName, null);
if (map != null) {
return map._setArtilleries.get(index);
}
return null;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public boolean saveData(String filename) throws IOException {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
file.createNewFile();
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("MapsCollection");
for (var storage : _mapsStorage.entrySet()) {
writer.println(String.format("%s%c%s", storage.getKey(), separatorDict, storage.getValue().getData(separatorDict, separatorData)));
}
2022-11-21 01:04:53 +04:00
writer.flush();
}
return true;
}
public boolean loadData(String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
return false;
}
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("MapsCollection")) {
return false;
}
_mapsStorage.clear();
while ((currentLine = reader.readLine()) != null) {
2022-11-21 01:04:53 +04:00
var elements = currentLine.split(String.format("\\%c", separatorDict));
AbstractMap map = switch (elements[1]) {
case "SimpleMap" -> new SimpleMap();
case "ForestMap" -> new ForestMap();
2022-11-21 01:04:53 +04:00
default -> null;
};
_mapsStorage.put(elements[0], new MapWithSetArtilleriesGeneric<>(_pictureWidth, _pictureHeight, map));
2022-11-21 01:04:53 +04:00
_mapsStorage.get(elements[0]).loadData(elements[2].split(separatorData + "\n?"));
}
}
return true;
}
2022-11-05 16:40:00 +04:00
}