Mochalov D.V. Hard LabWork06 #6

Closed
b0n3l3sS wants to merge 8 commits from LabWork06 into LabWork05
12 changed files with 344 additions and 11 deletions

View File

@ -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;
}
}

View File

@ -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));
}
}

View File

@ -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);

View File

@ -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);

View File

@ -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);

View File

@ -108,7 +108,6 @@ public class FormLocomotive extends JComponent{
super.repaint();
}
public static void main(String[] args) {
new FormMapWithSetLocomotives();
}
}

View File

@ -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);

View File

@ -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();
}

View File

@ -8,6 +8,9 @@ public interface IDrawningObject {
void MoveObject(Direction direction);
/// Отрисовка объекта
void DrawningObject(Graphics g);
String getInfo();
/// Получение текущей позиции объекта
float[] GetCurrentPosition();
//0 - up

View File

@ -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));
}
}
}

View File

@ -1,9 +1,11 @@
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class MapsCollection {
/// Словарь (хранилище) с картами
final HashMap<String, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>> _mapStorages;
final HashMap<String, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// Возвращение списка названий карт
public ArrayList<String> 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<String, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>>();
_mapStorages = new HashMap<String, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>>();
_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<DrawningObjectLocomotive, AbstractMap>(_pictureWidth, _pictureHeight, map));
if (!_mapStorages.containsKey(name)) _mapStorages.put(name, new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// Удаление карты
public void DelMap(String name)
@ -33,15 +38,149 @@ public class MapsCollection {
if (_mapStorages.containsKey(name)) _mapStorages.remove(name);
}
/// Доступ к парковке
public MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> Get(String ind)
public MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> 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<IDrawningObject, AbstractMap> map = Get(map_name);
Review

Нет проверки, что get вернул не null значение

Нет проверки, что get вернул не null значение
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<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.get(elems[0]).LoadData(elems[2].split(Character.toString(separatorData)));
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return true;
}
}

View File

@ -1,4 +1,5 @@
import java.util.ArrayList;
import java.util.Collections;
public class SetLocomotivesGeneric <T>
{
@ -34,6 +35,10 @@ public class SetLocomotivesGeneric <T>
return result;
}
public void Clear() {
_places.clear();
}
public T Get(int position)
{
if (position >= _maxCount || position < 0)
@ -46,4 +51,7 @@ public class SetLocomotivesGeneric <T>
{
return _places;
}
public void ReversePlaces() {
Collections.reverse(_places);
}
}