9 Commits

18 changed files with 542 additions and 63 deletions

View File

@@ -7,5 +7,14 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/apache-log4j-1.2.17/log4j-1.2.17.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>

0
loginfo.log Normal file
View File

0
logwarn.log Normal file
View File

View File

@@ -14,6 +14,11 @@ public class DrawingDeck extends JComponent implements IAdditionalDrawingObject{
}
}
@Override
public int GetDeckEnum()
{
return _decksEnum.GetAddEnum();
}
@Override
public void DrawDeck(Color colorDeck, Graphics g,float _startPosX,float _startPosY)
{
super.paintComponent(g);

View File

@@ -35,5 +35,18 @@ public class DrawingObjectShip implements IDrawingObject {
return _ship.GetCurrentPosition();
return null;
}
@Override
public String GetInfo()
{
if(_ship==null)
{
return null;
}
return ExtentionShip.GetDataForSave(_ship);
}
public static IDrawingObject Create(String data)
{
return new DrawingObjectShip(ExtentionShip.CreateDrawingShip(data));
}
}

View File

@@ -15,6 +15,11 @@ public class DrawingOvalDeck extends JComponent implements IAdditionalDrawingObj
}
}
@Override
public int GetDeckEnum()
{
return _decksEnum.GetAddEnum();
}
@Override
public void DrawDeck(Color colorDeck, Graphics g, float _startPosX, float _startPosY)
{
super.paintComponent(g);

View File

@@ -14,6 +14,11 @@ public class DrawingTriangleDeck extends JComponent implements IAdditionalDrawin
}
}
@Override
public int GetDeckEnum()
{
return _decksEnum.GetAddEnum();
}
@Override
public void DrawDeck(Color colorDeck, Graphics g,float _startPosX,float _startPosY)
{
super.paintComponent(g);

51
src/ExtentionShip.java Normal file
View File

@@ -0,0 +1,51 @@
import java.awt.*;
public class ExtentionShip {
private static final char _separatorForObject=':';
private static IAdditionalDrawingObject CreateDeck(String str,int num)
{
IAdditionalDrawingObject Deck=null;
switch(str)
{
case "DrawingDeck":
Deck=new DrawingDeck();
break;
case "DrawingTriangleDeck":
Deck=new DrawingTriangleDeck();
break;
case "DrawingOvalDeck":
Deck=new DrawingOvalDeck();
break;
}
Deck.SetAddEnum(num);
return Deck;
}
public static DrawingShip CreateDrawingShip(String info)
{
String[] strs = info.split(String.format("%s",_separatorForObject));
if(strs.length==5)
{
DrawingShip ship = new DrawingShip(Integer.parseInt(strs[0]),Integer.parseInt(strs[1]), new Color(Integer.parseInt(strs[2])),Integer.parseInt(strs[3]));
ship.SetDeck(CreateDeck(strs[4],Integer.parseInt(strs[3])));
return ship;
}
if(strs.length==8)
{
DrawingLiner liner=new DrawingLiner(Integer.parseInt(strs[0]),Integer.parseInt(strs[1]), new Color(Integer.parseInt(strs[2])),Integer.parseInt(strs[3]),new Color(Integer.parseInt(strs[5])),Boolean.parseBoolean(strs[6]),Boolean.parseBoolean(strs[7]));
liner.SetDeck(CreateDeck(strs[4],Integer.parseInt(strs[3])));
return liner;
}
return null;
}
public static String GetDataForSave(DrawingShip drawingShip)
{
var ship = drawingShip.Ship;
var str= String.format("%d%c%d%c%s%c%d%c%s",ship.GetSpeed(),_separatorForObject,(int)ship.GetWeight(),_separatorForObject,Integer.toString(ship.GetBodyColor().getRGB()),_separatorForObject,drawingShip.GetDeck().GetDeckEnum(),_separatorForObject,drawingShip.GetDeck().getClass().getSimpleName());
if(!(ship instanceof EntityLiner liner))
{
return str;
}
return String.format("%s%c%s%c%b%c%b",str,_separatorForObject,Integer.toString(liner.DopColor.getRGB()),_separatorForObject,liner.DopDeck,_separatorForObject,liner.Pool);
}
}

View File

@@ -1,16 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormMapWithSetShipsGeneric">
<grid id="27dc6" binding="Mainpanel" layout-manager="GridLayoutManager" row-count="4" 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="6" column-count="2" 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="798" height="526"/>
<xy x="20" y="20" width="798" height="551"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="9bb5a" binding="pictureBoxShip" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<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">
<grid row="2" column="0" row-span="3" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="600" height="400"/>
<preferred-size width="600" height="400"/>
<maximum-size width="600" height="400"/>
@@ -22,13 +22,13 @@
</grid>
<hspacer id="b305e">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<grid id="4fa91" binding="GroupBoxTools" layout-manager="GridLayoutManager" row-count="8" 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="1" column="1" row-span="3" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
<grid row="3" column="1" row-span="3" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
@@ -131,17 +131,17 @@
</component>
</children>
</grid>
<grid id="d087c" binding="GroupBoxMaps" layout-manager="GridLayoutManager" row-count="7" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<grid id="d087c" binding="GroupBoxMaps" layout-manager="GridLayoutManager" row-count="6" 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="3" indent="0" use-parent-layout="false"/>
<grid row="1" column="1" row-span="2" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="124b6" class="javax.swing.JTextField" binding="textBoxNewMapName">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
@@ -149,12 +149,12 @@
</component>
<vspacer id="3ed0f">
<constraints>
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="95ba3" class="javax.swing.JComboBox" binding="ComboBoxSelectorMap">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
<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>
@@ -165,7 +165,7 @@
</component>
<component id="fb777" class="javax.swing.JButton" binding="ButtonAddMap">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
<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="Добавить карту"/>
@@ -173,20 +173,15 @@
</component>
<component id="a358a" class="javax.swing.JButton" binding="ButtonDeleteMap">
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
<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"/>
</constraints>
<properties>
<text value="Удалить карту"/>
</properties>
</component>
<vspacer id="64e67">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="e221" class="javax.swing.JList" binding="ListBoxMaps" custom-create="true">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="2" anchor="0" fill="3" indent="0" use-parent-layout="false">
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="2" anchor="0" fill="3" indent="0" use-parent-layout="false">
<preferred-size width="150" height="50"/>
</grid>
</constraints>
@@ -194,6 +189,61 @@
</component>
</children>
</grid>
<grid id="e57df" class="javax.swing.JMenuBar" binding="MenuBar" 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"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="8737a" class="javax.swing.JMenu" binding="MenuFile" 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="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Файл"/>
</properties>
<border type="none"/>
<children>
<grid id="3edfc" class="javax.swing.JMenu" binding="MenuMap" layout-manager="FlowLayout" hgap="5" vgap="5" flow-align="1">
<constraints/>
<properties>
<text value="Карта"/>
</properties>
<border type="none"/>
<children>
<component id="d9dfb" class="javax.swing.JMenuItem" binding="SaveToolStripMap">
<constraints/>
<properties>
<text value="Сохранить"/>
</properties>
</component>
<component id="510d5" class="javax.swing.JMenuItem" binding="LoadToolStripMap">
<constraints/>
<properties>
<text value="Загрузить"/>
</properties>
</component>
</children>
</grid>
<component id="c2d9b" class="javax.swing.JMenuItem" binding="SaveToolStripMenu">
<constraints/>
<properties>
<text value="Сохранить"/>
<verticalAlignment value="0"/>
</properties>
</component>
<component id="8b9ff" class="javax.swing.JMenuItem" binding="LoadToolStripMenu">
<constraints/>
<properties>
<text value="Загрузить"/>
</properties>
</component>
</children>
</grid>
</children>
</grid>
</children>
</grid>
</form>

View File

@@ -6,7 +6,13 @@ import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import org.apache.log4j.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class FormMapWithSetShipsGeneric extends JFrame{
@@ -25,19 +31,26 @@ public class FormMapWithSetShipsGeneric extends JFrame{
private JTextField maskedTextBoxPosition;
private JTextField textBoxNewMapName;
private final int picWidth=600;
private final int picHeight=400;
private JButton ButtonAddMap;
private JList ListBoxMaps;
private JButton ButtonDeleteMap;
private JPanel GroupBoxMaps;
private JButton ButtonCheckDel;
private JMenuBar MenuBar;
private JMenu MenuFile;
private JMenuItem SaveToolStripMenu;
private JMenuItem LoadToolStripMenu;
private JMenu MenuMap;
private JMenuItem SaveToolStripMap;
private JMenuItem LoadToolStripMap;
private MapWithSetShipsGeneric<DrawingObjectShip,AbstractMap> _mapShipsCollectionGeneric;
private final HashMap<String,AbstractMap> _mapsDict = new HashMap<>(){{
put("Простая карта",new SimpleMap());
put("Карта море",new SeaMap());
}};
private final MapsCollection _mapsCollection;
private static Logger _logger = Logger.getLogger("FormMapWithSetShipsGeneric");
public void UpdateWindow(BufferedImage bmp)
{
pictureBoxShip.removeAll();
@@ -90,19 +103,30 @@ public class FormMapWithSetShipsGeneric extends JFrame{
public void actionPerformed(ActionEvent e) {
FormShipConfig formShipConfig = new FormShipConfig();
formShipConfig.AddEvent(newShip -> {
if (ListBoxMaps.getSelectedIndex() == -1) {
return;
}
if (newShip != null) {
DrawingObjectShip ship = new DrawingObjectShip(newShip);
if (_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).Add(ship) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен");
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект");
try
{
if (ListBoxMaps.getSelectedIndex() == -1) {
return;
}
if (newShip != null) {
DrawingObjectShip ship = new DrawingObjectShip(newShip);
if (_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).Add(ship) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен");
_logger.log(Level.INFO,"Добавлен объект: "+ship);
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект","Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.INFO,"Не удалось добавить объект:"+ship);
}
}
}catch (StorageOverflowException ex)
{
_logger.log(Level.WARN,"Ошибка переполнения хранилища: "+ex.getMessage());
JOptionPane.showMessageDialog(null, "Ошибка переполнения хранилища: "+ex.getMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Неизвестная ошибка: "+ex.getMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.FATAL,"Неизвестная ошибка: "+ex.getMessage());
}
});
formShipConfig.setSize(850, 300);
formShipConfig.setVisible(true);
@@ -114,6 +138,7 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if (ListBoxMaps.getSelectedIndex() == -1)
return;
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
_logger.log(Level.INFO, "Переход на карту: "+ListBoxMaps.getSelectedValue().toString());
}
});
ButtonDeleteShip.addActionListener(new ActionListener() {
@@ -129,14 +154,26 @@ public class FormMapWithSetShipsGeneric extends JFrame{
return;
}
int pos=Integer.parseInt(maskedTextBoxPosition.getText());
if(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).Delete(pos)!=null)
try
{
JOptionPane.showMessageDialog(null, "Объект удален");
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект");
var delShip = _mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).Delete(pos);
if(delShip!=null)
{
JOptionPane.showMessageDialog(null, "Объект удален");
_logger.log(Level.INFO,"Объект удален"+delShip);
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект","Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.INFO,"Не удалось удалить объект"+delShip);
}
} catch (ShipNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Ошибка удаления: "+ex.getMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.WARN,"Ошибка удаления: "+ex.getMessage());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Неизвестная ошибка: "+ex.getMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.FATAL,"Неизвестная ошибка: "+ex.getMessage());
}
}
});
@@ -244,13 +281,16 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if (ComboBoxSelectorMap.getSelectedIndex() == -1 || textBoxNewMapName.getText().isEmpty())
{
JOptionPane.showMessageDialog(null,"Не все данные заполнены","Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не все данные заполнены");
return;
}
if(!_mapsDict.containsKey(ComboBoxSelectorMap.getSelectedItem()))
{
JOptionPane.showMessageDialog(null,"Нет такой карты","Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Нет такой карты");
}
_mapsCollection.AddMap(textBoxNewMapName.getText(),_mapsDict.get(ComboBoxSelectorMap.getSelectedItem().toString()));
_logger.log(Level.INFO,"Добавлена карта: "+textBoxNewMapName.getText());
ReloadMaps();
}
});
@@ -264,6 +304,7 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if(JOptionPane.showConfirmDialog(null,"Удалить карту"+ListBoxMaps.getSelectedValue().toString()+"?","Удаление",JOptionPane.YES_NO_OPTION)==0)
{
_mapsCollection.DelMap(ListBoxMaps.getSelectedValue().toString());
_logger.log(Level.INFO, "Удалена карта: "+ListBoxMaps.getSelectedValue().toString());
ReloadMaps();
}
}
@@ -275,7 +316,7 @@ public class FormMapWithSetShipsGeneric extends JFrame{
{
return;
}
DrawingObjectShip ship=_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).GetShipsDeleted();
IDrawingObject ship=_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).GetShipsDeleted();
if(ship==null)
{
JOptionPane.showMessageDialog(null,"Коллекция пуста","Ошибка",JOptionPane.ERROR_MESSAGE);
@@ -286,6 +327,89 @@ public class FormMapWithSetShipsGeneric extends JFrame{
formShip.setVisible(true);
}
});
SaveToolStripMenu.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc= new JFileChooser();
int returnVal = fc.showSaveDialog(null);
if(returnVal==JFileChooser.APPROVE_OPTION)
{
try {
File selectedFile=fc.getSelectedFile();
_mapsCollection.SaveData(selectedFile.getPath());
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
_logger.log(Level.INFO,"Сохранение прошло успешно");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Не сохранилось: "+ex.getMessage(), "Результат",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не сохранилось: "+ex.getMessage());
}
}
}
});
LoadToolStripMenu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc= new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if(returnVal==JFileChooser.APPROVE_OPTION)
{
try {
File selectedFile=fc.getSelectedFile();
_mapsCollection.LoadData(selectedFile.getPath());
ReloadMaps();
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
_logger.log(Level.INFO,"Загрузка прошло успешно");
} catch (FileNotFoundException | IllegalArgumentException ex ) {
JOptionPane.showMessageDialog(null, "Не загрузилось: "+ex.getMessage(), "Результат",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не загрузилось: "+ex.getMessage());
}
}
}
});
SaveToolStripMap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(ListBoxMaps.getSelectedIndex()==-1)
{
return;
}
JFileChooser fc= new JFileChooser();
int returnVal = fc.showSaveDialog(null);
if(returnVal==JFileChooser.APPROVE_OPTION)
{
try {
File selectedFile=fc.getSelectedFile();
_mapsCollection.SaveMapData(selectedFile.getPath(),ListBoxMaps.getSelectedValue().toString());
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
_logger.log(Level.INFO,"Сохранение прошло успешно");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Не сохранилось: "+ex.getMessage(), "Результат",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не сохранилось: "+ex.getMessage());
}
}
}
});
LoadToolStripMap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc= new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if(returnVal==JFileChooser.APPROVE_OPTION)
{
try {
File selectedFile=fc.getSelectedFile();
_mapsCollection.LoadMapData(selectedFile.getPath());
ReloadMaps();
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
_logger.log(Level.INFO,"Загрузка прошло успешно");
} catch (FileNotFoundException | IllegalArgumentException ex ) {
JOptionPane.showMessageDialog(null, "Не загрузилось: "+ex.getMessage(), "Результат",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не загрузилось: "+ex.getMessage());
}
}
}
});
}
private void createUIComponents() {

View File

@@ -2,5 +2,6 @@ import java.awt.*;
public interface IAdditionalDrawingObject {
void SetAddEnum(int decksAmount);
int GetDeckEnum();
void DrawDeck(Color colorDeck, Graphics g, float _startPosX, float _startPosY);
}

View File

@@ -7,5 +7,6 @@ public interface IDrawingObject {
void DrawingObject(Graphics g);
float[] GetCurrentPosition();
public DrawingShip GetDrawingObjectShip();
String GetInfo();
}

View File

@@ -20,16 +20,18 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
_pictureHeight = picHeight;
_map = map;
}
public int Add(T ship)
{
public int Add(T ship) throws StorageOverflowException {
return _setShips.Insert(ship);
}
public T Delete(int position)
{
public T Delete(int position) throws ShipNotFoundException {
T ship=_setShips.Remove(position);
_deletedShips.add(ship);
return ship;
}
public void Clear()
{
_setShips.Clear();
}
public BufferedImage ShowSet()
{
BufferedImage bmp = new BufferedImage(_pictureWidth,_pictureHeight,BufferedImage.TYPE_INT_RGB);
@@ -38,8 +40,7 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
DrawShips(gr);
return bmp;
}
public BufferedImage ShowOnMap()
{
public BufferedImage ShowOnMap(){
Shaking();
for(var ship : _setShips)
{
@@ -55,8 +56,7 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
}
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_RGB);
}
private void Shaking()
{
private void Shaking(){
int j = _setShips.Count() - 1;
for (int i = 0; i < _setShips.Count(); i++)
{
@@ -67,8 +67,16 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
var ship = _setShips.Get(j);
if (ship != null)
{
_setShips.Insert(ship, i);
_setShips.Remove(j);
try {
_setShips.Insert(ship, i);
} catch (StorageOverflowException e) {
throw new RuntimeException(e);
}
try {
_setShips.Remove(j);
} catch (ShipNotFoundException e) {
throw new RuntimeException(e);
}
break;
}
}
@@ -127,6 +135,35 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
}
}
public String GetDataForMap(char separatorType,char separatorData,boolean IsInfoMap)
{
if(IsInfoMap)
{
StringBuilder data=new StringBuilder(String.format("%s%c",_map.getClass().getSimpleName(),separatorType));
return data.toString();
}
StringBuilder data=new StringBuilder();
for (var ship: _setShips)
{
data.append(String.format("%s%c",ship.GetInfo(),separatorData));
}
return data.toString();
}
public String GetData(char separatorType,char separatorData)
{
StringBuilder data=new StringBuilder(String.format("%s%c",_map.getClass().getSimpleName(),separatorType));
for (var ship: _setShips)
{
data.append(String.format("%s%c",ship.GetInfo(),separatorData));
}
return data.toString();
}
public void LoadData(String[] records) throws StorageOverflowException {
for(var rec:records)
{
_setShips.Insert((T) DrawingObjectShip.Create(rec));
}
}
public T GetSelectedShip(int ind){
return _setShips.Get(ind);
}

View File

@@ -1,15 +1,19 @@
import java.io.*;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.HashMap;
public class MapsCollection {
private final HashMap<String,MapWithSetShipsGeneric<DrawingObjectShip, AbstractMap>> _mapStorages;
private final HashMap<String,MapWithSetShipsGeneric<IDrawingObject, AbstractMap>> _mapStorages;
public ArrayList<String> Keys()
{
return new ArrayList<>(_mapStorages.keySet());
}
private final int _pictureWidth;
private final int _pictureHeight;
private final char separatorDict = '|';
private final char separatorData = ';';
public MapsCollection(int pictureWidth,int pictureHeight)
{
_mapStorages=new HashMap<>();
@@ -27,7 +31,7 @@ public class MapsCollection {
{
_mapStorages.remove(name);
}
public MapWithSetShipsGeneric<DrawingObjectShip,AbstractMap> Get(String ind)
public MapWithSetShipsGeneric<IDrawingObject,AbstractMap> Get(String ind)
{
if(_mapStorages.containsKey(ind))
{
@@ -35,15 +39,130 @@ public class MapsCollection {
}
return null;
}
public DrawingObjectShip Get(String name, int ind) {
public IDrawingObject Get(String name, int ind) {
if (_mapStorages.containsKey(name))
{
return _mapStorages.get(name).GetSelectedShip(ind);
}
return null;
}
public void SaveData(String filename) throws IOException {
File file = new File(filename);
if(file.exists())
{
file.delete();
}
try(BufferedWriter fw = new BufferedWriter(new FileWriter(file)))
{
fw.write(String.format("MapsCollection%s",System.lineSeparator()));
for(var storage:_mapStorages.keySet())
{
fw.write(String.format("%s%c%s%s",storage,separatorDict,_mapStorages.get(storage).GetData(separatorDict,separatorData),System.lineSeparator()));
}
}
}
public void LoadData(String filename) throws FileNotFoundException {
File file=new File(filename);
if(!file.exists())
{
throw new FileNotFoundException("Файл не найден");
}
try(BufferedReader fr = new BufferedReader(new FileReader(file)))
{
String str="";
if((str=fr.readLine())==null || !str.contains("MapsCollection"))
{
throw new IllegalArgumentException("Формат данных в файле неправильный");
}
_mapStorages.clear();
while((str=fr.readLine())!=null)
{
var tempElem = str.split(String.format("\\%c",separatorDict));
AbstractMap map =null;
switch (tempElem[1])
{
case "SimpleMap":
map=new SimpleMap();
break;
case "SeaMap":
map=new SeaMap();
break;
}
_mapStorages.put(tempElem[0],new MapWithSetShipsGeneric<IDrawingObject,AbstractMap>(_pictureWidth,_pictureHeight,map));
if(tempElem.length==3)
{
_mapStorages.get(tempElem[0]).LoadData(tempElem[2].split(String.valueOf(separatorData)));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (StorageOverflowException e) {
throw new RuntimeException(e);
}
}
public void SaveMapData(String filename,String Key)throws IOException
{
File file = new File(filename);
if(file.exists())
{
file.delete();
}
try(BufferedWriter fw = new BufferedWriter(new FileWriter(file)))
{
fw.write(String.format("Map_Info:%s",System.lineSeparator()));
var Map = _mapStorages.get(Key);
fw.write(String.format("%s%c%s%s",Key,separatorDict,Map.GetDataForMap(separatorDict,separatorData,true),System.lineSeparator()));
fw.write(String.format("Objects_In_Map_Info:%s",System.lineSeparator()));
fw.write(String.format("%s%s",Map.GetDataForMap(separatorDict,separatorData,false),System.lineSeparator()));
}
}
public void LoadMapData(String filename) throws FileNotFoundException {
File file=new File(filename);
if(!file.exists())
{
throw new FileNotFoundException("Файл не найден");
}
try(BufferedReader fr = new BufferedReader(new FileReader(file)))
{
String str="";
if((str=fr.readLine())==null || !str.contains("Map_Info:"))
{
throw new IllegalArgumentException("Формат данных в файле неправильный");
}
str=fr.readLine();
var tempElem = str.split(String.format("\\%c",separatorDict));
AbstractMap map =null;
switch (tempElem[1])
{
case "SimpleMap":
map=new SimpleMap();
break;
case "SeaMap":
map=new SeaMap();
break;
}
if(_mapStorages.containsKey(tempElem[0]))
{
MapWithSetShipsGeneric<IDrawingObject, AbstractMap> storage = _mapStorages.get(tempElem[0]);
storage.Clear();
}
_mapStorages.put(tempElem[0], new MapWithSetShipsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
String str_second=fr.readLine();
if(!str_second.contains("Objects_In_Map_Info:"))
{
throw new IllegalArgumentException("Формат данных в файле неправильный");
}
str_second= fr.readLine();
str=str+str_second;
tempElem = str.split(String.format("\\%c",separatorDict));
if(tempElem.length==3) {
_mapStorages.get(tempElem[0]).LoadData(tempElem[2].split(String.valueOf(separatorData)));
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (StorageOverflowException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -12,26 +12,31 @@ public class SetShipsGeneric<T extends Object> implements Iterable<T>{
_maxCount=count;
_places = new ArrayList<>();
}
public int Insert(T ship)
{
public int Insert(T ship) throws StorageOverflowException {
return Insert(ship, 0);
}
public int Insert(T ship, int position)
{
public int Insert(T ship, int position) throws StorageOverflowException {
if(_maxCount == Count())
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position > Count() || _maxCount == Count()) return -1;
_places.add(position,ship);
return position;
}
public T Remove(int position)
{
public T Remove(int position) throws ShipNotFoundException {
if (position >= Count() || position < 0)
{
return null;
throw new ShipNotFoundException(position);
}
T ship = (T) _places.get(position);
_places.remove(ship);
return ship;
}
public void Clear()
{
_places.clear();
}
public T Get(int position)
{
if (position >= Count() || position<0)
@@ -40,8 +45,7 @@ public class SetShipsGeneric<T extends Object> implements Iterable<T>{
}
return _places.get(position);
}
public void Set(int position,T value)
{
public void Set(int position,T value) throws StorageOverflowException {
if (position < _maxCount || position >= 0)
{
Insert(value,position);

View File

@@ -0,0 +1,14 @@
public class ShipNotFoundException extends Exception{
public ShipNotFoundException(int i){
super(String.format("%s%d","Не найден объект по позиции",i));
}
public ShipNotFoundException(){
super();
}
public ShipNotFoundException(String message){
super(message);
}
public ShipNotFoundException(String message,Exception ex){
super(message,ex);
}
}

View File

@@ -0,0 +1,14 @@
public class StorageOverflowException extends Exception {
public StorageOverflowException(int count){
super("В наборе превышено допустимое количество: "+count);
}
public StorageOverflowException(){
super();
}
public StorageOverflowException(String message){
super(message);
}
public StorageOverflowException(String message,Exception ex){
super(message,ex);
}
}

27
src/log4j.properties Normal file
View File

@@ -0,0 +1,27 @@
log4j.logger.FormMapWithSetShipsGeneric=INFO, fileAppender,adminAppender
log4j.additivity.file=false
log4j.additivity.admin=false
log4j.appender.fileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.fileAppender.File=loginfo.log
log4j.appender.fileAppender.MaxFileSize=1MB
log4j.appender.fileAppender.MaxBackupIndex=1
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.filter.F1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.fileAppender.filter.F1.LevelMin=INFO
log4j.appender.fileAppender.filter.F1.LevelMax=INFO
log4j.appender.fileAppender.filter.F1.AcceptOnMatch=true
log4j.appender.fileAppender.layout.ConversionPattern=%-5p %c{1}:%L - %m %d{dd-MM-yyyy}%n
log4j.appender.adminAppender=org.apache.log4j.RollingFileAppender
log4j.appender.adminAppender.File=logwarn.log
log4j.appender.adminAppender.MaxFileSize=1MB
log4j.appender.adminAppender.MaxBackupIndex=1
log4j.appender.adminAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.adminAppender.filter.F1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.adminAppender.filter.F1.LevelMin=WARN
log4j.appender.adminAppender.filter.F1.LevelMax=ERROR
log4j.appender.adminAppender.filter.F1.AcceptOnMatch=true
log4j.appender.adminAppender.layout.ConversionPattern=%-5p %c{1}:%L - %m %d{dd-MM-yyyy}%n