Compare commits

...

3 Commits

Author SHA1 Message Date
GokaPek
60f2e38cf7 Наследование 2023-10-09 20:56:25 +04:00
GokaPek
6c391ce4f7 Создание потомков 2023-10-07 17:44:27 +04:00
GokaPek
4d50d2fa27 Лаба 1 2023-10-03 14:57:43 +04:00
14 changed files with 657 additions and 99 deletions

View File

@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SelfPropelledArtilleryUnit.DrawningObjects;
namespace SelfPropelledArtilleryUnit.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
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;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SelfPropelledArtilleryUnit.DrawningObjects;
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningCar (паттерн Adapter)
/// </summary>
namespace SelfPropelledArtilleryUnit.MovementStrategy
{
public class DrawningObjectSPAU : IMoveableObject
{
private readonly DrawningSPAU? _drawningCar = null;
public DrawningObjectSPAU(DrawningSPAU drawningCar)
{
_drawningCar = drawningCar;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningCar == null || _drawningCar.EntitySPAU == null)
{
return null;
}
return new ObjectParameters(_drawningCar.GetPosX,
_drawningCar.GetPosY, _drawningCar.GetWidth, _drawningCar.GetHeight);
}
}
public int GetStep => (int)(_drawningCar?.EntitySPAU?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawningCar?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawningCar?.MoveTransport(direction);
}
}

View File

@ -4,8 +4,9 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SelfPropelledArtilleryUnit.Entities;
namespace SelfPropelledArtilleryUnit
namespace SelfPropelledArtilleryUnit.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
@ -15,7 +16,7 @@ namespace SelfPropelledArtilleryUnit
/// <summary>
/// Класс-сущность
/// </summary>
public EntitySPAU? EntitySPAU { get; private set; }
public EntitySPAU? EntitySPAU { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -27,11 +28,11 @@ namespace SelfPropelledArtilleryUnit
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
@ -46,30 +47,38 @@ namespace SelfPropelledArtilleryUnit
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="wing">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена,нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool wing, bool sportLine, int width, int height)
public DrawningSPAU(int speed, double weight, Color bodyColor, int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_carHeight >= height)
{
return false;
return;
}
if (_carWidth >= width)
{
return false;
return;
}
EntitySPAU = new EntitySPAU();
EntitySPAU.Init(speed, weight, bodyColor, additionalColor,
bodyKit, wing, sportLine);
return true;
EntitySPAU = new EntitySPAU(speed, weight, bodyColor);
}
public DrawningSPAU(int speed, double weight, Color bodyColor, int width, int height, int carWidth, int carHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_carWidth = carWidth;
_carHeight = carHeight;
if (_carHeight >= height)
{
return;
}
if (_carWidth >= width)
{
return;
}
EntitySPAU = new EntitySPAU(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
@ -78,7 +87,6 @@ namespace SelfPropelledArtilleryUnit
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
// TODO: Изменение x, y @
if (x < 0 || x > _pictureWidth - _carWidth)
{
x = 0;
@ -96,7 +104,7 @@ namespace SelfPropelledArtilleryUnit
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntitySPAU == null)
if (!CanMove(direction) || EntitySPAU == null)
{
return;
}
@ -104,56 +112,40 @@ namespace SelfPropelledArtilleryUnit
{
//влево
case DirectionType.Left:
if (_startPosX - EntitySPAU.Step > 0)
{
_startPosX -= (int)EntitySPAU.Step;
}
_startPosX -= (int)EntitySPAU.Step;
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntitySPAU.Step > 0)
{
_startPosY -= (int)EntitySPAU.Step;
}
_startPosY -= (int)EntitySPAU.Step;
break;
// вправо
case DirectionType.Right:
if (_startPosX + EntitySPAU.Step < _pictureWidth - _carWidth)
{
_startPosX += (int)EntitySPAU.Step;
}
_startPosX += (int)EntitySPAU.Step;
break;
//вниз
case DirectionType.Down:
if (_startPosY + EntitySPAU.Step < _pictureHeight - _carHeight)
{
_startPosY += (int)EntitySPAU.Step;
}
_startPosY += (int)EntitySPAU.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntitySPAU == null)
{
return;
}
Pen penBlack = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntitySPAU.AdditionalColor);
// обвесы
if (EntitySPAU.BodyKit)
{
//залповая усутановка
g.FillRectangle(additionalBrush, _startPosX + 15, _startPosY + 20, 20, 40);
g.DrawLine(penBlack, _startPosX + 5, _startPosY + 20, _startPosX + 15, _startPosY + 25);
}
//гусеницы
Brush brBlack = new SolidBrush(Color.Black);
Brush br = new SolidBrush(EntitySPAU.BodyColor);
Brush brBody = new SolidBrush(EntitySPAU.BodyColor);
g.FillEllipse(brBlack, _startPosX + 5, _startPosY + 50, 20, 20);
g.FillEllipse(brBlack, _startPosX + 30, _startPosY + 50, 20, 20);
g.FillEllipse(brBlack, _startPosX + 55, _startPosY + 50, 20, 20);
@ -166,7 +158,7 @@ namespace SelfPropelledArtilleryUnit
pointsGun[1].X = _startPosX + 40; pointsGun[1].Y = _startPosY + 45;
pointsGun[2].X = _startPosX + 135; pointsGun[2].Y = _startPosY + 5;
pointsGun[3].X = _startPosX + 130; pointsGun[3].Y = _startPosY + 0;
g.FillPolygon(br, pointsGun);
g.FillPolygon(brBody, pointsGun);
g.DrawPolygon(penBlack, pointsGun);
//корпус
Point[] pointsCorp = new Point[4];
@ -174,7 +166,7 @@ namespace SelfPropelledArtilleryUnit
pointsCorp[1].X = _startPosX + 10; pointsCorp[1].Y = _startPosY + 30;
pointsCorp[2].X = _startPosX + 130; pointsCorp[2].Y = _startPosY + 30;
pointsCorp[3].X = _startPosX + 135; pointsCorp[3].Y = _startPosY + 60;
g.FillPolygon(br, pointsCorp);
g.FillPolygon(brBody, pointsCorp);
g.DrawPolygon(penBlack, pointsCorp);
//башня
Point[] pointsHead = new Point[4];
@ -182,8 +174,48 @@ namespace SelfPropelledArtilleryUnit
pointsHead[1].X = _startPosX + 45; pointsHead[1].Y = _startPosY + 15;
pointsHead[2].X = _startPosX + 70; pointsHead[2].Y = _startPosY + 15;
pointsHead[3].X = _startPosX + 75; pointsHead[3].Y = _startPosY + 30;
g.FillPolygon(br, pointsHead);
g.FillPolygon(brBody, pointsHead);
g.DrawPolygon(penBlack, pointsHead);
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// /// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _carWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _carHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntitySPAU == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntitySPAU.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntitySPAU.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntitySPAU.Step < _pictureWidth - _carWidth,
//вниз
DirectionType.Down => _startPosY + EntitySPAU.Step < _pictureHeight - _carHeight,
_ => false,
};
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SelfPropelledArtilleryUnit.Entities;
namespace SelfPropelledArtilleryUnit.DrawningObjects
{
public class DrawningSPAUchild : DrawningSPAU
{
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия залповой установки</param>
public DrawningSPAUchild(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, int width, int height) : base(speed, weight, bodyColor, width, height)
{
if (EntitySPAU != null)
{
EntitySPAU = new EntitySPAUchild(speed, weight, bodyColor, additionalColor, bodyKit);
}
}
public override void DrawTransport(Graphics g)
{
if (EntitySPAU is not EntitySPAUchild entitySPAUchild)
{
return;
}
Pen penBlack = new Pen(Color.Black);
Brush additionalBrush = new SolidBrush(entitySPAUchild.AdditionalColor);
// обвесы
if (entitySPAUchild.BodyKit)
{
//залповая усутановка
g.FillRectangle(additionalBrush, _startPosX + 15, _startPosY + 20, 20, 40);
g.DrawLine(penBlack, _startPosX + 5, _startPosY + 20, _startPosX + 15, _startPosY + 25);
}
base.DrawTransport(g);
}
}
}

View File

@ -1,13 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit
namespace SelfPropelledArtilleryUnit.Entities
{
public class EntitySPAU
{
/// <summary>
/// Скорость
/// </summary>
@ -21,23 +16,7 @@ namespace SelfPropelledArtilleryUnit
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия обвеса
/// </summary>
public bool BodyKit { get; private set; }
/// <summary>
/// Признак (опция) наличия антикрыла
/// </summary>
public bool Wing { get; private set; }
/// <summary>
/// Признак (опция) наличия гоночной полосы
/// </summary>
public bool SportLine { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// Шаг перемещения САУ
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
@ -46,20 +25,10 @@ namespace SelfPropelledArtilleryUnit
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="wing">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool wing, bool sportLine)
{
public EntitySPAU(int speed, double weight, Color bodyColor) {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Wing = wing;
SportLine = sportLine;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Entities
{
public class EntitySPAUchild : EntitySPAU
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия залповой установки
/// </summary>
public bool BodyKit { get; private set; }
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия залповой установки</param>
public EntitySPAUchild(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
BodyKit = bodyKit;
}
}
}

View File

@ -34,6 +34,9 @@
buttonDown = new Button();
buttonLeft = new Button();
buttonRight = new Button();
buttonCreateParent = new Button();
buttonStep = new Button();
comboBoxStrategy = new ComboBox();
((System.ComponentModel.ISupportInitialize)pictureBoxSPAU).BeginInit();
SuspendLayout();
//
@ -49,11 +52,11 @@
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(22, 410);
buttonCreate.Location = new Point(134, 412);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(82, 29);
buttonCreate.Size = new Size(301, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.Text = "Создать САУ с залповой установкой";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
@ -101,11 +104,44 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonCreateParent
//
buttonCreateParent.Location = new Point(12, 409);
buttonCreateParent.Name = "buttonCreateParent";
buttonCreateParent.Size = new Size(116, 30);
buttonCreateParent.TabIndex = 6;
buttonCreateParent.Text = "Создать САУ";
buttonCreateParent.UseVisualStyleBackColor = true;
buttonCreateParent.Click += buttonCreateParent_Click;
//
// buttonStep
//
buttonStep.Location = new Point(794, 65);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(76, 30);
buttonStep.TabIndex = 7;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "0", "1" });
comboBoxStrategy.Location = new Point(767, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(103, 28);
comboBoxStrategy.TabIndex = 8;
//
// Form
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStep);
Controls.Add(buttonCreateParent);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
@ -127,5 +163,8 @@
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private Button buttonCreateParent;
private Button buttonStep;
private ComboBox comboBoxStrategy;
}
}

View File

@ -1,3 +1,6 @@
using SelfPropelledArtilleryUnit.DrawningObjects;
using SelfPropelledArtilleryUnit.MovementStrategy;
namespace SelfPropelledArtilleryUnit
{
public partial class Form : System.Windows.Forms.Form
@ -6,6 +9,12 @@ namespace SelfPropelledArtilleryUnit
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningSPAU? _drawningSPAU;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
@ -22,14 +31,12 @@ namespace SelfPropelledArtilleryUnit
{
return;
}
Bitmap bmp = new(pictureBoxSPAU.Width,
pictureBoxSPAU.Height);
Bitmap bmp = new(pictureBoxSPAU.Width, pictureBoxSPAU.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningSPAU.DrawTransport(gr);
pictureBoxSPAU.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
@ -38,26 +45,33 @@ namespace SelfPropelledArtilleryUnit
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawningSPAU = new DrawningSPAU();
_drawningSPAU.Init(random.Next(100, 300),
_drawningSPAU = new DrawningSPAUchild(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
random.Next(0, 256)), true,
pictureBoxSPAU.Width, pictureBoxSPAU.Height);
_drawningSPAU.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void buttonCreateParent_Click(object sender, EventArgs e)
{
Random random = new();
_drawningSPAU = new DrawningSPAU(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
pictureBoxSPAU.Width, pictureBoxSPAU.Height);
_drawningSPAU.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if(_drawningSPAU == null)
{
if (_drawningSPAU == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
@ -78,5 +92,43 @@ namespace SelfPropelledArtilleryUnit
}
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningSPAU == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectSPAU(_drawningSPAU), pictureBoxSPAU.Width,
pictureBoxSPAU.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SelfPropelledArtilleryUnit.DrawningObjects;
namespace SelfPropelledArtilleryUnit.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
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,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
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;
}
protected override 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,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
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 + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -8,8 +8,6 @@ namespace SelfPropelledArtilleryUnit
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form());
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}