Лабораторная работа №2

This commit is contained in:
MatveyPetrov 2024-02-06 17:05:23 +04:00
parent 56bcaa4f0c
commit ca87f5d55d
12 changed files with 590 additions and 13 deletions

View File

@ -11,6 +11,11 @@ namespace ProectMilitaryAircraft.Draw;
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -44,6 +44,27 @@ public class DrawningAircraft
/// </summary>
private readonly int _drawingMilitaryAircraftHeight = 110;
/// <summary>
/// Координа Х
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningMilitaryAircraftWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawingMilitaryAircraftHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
@ -148,20 +169,24 @@ public class DrawningAircraft
return true;
//Вправо
case DirectionType.Right:
#pragma warning disable CS8629 // Тип значения, допускающего NULL, может быть NULL.
if (_startPosX.Value + EntityAircraft.Step <= _pictureWidth.Value)
{
if (_startPosX + 98 <= _pictureWidth)
_startPosX += (int)EntityAircraft.Step;
}
#pragma warning restore CS8629 // Тип значения, допускающего NULL, может быть NULL.
return true;
//Влево
case DirectionType.Down:
#pragma warning disable CS8629 // Тип значения, допускающего NULL, может быть NULL.
if (_startPosY.Value + EntityAircraft.Step <= _pictureHeight.Value)
{
if (_startPosY + 90 <= _pictureHeight)
_startPosY += (int)EntityAircraft.Step;
}
#pragma warning restore CS8629 // Тип значения, допускающего NULL, может быть NULL.
return true;
default:
return false;
@ -207,6 +232,4 @@ public class DrawningAircraft
g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 50, _startPosX.Value + 60, _startPosY.Value + 55);
}
}

View File

@ -35,6 +35,8 @@
buttonRight = new Button();
buttonDown = new Button();
buttonCreateA = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxMilitaryAircraft).BeginInit();
SuspendLayout();
//
@ -43,14 +45,14 @@
pictureBoxMilitaryAircraft.Dock = DockStyle.Fill;
pictureBoxMilitaryAircraft.Location = new Point(0, 0);
pictureBoxMilitaryAircraft.Name = "pictureBoxMilitaryAircraft";
pictureBoxMilitaryAircraft.Size = new Size(1108, 499);
pictureBoxMilitaryAircraft.Size = new Size(953, 651);
pictureBoxMilitaryAircraft.TabIndex = 0;
pictureBoxMilitaryAircraft.TabStop = false;
//
// buttonCreateMA
//
buttonCreateMA.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateMA.Location = new Point(12, 464);
buttonCreateMA.Location = new Point(12, 616);
buttonCreateMA.Name = "buttonCreateMA";
buttonCreateMA.Size = new Size(172, 23);
buttonCreateMA.TabIndex = 1;
@ -65,7 +67,7 @@
buttonLeft.BackgroundImage = Properties.Resources.Left;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.ForeColor = SystemColors.ControlLightLight;
buttonLeft.Location = new Point(979, 458);
buttonLeft.Location = new Point(824, 610);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
@ -79,7 +81,7 @@
buttonUp.BackgroundImage = Properties.Resources.Up;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.ForeColor = SystemColors.ControlLightLight;
buttonUp.Location = new Point(1020, 417);
buttonUp.Location = new Point(865, 569);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 3;
@ -93,7 +95,7 @@
buttonRight.BackgroundImage = Properties.Resources.Right;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.ForeColor = SystemColors.ControlLightLight;
buttonRight.Location = new Point(1061, 458);
buttonRight.Location = new Point(906, 610);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 4;
@ -107,7 +109,7 @@
buttonDown.BackgroundImage = Properties.Resources.Down;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.ForeColor = SystemColors.ControlLightLight;
buttonDown.Location = new Point(1020, 458);
buttonDown.Location = new Point(865, 610);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 5;
@ -117,7 +119,7 @@
// buttonCreateA
//
buttonCreateA.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateA.Location = new Point(199, 464);
buttonCreateA.Location = new Point(199, 616);
buttonCreateA.Name = "buttonCreateA";
buttonCreateA.Size = new Size(172, 23);
buttonCreateA.TabIndex = 6;
@ -125,11 +127,35 @@
buttonCreateA.UseVisualStyleBackColor = true;
buttonCreateA.Click += ButtonCreateA_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К ценру", "К краю" });
comboBoxStrategy.Location = new Point(823, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(870, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormMilitaryAircraft
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1108, 499);
ClientSize = new Size(953, 651);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateA);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
@ -152,5 +178,7 @@
private Button buttonRight;
private Button buttonDown;
private Button buttonCreateA;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -8,16 +8,30 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProectMilitaryAircraft.Draw;
using ProectMilitaryAircraft.MovementStrategy;
namespace ProectMilitaryAircraft
{
public partial class FormMilitaryAircraft : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningAircraft? _DrawningAircraft;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategys? _AbstractStrategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormMilitaryAircraft()
{
InitializeComponent();
_AbstractStrategy = null;
}
private void Draw()
@ -45,7 +59,7 @@ namespace ProectMilitaryAircraft
break;
case nameof(DrawningMilitaryAircraft):
_DrawningAircraft = new DrawningMilitaryAircraft(rnd.Next(100, 300), rnd.Next(1000, 3000),
_DrawningAircraft = new DrawningMilitaryAircraft(rnd.Next(100, 300), rnd.Next(1000, 3000),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)), pictureBoxMilitaryAircraft.Width, pictureBoxMilitaryAircraft.Height);
@ -55,7 +69,8 @@ namespace ProectMilitaryAircraft
}
_DrawningAircraft.SetpictureSize(pictureBoxMilitaryAircraft.Width, pictureBoxMilitaryAircraft.Height);
_DrawningAircraft.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100));
_AbstractStrategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
@ -104,5 +119,43 @@ namespace ProectMilitaryAircraft
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_DrawningAircraft == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_AbstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_AbstractStrategy == null) { return; }
_AbstractStrategy.SetData(new MoveableAircraft(_DrawningAircraft), pictureBoxMilitaryAircraft.Width, pictureBoxMilitaryAircraft.Height);
}
if (_AbstractStrategy == null) { return; }
comboBoxStrategy.Enabled = false;
_AbstractStrategy.MakeStep();
Draw();
if (_AbstractStrategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_AbstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,139 @@
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.MovementStrategy;
/// <summary>
/// класс - стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategys
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObjects? _moveableObjects;
/// <summary>
/// Статус перемеения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObjects">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObjects moveableObjects, int width, int height)
{
if(moveableObjects == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObjects = moveableObjects;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTrgetDestansion())
{
_state |= StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns> Результат перемещения (true - да, false - неи)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns> Результат перемещения (true - да, false - неи)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение Вверх
/// </summary>
/// <returns> Результат перемещения (true - да, false - неи)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение Вниз
/// </summary>
/// <returns> Результат перемещения (true - да, false - неи)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObjects?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObjects?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTrgetDestansion();
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObjects?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObjects
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction"> Направление</param>
/// <returns>true - Объект перемещен, false - перемещение невозможно-v</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.MovementStrategy;
public class MoveToBorder : AbstractStrategys
{
protected override bool IsTrgetDestansion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.MovementStrategy;
public class MoveToCenter : AbstractStrategys
{
protected override bool IsTrgetDestansion()
{
ObjectParameters? objParams = GetObjectParameters;
if(objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2
&& objParams.ObjectMiddleVertical +GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if(objParams == null) { return;}
int diffx = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffx) > GetStep())
{
if (diffx > 0) { MoveLeft(); } else { MoveRight(); }
}
int diffy = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffy) > GetStep())
{
if (diffy > 0) { MoveUp(); } else { MoveDown(); }
}
}
}

View File

@ -0,0 +1,69 @@
using ProectMilitaryAircraft.Draw;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.MovementStrategy;
/// <summary>
/// Класс - реалицация IMoveableObjects с использованием DrawningAircraft
/// </summary>
public class MoveableAircraft : IMoveableObjects
{
/// <summary>
/// Поле - объект класса DrawningAircraft или его наследника
/// </summary>
private readonly DrawningAircraft? _Air = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="Air">Объект класса DrawningAircraft</param>
public MoveableAircraft(DrawningAircraft Air)
{
_Air = Air;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_Air == null || _Air.EntityAircraft == null || !_Air.GetPosX.HasValue || !_Air.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_Air.GetPosX.Value, _Air.GetPosY.Value, _Air.GetWidth, _Air.GetHeight);
}
}
public int GetStep => (int)(_Air?.EntityAircraft?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if(_Air == null || _Air.EntityAircraft == null)
{
return false;
}
return _Air.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,29 @@
namespace ProectMilitaryAircraft.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
///Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4,
}

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.MovementStrategy;
/// <summary>
/// Параметры - координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координата Х
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _width;
/// <summary>
/// Середнина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _height / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}