Compare commits

..

16 Commits

Author SHA1 Message Date
94d83a31ca LabWork06: Фиксы, возможен рефакторинг 2022-12-06 17:09:12 +04:00
47e81cce43 LabWork06: Лабораторная готова, возможен рефакторинг 2022-12-06 15:01:05 +04:00
5a2ef44c5c LabWork05: Лабораторная готова, возможен рефакторинг 2022-12-04 00:19:21 +04:00
8a33beaab2 Merge branch 'LabWork03' into LabWork04 2022-11-27 15:13:33 +04:00
076bdb8196 LabWork03: Фиксы 2022-11-27 15:08:50 +04:00
44da4da1bf Merge branch 'LabWork03' into LabWork04 2022-11-22 16:05:10 +04:00
2f4b0a65e7 LabWork03: Фиксы 2022-11-22 16:01:36 +04:00
2e82bbe98d LabWork04: Работа готова, возможен рефакторинг 2022-11-22 00:21:46 +04:00
a2cf154aa4 LabWork03: После удаления FormMap, лабораторка готова 2022-11-21 21:35:51 +04:00
f710cc4300 LabWork03: До удаления FormMap 2022-11-21 21:34:45 +04:00
67255fd203 LabWork02: Выполнено 2022-11-07 02:08:18 +04:00
4805ad09d0 LabWork02: Выполнено, требуется редактирование кода 2022-11-07 01:52:50 +04:00
1095fca9e8 LabWork02: Базовая часть перенесена 2022-11-07 00:26:51 +04:00
92a11ea687 LabWork01: Завершено 2022-11-05 23:32:00 +04:00
a48405450c LabWork01: Завершено, возможны мелкие поправки по оформлению 2022-11-05 23:24:05 +04:00
ac171b2770 LabWork01: Сделана базовая часть 2022-11-05 22:34:57 +04:00
35 changed files with 2872 additions and 0 deletions

117
AbstractMap.java Normal file
View File

@ -0,0 +1,117 @@
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public abstract class AbstractMap {
private IDrawningObject _drawningObject = null;
protected int[][] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected final Random _random = new Random();
protected final int _freeRoad = 0;
protected final int _barrier = 1;
public Image CreateMap(int width, int height, IDrawningObject drawningObject)
{
_width = width;
_height = height;
_drawningObject = drawningObject;
do {
GenerateMap();
} while (!SetObjectOnMap());
return DrawMapWithObject();
}
public Image MoveObject(Direction direction)
{
_drawningObject.moveObject(direction);
if (objectIntersects()) {
switch (direction) {
case Left -> _drawningObject.moveObject(Direction.Right);
case Right -> _drawningObject.moveObject(Direction.Left);
case Up -> _drawningObject.moveObject(Direction.Down);
case Down -> _drawningObject.moveObject(Direction.Up);
}
}
return DrawMapWithObject();
}
private boolean SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.nextInt(0, 10);
int y = _random.nextInt(0, 10);
_drawningObject.setObject(x, y, _width, _height);
var Location = _drawningObject.getCurrentPosition();
if (objectIntersects()){
int startLocX = (int)(Location[0] / _size_x);
int startLocY = (int)(Location[2] / _size_y);
int endLocX = (int)(Location[1] / _size_x);
int endLocY = (int)(Location[3] / _size_y);
for (int j = startLocX; j <= endLocX; j++)
{
for (int i = startLocY; i <= endLocY; i++)
{
if (_map[i][j] == _barrier) _map[i][j] = _freeRoad;
}
}
}
return true;
}
private boolean objectIntersects() {
float[] location = _drawningObject.getCurrentPosition();
Rectangle self = new Rectangle((int) location[0], (int) location[2], (int) location[1] - (int) location[0], (int) location[3] - (int) location[2]);
for (int i = 0; i < _map.length; i++)
{
for (int j = 0; j < _map[i].length; j++)
{
if (_map[i][j] == _barrier)
{
if (self.intersects(new Rectangle(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y)))
{
return true;
}
}
}
}
return false;
}
private Image DrawMapWithObject() {
Image img = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_ARGB);
if (_drawningObject == null || _map == null) {
return img;
}
Graphics2D g = (Graphics2D) img.getGraphics();
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[i].length; ++j)
{
if (_map[i][j] == _freeRoad)
{
DrawRoadPart(g, i, j);
} else if (_map[i][j] == _barrier)
{
DrawBarrierPart(g, i, j);
}
}
}
_drawningObject.drawningObject(g);
return img;
}
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics2D g, int i, int j);
protected abstract void DrawBarrierPart(Graphics2D g, int i, int j);
}

7
Direction.java Normal file
View File

@ -0,0 +1,7 @@
public enum Direction {
Up,
Down,
Left,
Right,
None
}

102
DrawningCrossRollers.java Normal file
View File

@ -0,0 +1,102 @@
import java.awt.*;
public class DrawningCrossRollers implements IDrawningRollers{
private RollersCount rollersCount;
private Color colorRollers;
public void setRollersCount(int count){
switch (count) {
case 4 -> rollersCount = RollersCount.Four;
case 5 -> rollersCount = RollersCount.Five;
case 6 -> rollersCount = RollersCount.Six;
default -> rollersCount = RollersCount.Four;
}
}
public DrawningCrossRollers(int count, Color colorRollers){
setRollersCount(count);
this.colorRollers = colorRollers;
}
public int getRollersCount() {
return rollersCount.getValue();
}
public void DrawRollers(Graphics2D g, float _startPosX, float _startPosY){
Color penColor = Color.BLACK;
Color mainColor = colorRollers==null ? Color.LIGHT_GRAY : colorRollers;
// Крупные катки - всегда
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 5, (int)_startPosY + 60, 22, 22);
g.setColor(penColor);
g.drawOval((int)_startPosX + 5, (int)_startPosY + 60, 22, 22);
// вертикальное перекрестие
g.fillRect((int)_startPosX + 14, (int)_startPosY + 65, 5, 14);
// горизонтальное перекрестие
g.fillRect((int)_startPosX + 10, (int)_startPosY + 69, 13, 5);
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 83, (int)_startPosY + 60, 22, 22);
g.setColor(penColor);
g.drawOval((int)_startPosX + 83, (int)_startPosY + 60, 22, 22);
// вертикальное перекрестие
g.fillRect((int)_startPosX + 92, (int)_startPosY + 65, 5, 14);
// горизонтальное перекрестие
g.fillRect((int)_startPosX + 88, (int)_startPosY + 69, 13, 5);
// Малые катки - всегда
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 43, (int)_startPosY + 58, 6, 6);
g.setColor(penColor);
g.drawOval((int)_startPosX + 43, (int)_startPosY + 58, 6, 6);
// вертикальное перекрестие
g.fillRect((int)_startPosX + 46, (int)_startPosY + 60, 1, 3);
// горизонтальное перекрестие
g.fillRect((int)_startPosX + 45, (int)_startPosY + 61, 3, 1);
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 61, (int)_startPosY + 58, 6, 6);
g.setColor(penColor);
g.drawOval((int)_startPosX + 61, (int)_startPosY + 58, 6, 6);
// вертикальное перекрестие
g.fillRect((int)_startPosX + 64, (int)_startPosY + 60, 1, 3);
// горизонтальное перекрестие
g.fillRect((int)_startPosX + 63, (int)_startPosY + 61, 3, 1);
// Средние катки - не всегда
switch (rollersCount){
case Six:
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 33, (int)_startPosY + 73, 10, 10);
g.setColor(penColor);
g.drawOval((int)_startPosX + 33, (int)_startPosY + 73, 10, 10);
// вертикальное перекрестие
g.fillRect((int)_startPosX + 37, (int)_startPosY + 75, 2, 6);
// горизонтальное перекрестие
g.fillRect((int)_startPosX + 35, (int)_startPosY + 77, 6, 2);
case Five:
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 68, (int)_startPosY + 73, 10, 10);
g.setColor(penColor);
g.drawOval((int)_startPosX + 68, (int)_startPosY + 73, 10, 10);
// вертикальное перекрестие
g.fillRect((int)_startPosX + 72, (int)_startPosY + 75, 2, 6);
// горизонтальное перекрестие
g.fillRect((int)_startPosX + 70, (int)_startPosY + 77, 6, 2);
}
// Центры крупных катков
g.setColor(Color.BLACK);
g.fillOval((int)_startPosX + 13, (int)_startPosY + 68, 6, 6);
g.fillOval((int)_startPosX + 91, (int)_startPosY + 68, 6, 6);
}
public void setColor(Color color) {
this.colorRollers = color;
}
}

View File

@ -0,0 +1,54 @@
import javax.print.DocFlavor;
import java.awt.*;
public class DrawningObjectExcavator implements IDrawningObject{
private DrawningTracktor _tracktor;
public DrawningObjectExcavator(DrawningTracktor tracktor) {
this._tracktor = tracktor;
}
public DrawningTracktor getTracktor() {
return _tracktor;
}
public float getStep() {
if (_tracktor != null && _tracktor.Tracktor != null) {
return _tracktor.Tracktor.getStep();
}
return 0;
}
public float[] getCurrentPosition() {
if (_tracktor != null) {
return _tracktor.getCurrentPosition();
}
return new float[] { 0, 0, 0, 0 };
}
public void moveObject(Direction direction) {
if (_tracktor != null) {
_tracktor.MoveTransport(direction);
}
}
public void setObject(int x, int y, int width, int height) {
_tracktor.SetPosition(x, y, width, height);
}
public void drawningObject(Graphics2D g) {
_tracktor.DrawTransport(g);
}
public String getInfo() {
if (_tracktor == null) {
return null;
}
return TracktorSerde.serialize(_tracktor);
}
public static IDrawningObject create(String data) {
return new DrawningObjectExcavator(TracktorSerde.deserialize(data));
}
}

78
DrawningRollers.java Normal file
View File

@ -0,0 +1,78 @@
import java.awt.*;
public class DrawningRollers implements IDrawningRollers {
private RollersCount rollersCount;
private Color colorRollers;
public void setRollersCount(int count){
switch (count) {
case 4 -> rollersCount = RollersCount.Four;
case 5 -> rollersCount = RollersCount.Five;
case 6 -> rollersCount = RollersCount.Six;
default -> rollersCount = RollersCount.Four;
}
}
public DrawningRollers(int count, Color colorRollers){
setRollersCount(count);
this.colorRollers = colorRollers;
}
public int getRollersCount() {
return rollersCount.getValue();
}
public void DrawRollers(Graphics2D g, float _startPosX, float _startPosY){
Color penColor = Color.BLACK;
Color mainColor = colorRollers==null ? Color.LIGHT_GRAY : colorRollers;
// Крупные катки - всегда
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 5, (int)_startPosY + 60, 22, 22);
g.setColor(penColor);
g.drawOval((int)_startPosX + 5, (int)_startPosY + 60, 22, 22);
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 83, (int)_startPosY + 60, 22, 22);
g.setColor(penColor);
g.drawOval((int)_startPosX + 83, (int)_startPosY + 60, 22, 22);
// Малые катки - всегда
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 43, (int)_startPosY + 58, 6, 6);
g.setColor(penColor);
g.drawOval((int)_startPosX + 43, (int)_startPosY + 58, 6, 6);
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 61, (int)_startPosY + 58, 6, 6);
g.setColor(penColor);
g.drawOval((int)_startPosX + 61, (int)_startPosY + 58, 6, 6);
// Средние катки - не всегда
switch (rollersCount){
case Six:
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 33, (int)_startPosY + 73, 10, 10);
g.setColor(penColor);
g.drawOval((int)_startPosX + 33, (int)_startPosY + 73, 10, 10);
case Five:
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 68, (int)_startPosY + 73, 10, 10);
g.setColor(penColor);
g.drawOval((int)_startPosX + 68, (int)_startPosY + 73, 10, 10);
}
// Центры крупных катков
g.setColor(Color.BLACK);
g.fillOval((int)_startPosX + 13, (int)_startPosY + 68, 6, 6);
g.fillOval((int)_startPosX + 91, (int)_startPosY + 68, 6, 6);
}
public void setColor(Color color) {
this.colorRollers = color;
}
}

133
DrawningSquaredRollers.java Normal file
View File

@ -0,0 +1,133 @@
import java.awt.*;
public class DrawningSquaredRollers implements IDrawningRollers {
private RollersCount rollersCount;
private Color colorRollers;
public void setRollersCount(int count){
switch (count) {
case 4 -> rollersCount = RollersCount.Four;
case 5 -> rollersCount = RollersCount.Five;
case 6 -> rollersCount = RollersCount.Six;
default -> rollersCount = RollersCount.Four;
}
}
public DrawningSquaredRollers(int count, Color colorRollers){
setRollersCount(count);
this.colorRollers = colorRollers;
}
public int getRollersCount() {
return rollersCount.getValue();
}
public void DrawRollers(Graphics2D g, float _startPosX, float _startPosY){
Color penColor = Color.BLACK;
Color mainColor = colorRollers==null ? Color.LIGHT_GRAY : colorRollers;
// Крупные катки - всегда
// Узор для больших катков
Polygon bigRomb = new Polygon(
new int[]{(int)_startPosX + 5, (int)_startPosX + 16, (int)_startPosX + 27, (int)_startPosX + 16},
new int[]{(int)_startPosY + 71, (int)_startPosY + 60, (int)_startPosY + 71, (int)_startPosY + 82},
4
);
Polygon bigCube = new Polygon(
new int[]{(int)_startPosX + 10, (int)_startPosX + 22, (int)_startPosX + 22, (int)_startPosX + 10},
new int[]{(int)_startPosY + 65, (int)_startPosY + 65, (int)_startPosY + 77, (int)_startPosY + 77},
4
);
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 5, (int)_startPosY + 60, 22, 22);
g.setColor(penColor);
g.drawOval((int)_startPosX + 5, (int)_startPosY + 60, 22, 22);
g.drawPolygon(bigRomb);
g.drawPolygon(bigCube);
// Сдвиг
bigRomb.translate(78,0);
bigCube.translate(78,0);
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 83, (int)_startPosY + 60, 22, 22);
g.setColor(penColor);
g.drawOval((int)_startPosX + 83, (int)_startPosY + 60, 22, 22);
g.drawPolygon(bigRomb);
g.drawPolygon(bigCube);
// Малые катки - всегда
// Узор
Polygon smallRomb = new Polygon(
new int[]{(int)_startPosX + 43, (int)_startPosX + 46, (int)_startPosX + 49, (int)_startPosX + 46},
new int[]{(int)_startPosY + 61, (int)_startPosY + 58, (int)_startPosY + 61, (int)_startPosY + 64},
4
);
Polygon smallCube = new Polygon(
new int[]{(int)_startPosX + 44, (int)_startPosX + 48, (int)_startPosX + 48, (int)_startPosX + 44},
new int[]{(int)_startPosY + 59, (int)_startPosY + 63, (int)_startPosY + 63, (int)_startPosY + 59},
4
);
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 43, (int)_startPosY + 58, 6, 6);
g.setColor(penColor);
g.drawOval((int)_startPosX + 43, (int)_startPosY + 58, 6, 6);
g.drawPolygon(smallRomb);
g.drawPolygon(smallCube);
// Сдвиг
smallRomb.translate(18,0);
smallCube.translate(18,0);
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 61, (int)_startPosY + 58, 6, 6);
g.setColor(penColor);
g.drawOval((int)_startPosX + 61, (int)_startPosY + 58, 6, 6);
g.drawPolygon(smallRomb);
g.drawPolygon(smallCube);
// Средние катки - не всегда
// Узор
Polygon middleRomb = new Polygon(
new int[]{(int)_startPosX + 33, (int)_startPosX + 38, (int)_startPosX + 43, (int)_startPosX + 38},
new int[]{(int)_startPosY + 78, (int)_startPosY + 73, (int)_startPosY + 78, (int)_startPosY + 83},
4
);
Polygon middleCube = new Polygon(
new int[]{(int)_startPosX + 35, (int)_startPosX + 41, (int)_startPosX + 41, (int)_startPosX + 35},
new int[]{(int)_startPosY + 75, (int)_startPosY + 75, (int)_startPosY + 81, (int)_startPosY + 81},
4
);
switch (rollersCount){
case Six:
// 1
g.setColor(mainColor);
g.fillOval((int)_startPosX + 33, (int)_startPosY + 73, 10, 10);
g.setColor(penColor);
g.drawOval((int)_startPosX + 33, (int)_startPosY + 73, 10, 10);
g.drawPolygon(middleRomb);
g.drawPolygon(middleCube);
case Five:
// Сдвиг
middleRomb.translate(35,0);
middleCube.translate(35,0);
// 2
g.setColor(mainColor);
g.fillOval((int)_startPosX + 68, (int)_startPosY + 73, 10, 10);
g.setColor(penColor);
g.drawOval((int)_startPosX + 68, (int)_startPosY + 73, 10, 10);
g.drawPolygon(middleRomb);
g.drawPolygon(middleCube);
}
// Центры крупных катков
g.setColor(Color.BLACK);
g.fillOval((int)_startPosX + 13, (int)_startPosY + 68, 6, 6);
g.fillOval((int)_startPosX + 91, (int)_startPosY + 68, 6, 6);
}
public void setColor(Color color) {
this.colorRollers = color;
}
}

View File

@ -0,0 +1,72 @@
import java.awt.*;
public class DrawningTrackedVehicle extends DrawningTracktor {
public DrawningTrackedVehicle(int speed, float weight, Color bodyColor, int countRollers, Color dopColor, boolean bucket, boolean supports){
super(speed, weight, bodyColor, countRollers, 130, 87);
Tracktor = new EntityTrackedVehicle(speed, weight, bodyColor, dopColor, bucket, supports);
}
public DrawningTrackedVehicle(EntityTrackedVehicle entity, IDrawningRollers rollers) {
super(entity, rollers);
}
@Override
public void DrawTransport(Graphics2D g){
if (!(Tracktor instanceof EntityTrackedVehicle trackedVehicle))
{
return;
}
Color pen;
Color dopBrush = trackedVehicle.getDopColor();
if (trackedVehicle.getBucket())
{
pen = trackedVehicle.getDopColor();
g.setStroke(new BasicStroke(5));
g.setColor(pen);
g.drawLine((int)_startPosX + 1, (int)_startPosY + 90, (int)_startPosX + 15, (int)_startPosY + 70);
g.drawLine((int)_startPosX + 15, (int)_startPosY + 72, (int)_startPosX + 15, (int)_startPosY + 50);
g.drawLine((int)_startPosX + 15, (int)_startPosY + 52, (int)_startPosX + 10, (int)_startPosY + 45);
g.drawLine((int)_startPosX + 15, (int)_startPosY + 60, (int)_startPosX + 40, (int)_startPosY + 50);
g.setStroke(new BasicStroke(1));
}
_startPosX += 20;
_startPosY += 5;
super.DrawTransport(g);
_startPosX -= 20;
_startPosY -= 5;
if (trackedVehicle.getSupports())
{
pen = Color.BLACK;
g.setColor(dopBrush);
g.fillRect((int)_startPosX + 100, (int)_startPosY + 50, 10, 42);
g.setColor(pen);
g.drawRect((int)_startPosX + 100, (int)_startPosY + 50, 10, 42);
g.setColor(dopBrush);
g.fillRect((int)_startPosX + 90, (int)_startPosY + 82, 30, 10);
g.setColor(pen);
g.drawRect((int)_startPosX + 90, (int)_startPosY + 82, 30, 10);
g.setColor(dopBrush);
g.fillRect((int)_startPosX + 45, (int)_startPosY + 50, 10, 42);
g.setColor(pen);
g.drawRect((int)_startPosX + 45, (int)_startPosY + 50, 10, 42);
g.setColor(dopBrush);
g.fillRect((int)_startPosX + 35, (int)_startPosY + 82, 30, 10);
g.setColor(pen);
g.drawRect((int)_startPosX + 35, (int)_startPosY + 82, 30, 10);
}
}
@Override
public void setColor(Color color) {
var tmp = (EntityTrackedVehicle) Tracktor;
Tracktor = new EntityTrackedVehicle(tmp.getSpeed(), tmp.getWeight(), color, tmp.getDopColor(), tmp.getBucket(), tmp.getSupports());
}
public void setDopColor(Color color) {
var tmp = (EntityTrackedVehicle) Tracktor;
Tracktor = new EntityTrackedVehicle(tmp.getSpeed(), tmp.getWeight(), tmp.getBodyColor(), color, tmp.getBucket(), tmp.getSupports());
}
}

189
DrawningTracktor.java Normal file
View File

@ -0,0 +1,189 @@
import java.awt.*;
// Класс, отвечающий за прорисовку и перемещение объекта-сущности
public class DrawningTracktor {
protected EntityTracktor Tracktor; // Класс-сущность
public EntityTracktor getTracktor(){
return Tracktor;
}
protected float _startPosX; // Левая координата отрисовки трактора
protected float _startPosY; // Верхняя кооридната отрисовки трактора
private Integer _pictureWidth = null; // Ширина окна отрисовки
private Integer _pictureHeight = null; // Высота окна отрисовки
protected int _tracktorWidth = 110; // Ширина отрисовки трактора
protected int _tracktorHeight = 87; // Высота отрисовки трактора
private IDrawningRollers drawningRollers;
// Инициализация свойств
public DrawningTracktor(int speed, float weight, Color bodyColor, int countRollers)
{
Tracktor = new EntityTracktor(speed, weight, bodyColor);
drawningRollers = RollersType.random(countRollers, bodyColor);
}
public DrawningTracktor(EntityTracktor entity, IDrawningRollers rollers) {
Tracktor = entity;
drawningRollers = rollers;
}
public IDrawningRollers getRollers() {
return drawningRollers;
}
protected DrawningTracktor(int speed, float weight, Color bodyColor, int countRollers, int tracktorWidth, int tracktorHeight){
this(speed, weight, bodyColor, countRollers);
_tracktorWidth = tracktorWidth;
_tracktorHeight = tracktorHeight;
}
// Установка позиции Трактора
public void SetPosition(int x, int y, int width, int height)
{
if (x + _tracktorWidth > width ||
x < 0 ||
y + _tracktorHeight > height ||
y < 0)
{
return;
}
_startPosX = x;
_startPosY = y;
_pictureWidth = width;
_pictureHeight = height;
}
// Изменение направления перемещения
public void MoveTransport(Direction direction)
{
if (_pictureWidth == null || _pictureHeight == null)
{
return;
}
switch (direction)
{
// вправо
case Right:
if (_startPosX + _tracktorWidth + Tracktor.getStep() < _pictureWidth)
{
_startPosX += Tracktor.getStep();
}
break;
//влево
case Left:
if (_startPosX - Tracktor.getStep() > 0)
{
_startPosX -= Tracktor.getStep();
}
break;
//вверх
case Up:
if (_startPosY - Tracktor.getStep() > 0)
{
_startPosY -= Tracktor.getStep();
}
break;
//вниз
case Down:
if (_startPosY + _tracktorHeight + Tracktor.getStep() < _pictureHeight)
{
_startPosY += Tracktor.getStep();
}
break;
}
}
// Отрисовка Трактора
public void DrawTransport(Graphics2D g)
{
if (_startPosX < 0 || _startPosY < 0 || _pictureHeight == null || _pictureWidth == null)
{
return;
}
Color penColor = Color.BLACK;
// корпус
Color br = Tracktor!=null ? Tracktor.getBodyColor() : Color.GRAY ;
g.setColor(br);
g.fillRect((int)_startPosX + 10, (int)_startPosY + 30, 90, 25);
g.setColor(penColor);
g.drawRect((int)_startPosX + 10, (int)_startPosY + 30, 90, 25);
// окно
g.setColor(Color.CYAN);
g.fillRect((int)_startPosX + 65, (int)_startPosY + 1, 30, 29);
g.setColor(penColor);
g.drawRect((int)_startPosX + 65, (int)_startPosY + 1, 30, 29);
// труба
g.setColor(Color.RED);
g.fillRect((int)_startPosX + 30, (int)_startPosY + 10, 10, 20);
g.setColor(penColor);
g.drawRect((int)_startPosX + 30, (int)_startPosY + 10, 10, 20);
// гусеница
g.setColor(Color.DARK_GRAY);
g.fillOval((int)_startPosX + 1, (int)_startPosY + 57, 20, 20);
g.setColor(penColor);
g.drawOval((int)_startPosX + 1, (int)_startPosY + 57, 20, 20);
g.setColor(Color.DARK_GRAY);
g.fillOval((int)_startPosX + 1, (int)_startPosY + 65, 20, 20);
g.setColor(penColor);
g.drawOval((int)_startPosX + 1, (int)_startPosY + 65, 20, 20);
g.setColor(Color.DARK_GRAY);
g.fillOval((int)_startPosX + 90, (int)_startPosY + 57, 20, 20);
g.setColor(penColor);
g.drawOval((int)_startPosX + 90, (int)_startPosY + 57, 20, 20);
g.setColor(Color.DARK_GRAY);
g.fillOval((int)_startPosX + 90, (int)_startPosY + 65, 20, 20);
g.setColor(penColor);
g.drawOval((int)_startPosX + 90, (int)_startPosY + 65, 20, 20);
g.setColor(Color.DARK_GRAY);
g.fillRect((int)_startPosX + 10, (int)_startPosY + 57, 90, 30);
g.fillRect((int)_startPosX + 1, (int)_startPosY + 65, 110, 10);
g.setColor(penColor);
g.drawLine((int)_startPosX + 10, (int)_startPosY + 57, (int)_startPosX + 100, (int)_startPosY + 57);
g.drawLine((int)_startPosX + 10, (int)_startPosY + 86, (int)_startPosX + 100, (int)_startPosY + 86);
g.drawLine((int)_startPosX + 1, (int)_startPosY + 65, (int)_startPosX + 1, (int)_startPosY + 75);
g.drawLine((int)_startPosX + 110, (int)_startPosY + 65, (int)_startPosX + 110, (int)_startPosY + 75);
drawningRollers.DrawRollers(g, (int) _startPosX, (int) _startPosY);
}
// Смена границ формы отрисовки
public void ChangeBorders(int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth <= _tracktorWidth || _pictureHeight <= _tracktorHeight)
{
_pictureWidth = null;
_pictureHeight = null;
return;
}
if (_startPosX + _tracktorWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _tracktorWidth;
}
if (_startPosY + _tracktorHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _tracktorHeight;
}
}
public float[] getCurrentPosition() {
return new float[] { _startPosX, _startPosX + _tracktorWidth - 1, _startPosY, _startPosY + _tracktorHeight - 1 };
// Left - 0
// Right - 1
// Top - 2
// Bottom - 3
}
public void setColor(Color color) {
Tracktor = new EntityTracktor(Tracktor.getSpeed(), Tracktor.getWeight(), color);
}
public void setRollers(IDrawningRollers rollers) {
drawningRollers = rollers;
}
}

58
DumpMap.java Normal file
View File

@ -0,0 +1,58 @@
import java.awt.*;
public class DumpMap extends AbstractMap{
private final Color barrierColor = new Color(165,42,42);
private final Color roadColor = Color.LIGHT_GRAY;
@Override
protected void DrawBarrierPart(Graphics2D g, int j, int i)
{
g.setColor(barrierColor);
g.fillRect(i * (int)_size_x, j * (int)_size_y, (int)_size_x, (int)_size_y);
}
@Override
protected void DrawRoadPart(Graphics2D g, int j, int i)
{
g.setColor(roadColor);
g.fillRect(i * (int)_size_x, j * (int)_size_y, (int)_size_x, (int)_size_y);
}
@Override
protected void GenerateMap()
{
_map = new int[100][100];
_size_x = (float)_width / _map[0].length;
_size_y = (float)_height / _map.length;
int counter = 0;
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[0].length; ++j)
{
_map[i][j] = _freeRoad;
}
}
while (counter < 20)
{
int x = _random.nextInt(0, 100);
int y = _random.nextInt(0, 100);
if (_map[y][x] == _freeRoad && x > 1 && x < 98 && y > 1 && y < 98)
{
_map[y][x] = _barrier;
_map[y][x + 1] = _barrier;
_map[y][x + 2] = _barrier;
_map[y][x - 1] = _barrier;
_map[y][x - 2] = _barrier;
_map[y + 1][x] = _barrier;
_map[y + 2][x] = _barrier;
_map[y - 1][x] = _barrier;
_map[y - 2][x] = _barrier;
_map[y + 1][x + 1] = _barrier;
_map[y - 1][x + 1] = _barrier;
_map[y + 1][x - 1] = _barrier;
_map[y - 1][x - 1] = _barrier;
counter++;
}
}
}
}

29
EntityTrackedVehicle.java Normal file
View File

@ -0,0 +1,29 @@
import java.awt.*;
public class EntityTrackedVehicle extends EntityTracktor {
// Дополнительный цвет
private Color dopColor;
// Признак наличия ковша
private boolean bucket;
// Признак наличия опор
private boolean supports;
public EntityTrackedVehicle(int speed, float weight, Color bodyColor, Color dopColor, boolean bucket, boolean supports){
super(speed, weight, bodyColor);
this.dopColor = dopColor;
this.bucket = bucket;
this.supports = supports;
}
public Color getDopColor(){
return dopColor;
}
public boolean getBucket(){
return bucket;
}
public boolean getSupports(){
return supports;
}
}

31
EntityTracktor.java Normal file
View File

@ -0,0 +1,31 @@
import java.awt.*;
import java.util.Random;
// Класс-сущность "Трактор"
public class EntityTracktor {
private int Speed;
private float Weight;
private Color BodyColor;
public int getSpeed() {
return Speed;
}
public float getWeight(){
return Weight;
}
public Color getBodyColor(){
return BodyColor;
}
public float getStep(){
return Speed * 100 / Weight;
}
// Инициализация полей объекта-класса Трактора
public EntityTracktor(int speed, float weight, Color bodyColor)
{
Random rnd = new Random();
Speed = speed <= 0 ? rnd.nextInt(50, 150) : speed;
Weight = weight <= 0 ? rnd.nextInt(40, 70) : weight;
BodyColor = bodyColor;
}
}

48
EntityWithRollers.java Normal file
View File

@ -0,0 +1,48 @@
import java.util.ArrayList;
import java.util.Random;
public class EntityWithRollers<T extends EntityTracktor, U extends IDrawningRollers> {
static Random rnd = new Random();
private ArrayList<T> entities;
private ArrayList<U> rollers;
public int maxEntitiesCount = 0;
public int maxRollersCount = 0;
public EntityWithRollers(int count) {
entities = new ArrayList<T>();
rollers = new ArrayList<U>();
maxEntitiesCount = count;
maxRollersCount = count;
}
public boolean add(T entity) {
if (entities.size() >= maxEntitiesCount){
return false;
}
entities.add(entity);
return true;
}
public boolean add(U roller) {
if (rollers.size() >= maxRollersCount){
return false;
}
rollers.add(roller);
return true;
}
public IDrawningObject constructTracktor() {
if (entities.size() == 0 || rollers.size() == 0) {
return null;
}
EntityTracktor entity = (EntityTracktor) entities.get(rnd.nextInt(0, entities.size()));
IDrawningRollers roller = (IDrawningRollers) rollers.get(rnd.nextInt(0, rollers.size()));
if (entity instanceof EntityTrackedVehicle advancedEntity) {
return new DrawningObjectExcavator(new DrawningTrackedVehicle(advancedEntity, roller));
}
return new DrawningObjectExcavator(new DrawningTracktor(entity, roller));
}
}

16
EventListener.java Normal file
View File

@ -0,0 +1,16 @@
import java.util.ArrayList;
import java.util.function.Consumer;
public class EventListener<T> {
private final ArrayList<Consumer<T>> listeners = new ArrayList<>();
public void addListener(Consumer<T> listener) {
listeners.add(listener);
}
public void emit(T tracktor) {
for (var listener : listeners) {
listener.accept(tracktor);
}
}
}

41
FormGallery.form Normal file
View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormGallery">
<grid id="27dc6" binding="contentPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="60075" binding="pictureBox" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="eba14" class="javax.swing.JButton" binding="buttonRefresh">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Перезагрузить"/>
</properties>
</component>
<hspacer id="852b8">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<vspacer id="6b8fb">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
</children>
</grid>
</children>
</grid>
</form>

66
FormGallery.java Normal file
View File

@ -0,0 +1,66 @@
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class FormGallery extends JFrame {
private static final Random rnd = new Random();
private JPanel contentPanel;
private JButton buttonRefresh;
private JPanel pictureBox;
private IDrawningObject first;
private IDrawningObject second;
private IDrawningObject third;
private final EntityWithRollers<EntityTracktor, IDrawningRollers> storage;
public FormGallery() {
setTitle("Галлерея");
setContentPane(contentPanel);
storage = new EntityWithRollers<>(20);
for(int i = 0; i < 20; i++) {
if (rnd.nextBoolean()) {
storage.add(new EntityTrackedVehicle(
rnd.nextInt(100, 300),
rnd.nextInt(1000, 2000),
new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256)),
new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256)),
rnd.nextBoolean(),
rnd.nextBoolean()
));
} else {
storage.add(new EntityTracktor(
rnd.nextInt(100, 300),
rnd.nextInt(1000, 2000),
new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256))
));
}
storage.add(RollersType.random(rnd.nextInt(4, 7), new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256))));
}
buttonRefresh.addActionListener(e -> {
first = storage.constructTracktor();
second = storage.constructTracktor();
third = storage.constructTracktor();
first.setObject(0, 10, pictureBox.getWidth(), pictureBox.getHeight());
second.setObject(150, 10, pictureBox.getWidth(), pictureBox.getHeight());
third.setObject(300, 10, pictureBox.getWidth(), pictureBox.getHeight());
repaint();
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2g = (Graphics2D) pictureBox.getGraphics();
if (first != null && second != null && third != null) {
first.drawningObject(g2g);
second.drawningObject(g2g);
third.drawningObject(g2g);
}
}
}

209
FormMapWithSetTracktor.form Normal file
View File

@ -0,0 +1,209 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormMapWithSetTracktor">
<grid id="27dc6" binding="ContentPanel" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="663" height="584"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="afeba" binding="toolsGroup" layout-manager="GridLayoutManager" row-count="15" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="0" anchor="0" fill="3" indent="0" use-parent-layout="false">
<maximum-size width="200" height="-1"/>
</grid>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="412e9" class="javax.swing.JLabel" binding="toolsLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Инструменты"/>
</properties>
</component>
<component id="ca274" class="javax.swing.JButton" binding="buttonAddTracktor">
<constraints>
<grid row="7" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить трактор"/>
</properties>
</component>
<component id="8925f" class="javax.swing.JFormattedTextField" binding="textBoxPosition">
<constraints>
<grid row="8" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="e424c" class="javax.swing.JButton" binding="buttonRemoveTracktor">
<constraints>
<grid row="9" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Удалить трактор"/>
</properties>
</component>
<component id="5e5ae" class="javax.swing.JButton" binding="buttonShowStorage">
<constraints>
<grid row="10" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Посмотреть хранилище"/>
</properties>
</component>
<component id="52c38" class="javax.swing.JButton" binding="buttonShowOnMap">
<constraints>
<grid row="11" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Показать карту"/>
</properties>
</component>
<component id="d1efe" class="javax.swing.JButton" binding="buttonLeft">
<constraints>
<grid row="14" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/arrowLeft.png"/>
<text value=""/>
</properties>
</component>
<component id="11d8a" class="javax.swing.JButton" binding="buttonRight">
<constraints>
<grid row="14" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/arrowRight.png"/>
<text value=""/>
</properties>
</component>
<component id="bffec" class="javax.swing.JButton" binding="buttonUp">
<constraints>
<grid row="13" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/arrowUp.png"/>
<text value=""/>
</properties>
</component>
<component id="1f0dc" class="javax.swing.JButton" binding="buttonDown">
<constraints>
<grid row="14" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/arrowDown.png"/>
<text value=""/>
</properties>
</component>
<vspacer id="71dd1">
<constraints>
<grid row="12" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<grid id="c0175" binding="mapsGroup" layout-manager="GridLayoutManager" row-count="6" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="4" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="5cce4" class="javax.swing.JLabel" binding="mapsLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Карты"/>
</properties>
</component>
<component id="65411" class="javax.swing.JTextField" binding="textFieldMapName">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="c455c" class="javax.swing.JComboBox" binding="comboBoxMapSelector">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<model>
<item value="Простая карта"/>
<item value="Свалка карта"/>
</model>
</properties>
</component>
<component id="e0b94" class="javax.swing.JButton" binding="buttonAddMap">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить карту"/>
</properties>
</component>
<component id="3ffeb" class="javax.swing.JList" binding="listBoxMaps">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="2" anchor="0" fill="3" indent="0" use-parent-layout="false">
<preferred-size width="150" height="50"/>
</grid>
</constraints>
<properties/>
</component>
<component id="7fd9" class="javax.swing.JButton" binding="buttonDeleteMap">
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Удалить карту"/>
</properties>
</component>
</children>
</grid>
<vspacer id="f967a">
<constraints>
<grid row="5" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="edacb" class="javax.swing.JButton" binding="buttonShowDeleted">
<constraints>
<grid row="6" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Показать удаленные"/>
</properties>
</component>
</children>
</grid>
<grid id="c1cce" binding="pictureBox" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
</children>
</grid>
</form>

302
FormMapWithSetTracktor.java Normal file
View File

@ -0,0 +1,302 @@
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Optional;
public class FormMapWithSetTracktor extends JFrame {
private JMenuBar menuBar;
private JPanel ContentPanel;
private JPanel pictureBox;
private JPanel toolsGroup;
private JLabel toolsLabel;
private JComboBox<String> comboBoxMapSelector;
private JButton buttonAddTracktor;
private JFormattedTextField textBoxPosition;
private JButton buttonRemoveTracktor;
private JButton buttonShowStorage;
private JButton buttonShowOnMap;
private JButton buttonUp;
private JButton buttonLeft;
private JButton buttonRight;
private JButton buttonDown;
private JLabel mapsLabel;
private JTextField textFieldMapName;
private JButton buttonAddMap;
private JList<String> listBoxMaps;
private JPanel mapsGroup;
private JButton buttonDeleteMap;
private JButton buttonShowDeleted;
private Image bufferedImage;
private final HashMap<String, AbstractMap> _mapsDict = new HashMap<>() {{
put("Простая карта", new SimpleMap());
put("Свалка карта", new DumpMap());
}};
private final MapsCollection _mapsCollection;
private final LinkedList<IDrawningObject> deletedObjects = new LinkedList<>();
public FormMapWithSetTracktor() {
this.setTitle("Трактор");
this.setContentPane(ContentPanel);
this.setSize(800,600);
this.setVisible(true);
try {
textBoxPosition.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter("##")));
} catch (ParseException e) {
e.printStackTrace();
}
_mapsCollection = new MapsCollection(pictureBox.getWidth(), pictureBox.getHeight());
menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Файл");
menuBar.add(fileMenu);
JMenuItem saveMenuItem = new JMenuItem("Сохранить");
saveMenuItem.addActionListener(e -> {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileNameExtensionFilter("TXT file", "txt"));
dialog.showSaveDialog(this);
try {
if (_mapsCollection.saveData(dialog.getSelectedFile().getAbsolutePath())) {
JOptionPane.showMessageDialog(this, "Сохранение прошло успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Не сохранилось", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
} catch (IOException ex) {
ex.printStackTrace();
}
});
fileMenu.add(saveMenuItem);
JMenuItem loadMenuItem = new JMenuItem("Загрузить");
loadMenuItem.addActionListener(e -> {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileNameExtensionFilter("TXT file", "txt"));
dialog.showOpenDialog(this);
try {
if (_mapsCollection.loadData(dialog.getSelectedFile().getAbsolutePath())) {
reloadMaps();
JOptionPane.showMessageDialog(this, "Загрузка прошла успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Не загрузилось", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
} catch (IOException ex) {
ex.printStackTrace();
}
});
fileMenu.add(loadMenuItem);
JMenuItem saveMapMenuItem = new JMenuItem("Сохранить карту");
saveMapMenuItem.addActionListener(e -> {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileNameExtensionFilter("TXT file", "txt"));
dialog.showSaveDialog(this);
try {
if (_mapsCollection.saveMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse(""), dialog.getSelectedFile().getAbsolutePath())) {
JOptionPane.showMessageDialog(this, "Сохранение прошло успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Не сохранилось", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
} catch (IOException ex) {
ex.printStackTrace();
}
});
fileMenu.add(saveMapMenuItem);
JMenuItem loadMapMenuItem = new JMenuItem("Загрузить карту");
loadMapMenuItem.addActionListener(e -> {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileNameExtensionFilter("TXT file", "txt"));
dialog.showOpenDialog(this);
try {
if (_mapsCollection.loadMap(dialog.getSelectedFile().getAbsolutePath())) {
reloadMaps();
JOptionPane.showMessageDialog(this, "Загрузка прошла успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Не загрузилось", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
} catch (IOException ex) {
ex.printStackTrace();
}
});
fileMenu.add(loadMapMenuItem);
setJMenuBar(menuBar);
comboBoxMapSelector.removeAllItems();
for (var key : _mapsDict.keySet()) {
comboBoxMapSelector.addItem(key);
}
buttonAddMap.addActionListener(e -> {
if (comboBoxMapSelector.getSelectedIndex() == -1 || textFieldMapName.getText() == null || textFieldMapName.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Не все данные заполнены", "Ошибка", JOptionPane.ERROR_MESSAGE);
return;
}
if (!_mapsDict.containsKey((String)comboBoxMapSelector.getSelectedItem())) {
JOptionPane.showMessageDialog(this, "Нет такой карты", "Ошибка", JOptionPane.ERROR_MESSAGE);
return;
}
_mapsCollection.addMap(textFieldMapName.getText(), _mapsDict.get((String)comboBoxMapSelector.getSelectedItem()));
reloadMaps();
});
buttonDeleteMap.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() == -1) {
return;
}
if (JOptionPane.showConfirmDialog(this, "Удалить карту " + listBoxMaps.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
_mapsCollection.deleteMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse(""));
reloadMaps();
}
});
listBoxMaps.addListSelectionListener(e -> {
if (listBoxMaps.getSelectedValue() != null) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
repaint();
}
});
buttonAddTracktor.addActionListener(e -> {
FormTracktorConfig form = new FormTracktorConfig();
form.addListener(tracktor -> {
if (listBoxMaps.getSelectedIndex() == -1) {
return;
}
if (tracktor != null) {
DrawningObjectExcavator objectTracktor = new DrawningObjectExcavator(tracktor);
if (_mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).addTracktor(objectTracktor) != -1)
{
JOptionPane.showMessageDialog(this, "Объект добавлен", "Успех", JOptionPane.INFORMATION_MESSAGE);
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
repaint();
}
else
{
JOptionPane.showMessageDialog(this, "Не удалось добавить объект", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
}
});
form.setVisible(true);
});
buttonRemoveTracktor.addActionListener(e -> {
String text = textBoxPosition.getText();
if (text == null || text.isEmpty()) {
return;
}
if (JOptionPane.showConfirmDialog(this, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return;
}
int position = Integer.parseInt(text);
IDrawningObject deleted = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).removeTracktorAt(position);
if (deleted!=null) {
deletedObjects.add(deleted);
JOptionPane.showMessageDialog(this, "Объект удалён", "Успех", JOptionPane.INFORMATION_MESSAGE);
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
repaint();
} else {
JOptionPane.showMessageDialog(this, "Не удалось удалить объект", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
});
buttonShowStorage.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() == -1) {
return;
}
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
repaint();
});
buttonShowOnMap.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() == -1) {
return;
}
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showOnMap();
repaint();
});
buttonShowDeleted.addActionListener(e -> {
if (!deletedObjects.isEmpty()) {
DrawningObjectExcavator deleted = (DrawningObjectExcavator) deletedObjects.pop();
FormTracktor dialog = new FormTracktor(deleted.getTracktor());
dialog.setSize(800, 500);
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} else {
JOptionPane.showMessageDialog(this, "Связанный список удалённых объектов пуст", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
});
buttonLeft.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() != -1) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).moveObject(Direction.Left);
repaint();
}
});
buttonRight.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() != -1) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).moveObject(Direction.Right);
repaint();
}
});
buttonUp.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() != -1) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).moveObject(Direction.Up);
repaint();
}
});
buttonDown.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() != -1) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).moveObject(Direction.Down);
repaint();
}
});
}
private void reloadMaps() {
int index = listBoxMaps.getSelectedIndex();
listBoxMaps.setListData(_mapsCollection.getKeys().toArray(new String[0]));
int size = listBoxMaps.getModel().getSize();
if (size > 0 && (index == -1 || index >= size)) {
listBoxMaps.setSelectedIndex(0);
} else if (index > -1 && index < size) {
listBoxMaps.setSelectedIndex(index);
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (bufferedImage != null) {
pictureBox.paintComponents(bufferedImage.getGraphics());
pictureBox.getGraphics().drawImage(bufferedImage, 0, 0, null);
}
}
}

123
FormTracktor.form Normal file
View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormTracktor">
<grid id="27dc6" binding="ContentPanel" layout-manager="GridLayoutManager" row-count="3" column-count="9" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="661" height="428"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="eb389" class="javax.swing.JButton" binding="buttonCreate">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Создать"/>
</properties>
</component>
<hspacer id="7a016">
<constraints>
<grid row="1" column="2" row-span="1" col-span="3" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<component id="83511" class="javax.swing.JLabel" binding="speedLabel">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Скорость:"/>
</properties>
</component>
<component id="49134" class="javax.swing.JLabel" binding="weightLabel">
<constraints>
<grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Вес:"/>
</properties>
</component>
<component id="15fa4" class="javax.swing.JLabel" binding="colorLabel">
<constraints>
<grid row="2" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Цвет:"/>
</properties>
</component>
<grid id="2fbf8" binding="pictureBox" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="9" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<component id="5a9f4" class="javax.swing.JButton" binding="buttonLeft">
<constraints>
<grid row="2" column="6" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/arrowLeft.png"/>
<text value=""/>
</properties>
</component>
<component id="3c09f" class="javax.swing.JButton" binding="buttonDown">
<constraints>
<grid row="2" column="7" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/arrowDown.png"/>
<text value=""/>
</properties>
</component>
<component id="6d42a" class="javax.swing.JButton" binding="buttonRight">
<constraints>
<grid row="2" column="8" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/arrowRight.png"/>
<text value=""/>
</properties>
</component>
<component id="82038" class="javax.swing.JButton" binding="buttonUp">
<constraints>
<grid row="1" column="7" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/arrowUp.png"/>
<text value=""/>
</properties>
</component>
<component id="a11cc" class="javax.swing.JButton" binding="buttonCreateModif">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Модификация"/>
</properties>
</component>
<component id="a48e3" class="javax.swing.JButton" binding="buttonSelect">
<constraints>
<grid row="2" column="5" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Выбрать"/>
</properties>
</component>
</children>
</grid>
</form>

134
FormTracktor.java Normal file
View File

@ -0,0 +1,134 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.Random;
public class FormTracktor extends JDialog {
private JPanel ContentPanel;
private JButton buttonCreate;
private JLabel speedLabel;
private JLabel weightLabel;
private JLabel colorLabel;
private JButton buttonLeft;
private JButton buttonDown;
private JButton buttonRight;
private JButton buttonUp;
private JPanel pictureBox;
private JButton buttonCreateModif;
private JButton buttonSelect;
private DrawningTracktor _tracktor;
private DrawningTracktor selectedTracktor;
public FormTracktor(){
setTitle("Трактор");
setContentPane(ContentPanel);
setSize(800, 500);
// Обработка нажатия кнопки "Создать"
buttonCreate.addActionListener(e->{
Random rnd = new Random();
Color color = JColorChooser.showDialog(this, "Цвет", new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256)));
if (color == null) {
color = new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256));
}
_tracktor = new DrawningTracktor(rnd.nextInt(100, 300), rnd.nextInt(1000, 2000), color, rnd.nextInt(3,8));
setData();
});
// Обработка нажатия кнопки "Модификация"
buttonCreateModif.addActionListener(e->{
Random rnd = new Random();
Color color = JColorChooser.showDialog(this, "Основной цвет", Color.white);
if (color == null) {
color = new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256));
}
Color dopColor = JColorChooser.showDialog(this, "Дополнительный цвет", Color.white);
if (dopColor == null) {
dopColor = new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256));
}
_tracktor = new DrawningTrackedVehicle(
rnd.nextInt(100, 300),
rnd.nextInt(1000, 2000),
color,
rnd.nextInt(3,8),
dopColor,
rnd.nextBoolean(),
rnd.nextBoolean()
);
setData();
});
buttonUp.addActionListener(e->{
if (_tracktor != null){
_tracktor.MoveTransport(Direction.Up);
repaint();
}
});
buttonLeft.addActionListener(e->{
if (_tracktor != null){
_tracktor.MoveTransport(Direction.Left);
repaint();
}
});
buttonDown.addActionListener(e->{
if (_tracktor != null){
_tracktor.MoveTransport(Direction.Down);
repaint();
}
});
buttonRight.addActionListener(e->{
if (_tracktor != null){
_tracktor.MoveTransport(Direction.Right);
repaint();
}
});
buttonSelect.addActionListener(e->{
selectedTracktor = _tracktor;
dispose();
});
pictureBox.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
if (_tracktor != null){
_tracktor.ChangeBorders(e.getComponent().getWidth(), e.getComponent().getHeight());
repaint();
}
}
});
}
private void setData() {
Random rnd = new Random();
_tracktor.SetPosition(rnd.nextInt(10, 100), rnd.nextInt(10, 100), pictureBox.getWidth(), pictureBox.getHeight());
speedLabel.setText("Скорость: " + _tracktor.getTracktor().getSpeed());
weightLabel.setText("Вес: " + _tracktor.getTracktor().getWeight());
colorLabel.setText("Цвет: " + String.format("%h",_tracktor.getTracktor().getBodyColor()));
repaint();
}
public FormTracktor(DrawningTracktor tracktor) {
this();
_tracktor = tracktor;
repaint();
}
public DrawningTracktor getSelectedTracktor() {
return selectedTracktor;
}
@Override
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D)pictureBox.getGraphics();
if (_tracktor != null){
_tracktor.DrawTransport(g2d);
}
}
}

341
FormTracktorConfig.form Normal file
View File

@ -0,0 +1,341 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormTracktorConfig">
<grid id="27dc6" binding="contentPanel" layout-manager="GridLayoutManager" row-count="3" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="773" height="382"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="fdfc8" binding="toolsPanel" layout-manager="GridLayoutManager" row-count="7" column-count="4" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="3" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none" title="Параметры"/>
<children>
<component id="6962a" class="javax.swing.JLabel" binding="speedLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="27572"/>
<text value="Скорость:"/>
</properties>
</component>
<component id="27572" class="javax.swing.JSpinner" binding="speedSpinner">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="871d8" class="javax.swing.JLabel" binding="weightLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="8e1be"/>
<text value="Вес:"/>
</properties>
</component>
<component id="8e1be" class="javax.swing.JSpinner" binding="weightSpinner">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="39e94" class="javax.swing.JCheckBox" binding="checkBoxBucket">
<constraints>
<grid row="2" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Признак наличия ковша"/>
</properties>
</component>
<component id="9d114" class="javax.swing.JCheckBox" binding="checkBoxSupports">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Признак наличия опорных стоек"/>
</properties>
</component>
<grid id="2044c" binding="colorsPanel" layout-manager="GridLayoutManager" row-count="2" column-count="4" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="2" row-span="5" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none" title="Цвета"/>
<children>
<grid id="784a6" binding="redPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-65536"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="abece" binding="greenPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-16711936"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="b2eb9" binding="bluePanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-16776961"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="482a4" binding="yellowPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="3" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-723926"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="1692f" binding="whitePanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-1"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="aaf16" binding="grayPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-10527145"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="d1a3c" binding="blackPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-16777216"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="e81e" binding="purplePanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="3" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-5173091"/>
</properties>
<border type="none"/>
<children/>
</grid>
</children>
</grid>
<grid id="f974a" binding="rollersPanel" layout-manager="GridLayoutManager" row-count="3" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="6" column="0" row-span="1" col-span="4" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none" title="Катки"/>
<children>
<component id="a92b0" class="javax.swing.JLabel" binding="rollersLabel">
<constraints>
<grid row="0" column="0" row-span="3" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="be4e0"/>
<text value="Количество катков:"/>
</properties>
</component>
<component id="be4e0" class="javax.swing.JSpinner" binding="rollersSpinner">
<constraints>
<grid row="0" column="1" row-span="3" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<maximum-size width="120" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="9f9ab" class="javax.swing.JLabel" binding="baseRollersLabel">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="100" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="Простые"/>
</properties>
</component>
<component id="ea1ae" class="javax.swing.JLabel" binding="crossRollersLabel">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="120" height="38"/>
<maximum-size width="120" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="С крестиками"/>
</properties>
</component>
<component id="15683" class="javax.swing.JLabel" binding="squaredRollersLabel">
<constraints>
<grid row="2" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="120" height="38"/>
<maximum-size width="120" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="С квадратами"/>
</properties>
</component>
</children>
</grid>
<component id="9f748" class="javax.swing.JLabel" binding="baseLabel">
<constraints>
<grid row="5" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="100" height="38"/>
</grid>
</constraints>
<properties>
<background color="-4720538"/>
<font size="16"/>
<text value="Простой"/>
</properties>
</component>
<component id="7569d" class="javax.swing.JLabel" binding="advancedLabel">
<constraints>
<grid row="5" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="120" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="Продвинутый"/>
</properties>
</component>
</children>
</grid>
<grid id="1a87d" binding="workspacePanel" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none" title="Предпоказ"/>
<children>
<component id="18903" class="javax.swing.JLabel" binding="colorLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="100" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="Цвет"/>
</properties>
</component>
<component id="fc724" class="javax.swing.JLabel" binding="additionalColorLabel">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="100" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="Доп. цвет"/>
</properties>
</component>
<grid id="47b0f" binding="pictureBox" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="200" height="200"/>
<maximum-size width="200" height="200"/>
</grid>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
</children>
</grid>
<component id="df1e6" class="javax.swing.JButton" binding="buttonAdd">
<constraints>
<grid row="1" column="1" row-span="2" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить"/>
</properties>
</component>
<component id="22a26" class="javax.swing.JButton" binding="buttonCancel">
<constraints>
<grid row="1" column="2" row-span="2" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Отмена"/>
</properties>
</component>
</children>
</grid>
</form>

153
FormTracktorConfig.java Normal file
View File

@ -0,0 +1,153 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.function.Consumer;
public class FormTracktorConfig extends JFrame {
private final EventListener<DrawningTracktor> eventHandler = new EventListener<>();
private DrawningTracktor _tracktor;
private JPanel contentPanel;
private JPanel toolsPanel;
private JPanel workspacePanel;
private JButton buttonAdd;
private JButton buttonCancel;
private JLabel colorLabel;
private JLabel additionalColorLabel;
private JPanel pictureBox;
private JLabel speedLabel;
private JSpinner speedSpinner;
private JLabel weightLabel;
private JSpinner weightSpinner;
private JCheckBox checkBoxBucket;
private JCheckBox checkBoxSupports;
private JPanel colorsPanel;
private JPanel redPanel;
private JPanel greenPanel;
private JPanel bluePanel;
private JPanel yellowPanel;
private JPanel whitePanel;
private JPanel grayPanel;
private JPanel blackPanel;
private JPanel purplePanel;
private JPanel rollersPanel;
private JLabel rollersLabel;
private JSpinner rollersSpinner;
private JLabel baseLabel;
private JLabel advancedLabel;
private JLabel baseRollersLabel;
private JLabel crossRollersLabel;
private JLabel squaredRollersLabel;
public FormTracktorConfig() {
this.setTitle("Создание объекта");
this.setSize(840, 480);
this.setContentPane(contentPanel);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// Создание границ
colorLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
additionalColorLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
pictureBox.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
baseLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
advancedLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
baseRollersLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
crossRollersLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squaredRollersLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
// Задание ограничений
rollersSpinner.setModel(new SpinnerNumberModel(4, 4, 6, 1));
speedSpinner.setModel(new SpinnerNumberModel(100, 100, 1000, 1));
weightSpinner.setModel(new SpinnerNumberModel(100, 100, 1000, 1));
// Создание обработчиков
var dragAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mouseReleased(e);
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
dispatchDrop((JComponent) e.getSource());
}
};
// Задание обработчиков
redPanel.addMouseListener(dragAdapter);
greenPanel.addMouseListener(dragAdapter);
bluePanel.addMouseListener(dragAdapter);
yellowPanel.addMouseListener(dragAdapter);
whitePanel.addMouseListener(dragAdapter);
grayPanel.addMouseListener(dragAdapter);
blackPanel.addMouseListener(dragAdapter);
purplePanel.addMouseListener(dragAdapter);
baseLabel.addMouseListener(dragAdapter);
advancedLabel.addMouseListener(dragAdapter);
baseRollersLabel.addMouseListener(dragAdapter);
crossRollersLabel.addMouseListener(dragAdapter);
squaredRollersLabel.addMouseListener(dragAdapter);
buttonAdd.addActionListener(e -> {
eventHandler.emit(_tracktor);
dispose();
});
buttonCancel.addActionListener(e -> dispose());
}
public void addListener(Consumer<DrawningTracktor> listener) {
eventHandler.addListener(listener);
}
public void dispatchDrop(JComponent droppedComponent) {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
if (droppedComponent == null) {
return;
}
if (droppedComponent instanceof JPanel panel) {
if (colorLabel.getMousePosition() != null) {
_tracktor.setColor(panel.getBackground());
_tracktor.getRollers().setColor(panel.getBackground());
}
if (additionalColorLabel.getMousePosition() != null && _tracktor instanceof DrawningTrackedVehicle _trackedVehicle) {
_trackedVehicle.setDopColor(panel.getBackground());
}
}
if (droppedComponent instanceof JLabel label && pictureBox.getMousePosition() != null) {
int speed = (Integer) speedSpinner.getValue();
int weight = (Integer) weightSpinner.getValue();
int rollersCount = (Integer) rollersSpinner.getValue();
boolean bucket = checkBoxBucket.isSelected();
boolean supports = checkBoxSupports.isSelected();
if (label == baseLabel) {
_tracktor = new DrawningTracktor(speed, weight, Color.WHITE, rollersCount);
} else if (label == advancedLabel) {
_tracktor = new DrawningTrackedVehicle(speed, weight, Color.WHITE, rollersCount, Color.WHITE, bucket, supports);
} else if (_tracktor != null && label == baseRollersLabel) {
_tracktor.setRollers(new DrawningRollers(rollersCount, _tracktor.getTracktor().getBodyColor()));
} else if (_tracktor != null && label == crossRollersLabel) {
_tracktor.setRollers(new DrawningCrossRollers(rollersCount, _tracktor.getTracktor().getBodyColor()));
} else if (_tracktor != null && label == squaredRollersLabel) {
_tracktor.setRollers(new DrawningSquaredRollers(rollersCount, _tracktor.getTracktor().getBodyColor()));
}
}
repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (_tracktor != null) {
g = pictureBox.getGraphics();
_tracktor.SetPosition(60, 75, pictureBox.getWidth(), pictureBox.getHeight());
_tracktor.DrawTransport((Graphics2D) g);
}
}
}

10
IDrawningObject.java Normal file
View File

@ -0,0 +1,10 @@
import java.awt.*;
public interface IDrawningObject {
float getStep();
void setObject(int x, int y, int width, int height);
void moveObject(Direction direction);
void drawningObject(Graphics2D g);
float[] getCurrentPosition();
String getInfo();
}

8
IDrawningRollers.java Normal file
View File

@ -0,0 +1,8 @@
import java.awt.*;
public interface IDrawningRollers {
void setRollersCount(int count);
void setColor(Color color);
void DrawRollers(Graphics2D g, float _startPosX, float _startPosY);
int getRollersCount();
}

View File

@ -0,0 +1,184 @@
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
public class MapWithSetTracktorGeneric <T extends IDrawningObject, U extends AbstractMap>{
public final int _pictureWidth;
public final int _pictureHeight;
public final int _placeSizeWidth = 150;
public final int _placeSizeHeight = 100;
public final SetTracktorGeneric<T> _setTracktor;
private final U _map;
public MapWithSetTracktorGeneric(int picWidth, int picHeight, U map) {
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setTracktor = new SetTracktorGeneric<>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
public U getMap() {
return _map;
}
public int addTracktor(T tracktor) {
return _setTracktor.insert(tracktor);
}
public T removeTracktorAt(int position) {
return _setTracktor.remove(position);
}
public Image showSet() {
BufferedImage img = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D gr = (Graphics2D)img.getGraphics();
drawBackground(gr);
drawTracktor(gr);
return img;
}
public Image showOnMap() {
shaking();
for (var tracktor : _setTracktor.getTracktors())
{
if (tracktor != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, tracktor);
}
}
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_RGB);
}
public Image moveObject(Direction direction) {
if (_map != null) {
return _map.MoveObject(direction);
}
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
}
private void shaking() {
int j = _setTracktor.getCount() - 1;
for (int i = 0; i < _setTracktor.getCount(); i++)
{
if (_setTracktor.get(i) == null)
{
for (; j > i; j--)
{
var tracktor = _setTracktor.get(j);
if (tracktor != null)
{
_setTracktor.insert(tracktor , i);
_setTracktor.remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
private void drawBackground(Graphics2D g) {
Color pen = Color.WHITE;
Stroke penStroke = new BasicStroke(3);
Color brush = Color.LIGHT_GRAY;
Color disabledPersonBadgeBrush = Color.WHITE;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
// Асфальт
g.setColor(brush);
g.fillRect( i * _placeSizeWidth, j * _placeSizeHeight, _placeSizeWidth, _placeSizeHeight);
// Разметка
g.setColor(pen);
g.setStroke(penStroke);
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, (i * _placeSizeWidth) + (_placeSizeWidth / 2), j * _placeSizeHeight);
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth, (j * _placeSizeHeight) + _placeSizeHeight);
g.drawLine(i * _placeSizeWidth, (j + 1) * _placeSizeHeight, (i * _placeSizeWidth) + (_placeSizeWidth / 2), (j + 1) * _placeSizeHeight);
if (j%2==0)
{
// Знак паркинга
g.setColor(pen);
g.setStroke(penStroke);
g.drawLine(i * _placeSizeWidth + 20, j * _placeSizeHeight + 60, i * _placeSizeWidth + 60, j * _placeSizeHeight + 60);
g.drawLine(i * _placeSizeWidth + 20, j * _placeSizeHeight + 60, i * _placeSizeWidth + 20, j * _placeSizeHeight + 40);
g.drawLine(i * _placeSizeWidth + 20, j * _placeSizeHeight + 40, i * _placeSizeWidth + 40, j * _placeSizeHeight + 40);
g.drawLine(i * _placeSizeWidth + 40, j * _placeSizeHeight + 40, i * _placeSizeWidth + 40, j * _placeSizeHeight + 60);
}
else
{
// Инвалид
// Колесо
g.setColor(pen);
g.setStroke(penStroke);
g.drawOval(i * _placeSizeWidth + 40, j * _placeSizeHeight + 50, 30, 30);
// Голова
g.setColor(disabledPersonBadgeBrush);
g.setStroke(new BasicStroke(1));
g.fillOval(i * _placeSizeWidth + 20, j * _placeSizeHeight + 60, 10, 10);
// Туловище
g.setColor(pen);
g.setStroke(penStroke);
g.drawLine(i * _placeSizeWidth + 25, j * _placeSizeHeight + 65, i * _placeSizeWidth + 55, j * _placeSizeHeight + 60);
// Рука
g.drawLine(i * _placeSizeWidth + 32, j * _placeSizeHeight + 65, i * _placeSizeWidth + 38, j * _placeSizeHeight + 55);
// Нога
g.drawLine(i * _placeSizeWidth + 55, j * _placeSizeHeight + 60, i * _placeSizeWidth + 60, j * _placeSizeHeight + 40);
// Голеностоп
g.drawLine(i * _placeSizeWidth + 60, j * _placeSizeHeight + 40, i * _placeSizeWidth + 65, j * _placeSizeHeight + 38);
}
}
}
g.setStroke(new BasicStroke(1));
}
private void drawTracktor(Graphics2D g) {
int width = _pictureWidth / _placeSizeWidth;
int curWidth = width-1;
int curHeight = 0;
for(var tracktor : _setTracktor.getTracktors()){
// установка позиции
// Влево - вниз
if (tracktor!=null){
tracktor.setObject(
curWidth * _placeSizeWidth,
curHeight * _placeSizeHeight,
_pictureWidth,
_pictureHeight);
tracktor.drawningObject(g);
if (curWidth > 0)
{
curWidth--;
}
else
{
curWidth = width-1;
curHeight++;
}
}
}
}
public String getData(char separatorType, char separatorData) {
StringBuilder data = new StringBuilder(String.format("%s%c", _map.getClass().getSimpleName(), separatorType));
for (var tracktor : _setTracktor.getTracktors()) {
data.append(String.format("%s%c", tracktor.getInfo(), separatorData));
}
return data.toString();
}
@SuppressWarnings("unchecked")
public void loadData(String[] records) {
for (int i = records.length - 1; i >= 0; i--) {
_setTracktor.insert((T) DrawningObjectExcavator.create(records[i]));
}
}
}

159
MapsCollection.java Normal file
View File

@ -0,0 +1,159 @@
import java.io.*;
import java.util.HashMap;
import java.util.Set;
public class MapsCollection {
private final HashMap<String, MapWithSetTracktorGeneric<IDrawningObject, AbstractMap>> _mapsStorage;
private final int _pictureWidth;
private final int _pictureHeight;
private final char separatorDict = '|';
private final char separatorData = ';';
public Set<String> getKeys() {
return _mapsStorage.keySet();
}
public MapsCollection(int pictureWidth, int pictureHeight) {
_mapsStorage = new HashMap<>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void addMap(String name, AbstractMap map) {
if (!_mapsStorage.containsKey(name)) {
_mapsStorage.put(name, new MapWithSetTracktorGeneric<>(_pictureWidth, _pictureHeight, map));
}
}
public void deleteMap(String name) {
_mapsStorage.remove(name);
}
public MapWithSetTracktorGeneric<IDrawningObject, AbstractMap> getMap(String name) {
return _mapsStorage.getOrDefault(name, null);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public boolean saveData(String filename) throws IOException {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
file.createNewFile();
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("MapsCollection");
for (var storage : _mapsStorage.entrySet()) {
writer.println(String.format("%s%c%s", storage.getKey(), separatorDict, storage.getValue().getData(separatorDict, separatorData)));
}
}
return true;
}
public boolean loadData(String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
return false;
}
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("MapsCollection")) {
return false;
}
_mapsStorage.clear();
while ((currentLine = reader.readLine()) != null) {
var elements = currentLine.split(String.format("\\%c", separatorDict));
AbstractMap map = switch (elements[1]) {
case "SimpleMap" -> new SimpleMap();
case "DumpMap" -> new DumpMap();
default -> null;
};
_mapsStorage.put(elements[0], new MapWithSetTracktorGeneric<>(_pictureWidth, _pictureHeight, map));
_mapsStorage.get(elements[0]).loadData(elements[2].split(separatorData + "\n?"));
}
}
return true;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public boolean saveMap(String mapName, String filename) throws IOException {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
file.createNewFile();
MapWithSetTracktorGeneric<IDrawningObject, AbstractMap> map = _mapsStorage.getOrDefault(mapName, null);
if (map == null) {
return false;
}
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("Map");
writer.println(mapName);
writer.println(map.getMap().getClass().getSimpleName());
for (var tracktor : map._setTracktor.getTracktors()) {
writer.println(tracktor.getInfo());
}
}
return true;
}
public boolean loadMap(String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
return false;
}
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("Map")) {
return false;
}
String mapName = reader.readLine();
MapWithSetTracktorGeneric<IDrawningObject, AbstractMap> map;
if (_mapsStorage.containsKey(mapName)) {
map = _mapsStorage.get(mapName);
if (!map.getMap().getClass().getSimpleName().equals(reader.readLine())) {
return false;
}
map._setTracktor.clear();
} else {
map = switch (reader.readLine()) {
case "SimpleMap" -> new MapWithSetTracktorGeneric<>(_pictureWidth, _pictureHeight, new SimpleMap());
case "DumpMap" -> new MapWithSetTracktorGeneric<>(_pictureWidth, _pictureHeight, new DumpMap());
default -> null;
};
_mapsStorage.put(mapName, map);
}
while ((currentLine = reader.readLine()) != null) {
map._setTracktor.insert(DrawningObjectExcavator.create(currentLine));
}
}
return true;
}
}

8
Program.java Normal file
View File

@ -0,0 +1,8 @@
import javax.swing.*;
public class Program {
public static void main(String[] args){
FormMapWithSetTracktor form = new FormMapWithSetTracktor();
form.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}

BIN
Resources/arrowDown.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
Resources/arrowLeft.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
Resources/arrowRight.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
Resources/arrowUp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

18
RollersCount.java Normal file
View File

@ -0,0 +1,18 @@
public enum RollersCount {
Four,
Five,
Six;
public int getValue() {
return switch (this) {
case Four -> 4;
case Five -> 5;
case Six -> 6;
};
}
@Override
public String toString() {
return Integer.toString(getValue());
}
}

17
RollersType.java Normal file
View File

@ -0,0 +1,17 @@
import java.awt.*;
import java.util.Random;
public enum RollersType {
Standard,
Squared,
Cross;
public static IDrawningRollers random(int rollersCount, Color bodyColor) {
return switch (new Random().nextInt(RollersType.values().length)) {
case 0 -> new DrawningRollers(rollersCount, bodyColor);
case 1 -> new DrawningSquaredRollers(rollersCount, bodyColor);
case 2 -> new DrawningCrossRollers(rollersCount, bodyColor);
default -> null;
};
}
}

56
SetTracktorGeneric.java Normal file
View File

@ -0,0 +1,56 @@
import java.util.ArrayList;
import java.util.Objects;
public class SetTracktorGeneric<T> {
private final ArrayList<T> _places;
private final int _maxCount;
public int getCount() {
return _places.size();
}
public SetTracktorGeneric(int count) {
_maxCount = count;
_places = new ArrayList<>(count);
}
public int insert(T tracktor) {
return insert(tracktor, 0);
}
public int insert(T tracktor, int position) {
if (position < 0 || position > getCount() || getCount() == _maxCount) {
return -1;
}
_places.add(position, tracktor);
return position;
}
@SuppressWarnings("unchecked")
public T remove(int position) {
if (position < 0 || position >= getCount())
{
return null;
}
T result = _places.get(position);
_places.remove(position);
return result;
}
@SuppressWarnings("unchecked")
public T get(int position) {
if (position < 0 || position >= getCount()) {
return null;
}
return _places.get(position);
}
public Iterable<T> getTracktors()
{
return _places;
}
public void clear() {
_places.clear();
}
}

40
SimpleMap.java Normal file
View File

@ -0,0 +1,40 @@
import java.awt.*;
import java.util.Arrays;
public class SimpleMap extends AbstractMap{
private final Color barrierColor = Color.BLACK;
private final Color roadColor = Color.GRAY;
@Override
protected void DrawBarrierPart(Graphics2D g, int i, int j) {
g.setColor(barrierColor);
g.fillRect(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y);
}
@Override
protected void DrawRoadPart(Graphics2D g, int i, int j) {
g.setColor(roadColor);
g.fillRect(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y);
}
@Override
protected void GenerateMap() {
_map = new int[100][100];
_size_x = (float)_width / _map[0].length;
_size_y = (float)_height / _map.length;
int counter = 0;
for (int[] row : _map) {
Arrays.fill(row, _freeRoad);
}
while (counter < 50)
{
int x = _random.nextInt(0, (int)_map[0].length);
int y = _random.nextInt(0, (int)_map.length);
if (_map[y][x] == _freeRoad)
{
_map[y][x] = _barrier;
counter++;
}
}
}
}

69
TracktorSerde.java Normal file
View File

@ -0,0 +1,69 @@
import java.awt.*;
public class TracktorSerde { // Tracktor Serialization/Deserialization
private static final char _separatorForObject = ':';
public static DrawningTracktor deserialize(String info) {
String[] strings = info.split(Character.toString(_separatorForObject));
int speed = Integer.parseInt(strings[0]);
float weight = Float.parseFloat(strings[1]);
Color bodyColor = new Color(Integer.parseInt(strings[2]));
IDrawningRollers rollers = switch (strings[3]) {
case "DrawningRollers" -> new DrawningRollers(Integer.parseInt(strings[4]), bodyColor);
case "DrawningCrossRollers" -> new DrawningCrossRollers(Integer.parseInt(strings[4]), bodyColor);
case "DrawningSquaredRollers" -> new DrawningSquaredRollers(Integer.parseInt(strings[4]), bodyColor);
default -> null;
};
if (strings.length == 5) {
EntityTracktor entity = new EntityTracktor(speed, weight, bodyColor);
return new DrawningTracktor(entity, rollers);
}
if (strings.length == 8) {
Color dopColor = new Color(Integer.parseInt(strings[5]));
boolean bucket = Boolean.parseBoolean(strings[6]);
boolean supports = Boolean.parseBoolean(strings[7]);
EntityTrackedVehicle entity = new EntityTrackedVehicle(speed, weight, bodyColor, dopColor, bucket, supports);
return new DrawningTrackedVehicle(entity, rollers);
}
return null;
}
public static String serialize(DrawningTracktor drawingTracktor) {
EntityTracktor tracktor = drawingTracktor.getTracktor();
String result = String.format(
"%d%c%s%c%d%c%s%c%d",
tracktor.getSpeed(),
_separatorForObject,
tracktor.getWeight(),
_separatorForObject,
tracktor.getBodyColor().getRGB(),
_separatorForObject,
drawingTracktor.getRollers().getClass().getSimpleName(),
_separatorForObject,
drawingTracktor.getRollers().getRollersCount()
);
if (!(tracktor instanceof EntityTrackedVehicle trackedVehicle)) {
return result;
}
return String.format(
"%s%c%d%c%b%c%b",
result,
_separatorForObject,
trackedVehicle.getDopColor().getRGB(),
_separatorForObject,
trackedVehicle.getBucket(),
_separatorForObject,
trackedVehicle.getSupports()
);
}
}