Compare commits

..

No commits in common. "29ba58c11aa92551bae758f12b3494135c6a2867" and "a9f39a20a9193d884b8c0d551dd526af5a701bc1" have entirely different histories.

8 changed files with 16 additions and 232 deletions

View File

@ -1,5 +1,4 @@
import java.awt.*; import java.awt.*;
import java.util.Objects;
import java.util.Random; import java.util.Random;
public class DrawningLocomotive { public class DrawningLocomotive {
@ -178,9 +177,9 @@ public class DrawningLocomotive {
IDrawningExtra drawningExtra = null; IDrawningExtra drawningExtra = null;
EntityLocomotive Locomotive = null; EntityLocomotive Locomotive = null;
String[] strs = info.split(Character.toString(_separatorForObject)); 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] == "Simple") drawningExtra = new ExtraWheelsDraw(Integer.parseInt(strs[6]), Locomotive.getBodyColor());
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 (strs[5] == "Star") drawningExtra = new ExtraStarWheelDraw(Integer.parseInt(strs[6]), Locomotive.getBodyColor());
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 (strs[5] == "Round") drawningExtra = new ExtraRoundWheelDraw(Integer.parseInt(strs[6]), Locomotive.getBodyColor());
if (drawningExtra == null) return null; if (drawningExtra == null) return null;
if (strs.length == 7) if (strs.length == 7)
{ {
@ -198,7 +197,7 @@ public class DrawningLocomotive {
new Color(Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4])), 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])), new Color(Integer.parseInt(strs[7]), Integer.parseInt(strs[8]), Integer.parseInt(strs[9])),
Boolean.parseBoolean(strs[10]), Boolean.parseBoolean(strs[10]),
Boolean.parseBoolean(strs[11]) Boolean.getBoolean(strs[11])
); );
return new DrawningWarmlyLocomotive(Locomotive, drawningExtra); return new DrawningWarmlyLocomotive(Locomotive, drawningExtra);
} }

View File

@ -6,11 +6,11 @@ public class ExtraRoundWheelDraw implements IDrawningExtra{
private Color color; private Color color;
public void setExtraNum(int num) { public void setExtraNum(int num) {
switch (num) { switch (num) {
case 3: { case 0: {
wheelsCount = WheelsCount.Three; wheelsCount = WheelsCount.Three;
break; break;
} }
case 4: { case 1: {
wheelsCount = WheelsCount.Four; wheelsCount = WheelsCount.Four;
break; break;
} }

View File

@ -6,11 +6,11 @@ public class ExtraStarWheelDraw implements IDrawningExtra{
private Color color; private Color color;
public void setExtraNum(int num) { public void setExtraNum(int num) {
switch (num) { switch (num) {
case 3: { case 0: {
wheelsCount = WheelsCount.Three; wheelsCount = WheelsCount.Three;
break; break;
} }
case 4: { case 1: {
wheelsCount = WheelsCount.Four; wheelsCount = WheelsCount.Four;
break; break;
} }

View File

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

View File

@ -263,73 +263,7 @@ public class FormMapWithSetLocomotives extends JComponent {
dialog.setVisible(true); 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.getContentPane().add(this);
formFrame.setVisible(true); formFrame.setVisible(true);

View File

@ -1,8 +1,5 @@
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
public class MapWithSetLocomotivesGeneric public class MapWithSetLocomotivesGeneric
@ -180,6 +177,7 @@ public class MapWithSetLocomotivesGeneric
/// Получение данных в виде строки /// Получение данных в виде строки
public String GetData(char separatorType, char separatorData) public String GetData(char separatorType, char separatorData)
{ {
//string data = $"{_map.GetType().Name}{separatorType}";
String data = ""+ _map.getClass() + separatorType; String data = ""+ _map.getClass() + separatorType;
for (var locomotive : _setLocomotives.GetLocomotives()) for (var locomotive : _setLocomotives.GetLocomotives())
{ {
@ -191,7 +189,6 @@ public class MapWithSetLocomotivesGeneric
/// Загрузка списка из массива строк /// Загрузка списка из массива строк
public void LoadData(String[] records) public void LoadData(String[] records)
{ {
Collections.reverse(Arrays.asList(records));
for (var rec : records) for (var rec : records)
{ {
_setLocomotives.Insert((T)DrawningObjectLocomotive.Create(rec)); _setLocomotives.Insert((T)DrawningObjectLocomotive.Create(rec));

View File

@ -1,11 +1,9 @@
import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
public class MapsCollection { public class MapsCollection {
/// Словарь (хранилище) с картами /// Словарь (хранилище) с картами
final HashMap<String, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>> _mapStorages; final HashMap<String, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>> _mapStorages;
/// Возвращение списка названий карт /// Возвращение списка названий карт
public ArrayList<String> keys() { public ArrayList<String> keys() {
@ -15,13 +13,10 @@ public class MapsCollection {
private final int _pictureWidth; private final int _pictureWidth;
/// Высота окна отрисовки /// Высота окна отрисовки
private final int _pictureHeight; private final int _pictureHeight;
// Сепараторы
private final String separatorDict = "~";
private final char separatorData = ';';
/// Конструктор /// Конструктор
public MapsCollection(int pictureWidth, int pictureHeight) public MapsCollection(int pictureWidth, int pictureHeight)
{ {
_mapStorages = new HashMap<String, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>>(); _mapStorages = new HashMap<String, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -29,7 +24,7 @@ public class MapsCollection {
public void AddMap(String name, AbstractMap map) public void AddMap(String name, AbstractMap map)
{ {
// Логика для добавления // Логика для добавления
if (!_mapStorages.containsKey(name)) _mapStorages.put(name, new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map)); if (!_mapStorages.containsKey(name)) _mapStorages.put(name, new MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>(_pictureWidth, _pictureHeight, map));
} }
/// Удаление карты /// Удаление карты
public void DelMap(String name) public void DelMap(String name)
@ -38,149 +33,15 @@ public class MapsCollection {
if (_mapStorages.containsKey(name)) _mapStorages.remove(name); if (_mapStorages.containsKey(name)) _mapStorages.remove(name);
} }
/// Доступ к парковке /// Доступ к парковке
public MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> Get(String ind) public MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> Get(String ind)
{ {
// Логика получения объекта // Логика получения объекта
if (_mapStorages.containsKey(ind)) return _mapStorages.get(ind); if (_mapStorages.containsKey(ind)) return _mapStorages.get(ind);
return null; return null;
} }
// Доп.индексатор из задания // Доп.индексатор из задания
public IDrawningObject Get (String name, int position) { public DrawningObjectLocomotive Get (String name, int position) {
if (_mapStorages.containsKey(name)) return _mapStorages.get(name)._setLocomotives.Get(position); if (_mapStorages.containsKey(name)) return _mapStorages.get(name)._setLocomotives.Get(position);
else return null; 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);
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,5 +1,4 @@
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
public class SetLocomotivesGeneric <T> public class SetLocomotivesGeneric <T>
{ {
@ -35,10 +34,6 @@ public class SetLocomotivesGeneric <T>
return result; return result;
} }
public void Clear() {
_places.clear();
}
public T Get(int position) public T Get(int position)
{ {
if (position >= _maxCount || position < 0) if (position >= _maxCount || position < 0)
@ -51,7 +46,4 @@ public class SetLocomotivesGeneric <T>
{ {
return _places; return _places;
} }
public void ReversePlaces() {
Collections.reverse(_places);
}
} }