Compare commits

...

8 Commits

Author SHA1 Message Date
insideq
1b3cbfe35e Лабораторная работа №6 2024-05-11 19:26:59 +04:00
insideq
d4678adf15 Лабораторная работа №5 2024-05-11 18:51:29 +04:00
insideq
e732147b23 Фикс 2024-05-11 18:38:29 +04:00
insideq
6aa347f8eb Лабораторная работа №4 2024-05-11 18:36:37 +04:00
insideq
cf1bbe3133 Фикс 2024-05-11 18:06:04 +04:00
insideq
6d2ced70f7 Лабораторная работа №3 2024-05-11 18:04:03 +04:00
insideq
33b6eb7cc2 Лабораторная работа №2 2024-05-11 17:47:53 +04:00
insideq
d8bc8f2549 Лабораторная работа №1 2024-05-11 17:38:33 +04:00
39 changed files with 2474 additions and 5 deletions

BIN
res/down.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 321 B

BIN
res/left.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 B

BIN
res/right.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 B

BIN
res/up.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 304 B

View File

@ -0,0 +1,61 @@
package CollectionAdditionalObjects;
import DifferentRollers.IDifferentRollers;
import Drawings.DrawingBulldozer;
import Drawings.DrawingExcavator;
import Entities.EntityBulldozer;
import Entities.EntityExcavator;
import java.lang.reflect.Array;
import java.util.Random;
public class AdditionalCollections <T extends EntityBulldozer, U extends IDifferentRollers>{
public T[] _collectionEntity;
public U[] _collectionRollers;
public AdditionalCollections(int size, Class<T> type1, Class<T> type2) {
_collectionEntity = (T[]) Array.newInstance(type1, size);
_collectionRollers = (U[]) Array.newInstance(type2, size);
CountEntities = size;
CountRollers = size;
}
public int CountEntities;
public int CountRollers;
public int Insert(T entity) {
int index = 0;
while (index < CountEntities) {
if (_collectionEntity[index] == null)
{
_collectionEntity[index] = entity;
return index;
}
++index;
}
return -1;
}
public int Insert(U rollers) {
int index = 0;
while (index < CountRollers) {
if (_collectionRollers[index] == null)
{
_collectionRollers[index] = rollers;
return index;
}
++index;
}
return -1;
}
public DrawingBulldozer CreateAdditionalCollectionBulldozer() {
Random random = new Random();
if (_collectionEntity == null || _collectionRollers == null) return null;
T entity = _collectionEntity[random.nextInt(CountEntities)];
U rollers = _collectionRollers[random.nextInt(CountRollers)];
DrawingBulldozer drawingBulldozer = null;
if (entity instanceof EntityExcavator) {
drawingBulldozer = new DrawingExcavator((EntityExcavator) entity, rollers);
}
else {
drawingBulldozer = new DrawingBulldozer(entity, rollers);
}
return drawingBulldozer;
}
}

View File

@ -0,0 +1,34 @@
package CollectionGenericObjects;
import Drawings.DrawingBulldozer;
import java.awt.*;
public abstract class AbstractCompany {
protected int _placeSizeWidth = 195;
protected int _placeSizeHeight = 80;
protected int _pictureWidth;
protected int _pictureHeight;
public ICollectionGenericObjects<DrawingBulldozer> _collection = null;
private int GetMaxCount() {
return _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
}
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawingBulldozer> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount(GetMaxCount());
}
//перегрузка операторов в джаве невозможна
public DrawingBulldozer GetRandomObject()
{
return _collection.Get((int)(Math.random()*GetMaxCount()));
}
public void SetPosition()
{
SetObjectsPosition();
}
public abstract void DrawBackground(Graphics graphics);
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,49 @@
package CollectionGenericObjects;
import Drawings.DrawingBulldozer;
import java.awt.*;
public class BulldozerSharingService extends AbstractCompany{
public BulldozerSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingBulldozer> collection) {
super(picWidth, picHeight, collection);
}
@Override
public void DrawBackground(Graphics g) {
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
g.setColor(Color.BLACK);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight);
}
}
@Override
protected void SetObjectsPosition() {
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int posWidth = width - 1;
int posHeight = 0;
for (int i = 0; i < (_collection.getCount()); i++) {
if (_collection.Get(i) != null) {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * posWidth + 4, posHeight * _placeSizeHeight + 4);
}
if (posWidth > 0)
posWidth--;
else {
posWidth = width - 1;
posHeight++;
}
if (posHeight > height) {
return;
}
}
}
}

View File

@ -0,0 +1,7 @@
package CollectionGenericObjects;
public enum CollectionType {
None,
Massive,
List
}

View File

@ -0,0 +1,14 @@
package CollectionGenericObjects;
public interface ICollectionGenericObjects<T>
{
int getCount();
void SetMaxCount(int count);
int Insert(T obj);
T Remove(int position);
T Get(int position);
CollectionType GetCollectionType();
Iterable<T> GetItems();
void ClearCollection();
}

View File

@ -0,0 +1,75 @@
package CollectionGenericObjects;
import java.util.*;
public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
private List<T> _collection;
private CollectionType collectionType = CollectionType.List;
private int _maxCount;
public int getCount() {
return _collection.size();
}
@Override
public void SetMaxCount(int size) {
if (size > 0) {
_maxCount = size;
}
}
public ListGenericObjects() {
_collection = new ArrayList<T>();
}
@Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public T Get(int position)
{
if (position >= getCount() || position < 0) return null;
return _collection.get(position);
}
@Override
public int Insert(T obj)
{
if (getCount() == _maxCount) return -1;
_collection.add(obj);
return getCount();
}
@Override
public T Remove(int position)
{
if (position >= getCount() || position < 0) return null;
T obj = _collection.get(position);
_collection.remove(position);
return obj;
}
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection.get(currentIndex++);
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T bulldozer : _collection) {
bulldozer = null;
}
}
}

View File

@ -0,0 +1,86 @@
package CollectionGenericObjects;
import Drawings.DrawingBulldozer;
import java.lang.reflect.Array;
import java.util.*;
public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
private T[] _collection = null;
private CollectionType collectionType = CollectionType.Massive;
private int Count;
@Override
public void SetMaxCount(int size) {
if (size > 0) {
if (_collection == null){
_collection = (T[]) Array.newInstance((Class) DrawingBulldozer.class, size);
Count = size;
}
}
}
@Override
public int getCount() {
return Count;
}
@Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public int Insert(T obj) {
int index = 0;
while (index < getCount())
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
++index;
}
return -1;
}
@Override
public T Remove(int position) {
if (position >= getCount() || position < 0)
return null;
T obj = (T) _collection[position];
_collection[position] = null;
return obj;
}
@Override
public T Get(int position) {
if (position >= getCount() || position < 0) return null;
return (T) _collection[position];
}
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection[currentIndex++];
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T bulldozer : _collection) {
bulldozer = null;
}
}
}

View File

@ -0,0 +1,195 @@
package CollectionGenericObjects;
import Drawings.DrawingBulldozer;
import Drawings.ExtensionDrawingBulldozer;
import java.io.*;
import java.util.*;
public class StorageCollection<T extends DrawingBulldozer> {
private Map<String, ICollectionGenericObjects<T>> _storages;
public StorageCollection()
{
_storages = new HashMap<String, ICollectionGenericObjects<T>>();
}
public Set<String> Keys() {
Set<String> keys = _storages.keySet();
return keys;
}
public void AddCollection(String name, CollectionType collectionType)
{
if (_storages.containsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages.put(name, new MassiveGenericObjects<T>());
else if (collectionType == CollectionType.List)
_storages.put(name, new ListGenericObjects<T>());
}
public void DelCollection(String name)
{
if (_storages.containsKey(name))
_storages.remove(name);
}
// в джаве отсутствуют индикаторы
public ICollectionGenericObjects<T> getCollectionObject(String name) {
if (_storages.containsKey(name))
return _storages.get(name);
return null;
}
//дополнительное задание 1
public T Get(String name, int position){
if(_storages.containsKey(name))
return _storages.get(name).Remove(position);
return null;
}
private String _collectionKey = "CollectionsStorage";
private String _collectionName = "StorageCollection";
private String _separatorForKeyValueS = "|";
private String _separatorForKeyValue = "\\|";
private String _separatorItemsS = ";";
private String _separatorItems = "\\;";
public boolean SaveData(String filename) {
if (_storages.isEmpty()) return false;
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionKey);
writer.write("\n");
for (Map.Entry<String, ICollectionGenericObjects<T>> value : _storages.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append(value.getKey());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().getCount());
sb.append(_separatorForKeyValueS);
for (T bulldozer : value.getValue().GetItems()) {
String data = ExtensionDrawingBulldozer.GetDataForSave((DrawingBulldozer) bulldozer);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
sb.append("\n");
writer.write(String.valueOf(sb));
}
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean LoadData(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionKey))
return false;
_storages.clear();
s = "";
while ((s = fs.readLine()) != null) {
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
continue;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
return false;
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawingBulldozer bulldozer = ExtensionDrawingBulldozer.CreateDrawingBulldozer(elem);
if (collection.Insert((T) bulldozer) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
}
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean SaveCollection(String filename, String name) {
if (_storages.isEmpty()) return false;
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionName);
writer.write("\n");
ICollectionGenericObjects<T> value = _storages.get(name);
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(_separatorForKeyValueS);
sb.append(value.GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getCount());
sb.append(_separatorForKeyValueS);
for (T bulldozer : value.GetItems()) {
String data = ExtensionDrawingBulldozer.GetDataForSave((DrawingBulldozer) bulldozer);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
writer.append(sb);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean LoadCollection(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionName))
return false;
if (_storages.containsKey(s)) {
_storages.get(s).ClearCollection();
}
s = fs.readLine();
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
return false;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
return false;
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawingBulldozer bulldozer = ExtensionDrawingBulldozer.CreateDrawingBulldozer(elem);
if (collection.Insert((T) bulldozer) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public ICollectionGenericObjects<T> CreateCollection(String s) {
switch (s) {
case "Massive":
return new MassiveGenericObjects<T>();
case "List":
return new ListGenericObjects<T>();
}
return null;
}
}

View File

@ -0,0 +1,32 @@
package DifferentRollers;
import java.awt.*;
public class DrawingRollersCross implements IDifferentRollers{
private RollersCount rollersCount;
@Override
public void setRollersCount(int numOfRoller){
for (RollersCount numofenum : RollersCount.values()){
if (numofenum.getNumOfRollers() == numOfRoller){
rollersCount = numofenum;
return;
}
}
}
@Override
public RollersCount getRollersCount(){
return rollersCount;
}
@Override
public void DrawRollers(Graphics2D g, int x, int y, int width, int height, Color bodyColor){
g.setColor(bodyColor);
g.fillOval(x, y, width, height);
g.setColor(Color.BLACK);
g.drawLine(x+2, y+2, x+6, y+6);
g.drawLine(x+2, y+6, x+6, y+2);
g.drawOval(x, y, width, height);
g.setColor(bodyColor);
}
}

View File

@ -0,0 +1,32 @@
package DifferentRollers;
import java.awt.*;
public class DrawingRollersPlus implements IDifferentRollers{
private RollersCount rollersCount;
@Override
public void setRollersCount(int numOfRoller){
for (RollersCount numofenum : RollersCount.values()){
if (numofenum.getNumOfRollers() == numOfRoller){
rollersCount = numofenum;
return;
}
}
}
@Override
public RollersCount getRollersCount(){
return rollersCount;
}
@Override
public void DrawRollers(Graphics2D g, int x, int y, int width, int height, Color bodyColor){
g.setColor(bodyColor);
g.fillOval(x, y, width, height);
g.setColor(Color.BLACK);
g.drawLine(x+4, y, x+4, y+8);
g.drawLine(x, y+4, x+8, y+4);
g.drawOval(x, y, width, height);
g.setColor(bodyColor);
}
}

View File

@ -0,0 +1,34 @@
package DifferentRollers;
import java.awt.*;
public class DrawingRollersStar implements IDifferentRollers{
private RollersCount rollersCount;
@Override
public void setRollersCount(int numOfRoller){
for (RollersCount numofenum : RollersCount.values()){
if (numofenum.getNumOfRollers() == numOfRoller){
rollersCount = numofenum;
return;
}
}
}
@Override
public RollersCount getRollersCount(){
return rollersCount;
}
@Override
public void DrawRollers(Graphics2D g, int x, int y, int width, int height, Color bodyColor){
g.setColor(bodyColor);
g.fillOval(x, y, width, height);
g.setColor(Color.BLACK);
g.drawLine(x+4, y, x+4, y+8);
g.drawLine(x, y+4, x+8, y+4);
g.drawLine(x+2, y+2, x+6, y+6);
g.drawLine(x+2, y+6, x+6, y+2);
g.drawOval(x, y, width, height);
g.setColor(bodyColor);
}
}

View File

@ -0,0 +1,9 @@
package DifferentRollers;
import java.awt.*;
public interface IDifferentRollers {
void setRollersCount(int numOfRoller);
RollersCount getRollersCount();
void DrawRollers(Graphics2D g, int x, int y, int width, int height, Color bodyColor);
}

View File

@ -0,0 +1,14 @@
package DifferentRollers;
public enum RollersCount {
OneRoller(1),
TwoRollers(2),
ThreeRollers(3);
private int numOfRollers;
RollersCount(int numOfRollers){
this.numOfRollers = numOfRollers;
}
public int getNumOfRollers(){
return numOfRollers;
}
}

View File

@ -0,0 +1,18 @@
package Drawings;
import javax.swing.*;
import java.awt.*;
public class CanvasExcavator extends JComponent{
public DrawingBulldozer _drawingBulldozer;
public CanvasExcavator(){}
public void paintComponent(Graphics g){
if(_drawingBulldozer == null){
return;
}
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
_drawingBulldozer.DrawTransport(g2d);
super.repaint();
}
}

View File

@ -0,0 +1,34 @@
package Drawings;
import CollectionGenericObjects.AbstractCompany;
import CollectionGenericObjects.ICollectionGenericObjects;
import CollectionGenericObjects.MassiveGenericObjects;
import javax.swing.*;
import java.awt.*;
public class CanvasFormBulldozerCollection<T> extends JComponent
{
public AbstractCompany company = null;
public void SetCollectionToCanvas(AbstractCompany company) {
this.company = company;
}
public CanvasFormBulldozerCollection(){}
public void paintComponent(Graphics g) {
super.paintComponents(g);
if (company == null || company._collection == null) {
return;
}
company.DrawBackground(g);
for (int i = 0; i < company._collection.getCount(); i++) {
Graphics2D g2d = (Graphics2D) g;
T obj = (T)company._collection.Get(i);
if (obj instanceof DrawingBulldozer) {
((DrawingBulldozer) obj).DrawTransport(g2d);
}
}
super.repaint();
}
}

View File

@ -0,0 +1,9 @@
package Drawings;
public enum DirectionType {
Unknow,
Up,
Down,
Left,
Right
}

View File

@ -0,0 +1,195 @@
package Drawings;
import DifferentRollers.DrawingRollersCross;
import DifferentRollers.DrawingRollersPlus;
import DifferentRollers.DrawingRollersStar;
import DifferentRollers.IDifferentRollers;
import Entities.EntityBulldozer;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class DrawingBulldozer extends JPanel {
public Entities.EntityBulldozer EntityBulldozer;
public IDifferentRollers drawingRollers;
public Integer _startPosX; // Левая координата отрисовки
public Integer _startPosY; // Верхняя координата отрисовки
private Integer _pictureWidth; // Ширина окна отрисовки
private Integer _pictureHeight; // Высота окна отрисовки
protected int _drawingExcWidth = 120; // Ширина отрисовки трактора
protected int _drawingExcHeight = 70; // Высота отрисовки трактора
public Integer GetPosX(){return _startPosX;}
public Integer GetPosY(){return _startPosY;}
public Integer GetWidth(){return _drawingExcWidth;}
public Integer GetHeight(){return _drawingExcHeight;}
protected DrawingBulldozer(){
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
public DrawingBulldozer(int speed, double weight, Color bodyColor){
super();
EntityBulldozer = new EntityBulldozer(speed, weight, bodyColor);
}
protected DrawingBulldozer(int _drawingExcWidth, int _drawingExcHeight) {
super();
this._drawingExcWidth = _drawingExcWidth;
this._drawingExcHeight = _drawingExcHeight;
}
public DrawingBulldozer(EntityBulldozer entity, IDifferentRollers rollers) {
EntityBulldozer = entity;
drawingRollers = rollers;
}
// Смена границ формы отрисовки
public void SetPictureSize(int width, int height)
{
if (_drawingExcWidth > width || _drawingExcHeight > height)
{
return;
}
if (_startPosX != null && _startPosY != null) {
if (_startPosX < 0) { _startPosX = 0; }
if (_startPosX + _drawingExcWidth > width) { _startPosX = width - _drawingExcWidth; }
if (_startPosY < 0) { _startPosY = 0; }
if (_startPosY + _drawingExcHeight > height) { _startPosY = height - _drawingExcHeight; }
}
_pictureWidth = width;
_pictureHeight = height;
}
//Установка позиции Экскаватора
public void SetPosition(int x, int y){
if (_pictureWidth == null || _pictureHeight == null)
{
return;
}
if (x + _drawingExcWidth > _pictureWidth || x < 0) {
Random random = new Random();
_startPosX = random.nextInt(_pictureWidth - _drawingExcWidth);
}
else {
_startPosX = x;
}
if (y + _drawingExcHeight > _pictureHeight || y < 0) {
Random random = new Random();
_startPosY = random.nextInt(_pictureHeight - _drawingExcHeight);
}
else {
_startPosY = y;
}
}
// Изменение направления движения
public boolean MoveTransport(DirectionType direction){
if (EntityBulldozer == null || _startPosX == null || _startPosY == null){
return false;
}
switch (direction) {
case Left:
if (_startPosX - EntityBulldozer.Step > 0) {
_startPosX -= (int) EntityBulldozer.Step;
}
return true;
case Up:
if (_startPosY - EntityBulldozer.Step > 0) {
_startPosY -= (int) EntityBulldozer.Step;
}
return true;
case Right:
if (_startPosX + EntityBulldozer.Step < _pictureWidth - _drawingExcWidth) {
_startPosX += (int) EntityBulldozer.Step;
}
return true;
case Down:
if (_startPosY + EntityBulldozer.Step < _pictureHeight - _drawingExcHeight) {
_startPosY += (int) EntityBulldozer.Step;
}
return true;
default:
return false;
}
}
public String[] GetStringRepresentationRollers() {
if (drawingRollers instanceof DrawingRollersPlus) {
return new String[]{String.valueOf(drawingRollers.getRollersCount().getNumOfRollers()), "DrawingRollersPlus"};
}
else if (drawingRollers instanceof DrawingRollersCross) {
return new String[]{String.valueOf(drawingRollers.getRollersCount().getNumOfRollers()), "DrawingRollersCross"};
}
else if (drawingRollers instanceof DrawingRollersStar) {
return new String[]{String.valueOf(drawingRollers.getRollersCount().getNumOfRollers()), "DrawingRollersStar"};
}
return null;
}
// Отрисовка Экскаватора
public void DrawTransport(Graphics2D g){
if (EntityBulldozer == null || _startPosX == null || _startPosY == null){
return;
}
// Границы экскаватора
g.setColor(Color.BLACK);
g.drawRect(_startPosX + 20, _startPosY + 25, 60, 20); // главная нижняя
g.drawRect(_startPosX + 35, _startPosY + 10, 5, 15);
g.drawRect(_startPosX + 55, _startPosY + 3, 22, 22); // кабина
g.setColor(EntityBulldozer.getBodyColor());
g.fillRect(_startPosX + 21, _startPosY + 26, 59, 19);
g.fillRect(_startPosX + 36, _startPosY + 11, 4, 14);
g.setColor(Color.cyan);
g.fillRect(_startPosX + 56, _startPosY + 4, 21, 21);
// Гусеница
g.setColor(Color.BLACK);
g.drawRect(_startPosX + 24, _startPosY + 47, 48, 17);
// Основные катки
g.setColor(Color.BLACK);
g.drawOval(_startPosX + 15, _startPosY + 47, 17, 17);
g.drawOval(_startPosX + 63, _startPosY + 47, 17, 17);
g.setColor(EntityBulldozer.getBodyColor());
g.fillOval(_startPosX + 15, _startPosY + 47, 17, 17);
g.fillOval(_startPosX + 63, _startPosY + 47, 17, 17);
// Малые катки
g.setColor(Color.BLACK);
g.drawOval(_startPosX + 40, _startPosY + 48, 5, 5);
g.drawOval(_startPosX + 50, _startPosY + 48, 5, 5);
g.setColor(EntityBulldozer.getBodyColor());
g.fillOval(_startPosX + 40, _startPosY + 48, 5, 5);
g.fillOval(_startPosX + 50, _startPosY + 48, 5, 5);
int x = _startPosX;
if (drawingRollers != null && drawingRollers.getRollersCount() != null){
switch (drawingRollers.getRollersCount()){
case OneRoller:
drawingRollers.DrawRollers(g,x + 34, _startPosY + 55, 8, 8, EntityBulldozer.getBodyColor());
break;
case TwoRollers:
drawingRollers.DrawRollers(g,x + 34, _startPosY + 55, 8, 8, EntityBulldozer.getBodyColor());
drawingRollers.DrawRollers(g,x + 44, _startPosY + 55, 8, 8, EntityBulldozer.getBodyColor());
break;
case ThreeRollers:
drawingRollers.DrawRollers(g,x + 34, _startPosY + 55, 8, 8, EntityBulldozer.getBodyColor());
drawingRollers.DrawRollers(g,x + 44, _startPosY + 55, 8, 8, EntityBulldozer.getBodyColor());
drawingRollers.DrawRollers(g,x + 54, _startPosY + 55, 8, 8, EntityBulldozer.getBodyColor());
break;
}
}
}
}

View File

@ -0,0 +1,72 @@
package Drawings;
import DifferentRollers.IDifferentRollers;
import Entities.EntityExcavator;
import java.awt.*;
public class DrawingExcavator extends DrawingBulldozer{
public DrawingExcavator(int speed, double weight, Color bodyColor, Color additionalColor, boolean prop, boolean ladle){
EntityBulldozer = new EntityExcavator(speed, weight, bodyColor, additionalColor, prop, ladle);
}
public DrawingExcavator(EntityExcavator entity, IDifferentRollers rollers) {
EntityBulldozer = entity;
drawingRollers = rollers;
}
// Отрисовка Экскаватора
@Override
public void DrawTransport(Graphics2D g){
if (EntityBulldozer == null || !(EntityBulldozer instanceof EntityExcavator excavator) || _startPosX == null || _startPosY == null){
return;
}
super.DrawTransport(g);
if (excavator.getProp()){
g.setColor(Color.BLACK);
//Опоры
//справа
g.drawRect(_startPosX + 80, _startPosY + 40, 11, 3);
g.drawRect(_startPosX + 87, _startPosY + 43, 5, 25);
g.drawRect(_startPosX + 84, _startPosY + 68, 11, 3);
//слева
g.drawRect(_startPosX + 6, _startPosY + 40, 13, 3);
g.drawRect(_startPosX + 4, _startPosY + 43, 5, 25);
g.drawRect(_startPosX + 1, _startPosY + 68, 11, 3);
g.setColor(excavator.getAdditionalColor());
//покраска справа
g.fillRect(_startPosX + 81, _startPosY + 41, 10, 2);
g.fillRect(_startPosX + 88, _startPosY + 44, 4, 24);
g.fillRect(_startPosX + 85, _startPosY + 69, 10, 2);
//покраска слева
g.fillRect(_startPosX + 7, _startPosY + 41, 12, 2);
g.fillRect(_startPosX + 5, _startPosY + 44, 4, 24);
g.fillRect(_startPosX + 2, _startPosY + 69, 10, 2);
}
if(excavator.getLadle()){
g.setColor(Color.BLACK);
//Ковш
//ковш(стрела)
g.drawRect(_startPosX + 77, _startPosY + 17, 14, 8);
g.drawRect(_startPosX + 91, _startPosY + 9, 20, 7);
g.drawRect(_startPosX + 111, _startPosY + 17, 9, 20);
int[] pointsLadleX = {_startPosX + 120, _startPosX + 104, _startPosX + 120};
int[] pointsLadleY = {_startPosY + 37, _startPosY + 54, _startPosY + 54};
Polygon Ladle = new Polygon(pointsLadleX, pointsLadleY, 3);
g.drawPolygon(Ladle);
g.setColor(excavator.getAdditionalColor());
g.fillPolygon(Ladle);
//покраска
g.fillRect(_startPosX + 78, _startPosY + 18, 13, 7);
g.fillRect(_startPosX + 92, _startPosY + 10, 19, 6);
g.fillRect(_startPosX + 112, _startPosY + 18, 8, 19);
}
}
}

View File

@ -0,0 +1,80 @@
package Drawings;
import DifferentRollers.DrawingRollersStar;
import DifferentRollers.DrawingRollersPlus;
import DifferentRollers.DrawingRollersCross;
import DifferentRollers.IDifferentRollers;
import Entities.*;
import java.util.ArrayList;
import java.util.Collections;
public class ExtensionDrawingBulldozer {
private static String _separatorForObjectS = ":";
private static String _separatorForObject = "\\:";
public static DrawingBulldozer CreateDrawingBulldozer(String info) {
String[] strs = info.split(_separatorForObject);
EntityBulldozer bulldozer;
IDifferentRollers rollers = null;
if (strs.length == 9)
{
String s = strs[8];
switch (s) {
case "DrawingRollersStar":
rollers = new DrawingRollersStar();
break;
case "DrawingRollersPlus":
rollers = new DrawingRollersPlus();
break;
case "DrawingRollersCross":
rollers = new DrawingRollersCross();
break;
}
if (rollers != null) rollers.setRollersCount(Integer.parseInt(strs[7]));
}
else if (strs.length == 6) {
String s = strs[5];
switch (s) {
case "DrawingRollersStar":
rollers = new DrawingRollersStar();
break;
case "DrawingRollersPlus":
rollers = new DrawingRollersPlus();
break;
case "DrawingRollersCross":
rollers = new DrawingRollersCross();
break;
}
if (rollers != null) rollers.setRollersCount(Integer.parseInt(strs[4]));
}
bulldozer = EntityExcavator.CreateEntityExcavator(strs);
if (bulldozer != null)
{
return new DrawingExcavator((EntityExcavator)bulldozer, rollers);
}
bulldozer = EntityBulldozer.CreateEntityBulldozer(strs);
if (bulldozer != null)
{
return new DrawingBulldozer(bulldozer, rollers);
}
return null;
}
public static String GetDataForSave(DrawingBulldozer drawingBulldozer)
{
if (drawingBulldozer == null) return "";
String[] arrayEntity = drawingBulldozer.EntityBulldozer.GetStringRepresentation();
String[] arrayRollers = drawingBulldozer.GetStringRepresentationRollers();
if (arrayEntity == null)
{
return "";
}
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, arrayEntity);
if (arrayRollers == null) {
Collections.addAll(list, "0", " ");
}
else Collections.addAll(list, arrayRollers);
return String.join(_separatorForObjectS, list);
}
}

View File

@ -0,0 +1,45 @@
package Entities;
import java.awt.*;
import java.util.Objects;
public class EntityBulldozer {
private Integer Speed;
public Integer getSpeed() {return Speed;}
public void setSpeed(int speed) {Speed = speed;}
private Double Weight;
public Double getWeight() {return Weight;}
public void setWeight(double weight) {Weight = weight;}
private Color BodyColor;
public Color getBodyColor() {
return BodyColor;
}
public void setBodyColor(Color color) {BodyColor = color;}
public double Step;
public EntityBulldozer(int speed, double weight, Color bodyColor){
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
Step = Speed * 100 / Weight;
}
public String[] GetStringRepresentation()
{
return new String[]{"EntityBulldozer", Speed.toString(), Weight.toString(), colorToHexString(BodyColor)};
}
public static EntityBulldozer CreateEntityBulldozer(String[] strs)
{
if (strs.length != 6 || !Objects.equals(strs[0], "EntityBulldozer"))
{
return null;
}
return new EntityBulldozer(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]));
}
public static String colorToHexString(Color color) {
return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
}
public static Color hexStringToColor(String hexString) {
return Color.decode(hexString);
}
}

View File

@ -0,0 +1,45 @@
package Entities;
import java.awt.*;
import java.util.Objects;
public class EntityExcavator extends EntityBulldozer{
private Color AdditionalColor;
public Color getAdditionalColor(){
return AdditionalColor;
}
public void setAdditionalColor(Color color) {AdditionalColor = color;}
public boolean Prop;
public boolean getProp(){
return Prop;
}
public void setProp(boolean prop) {Prop = prop;}
public boolean Ladle;
public void setLadle(boolean ladle) {Ladle = ladle;}
public boolean getLadle(){
return Ladle;
}
public EntityExcavator(int speed, double weight, Color bodyColor, Color additionalColor, boolean prop, boolean ladle){
super(speed, weight, bodyColor);
AdditionalColor = additionalColor;
Prop = prop;
Ladle = ladle;
}
@Override
public String[] GetStringRepresentation()
{
return new String[]{"EntityExcavator", getSpeed().toString(), getWeight().toString(),
colorToHexString(getBodyColor()), colorToHexString(getAdditionalColor()),
String.valueOf(Prop), String.valueOf(Ladle)};
}
public static EntityExcavator CreateEntityExcavator(String[] strs)
{
if (strs.length != 9 || !Objects.equals(strs[0], "EntityExcavator"))
{
return null;
}
return new EntityExcavator(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]),
hexStringToColor(strs[4]), Boolean.parseBoolean(strs[5]), Boolean.parseBoolean(strs[6]));
}
}

View File

@ -0,0 +1,137 @@
import CollectionAdditionalObjects.AdditionalCollections;
import CollectionGenericObjects.AbstractCompany;
import DifferentRollers.DrawingRollersCross;
import DifferentRollers.DrawingRollersPlus;
import DifferentRollers.DrawingRollersStar;
import DifferentRollers.IDifferentRollers;
import Drawings.DrawingBulldozer;
import Drawings.CanvasExcavator;
import Drawings.DrawingExcavator;
import Entities.EntityBulldozer;
import Entities.EntityExcavator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class FormAdditionalCollection extends JFrame {
public DrawingBulldozer drawingBulldozer = null;
private AbstractCompany company = null;
private CanvasExcavator canvasExc = new CanvasExcavator();
private AdditionalCollections<EntityBulldozer, IDifferentRollers> additionalCollection = null;
private Random random = new Random();
private JButton buttonGenerate = new JButton("Создать");
private JList<String> listEntity = new JList<String>();
private JList<String> listRollers = new JList<String>();
public FormAdditionalCollection() {
setTitle("Случайный объект");
setMinimumSize(new Dimension(650,310));
additionalCollection = new AdditionalCollections<EntityBulldozer, IDifferentRollers>(3, (Class) EntityBulldozer.class, (Class) IDifferentRollers.class);
AddEntities();
AddRollers();
buttonGenerate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
drawingBulldozer = additionalCollection.CreateAdditionalCollectionBulldozer();
drawingBulldozer.SetPictureSize(getWidth(), getHeight());
drawingBulldozer.SetPosition(50,50);
canvasExc._drawingBulldozer = drawingBulldozer;
canvasExc.repaint();
DrawingBulldozer copyBulldozer;
if (drawingBulldozer instanceof DrawingExcavator)
copyBulldozer = new DrawingExcavator((EntityExcavator) drawingBulldozer.EntityBulldozer, drawingBulldozer.drawingRollers);
else
copyBulldozer = new DrawingBulldozer(drawingBulldozer.EntityBulldozer, drawingBulldozer.drawingRollers);
company._collection.Insert(copyBulldozer);
FormBulldozerCollection.canvasShow();
String[] data1 = new String[additionalCollection.CountEntities];
for (int i = 0; i < additionalCollection.CountEntities; i++) {
EntityBulldozer entity = additionalCollection._collectionEntity[i];
data1[i] = ToString(entity);
}
String[] data2 = new String[additionalCollection.CountRollers];
for (int i = 0; i < additionalCollection.CountRollers; i++) {
IDifferentRollers rollers = additionalCollection._collectionRollers[i];
data2[i] = ToString(rollers);
}
listEntity.setListData(data1);
listRollers.setListData(data2);
}
});
buttonGenerate.setBounds(450, 10, 100, 50);
add(buttonGenerate);
listEntity.setBounds(10,200,300,60);
listRollers.setBounds(320,200,300,60);
add(listEntity);
add(listRollers);
add(canvasExc);
setVisible(true);
}
private String ToString(EntityBulldozer entity) {
String str = "";
if (entity instanceof EntityExcavator) str += "EntityExcavator ";
else str += "EntityBulldozer ";
str += entity.getBodyColor().toString();
return str;
}
private String ToString(IDifferentRollers rollers) {
if (rollers == null || rollers.getRollersCount() == null)
return "Dont have rollers";
String str = "Rollers ";
if (rollers instanceof DrawingRollersCross) str += "Type Cross ";
else if (rollers instanceof DrawingRollersPlus) str += "Type Plus ";
else str += "Type Star ";
str += rollers.getRollersCount().toString();
return str;
}
public void AddEntities() {
for (int i = 0; i < additionalCollection.CountEntities; i++) {
random = new Random();
int speed = random.nextInt(100, 300);
double weight = random.nextInt(1000, 3000);
Color bodycolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
EntityBulldozer entity;
if (random.nextBoolean()) {
entity = new EntityBulldozer(speed, weight, bodycolor);
}
else {
Color additionalcolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
boolean prop = random.nextBoolean();
boolean ladle = random.nextBoolean();
entity = new EntityExcavator(speed, weight, bodycolor,
additionalcolor, prop, ladle);
}
additionalCollection.Insert(entity);
}
}
public void AddRollers() {
for (int i = 0; i < additionalCollection.CountRollers; i++) {
random = new Random();
Integer numberOfRollers = random.nextInt(0, 4);
IDifferentRollers drawingRollers = null;
switch (random.nextInt(0,4)) {
case 1:
drawingRollers = new DrawingRollersCross();
break;
case 2:
drawingRollers = new DrawingRollersPlus();
break;
case 3:
drawingRollers = new DrawingRollersStar();
break;
default:
numberOfRollers = null;
break;
}
if (drawingRollers != null) drawingRollers.setRollersCount(numberOfRollers);
additionalCollection.Insert(drawingRollers);
}
}
void setCompany(AbstractCompany company) {
this.company = company;
}
}

View File

@ -0,0 +1,381 @@
import CollectionGenericObjects.*;
import Drawings.CanvasFormBulldozerCollection;
import Drawings.DrawingBulldozer;
import javax.swing.*;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.util.LinkedList;
import static java.lang.Integer.parseInt;
public class FormBulldozerCollection extends JFrame{
private String title;
private Dimension dimension;
public static CanvasFormBulldozerCollection<DrawingBulldozer> _canvasExcavator = new CanvasFormBulldozerCollection<DrawingBulldozer>();
private static AbstractCompany _company = null;
private LinkedList<DrawingBulldozer> _collectionRemoveObjects = new LinkedList<DrawingBulldozer>();
private StorageCollection<DrawingBulldozer> _storageCollection = new StorageCollection<DrawingBulldozer>();
private JTextField textBoxCollection = new JTextField();
private JRadioButton radioButtonMassive = new JRadioButton("Массив");
private JRadioButton radioButtonList = new JRadioButton("Список");
private JButton buttonAddCollection = new JButton("Добавить");
private JList listBoxCollection = new JList();
private JButton buttonRemoveCollection = new JButton("Удалить");
private JButton buttonCreateCompany = new JButton("Создать компанию");
private JButton CreateButton = new JButton("Создать бульдозер");
private JButton RemoveButton = new JButton("Удалить");
private JButton GoToCheckButton = new JButton("Тест");
private JButton RandomButton = new JButton("Случайный объект");
private JButton RemoveObjectsButton = new JButton("Показать удаленный");
private JButton RefreshButton = new JButton("Обновить");
private JComboBox ComboBoxCollections = new JComboBox(new String[]{"", "Хранилище"});
private JFormattedTextField MaskedTextField;
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("Файл");
private JMenuItem saveItem = new JMenuItem("Сохранить");
private JMenuItem loadItem = new JMenuItem("Загрузить");
private JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию");
private JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию");
public FormBulldozerCollection(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
}
public static void canvasShow() {
_company.SetPosition();
_canvasExcavator.SetCollectionToCanvas(_company);
_canvasExcavator.repaint();
}
public void Init() {
setTitle(title);
setMinimumSize(dimension);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MaskFormatter mask = null;
try {
mask = new MaskFormatter("##");
mask.setPlaceholder("00");
} catch (ParseException e) {
throw new RuntimeException(e);
}
MaskedTextField = new JFormattedTextField(mask);
CreateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null) return;
FormExcavatorConfig form = new FormExcavatorConfig("", new Dimension(700, 300));
form.setCompany(_company);
form.Init();
form.setLocationRelativeTo(null);
}
});
RemoveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null || MaskedTextField.getText() == null || listBoxCollection.getSelectedValue().toString() == null) {
return;
}
int pos = parseInt(MaskedTextField.getText());
int resultConfirmDialog = JOptionPane.showConfirmDialog(null,
"Удалить", "Удаление",
JOptionPane.YES_NO_OPTION);
if (resultConfirmDialog == JOptionPane.NO_OPTION) return;
DrawingBulldozer obj = _storageCollection.Get(listBoxCollection.getSelectedValue().toString(), pos);
if (obj != null) {
JOptionPane.showMessageDialog(null, "Объект удален");
_collectionRemoveObjects.push(obj);
canvasShow();
}
else {
JOptionPane.showMessageDialog(null, "Объект не удалось удалить");
}
}
});
GoToCheckButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null)
{
return;
}
DrawingBulldozer bulldozer = null;
int counter = 100;
while (bulldozer == null)
{
bulldozer = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (bulldozer == null)
{
return;
}
FormExcavator form = new FormExcavator("Экскаватор", new Dimension(900,565));
form.Init(bulldozer);
}
});
RandomButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null)
{
return;
}
FormAdditionalCollection form = new FormAdditionalCollection();
form.setCompany(_company);
}
});
RefreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null)
{
return;
}
canvasShow();
}
});
buttonAddCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (textBoxCollection.getText().isEmpty() || (!radioButtonMassive.isSelected()
&& !radioButtonList.isSelected())) {
JOptionPane.showMessageDialog(null, "Не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.isSelected())
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.isSelected())
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollection.getText(), collectionType);
RefreshListBoxItems();
}
});
buttonRemoveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
return;
}
int resultConfirmDialog = JOptionPane.showConfirmDialog(null,
"Удалить", "Удаление",
JOptionPane.YES_NO_OPTION);
if (resultConfirmDialog == JOptionPane.NO_OPTION) return;
_storageCollection.DelCollection(listBoxCollection.getSelectedValue().toString());
RefreshListBoxItems();
}
});
buttonCreateCompany.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawingBulldozer> collection =
_storageCollection.getCollectionObject(listBoxCollection.getSelectedValue().toString());
if (collection == null) {
JOptionPane.showMessageDialog(null, "Коллекция не проинициализирована");
return;
}
switch (ComboBoxCollections.getSelectedItem().toString()) {
case "Хранилище":
_company = new BulldozerSharingService(getWidth()-200, getHeight()-70,
collection);
break;
}
RefreshListBoxItems();
}
});
RemoveObjectsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_collectionRemoveObjects.isEmpty())
{
return;
}
DrawingBulldozer bulldozer = null;
bulldozer = _collectionRemoveObjects.pop();
if (bulldozer == null)
{
return;
}
FormExcavator form = new FormExcavator("Экскаватор", new Dimension(900,565));
form.Init(bulldozer);
}
});
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SaveFile();
}
});
loadItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LoadFile();
}
});
saveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Сохранение коллекции");
SaveCollection();
}
});
loadCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Загрузка коллекции");
LoadCollection();
}
});
JLabel labelCollectionName = new JLabel("Название коллекции");
ButtonGroup radioButtonsGroup = new ButtonGroup();
radioButtonsGroup.add(radioButtonMassive);
radioButtonsGroup.add(radioButtonList);
fileMenu.add(saveItem);
fileMenu.add(loadItem);
fileMenu.add(saveCollection);
fileMenu.add(loadCollection);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
_canvasExcavator.setBounds(0, 0, getWidth()-200, getHeight());
labelCollectionName.setBounds(getWidth()-190, 30, 150, 20);
textBoxCollection.setBounds(getWidth()-190, 52, 150, 25);
radioButtonMassive.setBounds(getWidth()-190, 80, 75, 20);
radioButtonList.setBounds(getWidth()-105, 80, 75, 20);
buttonAddCollection.setBounds(getWidth()-190, 105, 150, 20);
listBoxCollection.setBounds(getWidth()-190, 135, 150, 70);
buttonRemoveCollection.setBounds(getWidth()-190, 210, 150, 20);
ComboBoxCollections.setBounds(getWidth()-190, 10, 150, 20);
buttonCreateCompany.setBounds(getWidth()-190, 240, 150, 20);
CreateButton.setBounds(getWidth()-190, 280, 150, 30);
MaskedTextField.setBounds(getWidth()-190,360,150,30);
RemoveButton.setBounds(getWidth()-190, 400, 150, 30);
GoToCheckButton.setBounds(getWidth()-190, 440, 150, 30);
RandomButton.setBounds(getWidth()-190, 480, 150, 30);
RemoveObjectsButton.setBounds(getWidth()-190, 520, 150, 30);
RefreshButton.setBounds(getWidth()-190, getHeight()-100, 150, 30);
setSize(dimension.width,dimension.height);
setLayout(null);
add(_canvasExcavator);
add(labelCollectionName);
add(textBoxCollection);
add(radioButtonMassive);
add(radioButtonList);
add(buttonAddCollection);
add(listBoxCollection);
add(buttonRemoveCollection);
add(ComboBoxCollections);
add(buttonCreateCompany);
add(CreateButton);
add(MaskedTextField);
add(RemoveButton);
add(GoToCheckButton);
add(RandomButton);
add(RemoveObjectsButton);
add(RefreshButton);
setVisible(true);
}
private void RefreshListBoxItems()
{
DefaultListModel<String> list = new DefaultListModel<String>();
for (String name : _storageCollection.Keys()) {
if (name != "")
{
list.addElement(name);
}
}
listBoxCollection.setModel(list);
}
private String SaveWindow() {
FileDialog fileDialog = new FileDialog(this, "Сохранить файл", FileDialog.SAVE);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void SaveFile() {
String filename = SaveWindow();
if (_storageCollection.SaveData(filename)) {
JOptionPane.showMessageDialog(null, "Сохранено");
}
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private void SaveCollection() {
String filename = SaveWindow();
if (filename == null) {
JOptionPane.showMessageDialog(null, "Файл не выбран");
return;
}
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
}
if (_storageCollection.SaveCollection(filename, listBoxCollection.getSelectedValue().toString())) {
JOptionPane.showMessageDialog(null, "Коллекция сохранена");
}
else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Загрузить файл", FileDialog.LOAD);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void LoadFile() {
String filename = LoadWindow();
if (_storageCollection.LoadData(filename)) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно");
RefreshListBoxItems();
}
else JOptionPane.showMessageDialog(null, "Не загрузилось");
}
private void LoadCollection() {
String filename = LoadWindow();
if (_storageCollection.LoadCollection(filename)) {
JOptionPane.showMessageDialog(null, "Коллекция загружена");
RefreshListBoxItems();
}
else JOptionPane.showMessageDialog(null, "Ошибка загрузки");
}
}

135
src/FormExcavator.java Normal file
View File

@ -0,0 +1,135 @@
import Drawings.*;
import MovementStrategy.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FormExcavator extends JFrame {
private String title;
private Dimension dimension;
private int Width, Height;
private CanvasExcavator canvasExcavator = new CanvasExcavator();
private JButton UpButton = new JButton();
private JButton DownButton = new JButton();
private JButton LeftButton = new JButton();
private JButton RightButton = new JButton();
private AbstractStrategy _strategy;
private JComboBox ComboBoxStrategy = new JComboBox(new String[]{"К центру", "К краю"});
private JButton ButtonStrategy = new JButton("Шаг");
public FormExcavator(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
}
public void Init(DrawingBulldozer bulldozer) {
setTitle(title);
setMinimumSize(dimension);
Width = getWidth() - 15;
Height = getHeight() - 35;
ComboBoxStrategy.setEnabled(true);
_strategy = null;
canvasExcavator._drawingBulldozer = bulldozer;
Icon iconUp = new ImageIcon("res/up.png");
UpButton.setIcon(iconUp);
UpButton.setName("Up");
DownButton.setName("Down");
Icon iconDown = new ImageIcon("res/down.png");
DownButton.setIcon(iconDown);
LeftButton.setName("Left");
Icon iconLeft = new ImageIcon("res/left.png");
LeftButton.setIcon(iconLeft);
RightButton.setName("Right");
Icon iconRight = new ImageIcon("res/right.png");
RightButton.setIcon(iconRight);
ButtonStrategy.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (canvasExcavator._drawingBulldozer == null) return;
if (ComboBoxStrategy.isEnabled())
{
int index = ComboBoxStrategy.getSelectedIndex();
switch(index)
{
case 0:
_strategy = new MoveToCenter();
break;
case 1:
_strategy = new MoveToBorder();
break;
default:
_strategy = null;
break;
}
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableExcavator(canvasExcavator._drawingBulldozer), Width, Height);
}
if (_strategy == null)
{
return;
}
ComboBoxStrategy.setEnabled(false);
_strategy.MakeStep();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
ComboBoxStrategy.setEnabled(true);
_strategy = null;
}
}
});
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (canvasExcavator._drawingBulldozer == null) return;
boolean result = false;
switch ((((JButton)(event.getSource())).getName())) {
case "Up":
result = canvasExcavator._drawingBulldozer.MoveTransport(DirectionType.Up);
break;
case "Down":
result = canvasExcavator._drawingBulldozer.MoveTransport(DirectionType.Down);
break;
case "Left":
result = canvasExcavator._drawingBulldozer.MoveTransport(DirectionType.Left);
break;
case "Right":
result = canvasExcavator._drawingBulldozer.MoveTransport(DirectionType.Right);
break;
}
if (result) {
canvasExcavator.repaint();
}
}
};
UpButton.addActionListener(actionListener);
DownButton.addActionListener(actionListener);
LeftButton.addActionListener(actionListener);
RightButton.addActionListener(actionListener);
setSize(dimension.width,dimension.height);
setLayout(null);
canvasExcavator.setBounds(0,0, getWidth(), getHeight());
UpButton.setBounds(getWidth() - 110, getHeight() - 135, 35, 35);
DownButton.setBounds(getWidth() - 110, getHeight() - 85, 35, 35);
RightButton.setBounds(getWidth() - 60, getHeight() - 85, 35, 35);
LeftButton.setBounds(getWidth() - 160, getHeight() - 85, 35, 35);
ComboBoxStrategy.setBounds(getWidth() - 170, 10, 140, 25);
ButtonStrategy.setBounds(getWidth() - 130, 45, 100, 25);
add(UpButton);
add(DownButton);
add(RightButton);
add(LeftButton);
add(ButtonStrategy);
add(ComboBoxStrategy);
add(canvasExcavator);
setVisible(true);
}
}

View File

@ -0,0 +1,448 @@
import CollectionGenericObjects.AbstractCompany;
import DifferentRollers.DrawingRollersStar;
import DifferentRollers.DrawingRollersCross;
import DifferentRollers.DrawingRollersPlus;
import DifferentRollers.IDifferentRollers;
import Drawings.DrawingBulldozer;
import Drawings.DrawingExcavator;
import Entities.EntityExcavator;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
public class FormExcavatorConfig extends JFrame {
private String title;
private Dimension dimension;
private DrawingBulldozer _bulldozer;
private AbstractCompany company = null;
private JLabel labelSpeed = new JLabel("Скорость");
private JLabel labelWeight = new JLabel("Вес");
private JLabel labelBulldozer = new JLabel("Бульдозер", SwingConstants.CENTER);
private JLabel labelExcavator = new JLabel("Экскаватор", SwingConstants.CENTER);
private JLabel labelColor = new JLabel("Цвет");
private JLabel labelBodyColor = new JLabel("Цвет кузова", SwingConstants.CENTER);
private JLabel labelRollersStar = new JLabel("Катки Звезда",SwingConstants.CENTER);
private JLabel labelRollersCross = new JLabel("Катки Крест", SwingConstants.CENTER);
private JLabel labelRollersPlus = new JLabel("Катки Плюс", SwingConstants.CENTER);
private JLabel labelAdditionalColor = new JLabel("Доп. цвет", SwingConstants.CENTER);
private JLabel labelNumberOfRollers = new JLabel("Кол-во катков");
private JSpinner spinnerSpeed = new JSpinner();
private JSpinner spinnerWeight = new JSpinner();
private JSpinner spinnerRollersCount = new JSpinner();
private JCheckBox checkBoxLadle = new JCheckBox("Добавить ковш");
private JCheckBox checkBoxProp = new JCheckBox("Добавить опоры");
private JComponent panelObject = new JPanel();
private JPanel panelColorRed = new JPanel();
private JPanel panelColorGreen = new JPanel();
private JPanel panelColorBlue = new JPanel();
private JPanel panelColorYellow = new JPanel();
private JPanel panelColorBlack = new JPanel();
private JPanel panelColorWhite = new JPanel();
private JPanel panelColorGray = new JPanel();
private JPanel panelColorPink = new JPanel();
private JButton buttonAdd = new JButton("Добавить");
private JButton buttonCansel = new JButton("Назад");
public FormExcavatorConfig(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
}
public void Init() {
SpinnerModel numSpeed = new SpinnerNumberModel(100, 100, 1000, 1);
SpinnerModel numWeight = new SpinnerNumberModel(100, 100, 1000, 1);
spinnerSpeed.setModel(numSpeed);
spinnerWeight.setModel(numWeight);
SpinnerModel numRollers = new SpinnerNumberModel(0, 0, 3, 1);
spinnerRollersCount.setModel(numRollers);
panelObject = new Canvas();
panelObject.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
spinnerSpeed.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (_bulldozer == null) return;
_bulldozer.EntityBulldozer.setSpeed((int)spinnerSpeed.getValue());
}
});
spinnerWeight.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (_bulldozer == null) return;
_bulldozer.EntityBulldozer.setWeight((int)spinnerWeight.getValue());
}
});
checkBoxLadle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_bulldozer == null) return;
if (_bulldozer.EntityBulldozer instanceof EntityExcavator excavator) {
excavator.setLadle(checkBoxLadle.isSelected());
panelObject.repaint();
}
}
});
checkBoxProp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_bulldozer == null) return;
if (_bulldozer.EntityBulldozer instanceof EntityExcavator excavator) {
excavator.setProp(checkBoxProp.isSelected());
panelObject.repaint();
}
}
});
labelBulldozer.setBackground(Color.WHITE);
labelBulldozer.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelExcavator.setBackground(Color.WHITE);
labelExcavator.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelBodyColor.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelAdditionalColor.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelRollersCross.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelRollersStar.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelRollersPlus.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
MouseAdapter labelObjectsMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
};
TransferHandler labelObjectsTransferHandler = new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new StringSelection(((JLabel) c).getText());
}
};
labelBulldozer.addMouseListener(labelObjectsMouseDown);
labelBulldozer.setTransferHandler(labelObjectsTransferHandler);
labelExcavator.addMouseListener(labelObjectsMouseDown);
labelExcavator.setTransferHandler(labelObjectsTransferHandler);
MouseAdapter labelRollersMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
};
labelRollersCross.addMouseListener(labelRollersMouseDown);
labelRollersStar.addMouseListener(labelRollersMouseDown);
labelRollersPlus.addMouseListener(labelRollersMouseDown);
labelRollersCross.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new RollersTransferable(new DrawingRollersCross());
}
});
labelRollersStar.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new RollersTransferable(new DrawingRollersStar());
}
});
labelRollersPlus.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new RollersTransferable(new DrawingRollersPlus());
}
});
panelObject.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor) || support.isDataFlavorSupported(RollersTransferable.rollersDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
if (canImport(support)) {
try {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "Бульдозер":
_bulldozer = new DrawingBulldozer((int) spinnerSpeed.getValue(), (int) spinnerWeight.getValue(),
Color.WHITE);
break;
case "Экскаватор":
_bulldozer = new DrawingExcavator((int) spinnerSpeed.getValue(), (int) spinnerWeight.getValue(),
Color.WHITE, Color.BLACK, checkBoxLadle.isSelected(), checkBoxProp.isSelected());
break;
}
if (_bulldozer != null) {
_bulldozer.SetPictureSize(155,155);
_bulldozer.SetPosition(5,10);
}
else return false;
}
catch (UnsupportedFlavorException | IOException e) {}
try {
IDifferentRollers rollers = (IDifferentRollers) support.getTransferable().getTransferData(RollersTransferable.rollersDataFlavor);
_bulldozer.drawingRollers = rollers;
_bulldozer.drawingRollers.setRollersCount((int) spinnerRollersCount.getValue());
}catch (UnsupportedFlavorException | IOException e) {}
panelObject.repaint();
return true;
}
return false;
}
});
JPanel[] colorPanels = {
panelColorRed,
panelColorGreen,
panelColorBlue,
panelColorYellow,
panelColorWhite,
panelColorBlack,
panelColorGray,
panelColorPink,
};
panelColorRed.setBackground(Color.RED);
panelColorGreen.setBackground(Color.GREEN);
panelColorBlue.setBackground(Color.BLUE);
panelColorYellow.setBackground(Color.YELLOW);
panelColorWhite.setBackground(Color.WHITE);
panelColorBlack.setBackground(Color.BLACK);
panelColorGray.setBackground(Color.GRAY);
panelColorPink.setBackground(Color.MAGENTA);
MouseAdapter colorMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JPanel) e.getComponent()).getTransferHandler().exportAsDrag(((JPanel) e.getComponent()), e, TransferHandler.COPY);
}
};
for (var panelColor : colorPanels) {
panelColor.addMouseListener(colorMouseDown);
panelColor.setTransferHandler(new ColorTransferHandler());
}
labelBodyColor.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_bulldozer == null) return false;
_bulldozer.EntityBulldozer.setBodyColor(color);
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
});
labelAdditionalColor.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferSupport support) {
if (!(_bulldozer instanceof DrawingExcavator)) return false;
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_bulldozer == null) return false;
if (_bulldozer.EntityBulldozer instanceof EntityExcavator excavator) {
excavator.setAdditionalColor(color);
labelColor.setBackground(color);
return true;
}
return false;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
});
buttonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_bulldozer == null) return;
DrawingBulldozer copyBulldozer;
if (_bulldozer instanceof DrawingExcavator)
copyBulldozer = new DrawingExcavator((EntityExcavator) _bulldozer.EntityBulldozer, _bulldozer.drawingRollers);
else
copyBulldozer = new DrawingBulldozer(_bulldozer.EntityBulldozer, _bulldozer.drawingRollers);
company._collection.Insert(copyBulldozer);
FormBulldozerCollection.canvasShow();
dispose();
}
});
buttonCansel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
labelSpeed.setBounds(10, 17, 50, 15);
labelWeight.setBounds(10,43, 50, 15);
labelNumberOfRollers.setBounds(10, 68, 50, 15);
labelBulldozer.setBounds(10,150,90,30);
labelExcavator.setBounds(10,190,90,30);
labelColor.setBounds(170,10,30,15);
labelBodyColor.setBounds(500,5,75, 40);
labelAdditionalColor.setBounds(580,5,75,40);
labelRollersCross.setBounds(120, 210, 100, 40);
labelRollersStar.setBounds(230, 210, 100,40);
labelRollersPlus.setBounds(340,210,100,40);
spinnerSpeed.setBounds(60,15, 60,20);
spinnerWeight.setBounds(60,40, 60,20);
spinnerRollersCount.setBounds(60, 65,60,20);
checkBoxLadle.setBounds(8,85,150,20);
checkBoxProp.setBounds(8,105,150,20);
panelObject.setBounds(500,50,160,150);
panelColorRed.setBounds(170, 30, 40, 40);
panelColorGreen.setBounds(220, 30, 40,40);
panelColorBlue.setBounds(270,30,40,40);
panelColorYellow.setBounds(320,30,40,40);
panelColorWhite.setBounds(170, 80,40,40);
panelColorBlack.setBounds(220,80,40,40);
panelColorGray.setBounds(270,80,40,40);
panelColorPink.setBounds(320,80,40,40);
buttonAdd.setBounds(500, 210, 75, 40);
buttonCansel.setBounds(590, 210, 70, 40);
setSize(dimension.width, dimension.height);
setLayout(null);
add(labelSpeed);
add(labelWeight);
add(labelNumberOfRollers);
add(labelBodyColor);
add(labelBulldozer);
add(labelExcavator);
add(labelColor);
add(labelBodyColor);
add(labelAdditionalColor);
add(labelRollersCross);
add(labelRollersStar);
add(labelRollersPlus);
add(spinnerSpeed);
add(spinnerWeight);
add(spinnerRollersCount);
add(checkBoxLadle);
add(checkBoxProp);
add(panelObject);
add(panelColorRed);
add(panelColorGreen);
add(panelColorBlue);
add(panelColorYellow);
add(panelColorWhite);
add(panelColorBlack);
add(panelColorGray);
add(panelColorPink);
add(buttonAdd);
add(buttonCansel);
setVisible(true);
}
public void setCompany(AbstractCompany company) {
this.company = company;
}
private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent(Graphics g) {
if (_bulldozer == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_bulldozer.DrawTransport(g2d);
super.repaint();
}
}
private class ColorTransferable implements Transferable {
private Color color;
private static final DataFlavor colorDataFlavor = new DataFlavor(Color.class, "Color");
public ColorTransferable(Color color) {
this.color = color;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{colorDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return colorDataFlavor.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor)) {
return color;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
private class ColorTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new ColorTransferable(c.getBackground());
}
}
private class RollersTransferable implements Transferable {
private IDifferentRollers rollers;
private static final DataFlavor rollersDataFlavor = new DataFlavor(IDifferentRollers.class, "Rollers");
public RollersTransferable(IDifferentRollers rollers) {
this.rollers = rollers;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{rollersDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(rollersDataFlavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor)) {
return rollers;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
}

View File

@ -1,5 +0,0 @@
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

View File

@ -0,0 +1,56 @@
package MovementStrategy;
public abstract class AbstractStrategy {
private IMoveableObjects _moveableObject;
private StrategyStatus _state = StrategyStatus.NotInit;
public int FieldWidth;
public int FieldHeight;
public StrategyStatus GetStatus() {return _state;}
public void SetData(IMoveableObjects moveableObjects, int width, int height)
{
if (moveableObjects == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObjects;
FieldWidth = width;
FieldHeight = height;
}
public void MakeStep()
{
if (_state != StrategyStatus.InProgress) return;
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
protected boolean MoveLeft() {return MoveTo(MovementDirection.Left);}
protected boolean MoveRight() {return MoveTo(MovementDirection.Right);}
protected boolean MoveUp() {return MoveTo(MovementDirection.Up);}
protected boolean MoveDown() {return MoveTo(MovementDirection.Down);}
protected ObjectParameters GetObjectParameters() {return _moveableObject.GetObjectPosition();}
protected Integer GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject.GetStep();
}
protected abstract void MoveToTarget();
protected abstract boolean IsTargetDestination();
private boolean MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
boolean stateTryMoveObject = _moveableObject.TryMoveObject(movementDirection);
if (stateTryMoveObject) return stateTryMoveObject;
return false;
}
}

View File

@ -0,0 +1,7 @@
package MovementStrategy;
public interface IMoveableObjects {
ObjectParameters GetObjectPosition();
int GetStep();
boolean TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,26 @@
package MovementStrategy;
public class MoveToBorder extends AbstractStrategy{
@Override
protected boolean IsTargetDestination(){
ObjectParameters objParams = GetObjectParameters();
if (objParams == null){
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth - GetStep() && objParams.DownBorder + GetStep() >= FieldHeight - GetStep();
}
@Override
protected void MoveToTarget(){
ObjectParameters objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
//реализация в правый нижний угол
int x = objParams.RightBorder;
if (x + GetStep() < FieldWidth) MoveRight();
int y = objParams.DownBorder;
if (y + GetStep() < FieldHeight) MoveDown();
}
}

View File

@ -0,0 +1,48 @@
package MovementStrategy;
public class MoveToCenter extends AbstractStrategy{
@Override
protected boolean IsTargetDestination() {
ObjectParameters objParams = GetObjectParameters();
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight /2;
}
@Override
protected void MoveToTarget() {
ObjectParameters objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,45 @@
package MovementStrategy;
import Drawings.CanvasExcavator;
import Drawings.DrawingBulldozer;
import Drawings.DirectionType;
public class MoveableExcavator implements IMoveableObjects{
private CanvasExcavator canvas = new CanvasExcavator();
public MoveableExcavator(DrawingBulldozer drawingBulldozer){
canvas._drawingBulldozer = drawingBulldozer;
}
@Override
public ObjectParameters GetObjectPosition() {
if (canvas._drawingBulldozer == null || canvas._drawingBulldozer.EntityBulldozer == null ||
canvas._drawingBulldozer.GetPosX() == null || canvas._drawingBulldozer.GetPosY() == null)
{
return null;
}
return new ObjectParameters(canvas._drawingBulldozer.GetPosX(), canvas._drawingBulldozer.GetPosY(),
canvas._drawingBulldozer.GetWidth(), canvas._drawingBulldozer.GetHeight());
}
@Override
public int GetStep() {
return (int)(canvas._drawingBulldozer.EntityBulldozer.Step);
}
@Override
public boolean TryMoveObject(MovementDirection direction) {
if (canvas._drawingBulldozer == null || canvas._drawingBulldozer.EntityBulldozer == null)
{
return false;
}
return canvas._drawingBulldozer.MoveTransport(GetDirectionType(direction));
}
private static DirectionType GetDirectionType(MovementDirection direction)
{
switch (direction) {
case Left: return DirectionType.Left;
case Right: return DirectionType.Right;
case Up: return DirectionType.Up;
case Down: return DirectionType.Down;
default: return DirectionType.Unknow;
}
}
}

View File

@ -0,0 +1,8 @@
package MovementStrategy;
public enum MovementDirection {
Up,
Down,
Left,
Right
}

View File

@ -0,0 +1,27 @@
package MovementStrategy;
public class ObjectParameters {
private int _x;
private int _y;
private int _width;
private int _height;
public int LeftBorder = _x;
public int TopBorder = _y;
public int RightBorder = _x + _width;
public int DownBorder = _y + _height;
public int ObjectMiddleHorizontal = _x + _width / 2;
public int ObjectMiddleVertical = _y + _height / 2;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
LeftBorder = _x;
TopBorder = _y;
RightBorder = _x + _width;
DownBorder = _y + _height;
ObjectMiddleHorizontal = _x + _width / 2;
ObjectMiddleVertical = _y + _height / 2;
}
}

View File

@ -0,0 +1,7 @@
package MovementStrategy;
public enum StrategyStatus {
NotInit,
InProgress,
Finish
}

9
src/Program.java Normal file
View File

@ -0,0 +1,9 @@
import java.awt.*;
public class Program {
public static void main(String[] args) {
FormBulldozerCollection form = new FormBulldozerCollection("Коллекция экскаваторов", new Dimension(1100, 660));
form.Init();
form.setLocationRelativeTo(null);
}
}