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

This commit is contained in:
Рачеевский Олег 2024-05-08 11:34:52 +04:00
parent 3562fd7940
commit 78b506ca02
12 changed files with 596 additions and 4 deletions

View File

@ -8,6 +8,13 @@ namespace Project_Catamaran.Drawnings;
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -37,12 +37,38 @@ public class DrawningSimpleCatamaran
/// <summary>
/// Ширина прорисовки катамарана
/// </summary>
private readonly int _drawningCatamaranWidth = 90;
private readonly int _drawningCatamaranWidth = 100;
/// <summary>
/// Высота прорисовки катамарана
/// </summary>
private readonly int _drawningCatamaranHeight = 60;
private readonly int _drawningCatamaranHeight = 85;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningCatamaranWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningCatamaranHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
/// <summary>
/// Пустой конструктор
@ -207,6 +233,7 @@ public class DrawningSimpleCatamaran
Pen pen = new(Color.Black);
pen.Width = 2;
Brush simpleBrush = new SolidBrush(EntitySimpleCatamaran.BodyColor);
@ -219,7 +246,7 @@ public class DrawningSimpleCatamaran
g.DrawLine(pen, _startPosX.Value + 70, _startPosY.Value + 30, _startPosX.Value + 90, _startPosY.Value + 40);
g.DrawLine(pen, _startPosX.Value + 70, _startPosY.Value + 50, _startPosX.Value + 90, _startPosY.Value + 40);
//отрисовка цвета палубы
g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 30, 60, 20);
g.FillEllipse(simpleBrush, _startPosX.Value + 5, _startPosY.Value + 30, 60, 20);
// отрисовка поплавков

View File

@ -35,6 +35,8 @@ partial class FormCatamaran
buttonRight = new Button();
pictureBoxCatamaran = new PictureBox();
buttonCreateCatamaran = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCatamaran).BeginInit();
SuspendLayout();
//
@ -117,11 +119,33 @@ partial class FormCatamaran
buttonCreateCatamaran.UseVisualStyleBackColor = true;
buttonCreateCatamaran.Click += buttonCreateCatamaran_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(606, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(182, 33);
comboBoxStrategy.TabIndex = 8;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(676, 51);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(112, 34);
buttonStrategyStep.TabIndex = 9;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormCatamaran
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateCatamaran);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
@ -143,4 +167,6 @@ partial class FormCatamaran
private Button buttonRight;
private PictureBox pictureBoxCatamaran;
private Button buttonCreateCatamaran;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}

View File

@ -1,4 +1,5 @@
using Project_Catamaran.Drawnings;
using Project_Catamaran.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -13,11 +14,19 @@ namespace Project_Catamaran;
public partial class FormCatamaran : Form
{
private DrawningSimpleCatamaran? _drawningSimpleCatamaran;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
public FormCatamaran()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
@ -59,6 +68,8 @@ public partial class FormCatamaran : Form
}
_drawningSimpleCatamaran.SetPictureSize(pictureBoxCatamaran.Width, pictureBoxCatamaran.Height);
_drawningSimpleCatamaran.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
@ -114,4 +125,40 @@ public partial class FormCatamaran : Form
}
}
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningSimpleCatamaran == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableSimpleCatamaran(_drawningSimpleCatamaran), pictureBoxCatamaran.Width, pictureBoxCatamaran.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,143 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Catamaran.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _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(IMoveableObject 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,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Catamaran.MovementStrategy;
public interface IMoveableObject
{
/// <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,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Catamaran.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder - GetStep() <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder - GetStep() <= FieldHeight && objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,59 @@
using Project_Catamaran.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Catamaran.MovementStrategy;
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,66 @@
using Project_Catamaran.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Catamaran.MovementStrategy;
public class MoveableSimpleCatamaran : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningSimpleCatamaran или его наследника
/// </summary>
private readonly DrawningSimpleCatamaran? _catamaran = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="catamaran">Объект класса DrawningSimpleCatamaran</param>
public MoveableSimpleCatamaran(DrawningSimpleCatamaran catamaran)
{
_catamaran = catamaran;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_catamaran == null || _catamaran.EntitySimpleCatamaran == null || !_catamaran.GetPosX.HasValue || !_catamaran.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_catamaran.GetPosX.Value, _catamaran.GetPosY.Value, _catamaran.GetWidth, _catamaran.GetHeight);
}
}
public int GetStep => (int)(_catamaran?.EntitySimpleCatamaran?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_catamaran == null || _catamaran.EntitySimpleCatamaran == null)
{
return false;
}
return _catamaran.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,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Catamaran.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Catamaran.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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Catamaran.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}