diff --git a/DrawningLocomotive.java b/DrawningLocomotive.java index 015f2ef..08e46f6 100644 --- a/DrawningLocomotive.java +++ b/DrawningLocomotive.java @@ -1,4 +1,5 @@ import java.awt.*; +import java.util.Objects; import java.util.Random; public class DrawningLocomotive { @@ -150,4 +151,57 @@ public class DrawningLocomotive { { return new float[] {/*UP*/_startPosY, /*RIGHT*/ _startPosX + _locomotiveWidth, /*DOWN*/ _startPosY + _locomotiveHeight, /*LEFT*/ _startPosX}; } + + private static final char _separatorForObject = ':'; + public String getDataForSave() + { + var str = "" + Locomotive.getSpeed() + _separatorForObject + + Locomotive.getWeight() + _separatorForObject + + Locomotive.getBodyColor().getRed() + _separatorForObject + + Locomotive.getBodyColor().getGreen() + _separatorForObject + + Locomotive.getBodyColor().getBlue() + _separatorForObject + + drawningExtra.TypeString() + _separatorForObject + + drawningExtra.getWheelsCount(); + if (!(Locomotive instanceof EntityWarmlyLocomotive)) + { + return str; + } + return str + _separatorForObject + + ((EntityWarmlyLocomotive) Locomotive).ExtraColor.getRed() + _separatorForObject + + ((EntityWarmlyLocomotive) Locomotive).ExtraColor.getGreen() + _separatorForObject + + ((EntityWarmlyLocomotive) Locomotive).ExtraColor.getBlue() + _separatorForObject + + ((EntityWarmlyLocomotive) Locomotive).Pipe + _separatorForObject + + ((EntityWarmlyLocomotive) Locomotive).FuelStorage; + } + + public static DrawningLocomotive createDrawningLocomotive(String info) { + IDrawningExtra drawningExtra = null; + EntityLocomotive Locomotive = null; + String[] strs = info.split(Character.toString(_separatorForObject)); + if (strs[5].equals("Simple")) drawningExtra = new ExtraWheelsDraw(Integer.parseInt(strs[6]), new Color(Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4]))); + if (strs[5].equals("Star")) drawningExtra = new ExtraStarWheelDraw(Integer.parseInt(strs[6]), new Color(Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4]))); + if (Objects.equals(strs[5], "Round")) drawningExtra = new ExtraRoundWheelDraw(Integer.parseInt(strs[6]), new Color(Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4]))); + if (drawningExtra == null) return null; + if (strs.length == 7) + { + Locomotive = new EntityLocomotive( + Integer.parseInt(strs[0]), + Float.parseFloat(strs[1]), + new Color(Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4])) + ); + return new DrawningLocomotive(Locomotive, drawningExtra); + } + if (strs.length == 12) { + Locomotive = new EntityWarmlyLocomotive( + Integer.parseInt(strs[0]), + Float.parseFloat(strs[1]), + new Color(Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4])), + new Color(Integer.parseInt(strs[7]), Integer.parseInt(strs[8]), Integer.parseInt(strs[9])), + Boolean.parseBoolean(strs[10]), + Boolean.parseBoolean(strs[11]) + ); + return new DrawningWarmlyLocomotive(Locomotive, drawningExtra); + } + return null; + } } diff --git a/DrawningObjectLocomotive.java b/DrawningObjectLocomotive.java index 2695ed0..7c46d4d 100644 --- a/DrawningObjectLocomotive.java +++ b/DrawningObjectLocomotive.java @@ -39,4 +39,13 @@ public class DrawningObjectLocomotive implements IDrawningObject { { if (_locomotive != null) _locomotive.SetPosition(x, y, width, height); } + + public String getInfo(){ + if (_locomotive == null) return null; + return _locomotive.getDataForSave(); + } + + public static IDrawningObject Create(String data) { + return new DrawningObjectLocomotive(DrawningLocomotive.createDrawningLocomotive(data)); + } } diff --git a/ExtraRoundWheelDraw.java b/ExtraRoundWheelDraw.java index 669ef3c..e578f0b 100644 --- a/ExtraRoundWheelDraw.java +++ b/ExtraRoundWheelDraw.java @@ -6,11 +6,11 @@ public class ExtraRoundWheelDraw implements IDrawningExtra{ private Color color; public void setExtraNum(int num) { switch (num) { - case 0: { + case 3: { wheelsCount = WheelsCount.Three; break; } - case 1: { + case 4: { wheelsCount = WheelsCount.Four; break; } @@ -19,6 +19,15 @@ public class ExtraRoundWheelDraw implements IDrawningExtra{ } } + public String TypeString() { + return "Round"; + } + public int getWheelsCount() { + if (wheelsCount == WheelsCount.Two) return 2; + if (wheelsCount == WheelsCount.Three) return 3; + else return 4; + } + public ExtraRoundWheelDraw (int num, Color bodyColor) { setExtraNum(num); extraWheelsDraw = new ExtraWheelsDraw(num, bodyColor); diff --git a/ExtraStarWheelDraw.java b/ExtraStarWheelDraw.java index 17a8b33..b8ca923 100644 --- a/ExtraStarWheelDraw.java +++ b/ExtraStarWheelDraw.java @@ -6,11 +6,11 @@ public class ExtraStarWheelDraw implements IDrawningExtra{ private Color color; public void setExtraNum(int num) { switch (num) { - case 0: { + case 3: { wheelsCount = WheelsCount.Three; break; } - case 1: { + case 4: { wheelsCount = WheelsCount.Four; break; } @@ -19,6 +19,16 @@ public class ExtraStarWheelDraw implements IDrawningExtra{ } } + public String TypeString() { + return "Star"; + } + + public int getWheelsCount() { + if (wheelsCount == WheelsCount.Two) return 2; + if (wheelsCount == WheelsCount.Three) return 3; + else return 4; + } + public ExtraStarWheelDraw (int num, Color bodyColor) { setExtraNum(num); extraWheelsDraw = new ExtraWheelsDraw(num, bodyColor); diff --git a/ExtraWheelsDraw.java b/ExtraWheelsDraw.java index eb37d42..5af3526 100644 --- a/ExtraWheelsDraw.java +++ b/ExtraWheelsDraw.java @@ -26,6 +26,16 @@ public class ExtraWheelsDraw implements IDrawningExtra{ this.color = color; } + public String TypeString() { + return "Simple"; + } + + public int getWheelsCount() { + if (wheelsCount == WheelsCount.Two) return 2; + if (wheelsCount == WheelsCount.Three) return 3; + else return 4; + } + public void DrawExtra(int startPosX, int startPosY, Graphics2D g) { g.setColor(Color.BLACK); g.drawOval(startPosX, startPosY + 30, 20, 20); diff --git a/FormLocomotive.java b/FormLocomotive.java index 57fd25a..765b90b 100644 --- a/FormLocomotive.java +++ b/FormLocomotive.java @@ -108,7 +108,6 @@ public class FormLocomotive extends JComponent{ super.repaint(); } public static void main(String[] args) { - new FormMapWithSetLocomotives(); } } diff --git a/FormMapWithSetLocomotives.java b/FormMapWithSetLocomotives.java index ce8dfab..18610d1 100644 --- a/FormMapWithSetLocomotives.java +++ b/FormMapWithSetLocomotives.java @@ -263,7 +263,73 @@ public class FormMapWithSetLocomotives extends JComponent { dialog.setVisible(true); } }); - statusPanel.add(showDeletedButton); + // Сохранения и загрузки + JFileChooser fileChooser = new JFileChooser(); + // Сохранение всех хранилищ + JButton saveButton = new JButton("Save"); + saveButton.addActionListener(e -> { + fileChooser.setDialogTitle("Saving"); + int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this); + if (result == JFileChooser.APPROVE_OPTION ) { + if (_mapsCollection.SaveData(fileChooser.getSelectedFile().getAbsolutePath())) { + JOptionPane.showMessageDialog(null, "Save success"); + } + else JOptionPane.showMessageDialog(null, "Save failed"); + } + + }); + statusPanel.add(saveButton); + // Загрузка всех хранилищ + JButton loadButton = new JButton("Load"); + loadButton.addActionListener(e -> { + fileChooser.setDialogTitle("Loading"); + int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this); + if (result == JFileChooser.APPROVE_OPTION ) { + if (_mapsCollection.LoadData(fileChooser.getSelectedFile().getAbsolutePath())) { + JOptionPane.showMessageDialog(null, "Load success"); + } + else JOptionPane.showMessageDialog(null, "Load failed"); + } + ReloadMaps(); + repaint(); + }); + statusPanel.add(loadButton); + + // Сохранение выбранной карты + JButton saveMapButton = new JButton("Save Map"); + saveMapButton.addActionListener(e -> { + fileChooser.setDialogTitle("Saving Map"); + int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this); + if (result == JFileChooser.APPROVE_OPTION ) { + if (listBoxMaps.getSelectedIndex() == -1) + { + return; + } + if(listBoxMaps.getSelectedValue().toString() == null) return; + if (_mapsCollection.SaveMap(listBoxMaps.getSelectedValue().toString(), fileChooser.getSelectedFile().getAbsolutePath())) { + JOptionPane.showMessageDialog(null, "Map saving success"); + } + else JOptionPane.showMessageDialog(null, "Map saving fail"); + repaint(); + } + }); + statusPanel.add(saveMapButton); + + // Загрузка одной карты + JButton loadMapButton = new JButton("Load Map"); + loadMapButton.addActionListener(e -> { + fileChooser.setDialogTitle("Loading"); + int result = fileChooser.showSaveDialog(FormMapWithSetLocomotives.this); + if (result == JFileChooser.APPROVE_OPTION ) { + if (_mapsCollection.LoadMap(fileChooser.getSelectedFile().getAbsolutePath())) { + JOptionPane.showMessageDialog(null, "Load Map success"); + } + else JOptionPane.showMessageDialog(null, "Load Map failed"); + } + ReloadMaps(); + repaint(); + }); + statusPanel.add(loadMapButton); formFrame.getContentPane().add(this); formFrame.setVisible(true); diff --git a/IDrawningExtra.java b/IDrawningExtra.java index fc9cf41..ce860f0 100644 --- a/IDrawningExtra.java +++ b/IDrawningExtra.java @@ -4,4 +4,6 @@ public interface IDrawningExtra { void setExtraNum(int num); void DrawExtra(int startPosX, int startPosY, Graphics2D g); void SetColor(Color color); + String TypeString(); + int getWheelsCount(); } diff --git a/IDrawningObject.java b/IDrawningObject.java index 80b49ff..1167973 100644 --- a/IDrawningObject.java +++ b/IDrawningObject.java @@ -8,6 +8,9 @@ public interface IDrawningObject { void MoveObject(Direction direction); /// Отрисовка объекта void DrawningObject(Graphics g); + + String getInfo(); + /// Получение текущей позиции объекта float[] GetCurrentPosition(); //0 - up diff --git a/MapWithSetLocomotivesGeneric.java b/MapWithSetLocomotivesGeneric.java index a30b6c6..0df89e8 100644 --- a/MapWithSetLocomotivesGeneric.java +++ b/MapWithSetLocomotivesGeneric.java @@ -1,5 +1,8 @@ import java.awt.*; import java.awt.image.BufferedImage; +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collections; import java.util.LinkedList; public class MapWithSetLocomotivesGeneric @@ -174,4 +177,25 @@ public class MapWithSetLocomotivesGeneric } } + /// Получение данных в виде строки + public String GetData(char separatorType, char separatorData) + { + String data = ""+ _map.getClass() + separatorType; + for (var locomotive : _setLocomotives.GetLocomotives()) + { + data += "" + locomotive.getInfo() + separatorData; + } + return data; + } + + /// Загрузка списка из массива строк + public void LoadData(String[] records) + { + Collections.reverse(Arrays.asList(records)); + for (var rec : records) + { + _setLocomotives.Insert((T)DrawningObjectLocomotive.Create(rec)); + } + } + } diff --git a/MapsCollection.java b/MapsCollection.java index 4aae1fa..0c666b0 100644 --- a/MapsCollection.java +++ b/MapsCollection.java @@ -1,9 +1,11 @@ +import java.io.*; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; public class MapsCollection { /// Словарь (хранилище) с картами - final HashMap> _mapStorages; + final HashMap> _mapStorages; /// Возвращение списка названий карт public ArrayList keys() { @@ -13,10 +15,13 @@ public class MapsCollection { private final int _pictureWidth; /// Высота окна отрисовки private final int _pictureHeight; + // Сепараторы + private final String separatorDict = "~"; + private final char separatorData = ';'; /// Конструктор public MapsCollection(int pictureWidth, int pictureHeight) { - _mapStorages = new HashMap>(); + _mapStorages = new HashMap>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -24,7 +29,7 @@ public class MapsCollection { public void AddMap(String name, AbstractMap map) { // Логика для добавления - if (!_mapStorages.containsKey(name)) _mapStorages.put(name, new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); + if (!_mapStorages.containsKey(name)) _mapStorages.put(name, new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); } /// Удаление карты public void DelMap(String name) @@ -33,15 +38,149 @@ public class MapsCollection { if (_mapStorages.containsKey(name)) _mapStorages.remove(name); } /// Доступ к парковке - public MapWithSetLocomotivesGeneric Get(String ind) + public MapWithSetLocomotivesGeneric Get(String ind) { // Логика получения объекта if (_mapStorages.containsKey(ind)) return _mapStorages.get(ind); return null; } // Доп.индексатор из задания - public DrawningObjectLocomotive Get (String name, int position) { + public IDrawningObject Get (String name, int position) { if (_mapStorages.containsKey(name)) return _mapStorages.get(name)._setLocomotives.Get(position); else return null; } + + /// Сохранение информации по локомотивам в хранилище в файл + public boolean SaveData(String filename) + { + File file = new File(filename); + if (file.exists()) + { + file.delete(); + } + try(BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) { + bw.write("MapsCollection\n"); + for (var storage : _mapStorages.entrySet()) { + bw.write("" + storage.getKey() + separatorDict + storage.getValue().GetData(separatorDict.charAt(0), separatorData) + "\n"); + } + } + catch (IOException ex) { + System.out.println(ex.getMessage()); + } + return true; + } + + // Сохранение одной выбранной карты + public boolean SaveMap(String map_name, String filename) { + File file = new File(filename); + MapWithSetLocomotivesGeneric map = Get(map_name); + if (file.exists()) + { + file.delete(); + } + try(BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) { + bw.write("SingleMap\n"); + bw.write("" + map_name + "\n"); + bw.write("" + map.getClass() + "\n"); + for (var locomotive : map._setLocomotives.GetLocomotives()) { + bw.write("" + locomotive.getInfo() + "\n"); + } + } + catch (IOException ex) { + System.out.println(ex.getMessage()); + } + return true; + } + + // Загрузка одной карты + public boolean LoadMap(String filename){ + File file = new File(filename); + if (!file.exists()) + { + return false; + } + try { + BufferedReader br = new BufferedReader(new FileReader(filename)); + String curLine = br.readLine(); + if (!curLine.contains("SingleMap")) { + return false; + } + String mapName = br.readLine(); + String mapClass = br.readLine(); + if (_mapStorages.containsKey(mapName)) { + _mapStorages.get(mapName)._setLocomotives.Clear(); + while((curLine = br.readLine()) != null) { + _mapStorages.get(mapName)._setLocomotives.Insert(DrawningObjectLocomotive.Create(curLine)); + } + _mapStorages.get(mapName)._setLocomotives.ReversePlaces(); + return true; + } + AbstractMap map = null; + switch (mapClass) + { + case "class SimpleMap": + map = new SimpleMap(); + break; + case "class SpikeMap": + map = new SpikeMap(); + break; + case "class RailMap": + map = new RailMap(); + break; + } + _mapStorages.put(mapName, new MapWithSetLocomotivesGeneric<>(_pictureWidth, _pictureHeight, map)); + while((curLine = br.readLine()) != null) { + _mapStorages.get(mapName)._setLocomotives.Insert(DrawningObjectLocomotive.Create(curLine)); + } + _mapStorages.get(mapName)._setLocomotives.ReversePlaces(); + + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + return true; + } + + /// Загрузка информации по локомотивам в депо из файла + public boolean LoadData(String filename) + { + File file = new File(filename); + if (!file.exists()) + { + return false; + } + try { + BufferedReader br = new BufferedReader(new FileReader(filename)); + String curLine = br.readLine(); + if (!curLine.contains("MapsCollection")) { + return false; + } + + _mapStorages.clear(); + while ((curLine = br.readLine()) != null) { + var elems = curLine.split(separatorDict); + AbstractMap map = null; + + switch (elems[1]) + { + case "class SimpleMap": + map = new SimpleMap(); + break; + case "class SpikeMap": + map = new SpikeMap(); + break; + case "class RailMap": + map = new RailMap(); + break; + } + + _mapStorages.put(elems[0], new MapWithSetLocomotivesGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages.get(elems[0]).LoadData(elems[2].split(Character.toString(separatorData))); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + return true; + } + + } diff --git a/SetLocomotivesGeneric.java b/SetLocomotivesGeneric.java index 72f1f94..07fee4a 100644 --- a/SetLocomotivesGeneric.java +++ b/SetLocomotivesGeneric.java @@ -1,4 +1,5 @@ import java.util.ArrayList; +import java.util.Collections; public class SetLocomotivesGeneric { @@ -34,6 +35,10 @@ public class SetLocomotivesGeneric return result; } + public void Clear() { + _places.clear(); + } + public T Get(int position) { if (position >= _maxCount || position < 0) @@ -46,4 +51,7 @@ public class SetLocomotivesGeneric { return _places; } + public void ReversePlaces() { + Collections.reverse(_places); + } }