Tsukanova I.V. HardLabWork6 #8

Closed
Inohara wants to merge 4 commits from LabWork06 into LabWork05
14 changed files with 414 additions and 20 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_19" default="true" project-jdk-name="openjdk-19" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_19" project-jdk-name="openjdk-19" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -2,6 +2,7 @@ import java.awt.*;
public class DrawingBlocks implements IDrawingObjectBlock{
private BlockCount _block;
public int GetBlockCount(){return _block.GetBlockCount();}
public DrawingBlocks(BlockCount block) {
_block=block;
}

View File

@ -38,4 +38,16 @@ public class DrawingObjectWarship implements IDrawingObject {
if(_warship != null) return _warship.GetCurrentPosition();
return null;
}
@Override
public String GetInfo() {
if (_warship != null){
return ExtentionWarship.GetDataForSave(_warship);
}
return null;
}
public static IDrawingObject Create(String data){
return new DrawingObjectWarship(ExtentionWarship.CreateDrawingWarship(data));
}
}

View File

@ -5,6 +5,7 @@ public class DrawingRoundBlocks implements IDrawingObjectBlock{
public DrawingRoundBlocks(BlockCount block){
_block=block;
}
public int GetBlockCount(){return _block.GetBlockCount();}
@Override
public void SetBlockCount(int count){
for (BlockCount temp: BlockCount.values())

View File

@ -5,6 +5,7 @@ public class DrawingRoundRectangleBlocks implements IDrawingObjectBlock {
public DrawingRoundRectangleBlocks(BlockCount block) {
_block=block;
}
public int GetBlockCount(){return _block.GetBlockCount();}
@Override
public void SetBlockCount(int count){
for (BlockCount temp: BlockCount.values())

View File

@ -5,6 +5,7 @@ public class DrawingWarship extends JComponent {
protected EntityWarship Warship;
public EntityWarship GetWarship(){return Warship;}
protected IDrawingObjectBlock Blocks;
public String BlockType(){return Blocks.getClass().getName();}
private BlockCount _block;
protected int _startPosX;
@ -45,8 +46,8 @@ public class DrawingWarship extends JComponent {
Blocks = block;
}
public void SetBlocks(int blocksCount, IDrawingObjectBlock blocks){
Blocks = blocks;
public void SetBlocks(int blocksCount, IDrawingObjectBlock block){
Blocks = block;
Blocks.SetBlockCount(blocksCount);
}

64
src/ExtentionWarship.java Normal file
View File

@ -0,0 +1,64 @@
import java.awt.*;
public class ExtentionWarship {
private static final char _separatorForObject = ':';
private static BlockCount _block;
public static DrawingWarship CreateDrawingWarship(String info)
{
//speed - 0, weight - 1, color - 2, blocktype - 3, blockcount - 4,
//dopcolor - 5, bodykit - 6, cabin - 7, superengine- 8
String[] strs = info.split(String.valueOf(_separatorForObject));
IDrawingObjectBlock blockType = null;
switch (strs[3])
{
case "DrawingBlocks":
blockType = new DrawingBlocks(_block);
break;
case "DrawingRoundBlocks":
blockType = new DrawingRoundBlocks(_block);
break;
case "DrawingRoundRectangleBlocks":
blockType = new DrawingRoundRectangleBlocks(_block);
break;
}
if (strs.length == 5)
{
var temp = new DrawingWarship(Integer.parseInt(strs[0]),
Float.parseFloat(strs[1]),
new Color(Integer.parseInt(strs[2])),
Integer.parseInt(strs[4]));
temp.SetBlocks(Integer.parseInt(strs[4]), blockType);
return temp;
}
if (strs.length == 9)
{
var temp = new DrawingAircraftCarrier(Integer.parseInt(strs[0]),
Float.parseFloat(strs[1]),
new Color(Integer.parseInt(strs[2])),
new Color(Integer.parseInt(strs[5])),
Integer.parseInt(strs[4]),
Boolean.parseBoolean(strs[6]),
Boolean.parseBoolean(strs[7]),
Boolean.parseBoolean(strs[8]));
temp.SetBlocks(Integer.parseInt(strs[4]), blockType);
return temp;
}
return null;
}
public static String GetDataForSave(DrawingWarship drawingWarship)
{
var warship = drawingWarship.Warship;
var str = "" + warship.GetSpeed() + _separatorForObject + warship.GetWeight()
+ _separatorForObject + warship.GetBodyColor().getRGB() + _separatorForObject +
drawingWarship.BlockType() + _separatorForObject + drawingWarship.Blocks.GetBlockCount();
if (warship instanceof EntityAircraftCarrier aircraftCarrier)
{
return str + _separatorForObject + aircraftCarrier.GetDopColor().getRGB()
+ _separatorForObject + aircraftCarrier.GetBodyKit() + _separatorForObject
+ aircraftCarrier.GetCabin() + _separatorForObject + aircraftCarrier.GetSuperEngine();
}
return str;
}
}

View File

@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormMapWithSetWarships">
<grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="3" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="884" height="676"/>
<xy x="20" y="20" width="884" height="620"/>
</constraints>
<properties/>
<border type="none"/>
@ -11,7 +11,7 @@
<grid id="ae53a" binding="PictureBox" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<grid row="0" column="0" row-span="3" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<preferred-size width="727" height="24"/>
</grid>
</constraints>
@ -30,7 +30,7 @@
<grid id="16c60" binding="GroupBoxTools" layout-manager="GridLayoutManager" row-count="11" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="0" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
<grid row="1" column="1" row-span="2" col-span="1" vsize-policy="3" hsize-policy="0" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="bevel-lowered" title="Tools" title-justification="1" title-position="2">
@ -161,14 +161,6 @@
</constraints>
<properties/>
</component>
<component id="ddbe9" class="javax.swing.JButton" binding="CreateMapButton">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Create map"/>
</properties>
</component>
<component id="b2e9e" class="javax.swing.JButton" binding="DeleteMapButton">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
@ -185,14 +177,22 @@
</constraints>
<properties/>
</component>
<component id="ddbe9" class="javax.swing.JButton" binding="CreateMapButton">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Create map"/>
</properties>
</component>
<component id="8d7d6" class="javax.swing.JComboBox" binding="СomboBoxSelectorMap">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<model>
<item value="Простая карта"/>
<item value="Преграды-линии"/>
<item value="SimpleMap"/>
<item value="LineMap"/>
</model>
</properties>
</component>
@ -200,6 +200,56 @@
</grid>
</children>
</grid>
<grid id="fed73" class="javax.swing.JMenuBar" binding="menuStrip" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="1ed5d" class="javax.swing.JMenu" binding="menu" layout-manager="FlowLayout" hgap="5" vgap="5" flow-align="1">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="File"/>
</properties>
<border type="none"/>
<children>
<component id="ba181" class="javax.swing.JMenuItem" binding="saveToolStripMenuItem">
<constraints/>
<properties>
<text value="Save"/>
</properties>
</component>
<component id="601ab" class="javax.swing.JMenuItem" binding="loadToolStripMenuItem">
<constraints/>
<properties>
<text value="Load"/>
</properties>
</component>
<component id="62149" class="javax.swing.JMenuItem" binding="saveMapToolStripMenuItem">
<constraints/>
<properties>
<text value="SaveMap"/>
</properties>
</component>
<component id="5bcb" class="javax.swing.JMenuItem" binding="loadMapToolStripMenuItem">
<constraints/>
<properties>
<text value="LoadMap"/>
</properties>
</component>
</children>
</grid>
</children>
</grid>
<vspacer id="19c9">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
</children>
</grid>
</form>

View File

@ -1,7 +1,9 @@
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.function.Consumer;
@ -25,12 +27,18 @@ public class FormMapWithSetWarships extends JFrame{
private JButton CreateMapButton;
private JButton DeleteMapButton;
private JList ListBoxMaps;
private JMenuItem saveToolStripMenuItem;
private JMenuItem loadToolStripMenuItem;
private JMenuItem saveMapToolStripMenuItem;
private JMenuItem loadMapToolStripMenuItem;
private JMenuBar menuStrip;
private JMenu menu;
private Image bufferedImage;
private MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap> _mapWarshipsCollectionGeneric;
private MapsCollection _mapsCollection;
private final HashMap<String, AbstractMap> _mapsDict = new HashMap<>() {{
put("Простая карта", new SimpleMap());
put("Преграды-линии", new LineMap());
put("SimpleMap", new SimpleMap());
put("LineMap", new LineMap());
}};
public FormMapWithSetWarships(){
@ -84,6 +92,98 @@ public class FormMapWithSetWarships extends JFrame{
Icon iconRight = new ImageIcon("src\\Images\\ArrowRight.jpg");
ButtonRight.setIcon(iconRight);
File root = new File("D://2.1//RPP");
//сохранение
saveToolStripMenuItem.addActionListener(e -> {
JFileChooser fs = new JFileChooser();
fs.setCurrentDirectory(root);
fs.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt file", "txt");
fs.addChoosableFileFilter(filter);
fs.setDialogTitle("Save");
int result = fs.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fs.getSelectedFile();
if (_mapsCollection.SaveData(selectedFile.getPath()))
{
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат",JOptionPane.ERROR_MESSAGE);
}
}
});
//загрузка
loadToolStripMenuItem.addActionListener(e -> {
JFileChooser fs = new JFileChooser();
fs.setCurrentDirectory(root);
fs.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt file", "txt");
fs.addChoosableFileFilter(filter);
fs.setDialogTitle("Load");
int result = fs.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fs.getSelectedFile();
if (_mapsCollection.LoadData(selectedFile.getPath()))
{
ReloadMaps();
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось загрузить", "Результат",JOptionPane.ERROR_MESSAGE);
}
}
});
//сохранение карты
saveMapToolStripMenuItem.addActionListener(e -> {
JFileChooser fs = new JFileChooser();
fs.setCurrentDirectory(root);
fs.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt file", "txt");
fs.addChoosableFileFilter(filter);
fs.setDialogTitle("SaveMap");
int result = fs.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fs.getSelectedFile();
if (_mapsCollection.SaveMap(selectedFile.getPath(), ListBoxMaps.getSelectedValue().toString()))
{
JOptionPane.showMessageDialog(null, "Сохранение карты прошло успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Не сохранилась карта", "Результат",JOptionPane.ERROR_MESSAGE);
}
}
});
//загрузка карты
loadMapToolStripMenuItem.addActionListener(e -> {
JFileChooser fs = new JFileChooser();
fs.setCurrentDirectory(root);
fs.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt file", "txt");
fs.addChoosableFileFilter(filter);
fs.setDialogTitle("LoadMap");
int result = fs.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fs.getSelectedFile();
if (_mapsCollection.LoadMap(selectedFile.getPath()))
{
JOptionPane.showMessageDialog(null, "Загрузка карты прошла успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
ReloadMaps();
}
else
{
JOptionPane.showMessageDialog(null, "Не загрузилась карта", "Результат",JOptionPane.ERROR_MESSAGE);
}
}
});
ListBoxMaps.addListSelectionListener(e -> {
if(ListBoxMaps.getSelectedIndex() == -1)
return;

View File

@ -12,4 +12,6 @@ public interface IDrawingObject {
// Получение текущей позиции объекта
// /Left, Right, Top, Bottom)
float[] GetCurrentPosition();
//Получение информации по объекту
String GetInfo();
}

View File

@ -2,5 +2,6 @@ import java.awt.*;
public interface IDrawingObjectBlock {
void SetBlockCount(int count);
int GetBlockCount();
void DrawBlocks(Graphics2D g, int _startPosX, int _startPosY);
}

View File

@ -101,7 +101,7 @@ public class MapWithSetWarshipsGeneric <T extends IDrawingObject,U extends Abstr
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j <= _pictureHeight / _placeSizeHeight ; ++j)
for (int j = 0; j < _pictureHeight / _placeSizeHeight ; ++j)
{
g.setColor(brush);
g.setStroke(penWide);
@ -111,6 +111,7 @@ public class MapWithSetWarshipsGeneric <T extends IDrawingObject,U extends Abstr
g.setStroke(penThin);
}
}
}
private void DrawWarship(Graphics gr)
@ -138,4 +139,38 @@ public class MapWithSetWarshipsGeneric <T extends IDrawingObject,U extends Abstr
return null;
return _deletedWarship.pop();
}
public String GetData(char separatorType, char separatorData)
{
String data = _map.getClass().getName()+separatorType;
for (var warship : _setWarships)
{
data += warship.GetInfo() + separatorData;
}
return data;
}
public void LoadData(String[] records)
{
for (var rec : records)
{
_setWarships.Insert((T)DrawingObjectWarship.Create(rec));
}
}
public String GetDataMap(char separatorType, char separatorData)
{
String data = _map.getClass().getName() + separatorType + '\n';
for (var warship : _setWarships)
{
data += warship.GetInfo() + separatorData+'\n';
}
return data;
}
public void Clear() {
_setWarships.Clear();
}
}

View File

@ -1,3 +1,4 @@
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
@ -8,6 +9,8 @@ public class MapsCollection {
}
private final int _pictureWidth;
private final int _pictureHeight;
private final char separatorDict = '|';
private final char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
@ -45,4 +48,123 @@ public class MapsCollection {
}
return null;
}
public boolean SaveData(String filename) {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
try (BufferedWriter br = new BufferedWriter(new FileWriter(filename)))
{
br.write("MapsCollection\n");
for (var storage : _mapStorages.entrySet()) {
br.write(storage.getKey() + separatorDict + storage.getValue().GetData(separatorDict, separatorData) + "\n");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean LoadData(String filename)
{
if (!(new File(filename).exists()))
{
return false;
}
try (BufferedReader br = new BufferedReader(new FileReader(filename)))
{
String str = "";
if ((str = br.readLine()) == null || !str.contains("MapsCollection"))
{
return false;
}
//очищаем записи
_mapStorages.clear();
while ((str = br.readLine()) != null)
{
var elem = str.split(String.format("\\%c",separatorDict));
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "LineMap":
map = new LineMap();
break;
}
_mapStorages.put(elem[0], new MapWithSetWarshipsGeneric<>(_pictureWidth, _pictureHeight, map));
_mapStorages.get(elem[0]).LoadData(elem[2].split(separatorData + "\n?"));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
//Сохранение отдельного объекта класса-хранилища
public boolean SaveMap(String filename, String index) {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
var elem = _mapStorages.get(index);
if (elem==null)
return false;
try (BufferedWriter br = new BufferedWriter(new FileWriter(filename)))
{
br.write("MapsCollection\n");
br.write(index + separatorDict);
br.write(elem.GetDataMap(separatorDict, separatorData));
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
//Загрузка отдельного объекта класса-хранилища
public boolean LoadMap(String filename) {
if (!(new File(filename).exists()))
{
return false;
}
try (BufferedReader br = new BufferedReader(new FileReader(filename)))
{
String str = "";
if ((str = br.readLine()) == null || !str.contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
}
if ((str = br.readLine()) != null)
{
var elem = str.split(String.format("\\%c",separatorDict));
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "LineMap":
map = new LineMap();
break;
}
if(_mapStorages.containsKey(elem[0])){
_mapStorages.get(elem[0]).Clear();
}
else{
_mapStorages.put(elem[0],new MapWithSetWarshipsGeneric<>(_pictureWidth,_pictureHeight,map));
}
while((str = br.readLine()) != null) {
_mapStorages.get(elem[0]).LoadData(str.split(separatorData + "\n?"));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
}

View File

@ -47,4 +47,8 @@ public class SetWarshipsGeneric<T extends Object> implements Iterable<T>{
public Iterator<T> iterator() {
return _places.iterator();
}
public void Clear() {
_places.clear();
}
}