Compare commits

...

5 Commits

8 changed files with 232 additions and 16 deletions

View File

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

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

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

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

@ -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
@ -177,7 +180,6 @@ public class MapWithSetLocomotivesGeneric
/// Получение данных в виде строки
public String GetData(char separatorType, char separatorData)
{
//string data = $"{_map.GetType().Name}{separatorType}";
String data = ""+ _map.getClass() + separatorType;
for (var locomotive : _setLocomotives.GetLocomotives())
{
@ -189,6 +191,7 @@ public class MapWithSetLocomotivesGeneric
/// Загрузка списка из массива строк
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);
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);
}
}