ПИбд-23 Салин Олег Алексеевич Лабораторная работа №6 (усложненная) #7

Closed
Oleja123 wants to merge 3 commits from Lab6 into Lab5
6 changed files with 400 additions and 10 deletions

View File

@ -46,9 +46,31 @@ public class DrawningMonorail {
DrawningWheels = new DrawningWheelsCart(_monorailWidth - dif, _monorailHeight,_startPosX,_startPosY,wheelColor,tireColor);
else
DrawningWheels = new DrawningWheelsOrn(_monorailWidth - dif, _monorailHeight,_startPosX,_startPosY,wheelColor,tireColor);
DrawningWheels.ChangeWheelsNumb(rand.nextInt(1, 6));
DrawningWheels.ChangeWheelsNumb(rand.nextInt(4));
}
public int GetIDrawType(){
if(DrawningWheels instanceof DrawningWheels)
return 0;
if(DrawningWheels instanceof DrawningWheelsCart)
return 1;
if(DrawningWheels instanceof DrawningWheelsOrn)
return 2;
return -1;
}
public void ChangeIDraw(int variant){
IDraw cur;
int dif = _monorailWidth / 10;
if(variant == 0)
cur = new DrawningWheels(_monorailWidth - dif, _monorailHeight,_startPosX,_startPosY,Color.GRAY,Color.BLACK);
else if(variant == 1)
cur = new DrawningWheelsCart(_monorailWidth - dif, _monorailHeight,_startPosX,_startPosY, Color.GRAY,Color.BLACK);
else
cur = new DrawningWheelsOrn(_monorailWidth - dif, _monorailHeight,_startPosX,_startPosY,Color.GRAY, Color.BLACK);
ChangeIDraw(cur);
}
public void ChangeIDraw(IDraw obj){
DrawningWheels = obj;
obj.ChangeWheelsNumb(_wheelNumb);

View File

@ -0,0 +1,88 @@
package MonorailHard.DrawningObjects;
import MonorailHard.Entities.EntityLocomotive;
import java.awt.*;
public class ExtentionDrawningMonorail {
private static String getName(Color col){
if(col.equals(Color.RED))
return new String("RED");
if(col.equals(Color.GREEN))
return new String("GREEN");
if(col.equals(Color.BLUE))
return new String("BLUE");
if(col.equals(Color.YELLOW))
return new String("YELLOW");
if(col.equals(Color.WHITE))
return new String("WHITE");
if(col.equals(Color.GRAY))
return new String("GRAY");
if(col.equals(Color.BLACK))
return new String("BLACK");
if(col.equals(Color.PINK))
return new String("PINK");
return null;
}
private static Color getColor(String col){
if(col.equals("RED"))
return Color.RED;
if(col.equals("GREEN"))
return Color.GREEN;
if(col.equals("BLUE"))
return Color.BLUE;
if(col.equals("YELLOW"))
return Color.YELLOW;
if(col.equals("WHITE"))
return Color.WHITE;
if(col.equals("GRAY"))
return Color.GRAY;
if(col.equals("BLACK"))
return Color.BLACK;
if(col.equals("PINK"))
return Color.PINK;
return null;
}
public static DrawningMonorail CreateDrawningMonorail(String info, char separatorForObject,
int width, int height){
String[] strs = info.split(Character.toString(separatorForObject));
if(strs.length == 7){
DrawningMonorail toRet = new DrawningMonorail(Integer.parseInt(strs[0]),
Integer.parseInt(strs[1]), getColor(strs[2]),
getColor(strs[3]), getColor(strs[4]), width, height);
toRet.ChangeWheelsNumb(Integer.parseInt(strs[5]));
toRet.ChangeIDraw(Integer.parseInt(strs[6]));
return toRet;
}
if(strs.length == 10){
DrawningMonorail toRet = new DrawningLocomotive(Integer.parseInt(strs[0]),
Integer.parseInt(strs[1]), getColor(strs[2]),
getColor(strs[3]), getColor(strs[4]),
4, width, height, Boolean.parseBoolean(strs[7]),
Boolean.parseBoolean(strs[8]), getColor(strs[9]));
toRet.ChangeWheelsNumb(Integer.parseInt(strs[5]));
toRet.ChangeIDraw(Integer.parseInt(strs[6]));
return toRet;
}
return null;
}
public static String GetDataForSave(DrawningMonorail drawningMonorail, char separatorForObject){
var monorail = drawningMonorail.EntityMonorail;
if(monorail == null)
return null;
String colName = getName(monorail.BodyColor);
var str = String.format("%d%c%d%c%s%c%s%c%s%c%d%c%d", monorail.Speed(), separatorForObject, (int)monorail.Weight(),
separatorForObject, getName(monorail.BodyColor), separatorForObject,
getName(monorail.WheelColor), separatorForObject, getName(monorail.TireColor), separatorForObject,
drawningMonorail._wheelNumb, separatorForObject, drawningMonorail.GetIDrawType());
if(!(monorail instanceof EntityLocomotive)){
return str;
}
var nstr = String.format("%s%c%b%c%b%c%s", str, separatorForObject,
((EntityLocomotive) monorail).SecondCabine(), separatorForObject,
((EntityLocomotive) monorail).MagniteRail(), separatorForObject,
getName(((EntityLocomotive) monorail).AdditionalColor), separatorForObject);
return nstr;
}
}

View File

@ -1,18 +1,44 @@
package MonorailHard;
import MonorailHard.DrawningObjects.DrawningMonorail;
import MonorailHard.DrawningObjects.ExtentionDrawningMonorail;
import MonorailHard.Generics.MonorailGenericCollection;
import MonorailHard.Generics.MonorailGenericStorage;
import MonorailHard.Generics.MonorailTrashCollection;
import MonorailHard.MovementStrategy.DrawningObjectMonorail;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
class TxtSaveFilter extends FileFilter {
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return false;
}
String s = f.getName().toLowerCase();
return s.endsWith(".txt");
}
@Override
public String getDescription() {
return "*.txt";
}
}
public class FormMonorailCollection {
private final MonorailGenericStorage _storage;
@ -43,7 +69,20 @@ public class FormMonorailCollection {
listBoxStorages.setSelectedIndex(index);
}
public FormMonorailCollection(){
JMenuBar menuFile = new JMenuBar();
JMenu file = new JMenu("Файл");
menuFile.add(file);
JMenuItem saveFile = new JMenuItem("Сохранить");
JMenuItem loadFile = new JMenuItem("Загрузить");
JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию");
JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию");
file.add(saveCollection);
file.add(loadCollection);
file.add(saveFile);
file.add(loadFile);
MonorailTrashCollection<DrawningMonorail> _trashCollection = new MonorailTrashCollection<>();
JButton callTrashButton = new JButton("мусор");
_storage = new MonorailGenericStorage(pictureBoxWidth, pictureBoxHeight);
@ -78,11 +117,93 @@ public class FormMonorailCollection {
toolBox.add(refreshButton);
toolBox.add(callTrashButton);
collectionFrame.add(toolBox);
collectionFrame.setJMenuBar(menuFile);
collectionFrame.add(canv);
collectionFrame.setVisible(true);
canv._storage = _storage;
canv.listBoxStorages = listBoxStorages;
saveFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser("C:\\Users\\frenk\\OneDrive\\Рабочий стол\\lab6saves");
fc.addChoosableFileFilter(new TxtSaveFilter());
int retrieval = fc.showSaveDialog(null);
if (retrieval == JFileChooser.APPROVE_OPTION) {
File file = new File(fc.getSelectedFile() + "." + "txt");
try {
_storage.SaveData(file);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
});
saveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser("C:\\Users\\frenk\\OneDrive\\Рабочий стол\\lab6saves");
fc.addChoosableFileFilter(new TxtSaveFilter());
int retrieval = fc.showSaveDialog(null);
if (retrieval == JFileChooser.APPROVE_OPTION) {
File file = new File(fc.getSelectedFile() + "." + "txt");
try {
if(listBoxStorages.getSelectedIndex() == -1) {
return;
}
_storage._monorailStorages.get(listBoxStorages.getSelectedValue()).SaveData(file, listBoxStorages.getSelectedValue());
ReloadObjects();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
});
loadFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser("C:\\Users\\frenk\\OneDrive\\Рабочий стол\\lab6saves");
int ret = fc.showDialog(null, "Открыть файл");
if(ret == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
try {
_storage.LoadData(file);
canv._storage =_storage;
ReloadObjects();
canv.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
});
loadCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser("C:\\Users\\frenk\\OneDrive\\Рабочий стол\\lab6saves");
int ret = fc.showDialog(null, "Открыть файл");
if(ret == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
try {
_storage.LoadCollection(file);
ReloadObjects();
canv.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
});
addStorageButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@ -99,7 +220,7 @@ public class FormMonorailCollection {
if(listBoxStorages.getSelectedIndex() == -1) {
return;
}
_storage.DelSet(listBoxStorages.getSelectedValue());
_storage.DelSet(listBoxStorages.getSelectedValue(), _trashCollection);
ReloadObjects();
}
});
@ -213,4 +334,5 @@ class CollectionCanvas extends JComponent {
g2d.drawImage(_storage.Get(listBoxStorages.getSelectedValue()).ShowMonorails(), 0, 0, this);
super.repaint();
}
}

View File

@ -362,7 +362,6 @@ public class FormMonorailConfig {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "Простой":
_monorail = new DrawningMonorail(speed, weight, Color.WHITE,
Color.GRAY, Color.BLACK, _pictureBoxWidth, _pictureBoxHeight);
_monorail.ChangeWheelsNumb(wheelNumb);

View File

@ -1,21 +1,58 @@
package MonorailHard.Generics;
import MonorailHard.DrawningObjects.DrawningMonorail;
import MonorailHard.DrawningObjects.ExtentionDrawningMonorail;
import MonorailHard.MovementStrategy.DrawningObjectMonorail;
import MonorailHard.MovementStrategy.IMoveableObject;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
public class MonorailGenericCollection<T extends DrawningMonorail, U extends IMoveableObject> {
private final int _pictureWidth;
public static char _separatorRecords = ';';
public static char _separatorForObject = ':';
private final int _pictureHeight;
private final int _placeSizeWidth = 133;
private final int _placeSizeHeight = 50;
private final SetGeneric<T> _collection;
private SetGeneric<T> _collection;
public ArrayList<T> GetMonorails(){
return _collection.GetMonorails(_collection.Count);
}
public boolean SaveData(File f, String name) throws IOException {
if(f.exists()) {
f.delete();
}
f.createNewFile();
StringBuilder data = new StringBuilder();
data.append("MonorailCollection\n");
data.append(String.format("%s\n", name));
StringBuilder records = new StringBuilder();
for(DrawningMonorail elem : GetMonorails())
{
records.append(String.format("%s%c", ExtentionDrawningMonorail.GetDataForSave(elem, _separatorForObject),
_separatorRecords));
}
data.append(records);
if(data.length() == 0)
return false;
FileWriter writer = new FileWriter(f);
writer.write(data.toString());
writer.flush();
writer.close();
return true;
}
public MonorailGenericCollection(int picWidth, int picHeight){
int width = picWidth / _placeSizeWidth;
@ -89,4 +126,8 @@ public class MonorailGenericCollection<T extends DrawningMonorail, U extends IMo
DrawObjects(gr);
return bmp;
}
public void Clear(){
_collection = new SetGeneric<>(_pictureWidth * _pictureHeight);
}
}

View File

@ -1,16 +1,119 @@
package MonorailHard.Generics;
import MonorailHard.DrawningObjects.DrawningMonorail;
import MonorailHard.DrawningObjects.ExtentionDrawningMonorail;
import MonorailHard.MovementStrategy.DrawningObjectMonorail;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.List;
import java.util.Queue;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class MonorailGenericStorage {
final HashMap<String, MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail>> _monorailStorages;
public final HashMap<String, MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail>> _monorailStorages;
private static final char _separatorForKeyValue = '|';
private final char _separatorRecords = ';';
private static final char _separatorForObject = ':';
public boolean SaveData(File f) throws IOException {
if(f.exists()) {
f.delete();
}
f.createNewFile();
StringBuilder data = new StringBuilder();
data.append("MonorailStorage\n");
for(Map.Entry<String, MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail>> record : _monorailStorages.entrySet()){
StringBuilder records = new StringBuilder();
for(DrawningMonorail elem : record.getValue().GetMonorails())
{
records.append(String.format("%s%c", ExtentionDrawningMonorail.GetDataForSave(elem, _separatorForObject),
_separatorRecords));
}
data.append(String.format("%s%c%s\n", record.getKey(), _separatorForKeyValue, records.toString()));
}
if(data.length() == 0)
return false;
FileWriter writer = new FileWriter(f);
writer.write(data.toString());
writer.flush();
writer.close();
return true;
}
public boolean LoadData(File f) throws FileNotFoundException {
if(!f.exists())
return false;
StringBuilder bufferTextFromFile =new StringBuilder();
Scanner s = new Scanner(f);
while(s.hasNext())
bufferTextFromFile.append(s.next() + "\n");
s.close();
var strs = bufferTextFromFile.toString().split("\n");
if(strs == null || strs.length == 0)
return false;
if (!strs[0].startsWith("MonorailStorage"))
return false;
_monorailStorages.clear();
for(String data : strs){
String st = new String("\\" + Character.toString( _separatorForKeyValue));
String[]record = data.split(st);
if (record.length != 2)
continue;
MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail> collection =
new MonorailGenericCollection<>(_pictureWidth, _pictureHeight);
String[] set = record[1].split(Character.toString(_separatorRecords));
for(int i = set.length -1; i >=0; i--){
String elem = set[i];
DrawningMonorail monorail = ExtentionDrawningMonorail.CreateDrawningMonorail(elem,
_separatorForObject, _pictureWidth, _pictureHeight);
if (monorail != null)
{
if (!(collection.Insert(monorail)))
{
return false;
}
}
}
_monorailStorages.put(record[0], collection);
}
return true;
}
public boolean LoadCollection(File f) throws FileNotFoundException {
if(!f.exists())
return false;
StringBuilder bufferTextFromFile =new StringBuilder();
Scanner s = new Scanner(f);
while(s.hasNext())
bufferTextFromFile.append(s.next() + "\n");
s.close();
var strs = bufferTextFromFile.toString().split("\n");
if(strs == null || strs.length == 0)
return false;
if (!strs[0].startsWith("MonorailCollection"))
return false;
String collectionName = strs[1];
MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail> collection = GetCollection(collectionName);
if(collection == null)
collection = new MonorailGenericCollection<>(_pictureWidth, _pictureHeight);
else
collection.Clear();
String[] monorailsInfo = strs[2].split(Character.toString(MonorailGenericCollection._separatorRecords));
for(int i = monorailsInfo.length-1; i >= 0; i--){
String data = monorailsInfo[i];
DrawningMonorail monorail = ExtentionDrawningMonorail.CreateDrawningMonorail(data,
MonorailGenericCollection._separatorForObject, _pictureWidth, _pictureHeight);
if (monorail != null)
{
if (!(collection.Insert(monorail)))
{
return false;
}
}
}
AddSetFromFile(collectionName, collection);
return true;
}
public List<String> Keys(){
if(_monorailStorages == null)
return null;
@ -31,9 +134,20 @@ public class MonorailGenericStorage {
_monorailStorages.put(name, new MonorailGenericCollection<>(_pictureWidth, _pictureHeight));
}
public void DelSet(String name){
public void AddSetFromFile(String name, MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail> toAdd){
if(_monorailStorages.containsKey(name)){
_monorailStorages.remove(name);
}
_monorailStorages.put(name, toAdd);
}
public void DelSet(String name, MonorailTrashCollection<DrawningMonorail> trashBox){
if(!_monorailStorages.containsKey(name))
return;
MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail> cur = _monorailStorages.get(name);
for(int i = 0; i < cur.Size(); i++)
trashBox.Push(cur.Get(i));
_monorailStorages.remove(name);
}
@ -46,4 +160,8 @@ public class MonorailGenericStorage {
public DrawningMonorail Get(String collectionName, int position){
return _monorailStorages.get(collectionName).Get(position);
}
public MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail> GetCollection(String collectionName){
return _monorailStorages.get(collectionName);
}
}