Compare commits

...

6 Commits

Author SHA1 Message Date
bekodeg
5b1b1f2284 усложнённая работа 4 2023-12-12 15:21:05 +04:00
bekodeg
1924451a63 работа 3 база на яве 2023-12-05 20:49:29 +04:00
bekodeg
f9a8216e8c работа 2 сдана 2023-11-22 09:18:12 +04:00
bekodeg
0d75f13101 работа 2 2023-11-16 17:45:11 +04:00
bekodeg
bf7d70d980 работа 1 2023-11-15 15:32:50 +04:00
bekodeg
9beb5a38be работа 1 2023-11-08 10:22:00 +04:00
30 changed files with 1392 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 537 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 502 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 497 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 538 B

View File

@ -0,0 +1,7 @@
package DrawningObjects;
public enum CountEnum {
Min,
Mid,
Max
}

View File

@ -0,0 +1,50 @@
package DrawningObjects;
import Entities.*;
import MovementStrategy.*;
import java.awt.*;
public class DrawningElectricLocomotive extends DrawningLocomotive {
public DrawningElectricLocomotive(int speed, double weight,
Color bodyColor, Color additionalColor,
int typeWheels, int countWheels,
boolean horns, boolean battery,
int width, int height) {
super(speed, weight, bodyColor, typeWheels, countWheels, width, height, 120, 70);
entityLocomotive = new EntityElectricLocomotive(
speed, weight, bodyColor, additionalColor, horns, battery);
}
public DrawningElectricLocomotive(EntityLocomotive entity, IDrawWheels drawingWheels, int width, int height) {
super(entity, drawingWheels, width, height);
}
@Override
public void DrawTransport(Graphics g) {
super.DrawTransport(g);
EntityElectricLocomotive entityElectricLocomotiveLocomotive = (EntityElectricLocomotive)entityLocomotive;
if (entityElectricLocomotiveLocomotive.Horns) {
g.setColor(Color.black);
int[] posX = new int[]{
_startPosX + 50,
_startPosX + 40,
_startPosX + 50,
_startPosX + 60
};
int[] posY = new int[]{
_startPosY + 20,
_startPosY + 10,
_startPosY,
_startPosY + 10
};
g.drawPolygon(posX, posY, 4);
}
// отсек для батарей
if (entityElectricLocomotiveLocomotive.Battery) {
g.setColor(entityElectricLocomotiveLocomotive.AdditionalColor);
g.fillRect(_startPosX + 80, _startPosY + 45, 35, 9);
}
}
}

View File

@ -0,0 +1,187 @@
package DrawningObjects;
import Entities.EntityLocomotive;
import MovementStrategy.DirectionType;
import MovementStrategy.IMoveableObject;
import java.awt.*;
public class DrawningLocomotive {
public EntityLocomotive entityLocomotive;
protected int _pictureWidth;
protected int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected int _locomotiveWidth = 140;
protected int _locomotiveHeight = 75;
protected IDrawWheels wheels;
public int GetPosX() {
return _startPosX;
}
public int GetPosY() {
return _startPosY;
}
public int GetWidth() {
return _locomotiveWidth;
}
public int GetHeight() {
return _locomotiveHeight;
}
public DrawningLocomotive(int speed, double weight,
Color bodyColor,
int typeWheels, int countWheels,
int width, int height) {
if (width < _locomotiveWidth || height < _locomotiveHeight) {
return;
}
_pictureWidth = width;
_pictureHeight = height;
switch (typeWheels){
case 0:
wheels = new DrawningWheels();
break;
case 1:
wheels = new DrawningWheelsPolygon();
break;
case 2:
wheels = new DrawningWheelsStar();
break;
}
wheels.setWheelsCount(countWheels);
entityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
public DrawningLocomotive(int speed, double weight,
Color bodyColor,
int typeWheels, int countWheels,
int width, int height,
int locomotiveWidth, int locomotiveHeight) {
if (width < locomotiveWidth || height < locomotiveHeight) {
return;
}
_pictureWidth = width;
_pictureHeight = height;
_locomotiveWidth = locomotiveWidth;
_locomotiveHeight = locomotiveHeight;
switch (typeWheels){
case 0:
wheels = new DrawningWheels();
break;
case 1:
wheels = new DrawningWheelsPolygon();
break;
case 2:
wheels = new DrawningWheelsStar();
break;
}
wheels.setWheelsCount(countWheels);
entityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
public DrawningLocomotive(EntityLocomotive entity, IDrawWheels drawWheels, int width, int height) {
entityLocomotive = entity;
wheels = drawWheels;
_pictureWidth = width;
_pictureHeight = height;
}
public void SetPosition(int x, int y) {
x = Math.min(Math.max(0, x), _pictureWidth - _locomotiveWidth);
y = Math.min(Math.max(0, y), _pictureHeight - _locomotiveHeight);
_startPosX = x;
_startPosY = y;
}
public void DrawTransport(Graphics g) {
if (entityLocomotive == null) {
return;
}
// корпус
g.setColor(entityLocomotive.BodyColor);
int[] posX = {
_startPosX,
_startPosX + 10,
_startPosX + 140,
_startPosX + 140,
_startPosX
};
int[] posY = {
_startPosY + 40,
_startPosY + 20,
_startPosY + 20,
_startPosY + 60,
_startPosY + 60
};
g.fillPolygon(posX, posY, 5);
g.drawLine(_startPosX, _startPosY + 40,
_startPosX + 120, _startPosY + 40);
// окна
g.setColor(Color.blue);
g.fillRect(_startPosX + 12, _startPosY + 24, 30, 11);
g.fillRect(_startPosX + 55, _startPosY + 24, 11, 11);
g.fillRect(_startPosX + 75, _startPosY + 24, 11, 11);
g.fillRect(_startPosX + 95, _startPosY + 24, 11, 11);
// колёса
wheels.DrawWheels(g, _startPosX, _startPosY);
}
public void SetPictureSize(int width, int height) {
_pictureWidth = width;
_pictureHeight = height;
}
public IMoveableObject GetMoveableObject(){
return (IMoveableObject) this;
}
public boolean CanMove(DirectionType direction) {
if (entityLocomotive == null) {
return false;
}
switch (direction) {
case Down -> {
return _startPosY + _locomotiveHeight + entityLocomotive.Step < _pictureHeight;
}
case Up -> {
return _startPosY - entityLocomotive.Step > 0;
}
case Right -> {
return _startPosX + _locomotiveWidth + entityLocomotive.Step < _pictureWidth;
}
case Left -> {
return _startPosX - entityLocomotive.Step > 0;
}
}
return false;
}
public void MoveTransport(DirectionType direction) {
if (!CanMove(direction) || entityLocomotive == null) {
return;
}
switch (direction) {
case Left -> {
_startPosX -= (int) entityLocomotive.Step;
}
case Up -> {
_startPosY -= (int) entityLocomotive.Step;
}
case Right -> {
_startPosX += (int) entityLocomotive.Step;
}
case Down -> {
_startPosY += (int) entityLocomotive.Step;
}
}
}
}

View File

@ -0,0 +1,60 @@
package DrawningObjects;
import java.awt.*;
public class DrawningWheels implements IDrawWheels {
private CountEnum _wheelsCount;
final protected int _wheelsSize = 18;
@Override
public CountEnum WheelsCount() {
return _wheelsCount;
}
protected void drawWheel(Graphics g, int posX, int posY){
g.fillOval(posX, posY, _wheelsSize, _wheelsSize);
}
@Override
public void DrawWheels(Graphics g, int posX, int posY){
g.setColor(Color.black);
int count = 0;
switch (_wheelsCount){
case Min -> {
count = 2;
posX += 15;
}
case Mid -> {
count = 3;
posX += 5;
}
case Max -> {
count = 4;
}
}
for (int i = 0; i < count; ++i){
drawWheel(g, posX + (i * 18), posY + 55);
drawWheel(g, posX + 75 + (i * 18), posY + 55);
}
}
@Override
public void setWheelsCount(int count) {
count = Math.min(4, count);
count = Math.max(2, count);
switch (count) {
case 2:
_wheelsCount = CountEnum.Min;
break;
case 3:
_wheelsCount = CountEnum.Mid;
break;
case 4:
_wheelsCount = CountEnum.Max;
break;
}
}
public String toString(){
return "Обычное колёса";
}
}

View File

@ -0,0 +1,22 @@
package DrawningObjects;
import java.awt.*;
public class DrawningWheelsPolygon extends DrawningWheels {
private final int _segmentsCount = 6;
private final double _angle = Math.PI * 2 / _segmentsCount;
@Override
protected void drawWheel(Graphics g, int posX, int posY){
g.drawOval(posX, posY, _wheelsSize, _wheelsSize);
int[] pointsPosX = new int[_segmentsCount];
int[] pointsPosY = new int[_segmentsCount];
for (int i = 0; i < _segmentsCount; ++i){
pointsPosX[i] = (int)((Math.cos(_angle * i) + 1) * _wheelsSize / 2) + posX;
pointsPosY[i] = (int)((Math.sin(_angle * i) + 1) * _wheelsSize / 2) + posY;
}
g.drawPolygon(pointsPosX, pointsPosY, _segmentsCount);
}
public String toString(){
return "колёса с узором многоугольник";
}
}

View File

@ -0,0 +1,26 @@
package DrawningObjects;
import java.awt.*;
public class DrawningWheelsStar extends DrawningWheels {
private final int _segmentsCount = 8;
private final double _angle = Math.PI * 2 / _segmentsCount;
@Override
protected void drawWheel(Graphics g, int posX, int posY){
g.drawOval(posX, posY, _wheelsSize, _wheelsSize);
int[] pointsPosX = new int[_segmentsCount];
int[] pointsPosY = new int[_segmentsCount];
for (int i = 0; i < _segmentsCount; ++i){
pointsPosX[i] = (int)((Math.cos(_angle * i) + 1) * _wheelsSize / 2) + posX;
pointsPosY[i] = (int)((Math.sin(_angle * i) + 1) * _wheelsSize / 2) + posY;
}
for (int i = 0; i < _segmentsCount; ++i){
int inversePoint = (i + _segmentsCount / 2 + 1) % _segmentsCount;
g.drawLine(pointsPosX[i], pointsPosY[i],
pointsPosX[inversePoint], pointsPosY[inversePoint]);
}
}
public String toString(){
return "колёса с узором звезда";
}
}

View File

@ -0,0 +1,9 @@
package DrawningObjects;
import java.awt.*;
public interface IDrawWheels {
public CountEnum WheelsCount();
public void DrawWheels(Graphics g, int posX, int posY);
public void setWheelsCount(int count);
}

View File

@ -0,0 +1,20 @@
package Entities;
import DrawningObjects.IDrawWheels;
import java.awt.*;
import java.lang.FunctionalInterface;
public class EntityElectricLocomotive extends EntityLocomotive {
public Color AdditionalColor;
public boolean Horns;
public boolean Battery;
public EntityElectricLocomotive(int speed, double weight,
Color bodyColor, Color additionalColor,
boolean horns, boolean battery) {
super(speed, weight, bodyColor);
AdditionalColor = additionalColor;
Horns = horns;
Battery = battery;
}
}

View File

@ -0,0 +1,19 @@
package Entities;
import DrawningObjects.IDrawWheels;
import java.awt.*;
public class EntityLocomotive {
public int Speed;
public double Weight;
public Color BodyColor;
public double Step;
public EntityLocomotive(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
Step = Speed * 100.0f / Weight;
}
}

View File

@ -0,0 +1,261 @@
package Forms;
import DrawningObjects.*;
import MovementStrategy.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class FormElectricLocomotive extends JFrame {
private DrawningLocomotive _drawningLocomotive;
private AbstractStrategy _abstractStrategy;
private Canvas canvas;
private JButton buttonCreateElectricLocomotive;
private JButton buttonCreateLocomotive;
public JButton buttonSelectLocomotive;
private JButton buttonUp;
private JButton buttonRight;
private JButton buttonDown;
private JButton buttonLeft;
private JButton buttonStep;
private JTextField numberField;
private JComboBox<AbstractStrategy> comboBoxStrategy;
private JComboBox<IDrawWheels> comboBoxWheels;
public void Draw() {
if (_drawningLocomotive == null)
{
return;
}
Graphics g = canvas.getGraphics();
g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
_drawningLocomotive.DrawTransport(g);
}
public DrawningLocomotive GetSelectedLocomotive(){
return _drawningLocomotive;
}
private void InitializeComponent(){
buttonCreateElectricLocomotive = new JButton("Создать Электропоезд");
buttonCreateElectricLocomotive.setMargin(new Insets(0, 0, 0, 0));
buttonCreateLocomotive = new JButton("Создать локомотив");
buttonCreateLocomotive.setMargin(new Insets(0, 0, 0, 0));
buttonSelectLocomotive = new JButton("Выбор");
buttonSelectLocomotive.setMargin(new Insets(0, 0, 0, 0));
buttonStep = new JButton("шаг");
buttonStep.setName("шаг");
comboBoxStrategy = new JComboBox<>();
comboBoxStrategy.addItem(new MoveToCenter());
comboBoxStrategy.addItem(new MoveToBorder());
comboBoxWheels = new JComboBox<>();
comboBoxWheels.addItem(new DrawningWheels());
comboBoxWheels.addItem(new DrawningWheelsPolygon());
comboBoxWheels.addItem(new DrawningWheelsStar());
buttonUp = new JButton();
buttonUp.setBorderPainted(false);
buttonUp.setFocusPainted(false);
buttonUp.setContentAreaFilled(false);
buttonUp.setName("up");
buttonUp.setIcon(new ImageIcon("Resources/arrowUp.png"));
buttonUp.setSize(40, 40);
buttonRight = new JButton();
buttonRight.setBorderPainted(false);
buttonRight.setFocusPainted(false);
buttonRight.setContentAreaFilled(false);
buttonRight.setName("right");
buttonRight.setIcon(new ImageIcon("Resources/arrowRight.png"));
buttonRight.setSize(40, 40);
buttonDown = new JButton();
buttonDown.setBorderPainted(false);
buttonDown.setFocusPainted(false);
buttonDown.setContentAreaFilled(false);
buttonDown.setName("down");
buttonDown.setIcon(new ImageIcon("Resources/arrowDown.png"));
buttonDown.setSize(40, 40);
buttonLeft = new JButton();
buttonLeft.setBorderPainted(false);
buttonLeft.setFocusPainted(false);
buttonLeft.setContentAreaFilled(false);
buttonLeft.setName("left");
buttonLeft.setIcon(new ImageIcon("Resources/arrowLeft.png"));
buttonLeft.setSize(40, 40);
numberField = new JTextField();
setSize(1000, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Рисование локомотивов");
setLayout(null);
canvas = new Canvas();
canvas.setBounds(0, 0, 980, 560);
buttonCreateElectricLocomotive.setBounds(10, 470, 200, 40);
buttonCreateLocomotive.setBounds(10, 520, 200, 40);
buttonSelectLocomotive.setBounds(770, 520, 200, 40);
buttonUp.setBounds(50, 380, 40, 40);
buttonDown.setBounds(50, 420, 40, 40);
buttonRight.setBounds(90, 420, 40, 40);
buttonLeft.setBounds(10, 420, 40, 40);
numberField.setBounds(220, 470, 40, 40);
buttonStep.setBounds(770, 50, 200, 30);
comboBoxStrategy.setBounds(770, 10, 200, 30);
comboBoxWheels.setBounds(220, 520, 250, 40);
add(buttonCreateElectricLocomotive);
add(buttonCreateLocomotive);
add(buttonSelectLocomotive);
add(buttonUp);
add(buttonDown);
add(buttonRight);
add(buttonLeft);
add(numberField);
add(buttonStep);
add(comboBoxStrategy);
add(comboBoxWheels);
add(canvas);
}
private void InitializeLogic(){
buttonCreateElectricLocomotive.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
int countWheels;
try {
countWheels = Integer.parseInt(numberField.getText());
} catch (Exception ex) {
countWheels = 0;
}
IDrawWheels _drawWheels = (IDrawWheels) comboBoxWheels.getSelectedItem();
_drawWheels.setWheelsCount(countWheels);
System.out.println(e.getActionCommand());
Random random = new Random();
Color baseColor = JColorChooser.showDialog(null,"Основной цвет", Color.RED);
if (baseColor == null){
baseColor = new Color(random.nextInt(0, 256),
random.nextInt(0, 256),
random.nextInt(0, 256));
}
Color addColor = JColorChooser.showDialog(null,"Дополнительный цвет", Color.RED);
if (addColor == null){
addColor = new Color(random.nextInt(0, 256),
random.nextInt(0, 256),
random.nextInt(0, 256));
}
_drawningLocomotive = new DrawningElectricLocomotive(
random.nextInt(100, 300), random.nextInt(1000, 3000),
baseColor,
addColor,
comboBoxWheels.getSelectedIndex(), countWheels,
random.nextInt(0, 2) == 1, random.nextInt(0, 2) == 1,
canvas.getWidth(), canvas.getHeight()
);
_drawningLocomotive.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100));
Draw();
}
}
);
buttonCreateLocomotive.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
int countWheels;
try {
countWheels = Integer.parseInt(numberField.getText());
}
catch (Exception ex){
countWheels = 0;
}
System.out.println(e.getActionCommand());
Random random = new Random();
Color baseColor = JColorChooser.showDialog(null,"Основной цвет", Color.RED);
if (baseColor == null){
baseColor = new Color(random.nextInt(0, 256),
random.nextInt(0, 256),
random.nextInt(0, 256));
}
_drawningLocomotive = new DrawningLocomotive(
random.nextInt(100, 300), random.nextInt(1000, 3000),
baseColor,
comboBoxWheels.getSelectedIndex(), countWheels,
canvas.getWidth(), canvas.getHeight()
);
_drawningLocomotive.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100));
Draw();
}
}
);
buttonStep.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(((JButton)(e.getSource())).getName());
if (_drawningLocomotive == null){
return;
}
if (comboBoxStrategy.isEnabled()){
_abstractStrategy = (AbstractStrategy) comboBoxStrategy.getSelectedItem();
if (_abstractStrategy == null){
return;
}
_abstractStrategy.SetData(new DrawningObjectLocomotive(_drawningLocomotive),
canvas.getWidth(), canvas.getHeight());
comboBoxStrategy.setEnabled(false);
}
if (_abstractStrategy == null){
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish){
comboBoxStrategy.setEnabled(true);
_abstractStrategy = null;
}
}
}
);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println(((JButton)(e.getSource())).getName());
if (_drawningLocomotive == null)
{
return;
}
switch(((JButton)(e.getSource())).getName()){
case "up":
_drawningLocomotive.MoveTransport(DirectionType.Up);
break;
case "down":
_drawningLocomotive.MoveTransport(DirectionType.Down);
break;
case "left":
_drawningLocomotive.MoveTransport(DirectionType.Left);
break;
case "right":
_drawningLocomotive.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
};
buttonUp.addActionListener(actionListener);
buttonDown.addActionListener(actionListener);
buttonLeft.addActionListener(actionListener);
buttonRight.addActionListener(actionListener);
}
public FormElectricLocomotive(){
InitializeComponent();
InitializeLogic();
setVisible(true);
}
}

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="Forms.FormGenerateLocomotiveDop">
<grid id="27dc6" binding="PictureBox" layout-manager="GridLayoutManager" row-count="2" 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="378" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="4e6e1" class="javax.swing.JButton" binding="generateLocomotiveButton">
<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>
<vspacer id="a5af5">
<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>
</form>

View File

@ -0,0 +1,79 @@
package Forms;
import DrawningObjects.*;
import Entities.EntityElectricLocomotive;
import Entities.EntityLocomotive;
import Generics.DopLocomotiveGenericCollection;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Random;
public class FormGenerateLocomotiveDop extends JFrame {
private Random _random;
private DrawningLocomotive _drawingLocomotive;
private DopLocomotiveGenericCollection<EntityLocomotive, IDrawWheels> _genericDop;
private JButton generateLocomotiveButton;
private JPanel PictureBox;
public JPanel getPictureBox() {
return PictureBox;
}
public FormGenerateLocomotiveDop(){
_random = new Random();
_genericDop = new DopLocomotiveGenericCollection<>();
PictureBox.setPreferredSize(new Dimension(400, 400));
generateLocomotiveButton.addActionListener(this::generateLocomotive);
}
private void addRandomEntity(){
EntityLocomotive entityLocomotive;
if (_random.nextBoolean()){
entityLocomotive = new EntityLocomotive(
_random.nextInt(100, 300),
_random.nextInt(1000, 3000),
new Color(_random.nextInt(256), _random.nextInt(256), _random.nextInt(256))
);
} else {
entityLocomotive = new EntityElectricLocomotive(
_random.nextInt(100, 300),
_random.nextInt(1000, 3000),
new Color(_random.nextInt(256), _random.nextInt(256), _random.nextInt(256)),
new Color(_random.nextInt(256), _random.nextInt(256), _random.nextInt(256)),
_random.nextBoolean(),
_random.nextBoolean()
);
}
_genericDop.add(entityLocomotive);
}
private void addRandomWheels(){
int choice = _random.nextInt(3);
IDrawWheels drawWheels;
if (choice == 0){
drawWheels = new DrawningWheels();
} else if (choice == 1){
drawWheels = new DrawningWheelsStar();
} else {
drawWheels = new DrawningWheelsPolygon();
}
drawWheels.setWheelsCount(_random.nextInt(2, 4));
_genericDop.add(drawWheels);
}
private void generateLocomotive(ActionEvent e){
addRandomEntity();
addRandomWheels();
_drawingLocomotive = _genericDop.GenerateLocomotive(PictureBox.getWidth(), PictureBox.getHeight());
_drawingLocomotive.SetPosition((PictureBox.getWidth() - _drawingLocomotive.GetWidth()) / 2,
(PictureBox.getHeight() - _drawingLocomotive.GetHeight()) / 2);
Draw();
}
public void Draw() {
if (_drawingLocomotive == null) {
return;
}
Graphics g = PictureBox.getGraphics();
PictureBox.paint(g);
_drawingLocomotive.DrawTransport(g);
}
}

View File

@ -0,0 +1,151 @@
package Forms;
import DrawningObjects.DrawningLocomotive;
import Generics.LocomotivesGenericCollection;
import MovementStrategy.DrawningObjectLocomotive;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FormLocomotiveCollection extends JFrame {
private final LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive> _locomotives;
private Canvas canvas;
private FrameGenerateLocomotiveDop _formGenerateLocomotiveDop;
private JButton buttonAddLocomotive;
private JButton buttonRemoveLocomotive;
private JButton buttonRefreshCollection;
private JButton buttonOpenGenerateWindow;
private JTextField textBoxNumber;
private JPanel buttonBox;
public void repaint(){
if (_locomotives == null)
return;
Graphics g = canvas.getGraphics();
g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
canvas.setBackground(getBackground());
g.drawImage(_locomotives.ShowLocomotives(), 0, 0, canvas);
}
private void InitializeComponent(){
canvas = new Canvas();
buttonAddLocomotive = new JButton("Добавить локомотив");
buttonAddLocomotive.setMargin(new Insets(0, 0, 0, 0));
textBoxNumber = new JTextField();
buttonRemoveLocomotive = new JButton("Удалить локомотив");
buttonRemoveLocomotive.setMargin(new Insets(0, 0, 0, 0));
buttonRefreshCollection = new JButton("Обновить колекцию");
buttonRefreshCollection.setMargin(new Insets(0, 0, 0, 0));
buttonOpenGenerateWindow = new JButton("Открыть окно генерации");
buttonOpenGenerateWindow.setMargin(new Insets(0, 0, 0, 0));
buttonBox = new JPanel(new GridLayout(0, 1, 0, 10));
JLabel labelBB = new JLabel("Инструменты");
buttonBox.add(labelBB);
buttonBox.add(buttonAddLocomotive);
buttonBox.add(textBoxNumber);
buttonBox.add(buttonRemoveLocomotive);
buttonBox.add(buttonRefreshCollection);
buttonBox.setBounds(760, 3, 200, 220);
canvas.setBounds(10, 3, 740, 700);
buttonOpenGenerateWindow.setBounds(760, 600, 200, 40);
setSize(1000, 700);
setTitle("Колекция локомотивов");
setLayout(null);
add(buttonBox);
add(buttonOpenGenerateWindow);
add(canvas);
}
void InitializeLogic(){
buttonAddLocomotive.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FormElectricLocomotive form = new FormElectricLocomotive();
form.setVisible(true);
form.buttonSelectLocomotive.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (_locomotives.Add(form.GetSelectedLocomotive()) != -1){
JOptionPane.showMessageDialog(null,
"Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Объект добавлен");
repaint();
}
else {
JOptionPane.showMessageDialog(null,
"Не удалось добавить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Не удалось добавить объект");
}
form.dispose();
}
}
);
}
});
buttonRemoveLocomotive.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (JOptionPane.showConfirmDialog(null,
"Delete Tanker?", "Delete", JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION)
{
int pos = 0;
try {
pos = Integer.parseInt(textBoxNumber.getText());
}
catch (Exception ex){
System.out.println(ex.toString());
pos = 0;
}
if (_locomotives.Sub(pos) != null)
{
JOptionPane.showMessageDialog(null,
"Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
repaint();
}
else
{
JOptionPane.showMessageDialog(null,
"Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
}
repaint();
}
});
buttonRefreshCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
});
buttonOpenGenerateWindow.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_formGenerateLocomotiveDop != null) {
_formGenerateLocomotiveDop.dispose();
}
_formGenerateLocomotiveDop = new FrameGenerateLocomotiveDop();
_formGenerateLocomotiveDop.setVisible(true);
}
});
}
public FormLocomotiveCollection(){
InitializeComponent();
_locomotives = new LocomotivesGenericCollection<>(canvas.getWidth(), canvas.getHeight());
InitializeLogic();
setVisible(true);
}
}

View File

@ -0,0 +1,17 @@
package Forms;
import javax.swing.*;
public class FrameGenerateLocomotiveDop extends JFrame {
public FormGenerateLocomotiveDop formGenerateLocomotiveDop;
public FrameGenerateLocomotiveDop(){
super();
setTitle("Генерация локомотивов");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
formGenerateLocomotiveDop = new FormGenerateLocomotiveDop();
setContentPane(formGenerateLocomotiveDop.getPictureBox());
setDefaultLookAndFeelDecorated(false);
setLocation(300, 100);
pack();
}
}

View File

@ -0,0 +1,45 @@
package Generics;
import DrawningObjects.DrawningElectricLocomotive;
import DrawningObjects.DrawningLocomotive;
import DrawningObjects.IDrawWheels;
import Entities.EntityElectricLocomotive;
import Entities.EntityLocomotive;
import java.util.ArrayList;
import java.util.Random;
public class DopLocomotiveGenericCollection<T extends EntityLocomotive, U extends IDrawWheels> {
private ArrayList<T> _entitiesStorage;
private ArrayList<U> _drawWheelsStorage;
public DopLocomotiveGenericCollection(){
_entitiesStorage = new ArrayList<>();
_drawWheelsStorage = new ArrayList<>();
}
public void add(T obj){
_entitiesStorage.add(obj);
}
public void add(U obj){
_drawWheelsStorage.add(obj);
}
public DrawningLocomotive GenerateLocomotive(int pictureWidth, int pictureHeight) {
Random random = new Random();
if (_entitiesStorage.isEmpty()) {
return null;
}
T entityLocomotive = _entitiesStorage.get(random.nextInt(_entitiesStorage.size()));
U drawingWheels = null;
if (!_drawWheelsStorage.isEmpty()) {
drawingWheels = _drawWheelsStorage.get(random.nextInt(_drawWheelsStorage.size()));
}
DrawningLocomotive drawingLocomotive;
if (entityLocomotive instanceof EntityElectricLocomotive) {
drawingLocomotive = new DrawningElectricLocomotive((EntityLocomotive) entityLocomotive, drawingWheels, pictureWidth, pictureHeight);
} else {
drawingLocomotive = new DrawningLocomotive(entityLocomotive, drawingWheels, pictureWidth, pictureHeight);
}
return drawingLocomotive;
}
}

View File

@ -0,0 +1,79 @@
package Generics;
import DrawningObjects.DrawningLocomotive;
import MovementStrategy.IMoveableObject;
import java.awt.*;
import java.awt.image.BufferedImage;
public class LocomotivesGenericCollection<T extends DrawningLocomotive, U extends IMoveableObject> {
private int _pictureWidth;
private int _pictureHeight;
private final int _placeSizeWidth = 210;
private final int _placeSizeHeight = 90;
private SetGeneric<T> _collection;
public LocomotivesGenericCollection(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;
}
obj.SetPictureSize(_pictureWidth, _pictureHeight);
if (_collection.Insert(obj)) {
return 1;
}
return -1;
}
public T Sub(int pos){
T obj = _collection.Get(pos);
_collection.Remove(pos);
return obj;
}
public U GetU(int pos){
return (U) (_collection.Get(pos)).GetMoveableObject();
}
public Image ShowLocomotives()
{
BufferedImage bmp = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = bmp.getGraphics();
DrawBackground(g);
DrawObjects(g);
return bmp;
}
private void DrawBackground(Graphics g){
g.setColor(Color.BLACK);
g.setFont(new Font("myFont", Font.PLAIN, 3));
for (int i = 0; i < _pictureHeight / _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 ColumnCount = _pictureWidth / _placeSizeWidth;
int RowsCount = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count(); ++i) {
DrawningLocomotive drawningLocomotive = _collection.Get(i);
if (drawningLocomotive == null) {
continue;
}
drawningLocomotive.SetPosition(
(i % ColumnCount) * _placeSizeWidth,
((RowsCount - (i / ColumnCount) - 1) * _placeSizeHeight));
drawningLocomotive.DrawTransport(g);
}
}
}

View File

@ -0,0 +1,50 @@
package Generics;
import DrawningObjects.DrawningLocomotive;
public class SetGeneric<T extends DrawningLocomotive> {
private T[] _places;
public int Count(){
return _places.length;
}
public SetGeneric(int count){
_places = (T[])new DrawningLocomotive[count];
}
boolean Insert(T obj, int position){
if (position >= _places.length || position < 0){
return false;
}
int fillLineEnd = _places.length;
for (int i = position; i < _places.length; ++i){
if (_places[i] == null){
fillLineEnd = i;
break;
}
}
if (fillLineEnd == _places.length){
return false;
}
for (int i = fillLineEnd; i > position; --i){
_places[i] = _places[i - 1];
}
_places[position] = obj;
return true;
}
boolean Insert(T obj){
return Insert(obj, 0);
}
public boolean Remove(int position){
if (position >= _places.length || position < 0)
{
return false;
}
_places[position] = null;
return true;
}
public T Get(int position){
if (position >= _places.length || position < 0){
return null;
}
return _places[position];
}
}

View File

@ -0,0 +1,8 @@
import Forms.*;
public class Main {
public static void main(String[] args) {
FormLocomotiveCollection form = new FormLocomotiveCollection();
}
}

View File

@ -0,0 +1,93 @@
package MovementStrategy;
public abstract class AbstractStrategy {
private IMoveableObject _movableObject;
private Status _state = Status.NotInit;
private int _fieldWidth;
protected int FieldWidth() {
return _fieldWidth;
}
private int _fieldHeight;
protected int FieldHeight() {
return _fieldHeight;
}
public Status GetStatus() {
return _state;
}
public void SetData(IMoveableObject movableObject, int width, int height) {
if (movableObject == null) {
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_movableObject = movableObject;
_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 (_movableObject != null) {
return _movableObject.GetObjectPosition();
}
return null;
}
protected int GetStep() {
if (_state != Status.InProgress) {
return 0;
}
return _movableObject.GetStep();
}
protected abstract void MoveToTarget();
protected abstract boolean IsTargetDestination();
private boolean MoveTo(DirectionType directionType) {
if (_state != Status.InProgress) {
return false;
}
if (_movableObject != null && _movableObject.CheckCanMove(directionType)) {
_movableObject.MoveObject(directionType);
return true;
}
return false;
}
public void SetFieldSize(int width, int height) {
_fieldWidth = width;
_fieldHeight = height;
}
}

View File

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

View File

@ -0,0 +1,44 @@
package MovementStrategy;
import DrawningObjects.DrawningLocomotive;
public class DrawningObjectLocomotive implements IMoveableObject {
private DrawningLocomotive _drawningLocomotive = null;
public DrawningObjectLocomotive(DrawningLocomotive drawningLocomotive)
{
_drawningLocomotive = drawningLocomotive;
}
@Override
public ObjectParameters GetObjectPosition() {
if (_drawningLocomotive == null || _drawningLocomotive.entityLocomotive == null){
return null;
}
return new ObjectParameters(
_drawningLocomotive.GetPosX(), _drawningLocomotive.GetPosY(),
_drawningLocomotive.GetWidth(), _drawningLocomotive.GetHeight());
}
@Override
public int GetStep() {
if (_drawningLocomotive == null){
return 0;
}
return (int)_drawningLocomotive.entityLocomotive.Step;
}
@Override
public boolean CheckCanMove(DirectionType direction) {
if (_drawningLocomotive == null){
return false;
}
return _drawningLocomotive.CanMove(direction);
}
@Override
public void MoveObject(DirectionType direction) {
if (_drawningLocomotive == null){
return;
}
_drawningLocomotive.MoveTransport(direction);
}
}

View File

@ -0,0 +1,8 @@
package MovementStrategy;
public interface IMoveableObject {
public ObjectParameters GetObjectPosition();
int GetStep();
boolean CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);
}

View File

@ -0,0 +1,31 @@
package MovementStrategy;
public class MoveToBorder extends AbstractStrategy{
@Override
protected void MoveToTarget() {
var objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
MoveRight();
MoveDown();
}
@Override
protected boolean IsTargetDestination() {
var objParams = GetObjectParameters();
if (objParams == null){
return false;
}
return objParams.RightBorder() <= FieldWidth() &&
objParams.RightBorder() + GetStep() >= FieldWidth() &&
objParams.DownBorder() <= FieldHeight() &&
objParams.DownBorder() + GetStep() >= FieldHeight();
}
public String toString(){
return "идти к краю экрана";
}
}

View File

@ -0,0 +1,53 @@
package MovementStrategy;
public class MoveToCenter extends AbstractStrategy{
@Override
protected void MoveToTarget() {
var objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal() - FieldWidth() / 2;
if (Math.abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical() - FieldHeight() / 2;
if (Math.abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
@Override
protected boolean IsTargetDestination() {
var objParams = GetObjectParameters();
if (objParams == null){
return false;
}
return objParams.ObjectMiddleHorizontal() <= FieldWidth() / 2 &&
objParams.ObjectMiddleHorizontal() + GetStep() >= FieldWidth() / 2 &&
objParams.ObjectMiddleVertical() <= FieldHeight() / 2 &&
objParams.ObjectMiddleVertical() + GetStep() >= FieldHeight() / 2;
}
public String toString(){
return "идти к центру экрана";
}
}

View File

@ -0,0 +1,32 @@
package MovementStrategy;
public class ObjectParameters {
private int _x;
private int _y;
private int _width;
private 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,7 @@
package MovementStrategy;
public enum Status {
NotInit,
InProgress,
Finish
}