Compare commits

..

12 Commits
main ... lab4

Author SHA1 Message Date
791d5205b3 методы добавления из 3ей лабы исправлены на полиморфные 2023-12-03 10:15:33 +04:00
bcc4a0d32f готово!!! 2023-11-28 12:02:52 +04:00
facad042be работа с формой.... 2023-11-27 23:23:06 +04:00
aad104ad8e it's all 2023-11-27 10:20:47 +04:00
492fee19fe in progress 2023-11-26 19:10:56 +04:00
bcf703d795 reducing repetitive code 2023-11-23 15:26:05 +04:00
29e3f74627 lab2 2023-11-18 14:41:33 +04:00
28963e2235 lab2 2023-11-18 14:40:19 +04:00
2ab74c38dc lab2 2023-11-18 14:35:17 +04:00
5980b6eb32 clean2 2023-11-18 13:02:21 +04:00
2c02421db6 done 2023-11-18 12:55:54 +04:00
ec2c529fa5 lab 1 2023-11-18 12:42:03 +04:00
31 changed files with 1703 additions and 0 deletions

105
.gitignore vendored
View File

@ -12,3 +12,108 @@
# Built Visual Studio Code Extensions
*.vsix
# ---> Java
*.class
*.idea
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# ---> JetBrains
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

BIN
images/KeyDown.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
images/KeyLeft.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
images/KeyRight.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
images/KeyUp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -0,0 +1,159 @@
package Drawnings;
import java.awt.*;
import java.util.Random;
import Entities.*;
import MovementStrategy.*;
public class DrawningAirbus {
public EntityAirbus entityAirbus;
public IDrawningPortholes _portholes;
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
private int _airbusWidth = 124;
private int _airbusHeight = 44;
// Получение объекта IMoveableObject из объекта DrawningCar;
public IMoveableObject GetMoveableObject() {
return new DrawningObjectAirbus(this);
}
public int GetPosX() { return _startPosX; }
public int GetPosY() { return _startPosY; }
public int GetWidth() { return _airbusWidth; }
public int GetHeight() { return _airbusHeight; }
public DrawningAirbus(int speed, float weight, Color bodyColor, int countPortholes, int width, int height) {
if (width < _airbusHeight || height < _airbusWidth)
return;
_pictureWidth = width;
_pictureHeight = height;
entityAirbus = new EntityAirbus(speed, weight, bodyColor);
Random random = new Random();
switch (random.nextInt(0,3)) {
case 0:
_portholes = new DrawningPortholesCircle();
break;
case 1:
_portholes = new DrawningPortholesHeart();
break;
case 2:
_portholes = new DrawningPortholesSquare();
break;
default:
_portholes = new DrawningPortholesCircle();
break;
}
_portholes.SetCount(countPortholes);
}
public void SetPosition (int x, int y) {
if (x + _airbusWidth > _pictureWidth || y + _airbusHeight > _pictureHeight) {
_startPosX = _pictureWidth - _airbusWidth;
_startPosY = _pictureHeight - _airbusHeight;
}
else
{
_startPosX = x;
_startPosY = y;
}
}
public boolean CanMove(Direction direction)
{
if (entityAirbus == null)
{
return false;
}
switch (direction)
{
case Left:
return _startPosX - entityAirbus.Step > 0;
case Right:
return _startPosX + _airbusWidth + entityAirbus.Step < _pictureWidth;
case Up:
return _startPosY - entityAirbus.Step > 0;
case Down:
return _startPosY + _airbusHeight + entityAirbus.Step < _pictureHeight;
default:
return false;
}
}
public void MoveTransport(Direction direction){
if (entityAirbus == null) {
return;
}
switch (direction) {
case Left:
_startPosX -= entityAirbus.Step;
break;
case Right:
_startPosX += entityAirbus.Step;
break;
case Up:
_startPosY -= entityAirbus.Step;
break;
case Down:
_startPosY += entityAirbus.Step;
break;
}
}
public void DrawTransport(Graphics2D g) {
if (entityAirbus == null) {
return;
}
// тело
g.setColor(entityAirbus.getBodyColor());
g.fillRect(_startPosX+3, _startPosY+17, 103, 20);
g.setColor(Color.BLACK);
g.drawRect(_startPosX+3, _startPosY+17, 103, 20);
// иллюминаторы
_portholes.Draw(g, _startPosX, _startPosY);
// нос
int[] xPolygonNoise = {_startPosX+106, _startPosX + 120, _startPosX+106,};
int[] yPolygonNoise = {_startPosY+17, _startPosY+27, _startPosY+37};
g.setColor(entityAirbus.getBodyColor());
g.fillPolygon(xPolygonNoise, yPolygonNoise, xPolygonNoise.length);
g.setColor(Color.BLACK);
g.drawPolygon(xPolygonNoise, yPolygonNoise, xPolygonNoise.length);
// хвост
int[] xPolygonTale = { _startPosX+2, _startPosX+27, _startPosX+2};
int[] yPolygonTale = {_startPosY, _startPosY + 18,_startPosY+18};
g.setColor(entityAirbus.getBodyColor());
g.fillPolygon(xPolygonTale, yPolygonTale, xPolygonTale.length);
g.setColor(Color.BLACK);
g.drawPolygon(xPolygonTale, yPolygonTale, xPolygonTale.length);
// крыло
g.setColor(Color.BLACK);
g.fillOval(_startPosX+43, _startPosY+25, 22, 5);
g.drawOval(_startPosX+43, _startPosY+25, 22, 5);
// двигатель
g.setColor(Color.BLACK);
g.fillOval(_startPosX+1, _startPosY+15, 19, 5);
g.drawOval(_startPosX+1, _startPosY+15, 19, 5);
// шасси
g.setColor(entityAirbus.getBodyColor());
g.fillOval(_startPosX+25,_startPosY+38, 6, 6);
g.fillOval(_startPosX+30,_startPosY+38, 6, 6);
g.fillOval(_startPosX+100,_startPosY+38, 6, 6);
g.setColor(Color.BLACK);
g.drawOval(_startPosX+25,_startPosY+38, 6, 6);
g.drawOval(_startPosX+30,_startPosY+38, 6, 6);
g.drawOval(_startPosX+100,_startPosY+38, 6, 6);
}
}

View File

@ -0,0 +1,43 @@
package Drawnings;
import Entities.EntityPlane;
import java.awt.*;
public class DrawningPlane extends DrawningAirbus {
public DrawningPlane(int speed, float weight, Color bodyColor, int countPortholes, Color additionalColor, boolean isCompartment, boolean isAdditionalEngine, int width, int height)
{
super(speed, weight, bodyColor, countPortholes, width, height);
if (entityAirbus != null) {
entityAirbus = new EntityPlane(speed, weight, bodyColor, additionalColor, isCompartment, isAdditionalEngine);
}
}
@Override
public void DrawTransport(Graphics2D g) {
if (entityAirbus == null)
{
return;
}
Color additionalColor = ((EntityPlane)entityAirbus).getAdditionalColor();
// пассажирский отсек
if (((EntityPlane)entityAirbus).IsCompartment()) {
g.setColor(additionalColor);
g.fillOval(_startPosX + 57, _startPosY + 11, 39, 9);
g.setColor(Color.BLACK);
g.drawOval(_startPosX + 57, _startPosY + 11, 39, 9);
}
super.DrawTransport(g);
// доп двигатель
if (((EntityPlane)entityAirbus).IsAdditionalEngine()) {
g.setColor(additionalColor);
g.fillOval(_startPosX, _startPosY + 25, 11, 5);
g.setColor(Color.BLACK);
g.drawOval(_startPosX, _startPosY + 25, 11, 5);
}
}
}

View File

@ -0,0 +1,53 @@
package Drawnings;
import java.awt.*;
import Entities.*;
public class DrawningPortholesCircle implements IDrawningPortholes {
private CountPortholes _porthole;
public int Count;
public int getCount() {
return Count;
}
public void SetCount (int count) {
Count = count;
switch (Count) {
case 10:
_porthole = CountPortholes.Ten;
break;
case 20:
_porthole = CountPortholes.Twenty;
break;
case 30:
_porthole = CountPortholes.Thirty;
break;
default:
_porthole = CountPortholes.Ten;
break;
}
}
protected void drawPortholes(Graphics2D g, int posX, int posY){
g.setColor(Color.cyan);
g.fillOval(posX, posY, 3, 3);
g.setColor(Color.black);
g.drawOval(posX, posY, 3, 3);
}
public void Draw (Graphics2D g, int _startPosX, int _startPosY) {
for (int i = 0; i < 10; ++i) {
drawPortholes(g, _startPosX + 19 + i * 8, _startPosY + 21);
}
if (_porthole == CountPortholes.Ten) {
return;
}
for (int i = 0; i < 5; ++i) {
drawPortholes(g, _startPosX + 15 + i * 5, _startPosY + 26);
drawPortholes(g, _startPosX + 70 + i * 5, _startPosY + 26);
}
if (_porthole == CountPortholes.Twenty) {
return;
}
for (int i = 0; i < 10; ++i) {
drawPortholes(g, _startPosX + 19 + i * 8, _startPosY + 31);
}
}
}

View File

@ -0,0 +1,16 @@
package Drawnings;
import Entities.CountPortholes;
import java.awt.*;
public class DrawningPortholesHeart extends DrawningPortholesCircle {
protected void drawPortholes(Graphics2D g, int posX, int posY) {
int[] HeartX = {posX + 2, posX, posX, posX + 1, posX + 2, posX + 3, posX + 5, posX + 5};
int[] HeartY = {posY + 4, posY + 2, posY, posY, posY + 1, posY, posY, posY + 2};
g.setColor(Color.cyan);
g.fillPolygon(HeartX, HeartY, HeartX.length);
g.setColor(Color.black);
g.drawPolygon(HeartX, HeartY, HeartX.length);
}
}

View File

@ -0,0 +1,14 @@
package Drawnings;
import Entities.CountPortholes;
import java.awt.*;
public class DrawningPortholesSquare extends DrawningPortholesCircle {
protected void drawPortholes(Graphics2D g, int posX, int posY){
g.setColor(Color.cyan);
g.fillRect(posX, posY, 3, 3);
g.setColor(Color.black);
g.drawRect(posX, posY, 3, 3);
}
}

View File

@ -0,0 +1,10 @@
package Drawnings;
import java.awt.*;
import Entities.CountPortholes;
public interface IDrawningPortholes {
public int getCount();
public void SetCount (int count);
public void Draw (Graphics2D g, int _startPosX, int _startPoxY);
}

View File

@ -0,0 +1,6 @@
package Entities;
public enum CountPortholes {
Ten,
Twenty,
Thirty;
}

View File

@ -0,0 +1,30 @@
package Entities;
import java.awt.*;
public class EntityAirbus {
private int Speed;
private float Weight;
private Color BodyColor;
public float Step;
public int getSpeed() {
return Speed;
}
public float getWeight() {
return Weight;
}
public Color getBodyColor() {
return BodyColor;
}
public EntityAirbus(int speed, float weight, Color bodyColor)
{
Weight = weight;
Speed = speed;
BodyColor = bodyColor;
Step = Speed * 100 / (int) Weight;
}
}

View File

@ -0,0 +1,21 @@
package Entities;
import javax.swing.text.AttributeSet;
import java.awt.*;
public class EntityPlane extends EntityAirbus {
private Color AdditionalColor;
private boolean IsCompartment;
private boolean IsAdditionalEngine;
public EntityPlane(int speed, float weight, Color bodyColor, Color additionalColor, boolean isCompartment, boolean isAdditionalEngine) {
super(speed, weight, bodyColor);
AdditionalColor = additionalColor;
IsCompartment = isCompartment;
IsAdditionalEngine = isAdditionalEngine;
}
public Color getAdditionalColor() { return AdditionalColor; }
public boolean IsCompartment() { return IsCompartment; }
public boolean IsAdditionalEngine() { return IsAdditionalEngine; }
}

291
src/FormAirbus.java Normal file
View File

@ -0,0 +1,291 @@
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import Drawnings.*;
import MovementStrategy.*;
public class FormAirbus extends JFrame {
private int width;
private int height;
public DrawningAirbus _drawningAirbus;
private AbstractStrategy _abstractStrategy;
private Canvas canvas;
// выбор кол-ва иллюминаторов
JLabel labelCount;
private JTextField fieldCount;
// выбор стратегии
JLabel labelStrategy;
JComboBox comboBoxStrategy;
JButton buttonStrategy;
private JButton buttonCreateAirbus;
private JButton buttonCreatePlane;
public JButton buttonSelectAirbus;
private JButton buttonUp;
private JButton buttonDown;
private JButton buttonRight;
private JButton buttonLeft;
public FormAirbus() {
super("Создание самолёта");
InitializeComponent();
setVisible(true);
}
private void InitializeComponent()
{
canvas = new Canvas();
labelCount = new JLabel("Введите число иллюминаторов:");
fieldCount = new JTextField();
labelStrategy = new JLabel("Шаг стратегии:");
comboBoxStrategy = new JComboBox(new Integer[] {0, 1});
buttonStrategy = new JButton("Выбрать стратегию");
buttonStrategy.setMargin(new Insets(0, 0, 0, 0));
buttonCreateAirbus = new JButton("Создать аэробус");
buttonCreateAirbus.setMargin(new Insets(0, 0, 0, 0));
buttonCreatePlane = new JButton("Создать самолёт");
buttonCreatePlane.setMargin(new Insets(0, 0, 0, 0));
buttonSelectAirbus = new JButton("Выбрать");
buttonSelectAirbus.setMargin(new Insets(0, 0, 0, 0));
buttonUp = new JButton();
buttonUp.setName("up");
buttonUp.setIcon(new ImageIcon("images\\KeyUp.png"));
buttonRight = new JButton();
buttonRight.setName("right");
buttonRight.setIcon(new ImageIcon("images\\KeyRight.png"));
buttonLeft = new JButton();
buttonLeft.setName("left");
buttonLeft.setIcon(new ImageIcon("images\\KeyLeft.png"));
buttonDown = new JButton();
buttonDown.setName("down");
buttonDown.setIcon(new ImageIcon("images\\KeyDown.png"));
setSize(800,500);
setLayout(null);
buttonCreateAirbus.setBounds(12, 355, 130, 25);
buttonCreatePlane.setBounds(buttonCreateAirbus.getX()+140, 355, 130, 25);
buttonSelectAirbus. setBounds(buttonCreatePlane.getX()+140, 355, 130, 25);
labelCount.setBounds(42, 405, 240, 20);
fieldCount.setBounds(240, 407, 48, 20);
labelStrategy.setBounds(630, 20, 146, 33);
comboBoxStrategy.setBounds(630, 50, 146, 20);
buttonStrategy.setBounds(630, 80, 146, 33);
buttonUp.setBounds(679, 313, 48, 44);
buttonRight.setBounds( 728, 358, 48, 44);
buttonLeft.setBounds(630, 358, 48, 44);
buttonDown.setBounds( 679, 358, 48, 44);
labelCount.setBounds(12, 405, 240, 20);
fieldCount.setBounds(210, 407, 48, 20);
canvas.setBounds(0,0,790, 460);
add(buttonCreateAirbus);
add(buttonCreatePlane);
add(buttonSelectAirbus);
add(labelCount);
add(fieldCount);
add(labelStrategy);
add(comboBoxStrategy);
add(buttonStrategy);
add(buttonUp);
add(buttonRight);
add(buttonDown);
add(buttonLeft);
add(labelCount);
add(fieldCount);
add(canvas);
// логика формы
buttonCreateAirbus.addActionListener(buttonCreateAirbusListener);
buttonCreatePlane.addActionListener(buttonCreatePlaneListener);
buttonStrategy.addActionListener(buttonStrategyListener);
buttonUp.addActionListener(buttonsMoveListener);
buttonRight.addActionListener(buttonsMoveListener);
buttonDown.addActionListener(buttonsMoveListener);
buttonLeft.addActionListener(buttonsMoveListener);
}
ActionListener buttonCreateAirbusListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Random rand = new Random();
// базовый цвет
Color color = new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256));
Color selectedColor = JColorChooser.showDialog(null, "Выберите цвет", Color.BLACK);
if (selectedColor != null)
{
color = selectedColor;
}
int countPortholes;
try
{
countPortholes = Integer.parseInt(fieldCount.getText());
}
catch (Exception ex)
{
countPortholes = 0;
}
if (countPortholes != 10 && countPortholes != 20 && countPortholes != 30)
{
JOptionPane.showMessageDialog(null, "Число должно быть равно 10, 20 или 30.\nКол-во иллюминаторов приравнено к 10");
countPortholes = 10;
}
_drawningAirbus = new DrawningAirbus(
rand.nextInt(200) + 100, rand.nextInt(2000) + 1000,
color,
countPortholes,
canvas.getWidth(), canvas.getHeight());
_drawningAirbus.SetPosition(rand.nextInt(100) + 10, rand.nextInt(100) + 10);
comboBoxStrategy.setEnabled(true);
canvas.repaint();
}
};
ActionListener buttonCreatePlaneListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Random rand = new Random();
// базовый цвет
Color color = new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256));
Color selectedColor = JColorChooser.showDialog(null, "Выберите цвет", Color.BLACK);
if (selectedColor != null)
{
color = selectedColor;
}
// доп цвет
Color additionalColor = new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256));
selectedColor = JColorChooser.showDialog(null, "Выберите доп. цвет", Color.GRAY);
if (selectedColor != null)
{
additionalColor = selectedColor;
}
int countPortholes;
try
{
countPortholes = Integer.parseInt(fieldCount.getText());
}
catch (Exception ex)
{
countPortholes = 0;
}
if (countPortholes != 10 && countPortholes != 20 && countPortholes != 30)
{
JOptionPane.showMessageDialog(null, "Число должно быть равно 10, 20 или 30.\nКол-во иллюминаторов приравнено к 10");
countPortholes = 10;
}
_drawningAirbus = new DrawningPlane(
rand.nextInt(200) + 100, rand.nextInt(2000) + 1000,
color,
countPortholes,
additionalColor,
rand.nextBoolean(), rand.nextBoolean(),
canvas.getWidth(), canvas.getHeight());
_drawningAirbus.SetPosition(rand.nextInt(100) + 10, rand.nextInt(100) + 10);
comboBoxStrategy.setEnabled(true);
canvas.repaint();
}
};
ActionListener buttonStrategyListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_drawningAirbus == null)
{
return;
}
if (comboBoxStrategy.isEnabled()) {
switch (comboBoxStrategy.getSelectedIndex()) {
case 0:
_abstractStrategy = new MoveToCenter();
break;
case 1:
_abstractStrategy = new MoveToBorder();
break;
default:
_abstractStrategy = null;
break;
}
;
if (_abstractStrategy == null) {
return;
}
_abstractStrategy.SetData(new DrawningObjectAirbus(_drawningAirbus), canvas.getWidth(), canvas.getHeight());
comboBoxStrategy.setEnabled(false);
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.setEnabled(true);
_abstractStrategy = null;
}
canvas.repaint();
}
};
ActionListener buttonsMoveListener = new ActionListener() {
// реакция на нажатие
public void actionPerformed(ActionEvent e) {
if (_drawningAirbus == null)
{
return;
}
String command = ((JButton)(e.getSource())).getName();
switch (command) {
case "up":
_drawningAirbus.MoveTransport(Direction.Up);
break;
case "down":
_drawningAirbus.MoveTransport(Direction.Down);
break;
case "right":
_drawningAirbus.MoveTransport(Direction.Right);
break;
case "left":
_drawningAirbus.MoveTransport(Direction.Left);
break;
}
canvas.repaint();
}
};
class Canvas extends JComponent{
public Canvas() {}
public void paintComponent (Graphics g){
if (_drawningAirbus == null){
return;
}
super.paintComponents (g) ;
Graphics2D g2d = (Graphics2D)g;
_drawningAirbus.DrawTransport(g2d);
super.repaint();
}
}
}

View File

@ -0,0 +1,299 @@
import Drawnings.DrawningAirbus;
import Generics.AirbusGenericCollection;
import Generics.AirbusGenericStorage;
import MovementStrategy.DrawningObjectAirbus;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class FormAirbusCollection extends JFrame {
private Canvas canvas;
private AirbusGenericStorage _storage;
static int pictureBoxWidth = 650;
static int pictureBoxHeight = 460;
private JButton buttonGenerateAirbus;
private JButton buttonUpdate;
private JButton buttonAddAirbus;
private JButton buttonDeleteAirbus;
// работа с наборами
private JButton buttonAddStorage;
private JButton buttonDeleteStorage;
private JButton buttonGetDeleted;
private JTextField textFieldStorage;
private JList<String> listStorage;
private DefaultListModel<String> listModel;
LinkedList<DrawningAirbus> linkedListDeleted;
private JTextField textFieldNumber;
private AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus> _airbus;
FormAirbusCollection() {
listModel = new DefaultListModel<String>();
listStorage = new JList<String>(listModel);
_airbus = new AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus> (pictureBoxWidth, pictureBoxHeight);
_storage = new AirbusGenericStorage(pictureBoxWidth, pictureBoxHeight);
linkedListDeleted = new LinkedList<DrawningAirbus>();
canvas = new Canvas();
JFrame frame = new JFrame("Коллекция аэробусов");
buttonAddStorage = new JButton("Добавить набор");
buttonAddStorage.setMargin(new Insets(0, 0, 0, 0));
buttonDeleteStorage = new JButton("Удалить набор");
buttonDeleteStorage.setMargin(new Insets(0, 0, 0, 0));
buttonAddAirbus = new JButton("Добавить аэробус");
buttonAddAirbus.setMargin(new Insets(0, 0, 0, 0));
buttonDeleteAirbus = new JButton("Удалить аэробус");
buttonDeleteAirbus.setMargin(new Insets(0, 0, 0, 0));
buttonUpdate = new JButton("Обновить");
buttonUpdate.setMargin(new Insets(0, 0, 0, 0));
buttonGetDeleted = new JButton("Загрузить удалёнки");
buttonGetDeleted.setMargin(new Insets(0, 0, 0, 0));
buttonGenerateAirbus = new JButton("Форма генерации");
buttonGenerateAirbus.setMargin(new Insets(0,0,0,0));
textFieldStorage = new JTextField();
textFieldNumber = new JTextField();
setSize(800,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
textFieldStorage.setBounds(pictureBoxWidth, 20, 120, 25);
buttonAddStorage.setBounds(pictureBoxWidth, textFieldStorage.getY()+30, 120, 25);
listStorage.setBounds(pictureBoxWidth, buttonAddStorage.getY()+30, 120, 120);
buttonDeleteStorage.setBounds(pictureBoxWidth, listStorage.getY()+125, 120, 25);
buttonAddAirbus.setBounds(pictureBoxWidth, buttonDeleteStorage.getY()+30, 120, 25);
textFieldNumber.setBounds(pictureBoxWidth, buttonAddAirbus.getY()+30, 120, 25);
buttonDeleteAirbus.setBounds(pictureBoxWidth, textFieldNumber.getY()+30, 120, 25);
buttonUpdate.setBounds(pictureBoxWidth, buttonDeleteAirbus.getY()+30, 120, 25);
buttonGetDeleted.setBounds(pictureBoxWidth, buttonUpdate.getY()+30, 120, 25);
buttonGenerateAirbus.setBounds(pictureBoxWidth, buttonGetDeleted.getY()+30, 120, 25);
canvas.setBounds(0,0,pictureBoxWidth, pictureBoxHeight);
add(canvas);
add(buttonAddStorage);
add(listStorage);
add(textFieldStorage);
add(buttonDeleteStorage);
add(buttonAddAirbus);
add(buttonDeleteAirbus);
add(buttonUpdate);
add(buttonGenerateAirbus);
add(buttonGetDeleted);
add(textFieldNumber);
setVisible(true);
// логика формы
buttonAddStorage.addActionListener(AddStorageListener);
buttonDeleteStorage.addActionListener(DeleteStorageListener);
buttonGetDeleted.addActionListener(GetDeletedListener);
listStorage.addListSelectionListener(listSelectionListener);
buttonAddAirbus.addActionListener(AddAirbusListener);
buttonDeleteAirbus.addActionListener(DeleteAirbusListener);
buttonUpdate.addActionListener(UpdateAirbusListener);
buttonGenerateAirbus.addActionListener(OpenGenerationForm);
}
// секция работы с наборами
private void ReloadObject()
{
int index = listStorage.getSelectedIndex();
listModel.clear();
for (int i = 0; i < _storage.Keys().size(); i++)
{
listModel.addElement(_storage.Keys().get(i));
}
if (listModel.size() > 0 && (index == -1 || index >= listModel.size()))
{
listStorage.setSelectedIndex(0);
}
else if (listModel.size() > 0 && index > -1 && index < listModel.size())
{
listStorage.setSelectedIndex(index);
}
}
// добавить набор
ActionListener AddStorageListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (textFieldStorage.getText().length() == 0)
{
JOptionPane.showMessageDialog(null, "Не все данные заполнены", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
_storage.AddSet(textFieldStorage.getText());
ReloadObject();
}
};
// выбрать
ListSelectionListener listSelectionListener = new ListSelectionListener() {
// public т.к. в интерфейсе метод тоже public
public void valueChanged(ListSelectionEvent e) {
canvas.repaint();
}
};
// удалить набор
ActionListener DeleteStorageListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listStorage.getSelectedIndex() == -1)
return;
if (JOptionPane.showOptionDialog(null, "Удалить " + listStorage.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Да", "Нет"}, "Да")
== JOptionPane.NO_OPTION)
return;
_storage.DelSet(listStorage.getSelectedValue());
ReloadObject();
}
};
// загрузить удалёнки
ActionListener GetDeletedListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (linkedListDeleted.size() == 0)
{
JOptionPane.showMessageDialog(null, "Нет удалённых аэробусов", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
FormAirbus form = new FormAirbus();
form._drawningAirbus = linkedListDeleted.getLast();
linkedListDeleted.removeLast();
canvas.repaint();
}
};
// конец секции работы с наборами
ActionListener OpenGenerationForm = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
FormGenerationAirbus form = new FormGenerationAirbus();
dispose();
}
};
// добавить аэробус в набор
ActionListener AddAirbusListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
if (listStorage.getSelectedIndex() == -1)
return;
var obj = _storage.get(listStorage.getSelectedValue());
if (obj == null)
return;
// выбор аэробуса на второй форме
FormAirbus form = new FormAirbus();
form.buttonSelectAirbus.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DrawningAirbus selectedAirbus = form._drawningAirbus;
form.dispose();
if (selectedAirbus != null) {
if (obj.Add(selectedAirbus) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен");
canvas.repaint();
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Ошибка", JOptionPane.ERROR_MESSAGE);
canvas.repaint();
}
}
}
}
);
}
};
// удалить аэробус
ActionListener DeleteAirbusListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
if (listStorage.getSelectedIndex() == -1)
return;
var obj = _storage.get(listStorage.getSelectedValue());
if (obj == null)
return;
Object[] options= {"да", "нет"};
if (JOptionPane.showOptionDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Да", "Нет"}, "Да")
== JOptionPane.NO_OPTION)
return;
try {
int pos = Integer.parseInt(textFieldNumber.getText());
// запоминаем удалёнку
DrawningAirbus deleted = obj.GetT(pos);
if (obj.Remove(pos)) {
// добавить в список удалёнок
linkedListDeleted.add(deleted);
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
canvas.repaint();
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
};
// обновить
ActionListener UpdateAirbusListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
canvas.repaint();
}
};
class Canvas extends JComponent {
public Canvas() {}
public void paintComponent(Graphics g) {
super.paintComponents(g);
if (listStorage.getSelectedIndex() == -1)
return;
var obj = _storage.get(listStorage.getSelectedValue());
if (obj == null)
return;
if (obj.ShowAirbus() != null)
g.drawImage(obj.ShowAirbus(), 0, 0, this);
super.repaint();
}
}
}

View File

@ -0,0 +1,91 @@
import Drawnings.*;
import Entities.EntityAirbus;
import Entities.EntityPlane;
import Generics.AirbusGenericCollection;
import Generics.GenericParametrized;
import MovementStrategy.DrawningObjectAirbus;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class FormGenerationAirbus extends JFrame {
Canvas canvas;
GenericParametrized<EntityAirbus, IDrawningPortholes> generic;
DrawningAirbus _airbus;
private int _width = 800;
private int _height = 500;
JButton buttonGenerate;
FormGenerationAirbus() {
JFrame frame = new JFrame("Генерация аэробусов");
setSize(800,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
generic = new GenericParametrized<>(50, 50, _width, _height);
canvas = new FormGenerationAirbus.Canvas();
canvas.setBounds(0 , 0, _width, _height);
buttonGenerate = new JButton("Сгенерировать аэробус");
buttonGenerate.setMargin(new Insets(0, 0, 0, 0));
buttonGenerate.setBounds(600, 20, 170, 25);
add(canvas);
add(buttonGenerate);
setVisible(true);
buttonGenerate.addActionListener(GenerateAirbus);
}
ActionListener GenerateAirbus = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Random rand = new Random();
// генерация сущности
EntityAirbus entity;
if (rand.nextBoolean()) {
entity = new EntityAirbus(
rand.nextInt(200) + 100, rand.nextInt(2000) + 1000,
new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256)));
} else {
entity = new EntityPlane(rand.nextInt(200) + 100, rand.nextInt(2000) + 1000,
new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256)),
new Color(rand.nextInt(0, 256), rand.nextInt(0, 256), rand.nextInt(0, 256)),
rand.nextBoolean(), rand.nextBoolean());
}
generic.add(entity);
// генерация иллюминаторов
IDrawningPortholes potholes;
int n = rand.nextInt(3);
if (n == 0)
potholes = new DrawningPortholesCircle();
else if (n == 1)
potholes = new DrawningPortholesHeart();
else
potholes = new DrawningPortholesSquare();
potholes.SetCount(rand.nextInt(1,4)*10);
generic.add(potholes);
// отрисовка
_airbus = generic.randomDrawingObject();
_airbus.SetPosition(100, 100);
canvas.repaint();
}
};
class Canvas extends JComponent {
public Canvas() {}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D)g;
if (_airbus != null)
_airbus.DrawTransport(g2d);
super.repaint();
}
}
}

View File

@ -0,0 +1,102 @@
package Generics;
import java.awt.*;
import java.awt.image.BufferedImage;
import Drawnings.DrawningAirbus;
import MovementStrategy.IMoveableObject;
public class AirbusGenericCollection<T extends DrawningAirbus, U extends IMoveableObject> {
private int _pictureWidth;
private int _pictureHeight;
private int _placeSizeWidth = 124;
private int _placeSizeHeight = 44;
private SetGeneric<T> _collection;
public AirbusGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
// сложение
public int Add(T obj)
{
if (obj == null)
return -1;
return _collection.Insert(obj);
}
// вычитание
public boolean Remove(int pos)
{
if (_collection.Get(pos) == null)
return false;
return _collection.Remove(pos);
}
// получение объекта IMoveableObjecr
public U GetU(int pos)
{
if (_collection.Get(pos) != null)
return (U)_collection.Get(pos).GetMoveableObject();
return null;
}
// получение объекта DrawningAirbus
public T GetT(int pos)
{
if (_collection.Get(pos) != null)
return (T)_collection.GetAirbus().get(pos);
return null;
}
// вывод всего набора
public BufferedImage ShowAirbus()
{
BufferedImage bmp = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D gr = bmp.createGraphics();
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
// прорисовка фона
private void DrawBackground(Graphics gr)
{
gr.setColor(Color.BLACK);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; ++i)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
// линия разметки
gr.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
gr.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
}
// прорисовка объекта
private void DrawObjects(Graphics2D gr)
{
// координаты
int x = _pictureWidth / _placeSizeWidth - 1;
int y = _pictureHeight / _placeSizeHeight - 1;
for (var _airbus : _collection.GetAirbus())
{
if (_airbus != null) {
if (x < 0)
{
x = _pictureWidth / _placeSizeWidth - 1;
--y;
}
_airbus.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y);
_airbus.DrawTransport(gr);
--x;
}
}
}
}

View File

@ -0,0 +1,52 @@
package Generics;
import Drawnings.DrawningAirbus;
import MovementStrategy.DrawningObjectAirbus;
import java.util.HashMap;
import java.util.List;
public class AirbusGenericStorage {
HashMap <String, AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus>> _airbusStorages;
public List<String> Keys() {
return _airbusStorages.keySet().stream().toList();
}
private int _pictureWidth;
private int _pictureHeight;
public AirbusGenericStorage(int pictureWidth, int pictureHeight)
{
_airbusStorages = new HashMap<String, AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus>> ();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(String name)
{
if (_airbusStorages.containsKey(name))
// уже занят
return;
_airbusStorages.put(name, new AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus>(_pictureWidth, _pictureHeight));
}
public void DelSet(String name)
{
if (!_airbusStorages.containsKey(name))
return;
_airbusStorages.remove(name);
}
// Доступ к набору
public AirbusGenericCollection<DrawningAirbus, DrawningObjectAirbus> get(String ind)
{
if (_airbusStorages.containsKey(ind))
return _airbusStorages.get(ind);
return null;
}
// вызов удалёнок
public DrawningObjectAirbus get(String iStorage, int iAirbus){
if (!_airbusStorages.containsKey(iStorage))
return null;
return _airbusStorages.get(iStorage).GetU(iAirbus);
}
}

View File

@ -0,0 +1,76 @@
package Generics;
import java.util.ArrayList;
import java.util.Random;
import Entities.*;
import Drawnings.*;
public class GenericParametrized<T extends EntityAirbus, U extends IDrawningPortholes> {
private ArrayList<T> _airbus;
private ArrayList<U> _portholes;
private int CountAirbus;
private int CountPortholes;
private int MaxCountAirbus;
private int MaxCountPortoles;
private int _pictureWidth;
private int _pictureHeight;
public GenericParametrized(int maxCountAirbus, int maxCountPortoles, int pictureWidth, int pictureHeight)
{
MaxCountAirbus = maxCountAirbus;
CountAirbus = 0;
MaxCountPortoles = maxCountPortoles;
CountPortholes = 0;
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
_airbus = new ArrayList<T>();
_portholes = new ArrayList<U>();
}
public boolean add(T airbus)
{
if (airbus == null || CountAirbus >= MaxCountAirbus)
return false;
_airbus.add(airbus);
CountAirbus++;
return true;
}
public boolean add(U porthole)
{
if (porthole == null || CountPortholes >= MaxCountPortoles)
return false;
_portholes.add(porthole);
CountPortholes++;
return true;
}
public DrawningAirbus randomDrawingObject()
{
Random rand = new Random();
if (CountAirbus == 0 || CountPortholes == 0)
return null;
int ar = rand.nextInt(CountAirbus);
int port = rand.nextInt(CountPortholes);
DrawningAirbus drawningAirbus;
if (_airbus.get(ar) instanceof EntityPlane)
drawningAirbus = new DrawningPlane(
_airbus.get(ar).getSpeed(),
_airbus.get(ar).getWeight(),
_airbus.get(ar).getBodyColor(),
_portholes.get(port).getCount(),
((EntityPlane)_airbus.get(ar)).getAdditionalColor(),
((EntityPlane)_airbus.get(ar)).IsCompartment(),
((EntityPlane)_airbus.get(ar)).IsAdditionalEngine(),
_pictureWidth, _pictureHeight);
else
drawningAirbus = new DrawningAirbus(
_airbus.get(ar).getSpeed(),
_airbus.get(ar).getWeight(),
_airbus.get(ar).getBodyColor(),
_portholes.get(port).getCount(),
_pictureWidth, _pictureHeight);
return drawningAirbus;
}
}

View File

@ -0,0 +1,65 @@
package Generics;
import java.util.ArrayList;
import java.util.Iterator;
public class SetGeneric<T extends Object> {
// список объектов
private ArrayList<T> _places;
// кол-во объектов
private int maxCount;
public int Count()
{
return _places.size();
};
public SetGeneric(int count)
{
_places = new ArrayList<>(count);
maxCount = count;
}
// Добавление объекта в набор
public int Insert(T airbus)
{
return Insert(airbus, 0);
}
// Добавление объекта в набор на конкретную позицию
public int Insert(T airbus, int position)
{
if (position < 0 || position >= maxCount || Count() >= maxCount)
{
return -1;
}
_places.add(position, airbus);
return position;
}
// Удаление объекта из набора с конкретной позиции
public boolean Remove(int position)
{
if (position < 0 || position >= Count())
{
return false;
}
_places.remove(position);
return true;
}
// Получение объекта из набора по позиции
public T Get(int position)
{
if (position < 0 || position >= Count())
{
return null;
}
return _places.get(position);
}
public ArrayList<T> GetAirbus()
{
return _places;
}
}

6
src/Main.java Normal file
View File

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

View File

@ -0,0 +1,76 @@
package MovementStrategy;
public abstract class AbstractStrategy {
private IMoveableObject _moveableObject;
private Status _state = Status.NotInit;
protected int FieldWidth;
protected int 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;
_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(Direction.Left); }
protected boolean MoveRight() { return MoveTo(Direction.Right); }
protected boolean MoveUp() { return MoveTo(Direction.Up); }
protected boolean MoveDown() { return MoveTo(Direction.Down); }
// параметры
protected ObjectParameters GetObjectParameters() { return _moveableObject.GetObjectPosition(); }
// шаг
protected int GetStep()
{
if (_state != Status.InProgress)
{
return 0;
}
return _moveableObject.GetStep();
}
// перемещение
protected abstract void MoveToTarget();
// достигнута ли цель
protected abstract boolean IsTargetDestination();
// попытка перемещения по направлению
private boolean MoveTo(Direction directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject.CheckCanMove(directionType))
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}

View File

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

View File

@ -0,0 +1,24 @@
package MovementStrategy;
import Drawnings.*;
public class DrawningObjectAirbus implements IMoveableObject {
private DrawningAirbus _drawningAirbus = null;
public DrawningObjectAirbus(DrawningAirbus drawningAirbus)
{
_drawningAirbus = drawningAirbus;
}
public ObjectParameters GetObjectPosition()
{
if (_drawningAirbus == null || _drawningAirbus.entityAirbus == null)
{
return null;
}
return new ObjectParameters(_drawningAirbus.GetPosX(), _drawningAirbus.GetPosY(), _drawningAirbus.GetWidth(), _drawningAirbus.GetHeight());
}
public int GetStep() { return (int)_drawningAirbus.entityAirbus.Step; }
public boolean CheckCanMove(Direction direction) { return _drawningAirbus.CanMove(direction); }
public void MoveObject(Direction direction) { _drawningAirbus.MoveTransport(direction); }
}

View File

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

View File

@ -0,0 +1,53 @@
package MovementStrategy;
public class MoveToBorder extends AbstractStrategy {
@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;
}
// движение к цели
@Override
protected void MoveToTarget()
{
var objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
var diffX = FieldWidth;
if (Math.abs(diffX) > GetStep())
{
if (diffX < 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = FieldHeight;
if (Math.abs(diffY) > GetStep())
{
if (diffY < 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,53 @@
package MovementStrategy;
public class MoveToCenter extends AbstractStrategy {
@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;
}
// движение к цели
@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();
}
}
}
}

View File

@ -0,0 +1,25 @@
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
}