Compare commits

...

6 Commits
main ... Lab5

34 changed files with 1905 additions and 7 deletions

1
.idea/.name Normal file
View File

@ -0,0 +1 @@
DrawingRoadTrain.java

View File

@ -3,6 +3,7 @@
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/Resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_20" default="true" project-jdk-name="corretto-1.8" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="corretto-1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

BIN
Resources/ArrowDown.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
Resources/ArrowLeft.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
Resources/ArrowRight.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
Resources/ArrowUp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@ -1,5 +0,0 @@
public class Main {
public static void main(String[] args){
}
}

View File

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

View File

@ -0,0 +1,42 @@
package RoadTrain.DrawingObjects;
import java.awt.*;
import RoadTrain.Entities.*;
import RoadTrain.Extra.IDrawingWheels;
public class DrawingRoadTrain extends DrawingTruck{
public DrawingRoadTrain(int speed, double weight, Color bodyColor, Color
additionalColor, boolean waterContainer, boolean sweepingBrush, int width, int height, int wheelNumber)
{
super(speed, weight, bodyColor, width, height, wheelNumber);
if (entityTruck != null)
{
entityTruck = new EntityRoadTrain(speed, weight, bodyColor, wheelNumber,
additionalColor, waterContainer, sweepingBrush);
}
}
public DrawingRoadTrain(EntityRoadTrain truck, IDrawingWheels _wheelDrawing, int width, int height ){
super(truck, _wheelDrawing, width, height);
if (height < _truckHeight || width < _truckWidth)
return;
}
@Override
public void DrawTransport(Graphics g) {
if (!(entityTruck instanceof EntityRoadTrain RoadTrain)) {
return;
}
super.DrawTransport(g);
if (RoadTrain.GetWaterContainer()){
g.setColor(RoadTrain.GetAdditionalColor());
g.drawOval(_startPosX + 30, _startPosY, 10, 20);
g.fillOval(_startPosX + 30, _startPosY, 10, 20);
}
if (RoadTrain.GetSweepingBrush())
{
g.drawLine(_startPosX + 30, _startPosY + 10, _startPosX + 20, _startPosY + 10);
g.drawLine(_startPosX + 20, _startPosY + 10, _startPosX + 10, _startPosY + 30);
g.drawLine(_startPosX + 17, _startPosY + 30, _startPosX + 3, _startPosY + 30);
}
}
}

View File

@ -0,0 +1,152 @@
package RoadTrain.DrawingObjects;
import RoadTrain.DirectionType;
import RoadTrain.Entities.*;
import RoadTrain.Extra.*;
import RoadTrain.MovementStraregy.*;
import java.util.Random;
import java.awt.*;
public class DrawingTruck {
public EntityTruck entityTruck;
public IDrawingWheels drawingWheels;
public int _pictureWidth;
public int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
public IMoveableObject GetMoveableObject() { return new DrawingObjectTruck(this);}
public int GetPosX() {
return _startPosX;
}
public int GetPosY() {
return _startPosY;
}
public int GetWidth() {
return _truckWidth;
}
public int GetHeight() {
return _truckHeight;
}
protected int _truckWidth = 80;
protected int _truckHeight = 70;
public DrawingTruck(EntityTruck truck, IDrawingWheels _wheelDrawing, int width, int height){
if (height < _truckHeight || width < _truckWidth)
return;
_pictureWidth = width;
_pictureHeight = height;
entityTruck = truck;
drawingWheels = _wheelDrawing;
drawingWheels.SetWheelNumber(entityTruck.Numwheel);
}
public DrawingTruck(int speed, double weight, Color mainColor, int width, int height, int wheelNumber) {
if (width < _truckWidth || height < _truckHeight) {
return;
}
_pictureWidth = width;
_pictureHeight = height;
entityTruck = new EntityTruck(speed, weight, mainColor, wheelNumber);
Random rand = new Random();
drawingWheels = switch (rand.nextInt(0, 3)) {
case 0 -> new DrawingWheels();
case 1 -> new DrawingOneLineWheels();
case 2 -> new DrawingTwoLineWheels();
default -> new DrawingWheels();
};
drawingWheels.SetWheelNumber(wheelNumber);
}
protected DrawingTruck(int speed, double weight, Color mainColor,
int width, int height, int truckWidth, int truckHeight, int wheelNumber) {
if (width < truckWidth || height < truckHeight) {
return;
}
_pictureWidth = width;
_pictureHeight = height;
_truckWidth = truckWidth;
_truckHeight = truckHeight;
entityTruck = new EntityTruck(speed, weight, mainColor, wheelNumber);
Random rand = new Random();
drawingWheels = switch (rand.nextInt(0, 3)) {
case 0 -> new DrawingWheels();
case 1 -> new DrawingOneLineWheels();
case 2 -> new DrawingTwoLineWheels();
default -> new DrawingWheels();
};
drawingWheels.SetWheelNumber(wheelNumber);
}
public void SetPosition(int x, int y) {
if (x < 0)
{
x = 0;
}
else if (x + _truckWidth > _pictureWidth)
{
x = _pictureWidth - _truckWidth;
}
if (y < 0)
{
y = 0;
}
else if (y + _truckHeight > _pictureHeight)
{
y = _pictureHeight - _truckHeight;
}
_startPosX = x;
_startPosY = y;
}
public boolean CanMove(DirectionType direction) {
if (entityTruck == null) {
return false;
}
return switch (direction) {
case Left -> _startPosX - entityTruck.GetStep() > 0;
case Up -> _startPosY - entityTruck.GetStep() > 0;
case Right -> _startPosX + _truckWidth + entityTruck.GetStep() < _pictureWidth;
case Down -> _startPosY + _truckHeight + entityTruck.GetStep() < _pictureHeight;
};
}
public void MoveTransport(DirectionType direction) {
if (!CanMove(direction) || entityTruck == null) {
return;
}
switch (direction) {
case Left:
_startPosX -= (int) entityTruck.GetStep();
break;
case Up:
_startPosY -= (int) entityTruck.GetStep();
break;
case Right:
_startPosX += (int) entityTruck.GetStep();
break;
case Down:
_startPosY += (int) entityTruck.GetStep();
break;
}
}
public void DrawTransport(Graphics g) {
if (entityTruck == null) {
return;
}
drawingWheels.drawWheels(g,entityTruck.GetBodyColor(), _startPosX, _startPosY);
g.setColor(entityTruck.GetBodyColor());
g.drawLine(_startPosX + 20, _startPosY + 20, _startPosX + 70, _startPosY + 20);
g.drawRect( _startPosX + 60, _startPosY, 10, 20);
g.fillRect(_startPosX + 60, _startPosY, 10, 20);
}
}

View File

@ -0,0 +1,23 @@
package RoadTrain.Entities;
import java.awt.*;
public class EntityRoadTrain extends EntityTruck {
private Color AdditionalColor;
public void SetAdditionalColor(Color color){AdditionalColor = color;}
public Color GetAdditionalColor() { return AdditionalColor; }
private boolean WaterContainer;
public boolean GetWaterContainer(){
return WaterContainer;
}
private boolean SweepingBrush;
public boolean GetSweepingBrush(){
return SweepingBrush;
}
public EntityRoadTrain(int speed, double weight, Color bodyColor, int numwheel, Color
additionalColor, boolean waterContainer, boolean sweepingBrush) {
super(speed, weight, bodyColor, numwheel);
AdditionalColor = additionalColor;
WaterContainer = waterContainer;
SweepingBrush = sweepingBrush;
}
}

View File

@ -0,0 +1,33 @@
package RoadTrain.Entities;
import java.awt.*;
public class EntityTruck {
private int Speed;
public int GetSpeed() {
return Speed;
}
private double Weight;
public double GetWeight() {
return Weight;
}
private Color BodyColor;
public void SetBodyColor(Color color){BodyColor=color;}
public Color GetBodyColor() {
return BodyColor;
}
public int Numwheel;
public double GetStep() {
return (double) Speed * 100 / Weight;
}
public EntityTruck(int speed, double weight, Color bodyColor, int numwheel) {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
Numwheel = numwheel;
}
}

View File

@ -0,0 +1,54 @@
package RoadTrain.Extra;
import java.awt.*;
public class DrawingOneLineWheels implements IDrawingWheels{
private WheelNumber wheelNumber;
@Override
public void SetWheelNumber(int num) {
switch (num){
case 1:
wheelNumber = WheelNumber.One;
break;
case 2:
wheelNumber = WheelNumber.Two;
break;
default:
wheelNumber = WheelNumber.Three;
}
}
@Override
public WheelNumber GetWheelNumber() {
return wheelNumber;
}
@Override
public void drawWheels(Graphics g, Color color, int startPosX, int startPosY) {
drawOneWheel(g, color, startPosX, startPosY);
if (wheelNumber == WheelNumber.Two) {
drawTwoWheels(g, color, startPosX, startPosY);
}
if (wheelNumber == WheelNumber.Three){
drawThreeWheels(g, color, startPosX, startPosY);
}
}
private void drawOneWheel(Graphics g, Color color, int startPosX, int startPosY) {
drawWheel(g,color,startPosX+20,startPosY+20);
}
private void drawTwoWheels(Graphics g, Color color, int startPosX, int startPosY) {
drawOneWheel(g, color, startPosX, startPosY);
drawWheel(g,color,startPosX+30,startPosY+20);
}
private void drawThreeWheels(Graphics g, Color color, int startPosX, int startPosY) {
drawTwoWheels(g, color, startPosX, startPosY);
drawWheel(g,color,startPosX+60,startPosY+20);
}
private void drawWheel(Graphics g, Color color, int X, int Y){
g.setColor(color);
g.drawOval(X,Y,10,10);
g.fillOval(X,Y,10,10);
g.setColor(Color.black);
g.drawLine(X,Y+5,X+10,Y+5);
}
}

View File

@ -0,0 +1,55 @@
package RoadTrain.Extra;
import java.awt.*;
public class DrawingTwoLineWheels implements IDrawingWheels{
private WheelNumber wheelNumber;
@Override
public void SetWheelNumber(int num) {
switch (num){
case 1:
wheelNumber = WheelNumber.One;
break;
case 2:
wheelNumber = WheelNumber.Two;
break;
default:
wheelNumber = WheelNumber.Three;
}
}
@Override
public WheelNumber GetWheelNumber() {
return wheelNumber;
}
@Override
public void drawWheels(Graphics g, Color color, int startPosX, int startPosY) {
drawOneWheel(g, color, startPosX, startPosY);
if (wheelNumber == WheelNumber.Two) {
drawTwoWheels(g, color, startPosX, startPosY);
}
if (wheelNumber == WheelNumber.Three) {
drawThreeWheels(g, color, startPosX, startPosY);
}
}
private void drawOneWheel(Graphics g, Color color, int startPosX, int startPosY) {
drawWheel(g,color,startPosX+20,startPosY+20);
}
private void drawTwoWheels(Graphics g, Color color, int startPosX, int startPosY) {
drawOneWheel(g, color, startPosX, startPosY);
drawWheel(g,color,startPosX+30,startPosY+20);
}
private void drawThreeWheels(Graphics g, Color color, int startPosX, int startPosY) {
drawTwoWheels(g, color, startPosX, startPosY);
drawWheel(g,color,startPosX+60,startPosY+20);
}
private void drawWheel(Graphics g, Color color, int X, int Y){
g.setColor(color);
g.drawOval(X,Y,10,10);
g.fillOval(X,Y,10,10);
g.setColor(Color.black);
g.drawLine(X,Y+5,X+10,Y+5);
g.drawLine(X+5, Y,X+5,Y+10);
}
}

View File

@ -0,0 +1,65 @@
package RoadTrain.Extra;
import java.awt.*;
public class DrawingWheels implements IDrawingWheels{
private WheelNumber wheelNumber;
@Override
public void SetWheelNumber(int num){
switch (num){
case 1:
wheelNumber = WheelNumber.One;
break;
case 2:
wheelNumber = WheelNumber.Two;
break;
default:
wheelNumber = WheelNumber.Three;
}
};
@Override
public WheelNumber GetWheelNumber() {
return wheelNumber;
}
@Override
public void drawWheels(Graphics g, Color color, int startPosX, int startPosY) {
drawOneWheel(g, color, startPosX, startPosY);
if (wheelNumber == WheelNumber.Two) {
drawTwoWheels(g, color, startPosX, startPosY);
}
if (wheelNumber == WheelNumber.Three){
drawThreeWheels(g, color, startPosX, startPosY);
}
}
private void drawOneWheel(Graphics g, Color color, int startPosX, int startPosY) {
g.setColor(color);
g.drawOval(startPosX + 20, startPosY + 20, 10, 10);
g.fillOval(startPosX + 20, startPosY + 20, 10, 10);
}
private void drawTwoWheels(Graphics g, Color color, int startPosX, int startPosY) {
g.setColor(color);
g.drawOval(startPosX + 20, startPosY + 20, 10, 10);
g.drawOval( startPosX + 30, startPosY + 20, 10, 10);
g.fillOval(startPosX + 20, startPosY + 20, 10, 10);
g.fillOval(startPosX + 30, startPosY + 20, 10, 10);
}
private void drawThreeWheels(Graphics g, Color color, int startPosX, int startPosY) {
g.setColor(color);
g.drawOval(startPosX + 20, startPosY + 20, 10, 10);
g.drawOval( startPosX + 30, startPosY + 20, 10, 10);
g.drawOval(startPosX + 60, startPosY + 20, 10, 10);
g.fillOval(startPosX + 20, startPosY + 20, 10, 10);
g.fillOval(startPosX + 30, startPosY + 20, 10, 10);
g.fillOval(startPosX + 60, startPosY + 20, 10, 10);
}
}

View File

@ -0,0 +1,71 @@
package RoadTrain.Extra;
import java.util.ArrayList;
import java.util.Random;
import RoadTrain.Entities.*;
import RoadTrain.DrawingObjects.*;
public class GenericDopClass<T extends EntityTruck, U extends IDrawingWheels> {
private ArrayList<T> Trucks;
private ArrayList<U> Wheels;
private int maxCountTrucks;
private int countTrucks;
private int maxCountWheels;
private int countWheels;
private Random random;
private int _pictureWidth;
private int _pictureHeight;
public GenericDopClass(int _maxCountTrucks, int _maxCountWheels, int pictureWidth, int pictureHeight){
maxCountTrucks = _maxCountTrucks;
maxCountWheels = _maxCountWheels;
Trucks = new ArrayList<T>(maxCountTrucks);
Wheels = new ArrayList<U>(maxCountWheels);
countTrucks = 0;
countWheels = 0;
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
random = new Random();
}
public boolean add(T train){
if (train == null)
return false;
if (countTrucks > maxCountTrucks)
return false;
Trucks.add(countTrucks++, train);
return true;
}
public boolean add(U wheel){
if (wheel == null)
return false;
if (countWheels > maxCountWheels)
return false;
Wheels.add(countWheels++, wheel);
return true;
}
public DrawingTruck getDrawingObject(){
if (countTrucks == 0 || countWheels == 0)
return null;
if(Trucks.isEmpty()) {
return null;
}
T truck = Trucks.get(random.nextInt(Trucks.size()));
U wheel = null;
if(!Wheels.isEmpty()){
wheel = Wheels.get(random.nextInt(Wheels.size()));
}
DrawingTruck drawingTruck;
if (truck instanceof EntityRoadTrain){
drawingTruck = new DrawingRoadTrain((EntityRoadTrain)truck, wheel, _pictureWidth, _pictureHeight);
}
else{
drawingTruck = new DrawingTruck(truck, wheel, _pictureWidth, _pictureHeight);
}
return drawingTruck;
}
}

View File

@ -0,0 +1,9 @@
package RoadTrain.Extra;
import java.awt.*;
public interface IDrawingWheels {
void SetWheelNumber(int number);
WheelNumber GetWheelNumber();
void drawWheels(Graphics g, Color color, int startPosX, int startPosY);
}

View File

@ -0,0 +1,6 @@
package RoadTrain.Extra;
public enum WheelNumber {
One,
Two,
Three
}

View File

@ -0,0 +1,65 @@
package RoadTrain;
import RoadTrain.DrawingObjects.*;
import RoadTrain.Entities.*;
import RoadTrain.Extra.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class FormGenericDopClass extends JFrame {
static int pictureBoxWidth = 980;
static int pictureBoxHeight = 560;
public DrawingTruck _drawingTruck;
private class Canvas extends JComponent{
public Canvas(){
}
public void paintComponent (Graphics g){
if (_drawingTruck == null){
return;
}
super.paintComponents (g) ;
Graphics2D g2d = (Graphics2D)g;
_drawingTruck.SetPosition(50, 50);
_drawingTruck.DrawTransport(g2d);
super.repaint();
}
}
GenericDopClass<EntityTruck, IDrawingWheels> genericDopClass;
public FormGenericDopClass(){
_drawingTruck = null;
Canvas canv = new Canvas();
setSize (1000, 600);
setLayout(null);
canv.setBounds(0,0,pictureBoxWidth, pictureBoxHeight);
genericDopClass = new GenericDopClass<>(100, 100, pictureBoxWidth, pictureBoxHeight);
genericDopClass.add(new EntityTruck(100, 100, Color.BLUE, 1));
genericDopClass.add(new EntityTruck(100, 100, Color.RED, 2));
genericDopClass.add(new EntityTruck(100, 100, Color.GRAY, 1));
genericDopClass.add(new EntityRoadTrain(100, 100, Color.BLUE, 3, Color.ORANGE, true, true));
genericDopClass.add(new DrawingOneLineWheels());
genericDopClass.add(new DrawingTwoLineWheels());
JButton createButton = new JButton("Создать");
createButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
_drawingTruck = genericDopClass.getDrawingObject();
canv.repaint();
}
}
);
createButton.setBounds(pictureBoxWidth/2, pictureBoxHeight-20, 120, 20);
add(canv);
add(createButton);
setVisible(true);
}
}

View File

@ -0,0 +1,245 @@
package RoadTrain;
import RoadTrain.MovementStraregy.*;
import RoadTrain.Generics.*;
import RoadTrain.DrawingObjects.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class FormTruckCollection {
private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
if (jListStorage.getSelectedIndex() == -1)
{
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null)
{
return;
}
if (obj.ShowTrucks() != null) {
g.drawImage(obj.ShowTrucks(), 0, 0, this);
}
super.repaint();
}
}
Canvas canv;
static int pictureBoxWidth = 700;
static int pictureBoxHeight = 480;
private TrucksGenericStorage _storage;
public void Draw(){
canv.repaint();
}
private Stack<DrawingTruck> StackRemoved;
private JList<String> jListStorage;
private DefaultListModel<String> listModel;
private void ReloadObjects()
{
int index = jListStorage.getSelectedIndex();
listModel.clear();
for (String key : _storage.Keys()) {
listModel.addElement(key);
}
if (listModel.size() > 0 && (index == -1 || index >= listModel.size()))
{
jListStorage.setSelectedIndex(0);
}
else if (listModel.size() > 0 && index > -1 && index < listModel.size())
{
jListStorage.setSelectedIndex(index);
}
}
FormTruckCollection() {
listModel = new DefaultListModel<String>();
jListStorage = new JList<String>(listModel);
canv = new Canvas();
JFrame Frame = new JFrame ("TrucksCollection");
_storage = new TrucksGenericStorage(pictureBoxWidth, pictureBoxHeight);
JButton ButtonAddTruck = new JButton("Добавить технику");
ButtonAddTruck.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jListStorage.getSelectedIndex() == -1)
{
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null)
{
return;
}
FormTruckConfig form = new FormTruckConfig();
form.buttonAdd.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (obj != null && obj.Add(form._Truck) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
form.w.dispose();
}
}
);
}
}
);
StackRemoved = new Stack<DrawingTruck>();
JTextField TextBoxNumber = new JTextField();
JButton ButtonRemoveTruck = new JButton("Удалить технику");
ButtonRemoveTruck.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jListStorage.getSelectedIndex() == -1)
{
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null)
{
return;
}
if (JOptionPane.showConfirmDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return;
}
for (char it : TextBoxNumber.getText().toCharArray())
if (it < '0' || it > '9') {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (TextBoxNumber.getText().length() == 0) {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
int pos = Integer.parseInt(TextBoxNumber.getText());
var removed = obj.remove(pos);
if (removed != null)
{
StackRemoved.push(removed);
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
} else {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
}
}
);
JButton buttonGetRemoved = new JButton("Вернуть удаленные");
buttonGetRemoved.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (StackRemoved.size()==0){
JOptionPane.showMessageDialog(null, "Нет удалённых", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
RoadTrainForm form = new RoadTrainForm();
form._drawingTruck = StackRemoved.pop();
form.Draw();
}
}
);
JButton ButtonRefreshCollection = new JButton("Обновить коллекцию");
ButtonRefreshCollection.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
Draw();
}
}
);
JButton FormTruckGenerate = new JButton("Генерировать");
FormTruckGenerate.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
FormGenericDopClass formGenericDopClass = new FormGenericDopClass();
}
}
);
JTextField textBoxSetName = new JTextField();
JButton buttonAddSet = new JButton("Добавить набор");
buttonAddSet.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (textBoxSetName.getText().length() == 0)
{
JOptionPane.showMessageDialog(null, "Не все данные заполнены", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Не все данные заполнены");
return;
}
_storage.AddSet(textBoxSetName.getText());
ReloadObjects();
}
}
);
jListStorage.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e){
Draw();
}
}
);
JButton buttonRemoveSet = new JButton("Убрать набор");
buttonRemoveSet.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (jListStorage.getSelectedIndex() == -1)
{
return;
}
if (JOptionPane.showConfirmDialog(null, "Удалить объект " + jListStorage.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
{
return;
}
_storage.DelSet(jListStorage.getSelectedValue());
ReloadObjects();
}
}
);
Frame.setSize (880, 520);
Frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Frame.setLayout(null);
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
ButtonAddTruck.setBounds(pictureBoxWidth, 0, 160, 20);
TextBoxNumber.setBounds(pictureBoxWidth, 30, 160, 20);
ButtonRemoveTruck.setBounds(pictureBoxWidth, 60, 160, 20);
ButtonRefreshCollection.setBounds(pictureBoxWidth, 90, 160, 20);
FormTruckGenerate.setBounds(pictureBoxWidth, 120, 160, 20);
buttonAddSet.setBounds(pictureBoxWidth, 150, 160, 20);
textBoxSetName.setBounds(pictureBoxWidth, 180, 160, 20);
jListStorage.setBounds(pictureBoxWidth, 210, 160, 80);
buttonRemoveSet.setBounds(pictureBoxWidth, 300, 160, 20);
buttonGetRemoved.setBounds(pictureBoxWidth, 330, 160, 20);
Frame.add(canv);
Frame.add(ButtonAddTruck);
Frame.add(ButtonRemoveTruck);
Frame.add(ButtonRefreshCollection);
Frame.add(TextBoxNumber);
Frame.add(FormTruckGenerate);
Frame.add(buttonAddSet);
Frame.add(textBoxSetName);
Frame.add(jListStorage);
Frame.add(buttonRemoveSet);
Frame.add(buttonGetRemoved);
Frame.setVisible(true);
}
}

View File

@ -0,0 +1,403 @@
package RoadTrain;
import RoadTrain.DrawingObjects.*;
import RoadTrain.Extra.*;
import RoadTrain.Entities.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.util.*;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.event.*;
import java.io.IOException;
public class FormTruckConfig {
private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent(Graphics g) {
if (_Truck == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_Truck.DrawTransport(g2d);
super.repaint();
}
}
private class LabelTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new StringSelection(((JLabel) c).getText());
}
}
private class ColorTransferable implements Transferable {
private Color color;
private static final DataFlavor colorDataFlavor = new DataFlavor(Color.class, "Color");
public ColorTransferable(Color color) {
this.color = color;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{colorDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return colorDataFlavor.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return color;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
private class PanelTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new ColorTransferable(((JPanel) c).getBackground());
}
}
private class LabelMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
}
private class PanelMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
((JPanel) e.getComponent()).getTransferHandler().exportAsDrag(((JPanel) e.getComponent()), e, TransferHandler.COPY);
}
}
private class WheelTransferable implements Transferable {
private IDrawingWheels wheelDrawing;
private static final DataFlavor wheelDrawingDataFlavor = new DataFlavor(IDrawingWheels.class, "Рисование колес");
public WheelTransferable(IDrawingWheels wheelDrawing) {
this.wheelDrawing = wheelDrawing;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{wheelDrawingDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(wheelDrawingDataFlavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return wheelDrawing;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
private class ComponentWheel extends JComponent {
public IDrawingWheels wheelDrawing;
public ComponentWheel(IDrawingWheels _wheelDrawing) {
wheelDrawing = _wheelDrawing;
this.addMouseListener(
new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((ComponentWheel) e.getComponent()).getTransferHandler().exportAsDrag(((ComponentWheel) e.getComponent()), e, TransferHandler.COPY);
}
}
);
this.setTransferHandler(
new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new WheelTransferable(((ComponentWheel) c).wheelDrawing);
}
}
);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
wheelDrawing.drawWheels(g2d, Color.BLUE, -20, -20);
super.repaint();
}
}
final int WindowHeight = 700;
final int WindowWidth = 800;
final int CanvasHeight = 600;
final int CanvasWidth = 600;
public DrawingTruck _Truck = null;
public JButton buttonAdd;
public JFrame w;
public Canvas canvas;
public FormTruckConfig() {
Border border = BorderFactory.createLineBorder(Color.GRAY);
JLabel labelSpeed = new JLabel("Скорость");
JLabel labelWeight = new JLabel("Вес");
JLabel labelWheelNum = new JLabel("Колеса");
SpinnerModel spinnerModel = new SpinnerNumberModel(100, 100, 1000, 1);
JSpinner numericSpeed = new JSpinner(spinnerModel);
SpinnerModel spinnerModel2 = new SpinnerNumberModel(100, 100, 1000, 1);
JSpinner numericWeight = new JSpinner(spinnerModel2);
SpinnerModel spinnerModel3 = new SpinnerNumberModel(1, 1, 3, 1);
JSpinner numericWheelNum = new JSpinner(spinnerModel3);
JCheckBox checkBoxWaterContainer = new JCheckBox("Бак с водой");
JCheckBox checkBoxSweepingBrush = new JCheckBox("Щетка");
JPanel[] colorPanels = {
new JPanel(), new JPanel(), new JPanel(), new JPanel(),
new JPanel(), new JPanel(), new JPanel(), new JPanel(),
};
colorPanels[0].setBackground(Color.BLACK);
colorPanels[1].setBackground(Color.BLUE);
colorPanels[2].setBackground(Color.GRAY);
colorPanels[3].setBackground(Color.YELLOW);
colorPanels[4].setBackground(Color.RED);
colorPanels[5].setBackground(Color.GREEN);
colorPanels[6].setBackground(Color.ORANGE);
colorPanels[7].setBackground(Color.WHITE);
for (var it : colorPanels) {
it.setTransferHandler(new PanelTransferHandler());
it.addMouseListener(new PanelMouseAdapter());
}
JLabel labelTruck = new JLabel("Грузовик");
labelTruck.setTransferHandler(new LabelTransferHandler());
labelTruck.addMouseListener(new LabelMouseAdapter());
labelTruck.setBorder(border);
labelTruck.setHorizontalAlignment(SwingConstants.CENTER);
labelTruck.setVerticalAlignment(SwingConstants.CENTER);
JLabel labelRoadtrain = new JLabel("Очист.машина");
labelRoadtrain.setTransferHandler(new LabelTransferHandler());
labelRoadtrain.addMouseListener(new LabelMouseAdapter());
labelRoadtrain.setBorder(border);
labelRoadtrain.setHorizontalAlignment(SwingConstants.CENTER);
labelRoadtrain.setVerticalAlignment(SwingConstants.CENTER);
JLabel labelColor = new JLabel("Цвет");
labelColor.setBorder(border);
labelColor.setHorizontalAlignment(SwingConstants.CENTER);
labelColor.setVerticalAlignment(SwingConstants.CENTER);
labelColor.setTransferHandler(
new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_Truck == null)
return false;
_Truck.entityTruck.SetBodyColor(color);
canvas.repaint();
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
);
JLabel labelAdditionalColor = new JLabel("Доп.Цвет");
labelAdditionalColor.setBorder(border);
labelAdditionalColor.setHorizontalAlignment(SwingConstants.CENTER);
labelAdditionalColor.setVerticalAlignment(SwingConstants.CENTER);
labelAdditionalColor.setTransferHandler(
new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_Truck == null)
return false;
if (!(_Truck instanceof DrawingRoadTrain))
return false;
((EntityRoadTrain) _Truck.entityTruck).SetAdditionalColor(color);
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
);
JLabel labelWheel = new JLabel("Колеса");
labelWheel.setBorder(border);
labelWheel.setHorizontalAlignment(SwingConstants.CENTER);
labelWheel.setVerticalAlignment(SwingConstants.CENTER);
labelWheel.setTransferHandler(
new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(WheelTransferable.wheelDrawingDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
IDrawingWheels wheelDrawing = (IDrawingWheels) support.getTransferable().getTransferData(WheelTransferable.wheelDrawingDataFlavor);
if (_Truck == null)
return false;
wheelDrawing.SetWheelNumber(_Truck.entityTruck.Numwheel);
_Truck.drawingWheels = wheelDrawing;
canvas.repaint();
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
);
canvas = new Canvas();
canvas.setTransferHandler(
new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "Грузовик":
_Truck = new DrawingTruck((int) numericSpeed.getValue(), (int) numericWeight.getValue(), Color.WHITE, CanvasWidth, CanvasHeight, (int) numericWheelNum.getValue());
break;
case "Очист.машина":
_Truck = new DrawingRoadTrain((int) numericSpeed.getValue(), (int) numericWeight.getValue(), Color.WHITE, Color.BLACK, checkBoxWaterContainer.isSelected(), checkBoxSweepingBrush.isSelected(), CanvasWidth, CanvasHeight, (int) numericWheelNum.getValue());
break;
}
canvas.repaint();
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
);
buttonAdd = new JButton("Добавить");
JButton buttonCancel = new JButton("Отменить");
ComponentWheel componentWheels = new ComponentWheel(new DrawingWheels());
ComponentWheel componentWheelsOneLine = new ComponentWheel(new DrawingOneLineWheels());
ComponentWheel componentWheelsTwoLine = new ComponentWheel(new DrawingTwoLineWheels());
labelSpeed.setBounds(10, 10, 40, 20);
labelWeight.setBounds(10, 40, 40, 20);
labelWheelNum.setBounds(10, 70, 40, 20);
numericSpeed.setBounds(55, 10, 80, 20);
numericWeight.setBounds(55, 40, 80, 20);
numericWheelNum.setBounds(55, 70, 80, 20);
checkBoxWaterContainer.setBounds(10, 100, 120, 20);
checkBoxSweepingBrush.setBounds(10, 130, 120, 20);
for (int i = 0; i < colorPanels.length; i += 2) {
colorPanels[i].setBounds(10, 200 + i / 2 * 60, 50, 50);
colorPanels[i + 1].setBounds(70, 200 + i / 2 * 60, 50, 50);
}
componentWheels.setBounds(10, 470, 10, 10);
componentWheelsOneLine.setBounds(50, 470, 10, 10);
componentWheelsTwoLine.setBounds(90, 470, 10, 10);
labelTruck.setBounds(10, 500, 50, 30);
labelRoadtrain.setBounds(70, 500, 50, 30);
labelColor.setBounds(WindowWidth - CanvasWidth, 10, CanvasWidth / 3, 30);
labelAdditionalColor.setBounds(WindowWidth - CanvasWidth + CanvasWidth / 3, 10, CanvasWidth / 3, 30);
labelWheel.setBounds(WindowWidth - CanvasWidth + CanvasWidth * 2 / 3, 10, CanvasWidth / 3, 30);
canvas.setBounds(WindowWidth - CanvasWidth, 50, CanvasWidth, CanvasHeight);
buttonAdd.setBounds(WindowWidth - CanvasWidth, CanvasHeight + 60, CanvasWidth / 3, 30);
buttonCancel.setBounds(WindowWidth - CanvasWidth + CanvasWidth * 2 / 3, CanvasHeight + 60, CanvasWidth / 3, 30);
w = new JFrame();
w.setSize(WindowWidth + 20, WindowHeight + 40);
w.setLayout(null);
w.add(labelSpeed);
w.add(labelWeight);
w.add(labelWheelNum);
w.add(numericSpeed);
w.add(numericWeight);
w.add(numericWheelNum);
w.add(checkBoxWaterContainer);
w.add(checkBoxSweepingBrush);
for (var it : colorPanels)
w.add(it);
w.add(labelTruck);
w.add(labelRoadtrain);
w.add(labelColor);
w.add(labelAdditionalColor);
w.add(labelWheel);
w.add(canvas);
w.add(buttonAdd);
w.add(buttonCancel);
w.add(componentWheels);
w.add(componentWheelsOneLine);
w.add(componentWheelsTwoLine);
w.setVisible(true);
buttonCancel.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
w.dispose();
}
}
);
}
}

View File

@ -0,0 +1,77 @@
package RoadTrain.Generics;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class SetGeneric<T extends Object> {
private ArrayList<T> _places;
public int Count() {
return _places.size();
}
private int _maxCount;
public SetGeneric(int count) {
_maxCount = count;
_places = new ArrayList<T>(count);
}
public int Insert(T train) {
if (_places.size() >= _maxCount)
return -1;
_places.add(0, train);
return 0;
}
public boolean Insert(T train, int position) {
if (_places.size() >= _maxCount)
return false;
if (position < 0 || position > _places.size())
return false;
if (position == _places.size())
_places.add(train);
else
_places.add(position, train);
return true;
}
public boolean Remove(int position) {
if (position < 0 || position >= _places.size())
return false;
_places.remove(position);
return true;
}
public T Get(int position) {
if (position < 0 || position >= _places.size())
return null;
return _places.get(position);
}
public Iterable<T> GetTrucks(final Integer maxTrains) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < _places.size() && (maxTrains == null || count < maxTrains);
}
@Override
public T next() {
if (hasNext()) {
count++;
return _places.get(currentIndex++);
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}

View File

@ -0,0 +1,87 @@
package RoadTrain.Generics;
import RoadTrain.DrawingObjects.*;
import RoadTrain.MovementStraregy.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class TrucksGenericCollection<T extends DrawingTruck, U extends IMoveableObject> {
// Высота и Ширина окна прорисовки
private int _pictureWidth;
private int _pictureHeight;
// Размер занимаемого объектом места (ширина и высота)
private int _placeSizeWidth = 180;
private int _placeSizeHeight = 90;
// Набор объектов
private SetGeneric<T> _collection;
// Конструктор
public TrucksGenericCollection(int pictureWidth, int pictureHeight) {
int width = pictureWidth / _placeSizeWidth;
int height = pictureHeight / _placeSizeHeight;
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
_collection = new SetGeneric<T>(width * height);
}
// Перегрузка оператора сложения
public int Add(T obj) {
if (obj == null) {
return -1;
}
return _collection.Insert(obj);
}
// Перегрузка оператора вычитания
public T remove(int pos) {
T obj = _collection.Get(pos);
if (obj != null) {
_collection.Remove(pos);
}
return obj;
}
// Получение объекта IMoveableObject
public U GetU(int pos) {
return (U) _collection.Get(pos).GetMoveableObject();
}
// Вывод всего набора объектов
public BufferedImage ShowTrucks() {
BufferedImage bitmap = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bitmap.createGraphics();
DrawBackground(g);
DrawObjects(g);
g.dispose();
return bitmap;
}
// Метод отрисовки фона
private void DrawBackground(Graphics g) {
g.setColor(Color.BLACK);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) {
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) {
// Линия разметки места
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void DrawObjects(Graphics g) {
int i = 0;
for (T t : _collection.GetTrucks(100))
{
if (t != null) {
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (t instanceof DrawingRoadTrain)
((DrawingRoadTrain) t).DrawTransport((Graphics2D) g);
else
t.DrawTransport((Graphics2D) g);
}
i++;
}
}
}

View File

@ -0,0 +1,45 @@
package RoadTrain.Generics;
import RoadTrain.DrawingObjects.*;
import RoadTrain.MovementStraregy.*;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
public class TrucksGenericStorage {
HashMap<String, TrucksGenericCollection<DrawingTruck, DrawingObjectTruck>> _truckStorages;
public List<String> Keys(){return _truckStorages.keySet().stream().collect(Collectors.toList());}
private int _pictureWidth;
private int _pictureHeight;
public TrucksGenericStorage(int pictureWidth, int pictureHeight)
{
_truckStorages = new HashMap<String, TrucksGenericCollection<DrawingTruck, DrawingObjectTruck>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(String name)
{
if (_truckStorages.containsKey(name))
return;
_truckStorages.put(name, new TrucksGenericCollection<DrawingTruck, DrawingObjectTruck>(_pictureWidth, _pictureHeight));
}
public void DelSet(String name)
{
if (!_truckStorages.containsKey(name))
return;
_truckStorages.remove(name);
}
public TrucksGenericCollection<DrawingTruck, DrawingObjectTruck> get(String ind)
{
if (_truckStorages.containsKey(ind))
return _truckStorages.get(ind);
return null;
}
public DrawingObjectTruck get(String ind1, int ind2){
if (!_truckStorages.containsKey(ind1))
return null;
return _truckStorages.get(ind1).GetU(ind2);
}
}

7
src/RoadTrain/Main.java Normal file
View File

@ -0,0 +1,7 @@
package RoadTrain;
public class Main {
public static void main(String[] args){
FormTruckCollection formTruckCollection = new FormTruckCollection();
}
}

View File

@ -0,0 +1,93 @@
package RoadTrain.MovementStraregy;
import RoadTrain.DirectionType;
public abstract class AbstractStrategy {
private IMoveableObject moveableObject;
private Status state = Status.NotInit;
private int fieldWidth;
protected int GetFieldWidth() {
return fieldWidth;
}
private int fieldHeight;
protected int GetFieldHeight() {
return fieldHeight;
}
public Status GetStatus() {
return state;
}
public void SetData(IMoveableObject moveableObject, int width, int height) {
if (moveableObject == null) {
state = Status.NotInit;
return;
}
state = Status.InProgress;
this.moveableObject = moveableObject;
fieldWidth = width;
fieldHeight = height;
}
public void MakeStep() {
if (state != Status.InProgress) {
return;
}
if (isTargetDestination()) {
state = Status.Finish;
return;
}
MoveToTarget();
}
protected boolean MoveLeft() {
return MoveTo(DirectionType.Left);
}
protected boolean MoveRight() {
return MoveTo(DirectionType.Right);
}
protected boolean MoveUp() {
return MoveTo(DirectionType.Up);
}
protected boolean MoveDown() {
return MoveTo(DirectionType.Down);
}
protected ObjectParameters GetObjectParameters() {
if (moveableObject == null) {
return null;
}
return moveableObject.GetObjectPosition();
}
protected Integer GetStep() {
if (state != Status.InProgress) {
return null;
}
return moveableObject.GetStep();
}
protected abstract void MoveToTarget();
protected abstract boolean isTargetDestination();
private boolean MoveTo(DirectionType directionType) {
if (state != Status.InProgress) {
return false;
}
if (moveableObject == null) {
return false;
}
if (moveableObject.CheckCanMove(directionType)) {
moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}

View File

@ -0,0 +1,39 @@
package RoadTrain.MovementStraregy;
import RoadTrain.DirectionType;
import RoadTrain.DrawingObjects.*;
public class DrawingObjectTruck implements IMoveableObject{
private DrawingTruck _drawingTruck = null;
public DrawingObjectTruck (DrawingTruck drawingTruck)
{
_drawingTruck = drawingTruck;
}
@Override
public ObjectParameters GetObjectPosition() {
if (_drawingTruck == null || _drawingTruck.entityTruck == null) {
return null;
}
return new ObjectParameters(_drawingTruck.GetPosX(), _drawingTruck.GetPosY(),
_drawingTruck.GetWidth(), _drawingTruck.GetHeight());
}
@Override
public int GetStep() {
if (_drawingTruck != null && _drawingTruck.entityTruck!=null)
return (int)(_drawingTruck.entityTruck.GetStep());
return 0;
}
@Override
public boolean CheckCanMove(DirectionType direction) {
if (_drawingTruck != null)
return _drawingTruck.CanMove(direction);
return false;
}
@Override
public void MoveObject(DirectionType direction) {
if (_drawingTruck != null)
_drawingTruck.MoveTransport(direction);
}
}

View File

@ -0,0 +1,12 @@
package RoadTrain.MovementStraregy;
import RoadTrain.DirectionType;
public interface IMoveableObject{
ObjectParameters GetObjectPosition();
int GetStep();
boolean CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);
}

View File

@ -0,0 +1,35 @@
package RoadTrain.MovementStraregy;
public class MoveToBorder extends AbstractStrategy{
@Override
protected boolean isTargetDestination() {
var objParams = GetObjectParameters();
if (objParams == null) {
return false;
}
return objParams.RightBorder() <= GetFieldWidth() &&
objParams.RightBorder() + GetStep() >= GetFieldWidth() &&
objParams.DownBorder() <= GetFieldHeight() &&
objParams.DownBorder() + GetStep() >= GetFieldHeight();
}
@Override
protected void MoveToTarget() {
var objParams = GetObjectParameters();
if (objParams == null) {
return;
}
var diffX = objParams.ObjectMiddleHorizontal() - GetFieldWidth();
if (Math.abs(diffX) > GetStep()) {
if (diffX < 0) {
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical() - GetFieldHeight();
if (Math.abs(diffY) > GetStep()) {
if (diffY < 0) {
MoveDown();
}
}
}
}

View File

@ -0,0 +1,39 @@
package RoadTrain.MovementStraregy;
public class MoveToCenter extends AbstractStrategy{
@Override
protected boolean isTargetDestination() {
var objParams = GetObjectParameters();
if (objParams == null) {
return false;
}
return objParams.ObjectMiddleHorizontal() <= GetFieldWidth() / 2 &&
objParams.ObjectMiddleHorizontal() + GetStep() >= GetFieldWidth() / 2 &&
objParams.ObjectMiddleVertical() <= GetFieldHeight() / 2 &&
objParams.ObjectMiddleVertical() + GetStep() >= GetFieldHeight() / 2;
}
@Override
protected void MoveToTarget() {
var objParams = GetObjectParameters();
if (objParams == null) {
return;
}
var diffX = objParams.ObjectMiddleHorizontal() - GetFieldWidth() / 2;
if (Math.abs(diffX) > GetStep()) {
if (diffX > 0) {
MoveLeft();
} else {
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical() - GetFieldHeight() / 2;
if (Math.abs(diffY) > GetStep()) {
if (diffY > 0) {
MoveUp();
} else {
MoveDown();
}
}
}
}

View File

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

View File

@ -0,0 +1,6 @@
package RoadTrain.MovementStraregy;
public enum Status {
NotInit,
InProgress,
Finish
}

View File

@ -0,0 +1,190 @@
package RoadTrain;
import RoadTrain.DrawingObjects.*;
import RoadTrain.MovementStraregy.*;
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.util.*;
public class RoadTrainForm{
public DrawingTruck _drawingTruck;
private AbstractStrategy _abstractStrategy;
public JButton buttonSelectTruck;
Canvas canv;
public JFrame frame;
public void Draw(){
canv.repaint();
}
public RoadTrainForm(){
frame = new JFrame("RoadTrain");
JButton buttonCreateTruck = new JButton("Создать грузовик");
buttonCreateTruck.setFocusPainted(false);
buttonCreateTruck.setContentAreaFilled(false);
buttonSelectTruck = new JButton("Добавить грузовик");
buttonSelectTruck.setFocusPainted(false);
buttonSelectTruck.setContentAreaFilled(false);
JButton buttonCreateRoadTrain = new JButton("Создать очистительную машину");
buttonCreateRoadTrain.setFocusPainted(false);
buttonCreateRoadTrain.setContentAreaFilled(false);
String[] items = {
"Form center",
"Form border"
};
JComboBox comboBoxStrategy = new JComboBox(items);
JButton buttonStep = new JButton("Шаг");
buttonStep.setFocusPainted(false);
buttonStep.setContentAreaFilled(false);
JButton buttonUp = new JButton();
buttonUp.setFocusPainted(false);
buttonUp.setContentAreaFilled(false);
buttonUp.setName("up");
buttonUp.setIcon(new ImageIcon(((new ImageIcon("Resources/ArrowUp.png")).getImage()).getScaledInstance(35, 35, java.awt.Image.SCALE_SMOOTH)));
JButton buttonDown = new JButton();
buttonDown.setFocusPainted(false);
buttonDown.setContentAreaFilled(false);
buttonDown.setName("down");
buttonDown.setIcon(new ImageIcon(((new ImageIcon("Resources/ArrowDown.png")).getImage()).getScaledInstance(35, 35, java.awt.Image.SCALE_SMOOTH)));
JButton buttonLeft = new JButton();
buttonLeft.setFocusPainted(false);
buttonLeft.setContentAreaFilled(false);
buttonLeft.setName("left");
buttonLeft.setIcon(new ImageIcon(((new ImageIcon("Resources/ArrowLeft.png")).getImage()).getScaledInstance(35, 35, java.awt.Image.SCALE_SMOOTH)));
JButton buttonRight = new JButton();
buttonRight.setFocusPainted(false);
buttonRight.setContentAreaFilled(false);
buttonRight.setName("right");
buttonRight.setIcon(new ImageIcon(((new ImageIcon("Resources/ArrowRight.png")).getImage()).getScaledInstance(35, 35, java.awt.Image.SCALE_SMOOTH)));
buttonCreateTruck.addActionListener(
e -> {
Random random = new Random();
Color color = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
Color selectedColor = JColorChooser.showDialog(frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null)
{
color = selectedColor;
}
_drawingTruck = new DrawingTruck(random.nextInt(200) + 100,
random.nextInt(2000) + 1000,
color, this.canv.getWidth(), this.canv.getHeight(), random.nextInt(3));
_drawingTruck.SetPosition(random.nextInt(100), random.nextInt(90));
Draw();
}
);
buttonCreateRoadTrain.addActionListener(
e -> {
Random random = new Random();
Color color = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
Color selectedColor = JColorChooser.showDialog(frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null)
{
color = selectedColor;
}
Color color2 = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
selectedColor = JColorChooser.showDialog(frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null)
{
color2 = selectedColor;
}
_drawingTruck = new DrawingRoadTrain(random.nextInt(200) + 100,
random.nextInt(2000) + 1000,
color, color2, random.nextBoolean(), random.nextBoolean(),
this.canv.getWidth(), this.canv.getHeight(), random.nextInt(3));
_drawingTruck.SetPosition(random.nextInt(100), random.nextInt(90));
Draw();
}
);
ActionListener actionListener = e -> {
if (_drawingTruck == null){
return;
}
switch ((((JButton)(e.getSource())).getName())){
case "up":
_drawingTruck.MoveTransport(DirectionType.Up);
break;
case "down":
_drawingTruck.MoveTransport(DirectionType.Down);
break;
case "left":
_drawingTruck.MoveTransport(DirectionType.Left);
break;
case "right":
_drawingTruck.MoveTransport(DirectionType.Right);
break;
}
Draw();
};
buttonUp.addActionListener(actionListener);
buttonDown.addActionListener(actionListener);
buttonLeft.addActionListener(actionListener);
buttonRight.addActionListener(actionListener);
buttonStep.addActionListener(e -> {
if (_drawingTruck == null) {
return;
}
if (comboBoxStrategy.isEnabled()) {
_abstractStrategy = switch (comboBoxStrategy.getSelectedIndex()) {
case 0 -> new MoveToCenter();
case 1 -> new MoveToBorder();
default -> null;
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectTruck(_drawingTruck), this.canv.getWidth(), this.canv.getHeight());
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.setEnabled(false);
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.setEnabled(true);
_abstractStrategy = null;
}
});
frame.setSize(910, 500);
frame.setLayout(null);
canv = new Canvas();
canv.setBounds(0, 0, 900, 500);
buttonCreateTruck.setBounds(20, 420, 100, 40);
buttonCreateRoadTrain.setBounds(140, 420, 100, 40);
buttonUp.setBounds(800, 380, 40, 40);
buttonDown.setBounds(800, 420, 40, 40);
buttonLeft.setBounds(760, 420, 40, 40);
buttonRight.setBounds(840, 420, 40, 40);
comboBoxStrategy.setBounds(800,10,100,50);
buttonStep.setBounds(800,80,100,40);
buttonSelectTruck.setBounds(740, 140, 150, 20);
frame.add(canv);
frame.add(buttonCreateTruck);
frame.add(buttonCreateRoadTrain);
frame.add(buttonUp);
frame.add(buttonDown);
frame.add(buttonLeft);
frame.add(buttonRight);
frame.add(comboBoxStrategy);
frame.add(buttonStep);
frame.add(buttonSelectTruck);
frame.setVisible(true);
}
class Canvas extends JComponent{
public Canvas(){}
public void paintComponent(Graphics g){
if (_drawingTruck == null){
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D)g;
_drawingTruck.DrawTransport(g2d);
super.repaint();
}
}
}