diff --git a/src/drawing_objects/DrawingShip.java b/src/drawing_objects/DrawingShip.java index 64c2448..c5931cb 100644 --- a/src/drawing_objects/DrawingShip.java +++ b/src/drawing_objects/DrawingShip.java @@ -10,7 +10,7 @@ public class DrawingShip { public EntityShip getEntityShip(){ return entityShip; } - private IDrawBlocks drawingBlocks; + public IDrawBlocks drawingBlocks; public void setDrawingBlocks(IDrawBlocks blocks){ drawingBlocks = blocks; } diff --git a/src/drawing_objects/ExtensionDrawingShip.java b/src/drawing_objects/ExtensionDrawingShip.java new file mode 100644 index 0000000..d5f20bc --- /dev/null +++ b/src/drawing_objects/ExtensionDrawingShip.java @@ -0,0 +1,80 @@ +package drawing_objects; + +import entities.EntityBattleship; + +import java.awt.*; + +public class ExtensionDrawingShip { + private static String getColorName(Color col){ + if(col.equals(Color.RED)) + return "RED"; + if(col.equals(Color.GREEN)) + return "GREEN"; + if(col.equals(Color.BLUE)) + return "BLUE"; + if(col.equals(Color.YELLOW)) + return "YELLOW"; + if(col.equals(Color.WHITE)) + return "WHITE"; + if(col.equals(Color.GRAY)) + return "GRAY"; + if(col.equals(Color.BLACK)) + return "BLACK"; + if(col.equals(Color.PINK)) + return "PINK"; + return null; + } + + private static Color getColor(String col){ + if(col.equals("RED")) + return Color.RED; + if(col.equals("GREEN")) + return Color.GREEN; + if(col.equals("BLUE")) + return Color.BLUE; + if(col.equals("YELLOW")) + return Color.YELLOW; + if(col.equals("WHITE")) + return Color.WHITE; + if(col.equals("GRAY")) + return Color.GRAY; + if(col.equals("BLACK")) + return Color.BLACK; + if(col.equals("MAGENTA")) + return Color.MAGENTA; + return null; + } + public static DrawingShip createDrawingShip(String info, char separatorForObject, int width, int height){ + String[] strs = info.split(Character.toString(separatorForObject)); + if(strs.length == 5){ + return new DrawingShip(Integer.parseInt(strs[0]), + Integer.parseInt(strs[1]), getColor(strs[2]), width, height, + Integer.parseInt(strs[3]), Integer.parseInt(strs[4])); + } + if(strs.length == 8){ + return new DrawingBattleship(Integer.parseInt(strs[0]), + Integer.parseInt(strs[1]), getColor(strs[2]), getColor(strs[5]), + Boolean.parseBoolean(strs[6]), Boolean.parseBoolean(strs[7]), + width, height, Integer.parseInt(strs[3]), Integer.parseInt(strs[4])); + } + return null; + } + public static String getDataForSave(DrawingShip DrawingShip, char separatorForObject){ + var ship = DrawingShip.getEntityShip(); + if(ship == null) + return null; + var str = String.format("%d%c%d%c%s%c%d%c%d", + ship.getSpeed(), separatorForObject, + (int)ship.getWeight(), separatorForObject, + getColorName(ship.getBodyColor()), separatorForObject, + DrawingShip.drawingBlocks.getType(), separatorForObject, + DrawingShip.drawingBlocks.getNumber()); + if(!(ship instanceof EntityBattleship)){ + return str; + } + return String.format("%s%c%s%c%b%c%b%", str, separatorForObject, + getColorName(((EntityBattleship) ship).getAdditionalColor()), separatorForObject, + ((EntityBattleship) ship).getTurret(), separatorForObject, + ((EntityBattleship) ship).getRocketLauncher()); + } +} diff --git a/src/frames/FrameShipsCollection.java b/src/frames/FrameShipsCollection.java index a3e4ac6..c30e7a5 100644 --- a/src/frames/FrameShipsCollection.java +++ b/src/frames/FrameShipsCollection.java @@ -2,7 +2,9 @@ package frames; import javax.swing.*; import javax.swing.border.StrokeBorder; +import javax.swing.filechooser.FileFilter; import java.awt.*; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; @@ -12,6 +14,20 @@ import drawing_objects.*; import generics.*; import movement_strategy.*; +class TxtSaveFilter extends FileFilter { + @Override + public boolean accept(File f) { + if (f.isDirectory()) { + return false; + } + String s = f.getName().toLowerCase(); + return s.endsWith(".txt"); + } + @Override + public String getDescription() { + return "*.txt"; + } +} public class FrameShipsCollection extends JFrame { private final ShipsGenericStorage storage; LinkedList trashCollection = new LinkedList<>(); @@ -43,6 +59,18 @@ public class FrameShipsCollection extends JFrame { super.repaint(); } }; + JMenuBar menuFile = new JMenuBar(); + JMenu file = new JMenu("Файл"); + menuFile.add(file); + JMenuItem saveFile = new JMenuItem("Сохранить"); + JMenuItem loadFile = new JMenuItem("Загрузить"); + JMenuItem saveSet = new JMenuItem("Сохранить коллекцию"); + JMenuItem loadSet = new JMenuItem("Загрузить коллекцию"); + file.add(saveSet); + file.add(loadSet); + file.add(saveFile); + file.add(loadFile); + setJMenuBar(menuFile); pictureBoxCollection.setPreferredSize(new Dimension(700, 450)); JButton buttonAddShip = new JButton("Добавить корабль"); textFieldNumber = new TextField(); @@ -64,6 +92,10 @@ public class FrameShipsCollection extends JFrame { buttonRemoveShip.addActionListener(e -> buttonRemoveShipClick()); buttonRefreshCollection.addActionListener(e -> buttonRefreshCollectionClick()); buttonTrash.addActionListener(e -> buttonTrashClick()); + saveFile.addActionListener(e -> saveFile()); + saveSet.addActionListener(e -> saveSet()); + loadFile.addActionListener(e -> loadFile()); + loadSet.addActionListener(e -> loadSet()); //panels and constraints initialisation JPanel panelTools = new JPanel(new GridBagLayout()); panelTools.setBorder(new StrokeBorder(new BasicStroke(3))); @@ -140,7 +172,7 @@ public class FrameShipsCollection extends JFrame { private void buttonDeleteSet_Click() { if (listStorages.getSelectedIndex() == -1) return; - storage.delSet(listStorages.getSelectedValue()); + storage.delSet(listStorages.getSelectedValue(), trashCollection); reloadObjects(); } private void buttonAddShipClick() { @@ -194,4 +226,62 @@ public class FrameShipsCollection extends JFrame { } frame.setShip(trashCollection.pop()); } + private void saveFile(){ + JFileChooser fc = new JFileChooser("C:\\Users\\user\\Documents"); + fc.addChoosableFileFilter(new TxtSaveFilter()); + int retrieval = fc.showSaveDialog(null); + if (retrieval == JFileChooser.APPROVE_OPTION) { + File file = new File(fc.getSelectedFile() + "." + "txt"); + try { + storage.saveData(file); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + } + private void saveSet(){ + JFileChooser fc = new JFileChooser("C:\\Users\\user\\Documents"); + fc.addChoosableFileFilter(new TxtSaveFilter()); + int retrieval = fc.showSaveDialog(null); + if (retrieval == JFileChooser.APPROVE_OPTION) { + File file = new File(fc.getSelectedFile() + "." + "txt"); + try { + if(listStorages.getSelectedIndex() == -1) { + return; + } + storage.shipsStorages.get(listStorages.getSelectedValue()).saveData(file, listStorages.getSelectedValue()); + reloadObjects(); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + } + private void loadFile(){ + JFileChooser fc = new JFileChooser("C:\\Users\\user\\Documents"); + int ret = fc.showDialog(null, "Открыть файл"); + if(ret == JFileChooser.APPROVE_OPTION){ + File file = fc.getSelectedFile(); + try { + storage.loadData(file); + reloadObjects(); + pictureBoxCollection.repaint(); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + } + private void loadSet(){ + JFileChooser fc = new JFileChooser("C:\\Users\\user\\Documents"); + int ret = fc.showDialog(null, "Открыть файл"); + if(ret == JFileChooser.APPROVE_OPTION){ + File file = fc.getSelectedFile(); + try { + storage.loadCollection(file); + reloadObjects(); + pictureBoxCollection.repaint(); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + } } diff --git a/src/generics/SetGeneric.java b/src/generics/SetGeneric.java index 0e90f12..ace58ef 100644 --- a/src/generics/SetGeneric.java +++ b/src/generics/SetGeneric.java @@ -4,7 +4,6 @@ import java.util.ArrayList; public class SetGeneric{ private final ArrayList places; - public int getCount() {return places.size();} private final int maxCount; public SetGeneric(int count){ maxCount = count; @@ -27,9 +26,15 @@ public class SetGeneric{ places.remove(position); return true; } + public int getCount() { + return places.size(); + } public T get(int position){ if(!(position >= 0 && position < places.size())) return null; return places.get(position); } + public ArrayList getShips(){ + return new ArrayList<>(places); + } } \ No newline at end of file diff --git a/src/generics/ShipsGenericCollection.java b/src/generics/ShipsGenericCollection.java index 4806eab..c0ac8a8 100644 --- a/src/generics/ShipsGenericCollection.java +++ b/src/generics/ShipsGenericCollection.java @@ -4,16 +4,19 @@ import drawing_objects.*; import movement_strategy.*; import java.awt.*; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; public class ShipsGenericCollection{ private final int pictureWidth; private final int pictureHeight; private final int placeSizeWidth = 220; private final int placeSizeHeight = 60; - private final SetGeneric collection; - public int getCount(){ - return collection.getCount(); - } + public static char separatorRecords = ';'; + public static char separatorForObject = ':'; + private SetGeneric collection; public ShipsGenericCollection(int picWidth, int picHeight){ int width = picWidth / placeSizeWidth; int height = picHeight / placeSizeHeight; @@ -39,11 +42,14 @@ public class ShipsGenericCollection getShips(){ + return collection.getShips(); + } + public void clear(){ + collection = new SetGeneric<>(pictureWidth * pictureHeight); + } } diff --git a/src/generics/ShipsGenericStorage.java b/src/generics/ShipsGenericStorage.java index dceae6c..022aec7 100644 --- a/src/generics/ShipsGenericStorage.java +++ b/src/generics/ShipsGenericStorage.java @@ -1,15 +1,24 @@ package generics; import drawing_objects.DrawingShip; +import drawing_objects.ExtensionDrawingShip; import movement_strategy.DrawingObjectShip; +import java.io.*; +import java.util.*; +import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; +import java.util.Map; public class ShipsGenericStorage { private final int pictureWidth; private final int pictureHeight; - final HashMap> shipsStorages; + public final HashMap> shipsStorages; + private static final char separatorForKeyValue = '|'; + private final char separatorRecords = ';'; + private static final char separatorForObject = ':'; public ShipsGenericStorage(int pictureWidth, int pictureHeight){ shipsStorages = new HashMap<>(); this.pictureWidth = pictureWidth; @@ -23,11 +32,6 @@ public class ShipsGenericStorage { return; shipsStorages.put(name, new ShipsGenericCollection<>(pictureWidth, pictureHeight)); } - public void delSet(String name){ - if(!shipsStorages.containsKey(name)) - return; - shipsStorages.remove(name); - } public ShipsGenericCollection getSet(String name){ if(!shipsStorages.containsKey(name)) return null; @@ -36,4 +40,113 @@ public class ShipsGenericStorage { public DrawingShip getShip(String collectionName, int position){ return shipsStorages.get(collectionName).get(position); } + public boolean saveData(File f) throws IOException { + if(f.exists()) { + f.delete(); + } + f.createNewFile(); + StringBuilder data = new StringBuilder(); + data.append("ShipStorage\n"); + for(Map.Entry> record : shipsStorages.entrySet()){ + StringBuilder records = new StringBuilder(); + for(DrawingShip elem : record.getValue().getShips()) { + records.append(String.format("%s%c", ExtensionDrawingShip.getDataForSave(elem, separatorForObject), separatorRecords)); + } + data.append(String.format("%s%c%s\n", record.getKey(), separatorForKeyValue, records)); + } + if(data.length() == 0) + return false; + FileWriter writer = new FileWriter(f); + writer.write(data.toString()); + writer.flush(); + writer.close(); + return true; + } + public boolean loadData(File f) throws FileNotFoundException { + if(!f.exists()) + return false; + StringBuilder bufferTextFromFile =new StringBuilder(); + Scanner s = new Scanner(f); + while(s.hasNext()) + bufferTextFromFile.append(s.next()).append("\n"); + s.close(); + var strs = bufferTextFromFile.toString().split("\n"); + if(strs.length == 0) + return false; + if (!strs[0].startsWith("ShipStorage")) + return false; + shipsStorages.clear(); + for(String data : strs){ + String st = "\\" + separatorForKeyValue; + String[]record = data.split(st); + if (record.length != 2) + continue; + ShipsGenericCollection collection = new ShipsGenericCollection<>(pictureWidth, pictureHeight); + String[] set = record[1].split(Character.toString(separatorRecords)); + for(int i = set.length -1; i >=0; i--){ + String elem = set[i]; + DrawingShip ship = ExtensionDrawingShip.createDrawingShip(elem, separatorForObject, pictureWidth, pictureHeight); + if (ship != null) + { + if (!(collection.insert(ship))) + { + return false; + } + } + } + shipsStorages.put(record[0], collection); + } + return true; + } + public boolean loadCollection(File f) throws FileNotFoundException { + if(!f.exists()) + return false; + StringBuilder bufferTextFromFile =new StringBuilder(); + Scanner s = new Scanner(f); + while(s.hasNext()) + bufferTextFromFile.append(s.next()).append("\n"); + s.close(); + var strs = bufferTextFromFile.toString().split("\n"); + if(strs.length == 0) + return false; + if (!strs[0].startsWith("ShipCollection")) + return false; + String collectionName = strs[1]; + ShipsGenericCollection collection = getCollection(collectionName); + if(collection == null) + collection = new ShipsGenericCollection<>(pictureWidth, pictureHeight); + else + collection.clear(); + String[] shipsInfo = strs[2].split(Character.toString(ShipsGenericCollection.separatorRecords)); + for(int i = shipsInfo.length-1; i >= 0; i--){ + String data = shipsInfo[i]; + DrawingShip ship = ExtensionDrawingShip.createDrawingShip(data, ShipsGenericCollection.separatorForObject, pictureWidth, pictureHeight); + if (ship != null) + { + if (!(collection.insert(ship))) + { + return false; + } + } + } + addSetFromFile(collectionName, collection); + return true; + } + public void addSetFromFile(String name, ShipsGenericCollection toAdd){ + if(shipsStorages.containsKey(name)){ + shipsStorages.remove(name); + } + shipsStorages.put(name, toAdd); + } + public void delSet(String name, LinkedList trashBox){ + if(!shipsStorages.containsKey(name)) + return; + ShipsGenericCollection cur = shipsStorages.get(name); + for(int i = 0; i < cur.getCount(); i++) + trashBox.push(cur.get(i)); + shipsStorages.remove(name); + } + public ShipsGenericCollection getCollection(String collectionName){ + return shipsStorages.get(collectionName); + } }