PIbd-11 Kudrinsky_O.S. LabWork02 Simple #4

Closed
8floom wants to merge 4 commits from LabWork02 into LabWork01
16 changed files with 791 additions and 158 deletions

View File

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

View File

@ -0,0 +1,70 @@
using ProjectContainerShip.Entities;
namespace ProjectContainerShip.Drawings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningContainerShip : DrawningShip
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodycolor">Основной цвет</param>
/// <param name="additionalcolor">Дополнительный цвет</param>
/// <param name="crane">Признак наличия крана</param>
/// <param name="container">Признак наличия контейнеров</param>
public DrawningContainerShip(int speed, double weight, Color bodycolor, Color additionalcolor, bool crane, bool container) : base(120,40)
{
EntityShip = new EntityContainerShip(speed, weight, bodycolor, additionalcolor, crane, container);
}
public override void DrawTransport(Graphics g)
{
if (EntityShip == null || EntityShip is not EntityContainerShip containerShip || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(containerShip.AdditionalColor);
if (containerShip.Container)
{
// Верхний маленький контейнер
Point[] container =
{
new Point((int)_startPosX + 30, (int)_startPosY + 10),
new Point((int)_startPosX + 30, (int)_startPosY ),
new Point((int)_startPosX + 55, (int)_startPosY),
new Point((int)_startPosX + 55, (int)_startPosY + 10)
};
g.FillPolygon(additionalBrush, container);
g.DrawPolygon(pen, container);
//Контейнер под маленьким контейнером
g.FillRectangle(additionalBrush, (int)_startPosX + 20, (int)_startPosY + 10, 27, 10);
g.DrawRectangle(pen, (int)_startPosX + 20, (int)_startPosY + 10, 27, 10);
}
base.DrawTransport(g);
if (containerShip.Crane)
{
g.DrawLine(pen, (int)_startPosX + 70, (int)_startPosY + 10, (int)_startPosX + 70, (int)_startPosY);
g.DrawLine(pen, (int)_startPosX + 70, (int)_startPosY, (int)_startPosX + 110, (int)_startPosY);
g.DrawLine(pen, (int)_startPosX + 70, (int)_startPosY, (int)_startPosX + 110, (int)_startPosY + 5);
g.DrawLine(pen, (int)_startPosX + 110, (int)_startPosY, (int)_startPosX + 110, (int)_startPosY + 30);
//Хваталка контейнера
g.DrawLine(pen, (int)(_startPosX + 100), (int)(_startPosY + 30), (int)_startPosX + 120, (int)(_startPosY + 30));
g.DrawLine(pen, (int)(_startPosX + 100), (int)(_startPosY + 30), (int)_startPosX + 100, (int)(_startPosY + 35));
g.DrawLine(pen, (int)(_startPosX + 120), (int)(_startPosY + 30), (int)_startPosX + 120, (int)(_startPosY + 35));
}
}
}

View File

@ -1,11 +1,18 @@
namespace ProjectContainerShip;
using ProjectContainerShip.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class DrawningContainerShip
namespace ProjectContainerShip.Drawings;
public class DrawningShip
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityContainerShip? EntityContainerShip { get; private set; }
public EntityShip? EntityShip { get; protected set; }
/// <summary>
/// Ширина окна
@ -20,42 +27,76 @@ public class DrawningContainerShip
/// <summary>
/// Левая координата прорисовки контейнеровоза
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки контейнеровоза
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки контейнеровоза
/// </summary>
private readonly int _drawningContainerShipWidth = 120;
private readonly int _drawningContainerShipWidth = 100;
/// <summary>
/// Высота прорисовки контейнеровоза
/// </summary>
private readonly int _drawningContainerShipHeight = 40;
private readonly int _drawningContainerShipHeight = 30;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodycolor">Основной цвет</param>
/// <param name="additionalcolor">Дополнительный цвет</param>
/// <param name="crane">Признак наличия крана</param>
/// <param name="container">Признак наличия контейнеров</param>
public void Init(int speed, double weight, Color bodycolor, Color additionalcolor, bool crane, bool container)
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningContainerShipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningContainerShipHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningShip()
{
EntityContainerShip = new EntityContainerShip();
EntityContainerShip.Init(speed,weight,bodycolor,additionalcolor,crane,container);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodycolor">Основной цвет</param>
public DrawningShip(int speed, double weight, Color bodycolor) : this()
{
EntityShip = new EntityShip(speed, weight, bodycolor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningContainerShipWidth">Ширина прорисовки корабля</param>
/// <param name="drawningContainerShipHeight">Высота прорисовки корабля</param>
protected DrawningShip(int drawningContainerShipWidth, int drawningContainerShipHeight) : this()
{
_drawningContainerShipWidth = drawningContainerShipWidth;
_drawningContainerShipHeight = drawningContainerShipHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
@ -64,7 +105,7 @@ public class DrawningContainerShip
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
if (_drawningContainerShipWidth > width || _drawningContainerShipHeight> height)
if (_drawningContainerShipWidth > width || _drawningContainerShipHeight > height)
{
return false;
}
@ -98,7 +139,7 @@ public class DrawningContainerShip
{
return;
}
if (x + _drawningContainerShipWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningContainerShipWidth;
@ -121,7 +162,7 @@ public class DrawningContainerShip
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityContainerShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@ -130,30 +171,30 @@ public class DrawningContainerShip
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityContainerShip.Step > 0)
if (_startPosX.Value - EntityShip.Step > 0)
{
_startPosX -= (int)EntityContainerShip.Step;
_startPosX -= (int)EntityShip.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityContainerShip.Step > 0)
if (_startPosY.Value - EntityShip.Step > 0)
{
_startPosY -= (int)EntityContainerShip.Step;
_startPosY -= (int)EntityShip.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + _drawningContainerShipWidth + EntityContainerShip.Step < _pictureWidth)
if (_startPosX.Value + _drawningContainerShipWidth + EntityShip.Step < _pictureWidth)
{
_startPosX += (int)EntityContainerShip.Step;
_startPosX += (int)EntityShip.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + _drawningContainerShipHeight + EntityContainerShip.Step < _pictureHeight)
if (_startPosY.Value + _drawningContainerShipHeight + EntityShip.Step < _pictureHeight)
{
_startPosY += (int)EntityContainerShip.Step;
_startPosY += (int)EntityShip.Step;
}
return true;
default:
@ -165,15 +206,14 @@ public class DrawningContainerShip
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityContainerShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityContainerShip.AdditionalColor);
//Корпус контейнеровоза
g.DrawPolygon(pen, new Point[]
@ -184,8 +224,7 @@ public class DrawningContainerShip
}
);
Brush br = new SolidBrush(EntityContainerShip.BodyColor);
Brush br = new SolidBrush(EntityShip.BodyColor);
g.FillPolygon(br, new Point[]
{
new Point((int)_startPosX+10,(int)_startPosY+20),new Point((int)_startPosX+100,(int)_startPosY+20),
@ -200,44 +239,7 @@ public class DrawningContainerShip
g.DrawLine(pen, (int)_startPosX + 26, (int)_startPosY + 31, (int)_startPosX + 30, (int)_startPosY + 31);
//Длинный контейнер справа
g.DrawRectangle(pen,(int)_startPosX+40,(int)_startPosY+10,57,10);
g.DrawRectangle(pen, (int)_startPosX + 40, (int)_startPosY + 10, 57, 10);
g.FillRectangle(br, (int)_startPosX + 40, (int)_startPosY + 10, 57, 10);
//Кран
if (EntityContainerShip.Crane)
{
g.DrawLine(pen, (int)_startPosX + 70, (int)_startPosY + 10, (int)_startPosX + 70, (int)_startPosY);
g.DrawLine(pen, (int)_startPosX + 70, (int)_startPosY, (int)_startPosX + 110, (int)_startPosY);
g.DrawLine(pen, (int)_startPosX + 70, (int)_startPosY, (int)_startPosX + 110, (int)_startPosY + 5);
g.DrawLine(pen, (int)_startPosX + 110, (int)_startPosY, (int)_startPosX + 110, (int)_startPosY + 30);
//Хваталка крана
g.DrawLine(pen,(int)(_startPosX + 100),(int)(_startPosY + 30), (int)_startPosX + 120, (int)(_startPosY + 30));
g.DrawLine(pen, (int)(_startPosX + 100), (int)(_startPosY + 30), (int)_startPosX + 100, (int)(_startPosY + 35));
g.DrawLine(pen, (int)(_startPosX + 120), (int)(_startPosY + 30), (int)_startPosX + 120, (int)(_startPosY + 35));
}
//Контейнер
if (EntityContainerShip.Container)
{
// Верхний маленький контейнер
Point[] container =
{
new Point((int)_startPosX + 30, (int)_startPosY + 10),
new Point((int)_startPosX + 30, (int)_startPosY ),
new Point((int)_startPosX + 55, (int)_startPosY),
new Point((int)_startPosX + 55, (int)_startPosY + 10)
};
g.FillPolygon(additionalBrush, container);
g.DrawPolygon(pen, container);
//Контейнер под маленьким контейнером
g.FillRectangle(additionalBrush, (int)_startPosX + 20, (int)_startPosY + 10, 27, 10);
g.DrawRectangle(pen, (int)_startPosX + 20, (int)_startPosY + 10, 27, 10);
}
}
}

View File

@ -0,0 +1,39 @@
namespace ProjectContainerShip.Entities;
/// <summary>
/// Класс-сущность Контейнеровоз
/// </summary>
public class EntityContainerShip : EntityShip
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия крана
/// </summary>
public bool Crane { get; private set; }
/// <summary>
/// Признак (опция) наличия контейнеров
/// </summary>
public bool Container { get; private set; }
/// <summary>
/// Инициализация поле объекта-класса Контейнеровоза
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес контейнеровоза</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="crane">Признак наличия крана</param>
/// <param name="container">Признак наличия контейнеров</param>
public EntityContainerShip(int speed, double weight, Color bodyColor, Color additionalColor, bool crane, bool container) : base(speed,weight,bodyColor)
{
AdditionalColor = additionalColor;
Crane = crane;
Container = container;
}
}

View File

@ -0,0 +1,40 @@
namespace ProjectContainerShip.Entities;
/// <summary>
/// Класс-сущность "Корабль"
/// </summary>
public class EntityShip
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения грузового судна
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес контейнеровоза</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityShip(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -1,62 +0,0 @@
namespace ProjectContainerShip;
/// <summary>
/// Класс-сущность Контейнеровоз
/// </summary>
public class EntityContainerShip
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия крана
/// </summary>
public bool Crane { get; private set; }
/// <summary>
/// Признак (опция) наличия контейнеров
/// </summary>
public bool Container { get; private set; }
/// <summary>
/// Шаг перемещения грузового судна
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
///
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес контейнеровоза</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="crane">Признак наличия крана</param>
/// <param name="container">Признак наличия контейнеров</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool crane, bool container)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Crane = crane;
Container = container;
}
}

View File

@ -1,4 +1,5 @@
namespace ProjectContainerShip

namespace ProjectContainerShip
{
partial class FormContainerShip
{
@ -34,6 +35,9 @@
buttonRight = new Button();
buttonDown = new Button();
buttonUp = new Button();
buttonCreateShip = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxContainerShip).BeginInit();
SuspendLayout();
//
@ -45,15 +49,16 @@
pictureBoxContainerShip.Size = new Size(1256, 529);
pictureBoxContainerShip.TabIndex = 0;
pictureBoxContainerShip.TabStop = false;
pictureBoxContainerShip.Click += pictureBoxContainerShip_Click;
//
// buttonCreateContainerShip
//
buttonCreateContainerShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateContainerShip.Location = new Point(12, 457);
buttonCreateContainerShip.Name = "buttonCreateContainerShip";
buttonCreateContainerShip.Size = new Size(150, 46);
buttonCreateContainerShip.Size = new Size(316, 46);
buttonCreateContainerShip.TabIndex = 1;
buttonCreateContainerShip.Text = "Создать";
buttonCreateContainerShip.Text = "Создать контейнеровоз";
buttonCreateContainerShip.UseVisualStyleBackColor = true;
buttonCreateContainerShip.Click += ButtonCreateContainerShip_Click;
//
@ -105,11 +110,47 @@
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonCreateShip
//
buttonCreateShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateShip.Location = new Point(358, 457);
buttonCreateShip.Name = "buttonCreateShip";
buttonCreateShip.Size = new Size(316, 46);
buttonCreateShip.TabIndex = 6;
buttonCreateShip.Text = "Создать корабль";
buttonCreateShip.UseVisualStyleBackColor = true;
buttonCreateShip.Click += ButtonCreateShip_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру ", "К краю" });
comboBoxStrategy.Location = new Point(1002, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(242, 40);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(1094, 58);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(150, 46);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormContainerShip
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1256, 529);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateShip);
Controls.Add(buttonUp);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
@ -122,6 +163,11 @@
ResumeLayout(false);
}
private void pictureBoxContainerShip_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
@ -132,5 +178,8 @@
private Button buttonRight;
private Button buttonDown;
private Button buttonUp;
private Button buttonCreateShip;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,4 +1,6 @@
using System;
using ProjectContainerShip.Drawings;
using ProjectContainerShip.MovementStrategy;
namespace ProjectContainerShip;
@ -10,7 +12,12 @@ public partial class FormContainerShip : Form
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningContainerShip? _drawningContainerShip;
private DrawningShip? _drawningShip;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
@ -18,6 +25,7 @@ public partial class FormContainerShip : Form
public FormContainerShip()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -25,34 +33,56 @@ public partial class FormContainerShip : Form
/// </summary>
private void Draw()
{
if (_drawningContainerShip == null)
if (_drawningShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxContainerShip.Width, pictureBoxContainerShip.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningContainerShip.DrawTransport(gr);
_drawningShip.DrawTransport(gr);
pictureBoxContainerShip.Image = bmp;
}
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningShip):
_drawningShip = new DrawningShip(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningContainerShip):
_drawningShip = new DrawningContainerShip(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)));
break;
default:
return;
}
_drawningShip.SetPictureSize(pictureBoxContainerShip.Width, pictureBoxContainerShip.Height);
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать контейнеровоз"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateContainerShip_Click(object sender, EventArgs e)
{
Random random = new();
_drawningContainerShip = new DrawningContainerShip();
_drawningContainerShip.Init(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)));
_drawningContainerShip.SetPictureSize(pictureBoxContainerShip.Width, pictureBoxContainerShip.Height);
_drawningContainerShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonCreateContainerShip_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningContainerShip));
/// <summary>
/// Обработка нажатия кнопки "Создать корабль"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateShip_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningShip));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
@ -61,7 +91,7 @@ public partial class FormContainerShip : Form
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningContainerShip == null)
if (_drawningShip == null)
{
return;
}
@ -71,16 +101,16 @@ public partial class FormContainerShip : Form
switch (name)
{
case "buttonUp":
result = _drawningContainerShip.MoveTransport(DirectionType.Up);
result = _drawningShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningContainerShip.MoveTransport(DirectionType.Down);
result = _drawningShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningContainerShip.MoveTransport(DirectionType.Left);
result = _drawningShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningContainerShip.MoveTransport(DirectionType.Right);
result = _drawningShip.MoveTransport(DirectionType.Right);
break;
}
@ -89,4 +119,44 @@ public partial class FormContainerShip : Form
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningShip == null) return;
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableShip(_drawningShip), pictureBoxContainerShip.Width, pictureBoxContainerShip.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

View File

@ -0,0 +1,132 @@
namespace ProjectContainerShip.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObjects? _moveableObject;
/// <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="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObjects moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_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 => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,21 @@
namespace ProjectContainerShip.MovementStrategy;
public interface IMoveableObjects
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,31 @@
namespace ProjectContainerShip.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null) return false;
return objParams.RightBorder + GetStep() >= FieldWidth
&& objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null) return;
int diffX = objParams.LeftBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,54 @@
namespace ProjectContainerShip.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
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,64 @@
using ProjectContainerShip.Drawings;
namespace ProjectContainerShip.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObjects с использованием DrawningShip
/// </summary>
public class MoveableShip : IMoveableObjects
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// </summary>
private readonly DrawningShip? _ship = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="ship">Объект класса DrawningShip</param>
public MoveableShip(DrawningShip ship)
{
_ship = ship;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_ship == null || _ship.EntityShip == null || !_ship.GetPosX.HasValue || !_ship.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_ship.GetPosX.Value, _ship.GetPosY.Value, _ship.GetWidth, _ship.GetHeight);
}
}
public int GetStep => (int)(_ship?.EntityShip?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_ship == null || _ship.EntityShip == null)
{
return false;
}
return _ship.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,27 @@
namespace ProjectContainerShip.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,69 @@
namespace ProjectContainerShip.MovementStrategy;
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </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 + _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

@ -0,0 +1,22 @@
namespace ProjectContainerShip.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}