From 57e2f225a37965c54cb70b1637161582489863ae Mon Sep 17 00:00:00 2001 From: victinass Date: Fri, 1 Mar 2024 20:00:22 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=962?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Battleship/Drawings/DirectionType.cs | 5 + .../Battleship/Drawings/DrawingBattleship.cs | 4 +- .../Battleship/Drawings/DrawingWarship.cs | 22 ++- .../Battleship/Entities/EntityBattleship.cs | 9 +- .../Battleship/FormBattleship.Designer.cs | 28 ++++ Battleship/Battleship/FormBattleship.cs | 57 ++++++++ .../MovementStrategy/AbstractStrategy.cs | 137 ++++++++++++++++++ .../MovementStrategy/IMoveableObjectcs.cs | 21 +++ .../MovementStrategy/MoveToBorder.cs | 40 +++++ .../MovementStrategy/MoveToCenter.cs | 61 ++++++++ .../MovementStrategy/MoveableWarship.cs | 64 ++++++++ .../MovementStrategy/MovementDirection.cs | 27 ++++ .../MovementStrategy/ObjectParameters.cs | 72 +++++++++ .../MovementStrategy/StrategyStatus.cs | 22 +++ 14 files changed, 559 insertions(+), 10 deletions(-) create mode 100644 Battleship/Battleship/MovementStrategy/AbstractStrategy.cs create mode 100644 Battleship/Battleship/MovementStrategy/IMoveableObjectcs.cs create mode 100644 Battleship/Battleship/MovementStrategy/MoveToBorder.cs create mode 100644 Battleship/Battleship/MovementStrategy/MoveToCenter.cs create mode 100644 Battleship/Battleship/MovementStrategy/MoveableWarship.cs create mode 100644 Battleship/Battleship/MovementStrategy/MovementDirection.cs create mode 100644 Battleship/Battleship/MovementStrategy/ObjectParameters.cs create mode 100644 Battleship/Battleship/MovementStrategy/StrategyStatus.cs diff --git a/Battleship/Battleship/Drawings/DirectionType.cs b/Battleship/Battleship/Drawings/DirectionType.cs index 7ed8765..dee01fc 100644 --- a/Battleship/Battleship/Drawings/DirectionType.cs +++ b/Battleship/Battleship/Drawings/DirectionType.cs @@ -4,6 +4,11 @@ /// public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, + /// /// Вверх /// diff --git a/Battleship/Battleship/Drawings/DrawingBattleship.cs b/Battleship/Battleship/Drawings/DrawingBattleship.cs index dfb481f..fdb8d10 100644 --- a/Battleship/Battleship/Drawings/DrawingBattleship.cs +++ b/Battleship/Battleship/Drawings/DrawingBattleship.cs @@ -19,9 +19,9 @@ public class DrawingBattleship : DrawingWarship /// Признак наличия башни /// - public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base (129, 60) + public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 60) { - //Warship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor); + EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor); } public override void DrawTransport(Graphics g) diff --git a/Battleship/Battleship/Drawings/DrawingWarship.cs b/Battleship/Battleship/Drawings/DrawingWarship.cs index 7d04815..2480935 100644 --- a/Battleship/Battleship/Drawings/DrawingWarship.cs +++ b/Battleship/Battleship/Drawings/DrawingWarship.cs @@ -39,6 +39,26 @@ public class DrawingWarship /// private readonly int _drawingWarshipHeight = 40; + /// + /// Координата Х объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawingWarshipWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawingWarshipHeight; + /// /// Пустой конструктор /// @@ -73,7 +93,7 @@ public class DrawingWarship } /// - /// + /// Установка границ поля /// /// Ширина поля /// Высота поля diff --git a/Battleship/Battleship/Entities/EntityBattleship.cs b/Battleship/Battleship/Entities/EntityBattleship.cs index 3f34b2f..c961dc1 100644 --- a/Battleship/Battleship/Entities/EntityBattleship.cs +++ b/Battleship/Battleship/Entities/EntityBattleship.cs @@ -3,12 +3,8 @@ /// /// Класс-сущность Линкор /// -internal class EntityBattleship : EntityWarship +public class EntityBattleship : EntityWarship { - public EntityBattleship(int speed, double weight, Color bodyColor) : base(speed, weight, bodyColor) - { - } - /// /// Скорость /// @@ -45,14 +41,13 @@ internal class EntityBattleship : EntityWarship /// public double Step => Speed * 100 / Weight; - /// /// Инициализация полей объекта-класса линкора /// /// /// /// - public void EntityWarship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) + public EntityBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(speed, weight, bodyColor) { Speed = speed; Weight = weight; diff --git a/Battleship/Battleship/FormBattleship.Designer.cs b/Battleship/Battleship/FormBattleship.Designer.cs index 763764d..7b7abf3 100644 --- a/Battleship/Battleship/FormBattleship.Designer.cs +++ b/Battleship/Battleship/FormBattleship.Designer.cs @@ -35,6 +35,8 @@ partial class FormBattleship buttonRight = new Button(); buttonUp = new Button(); buttonCreateWarshit = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit(); SuspendLayout(); // @@ -116,11 +118,35 @@ partial class FormBattleship buttonCreateWarshit.UseVisualStyleBackColor = true; buttonCreateWarshit.Click += buttonCreateWarshit_Click; // + // comboBoxStrategy + // + comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(795, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(151, 28); + comboBoxStrategy.TabIndex = 6; + // + // buttonStrategyStep + // + buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonStrategyStep.Location = new Point(851, 56); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(94, 29); + buttonStrategyStep.TabIndex = 7; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormBattleship // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(957, 559); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateWarshit); Controls.Add(buttonUp); Controls.Add(buttonRight); @@ -143,4 +169,6 @@ partial class FormBattleship private Button buttonUp; private Button buttonLeft; private Button buttonCreateWarshit; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } \ No newline at end of file diff --git a/Battleship/Battleship/FormBattleship.cs b/Battleship/Battleship/FormBattleship.cs index 4673128..27ff7be 100644 --- a/Battleship/Battleship/FormBattleship.cs +++ b/Battleship/Battleship/FormBattleship.cs @@ -1,4 +1,5 @@ using Battleship.Drawings; +using Battleship.MovementStrategy; namespace Battleship; /// @@ -11,9 +12,18 @@ public partial class FormBattleship : Form /// private DrawingWarship? _drawingWarship; //поля с нижнего подчеркивания + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + + /// + /// Конструктор формы + /// public FormBattleship() { InitializeComponent(); + _strategy = null; } /// /// Метод прорисовки машины @@ -54,6 +64,8 @@ public partial class FormBattleship : Form _drawingWarship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height); _drawingWarship.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxBattleship.Width, pictureBoxBattleship.Height); + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } @@ -79,6 +91,11 @@ public partial class FormBattleship : Form } + /// + /// кнопки вверх/вниз/влево/вправо + /// + /// + /// private void buttonMove_Click(object sender, EventArgs e) { if (_drawingWarship == null) @@ -109,4 +126,44 @@ public partial class FormBattleship : Form Draw(); } } + + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawingWarship == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex + switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableWarship(_drawingWarship), + pictureBoxBattleship.Width, pictureBoxBattleship.Height); + } + + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } \ No newline at end of file diff --git a/Battleship/Battleship/MovementStrategy/AbstractStrategy.cs b/Battleship/Battleship/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..ee4aaaf --- /dev/null +++ b/Battleship/Battleship/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,137 @@ +namespace Battleship.MovementStrategy; + +public abstract class AbstractStrategy +{ + /// + /// Перемещаемый объект + /// + private IMoveableObjectcs? _moveableObjects; + + /// + /// Статус перемещения + /// + private StrategyStatus _state = StrategyStatus.NotIInit; + + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + + /// + /// Высота поля + /// + protected int FieldHeight { get; private set;} + + /// + /// Статус перемещения + /// + /// + public StrategyStatus GetStatus() { return _state; } + + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObjectcs moveableObjectcs, int width, int height) + { + if (moveableObjectcs == null) + { + _state = StrategyStatus.NotIInit; + return; + } + + _state = StrategyStatus.InProgress; + _moveableObjects = moveableObjectcs; + FieldWidth = width; + FieldHeight = height; + } + + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + + if (IsTargetDestination()) + { + _state = StrategyStatus.Finish; + return; + } + + MoveToTarget(); + } + + /// + /// Перемещение влево + /// + /// + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + + /// + /// Перемещение вправо + /// + /// + protected bool MoveRight() => MoveTo(MovementDirection.Right); + + /// + /// Перемещение вверх + /// + /// + protected bool MoveUp() => MoveTo(MovementDirection.Up); + + /// + /// Перемещение вниз + /// + /// + protected bool MoveDown() => MoveTo(MovementDirection.Down); + + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => _moveableObjects?.GetObjectPosition; + + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != StrategyStatus.InProgress) + { + return null; + } + return _moveableObjects?.GetStep; + } + + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestination(); + + /// + /// Попытка перемещения в требуемом направлении + /// + /// + /// + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + + return _moveableObjects?.TryMoveObject(movementDirection) ?? false; + } +} diff --git a/Battleship/Battleship/MovementStrategy/IMoveableObjectcs.cs b/Battleship/Battleship/MovementStrategy/IMoveableObjectcs.cs new file mode 100644 index 0000000..913cef6 --- /dev/null +++ b/Battleship/Battleship/MovementStrategy/IMoveableObjectcs.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Battleship.MovementStrategy; + +public interface IMoveableObjectcs +{ + ObjectParameters? GetObjectPosition { get; } + + int GetStep { get; } + + /// + /// Шаг объекта + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/Battleship/Battleship/MovementStrategy/MoveToBorder.cs b/Battleship/Battleship/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..e941770 --- /dev/null +++ b/Battleship/Battleship/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Battleship.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestination() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder + GetStep() >= FieldWidth && + 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()) + { + MoveRight(); + } + var diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + MoveDown(); + } + } +} diff --git a/Battleship/Battleship/MovementStrategy/MoveToCenter.cs b/Battleship/Battleship/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..7fd9ad9 --- /dev/null +++ b/Battleship/Battleship/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Battleship.MovementStrategy; + +/// +/// Стратегия перемещения объекта в центр экрана +/// +public class MoveToCenter : AbstractStrategy +{ + protected override bool IsTargetDestination() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams != null ) + { + return false; + } + + return objParams.ObjectMiddleHorizontall - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontall + 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.ObjectMiddleHorizontall - 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(); + } + } + } +} diff --git a/Battleship/Battleship/MovementStrategy/MoveableWarship.cs b/Battleship/Battleship/MovementStrategy/MoveableWarship.cs new file mode 100644 index 0000000..d373450 --- /dev/null +++ b/Battleship/Battleship/MovementStrategy/MoveableWarship.cs @@ -0,0 +1,64 @@ +using Battleship.Drawings; + +namespace Battleship.MovementStrategy; + +/// +/// Класс-реализация IMoveableObjectcs с использованием DrawingWarship +/// +public class MoveableWarship : IMoveableObjectcs +{ + /// + /// Gле-объект класса DrawingWarship или его наследника + /// + private DrawingWarship? _warship = null; + + /// + /// Конструктор + /// + /// + public MoveableWarship(DrawingWarship warship) + { + _warship = warship; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_warship == null || _warship.EntityWarship == null || !_warship.GetPosX.HasValue || !_warship.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_warship.GetPosX.Value, _warship.GetPosY.Value, _warship.GetWidth, _warship.GetHeight); + } + } + + public int GetStep => (int)(_warship?.EntityWarship?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_warship == null || _warship.EntityWarship == null) + { + return false; + } + + return _warship.MoveTransport(GetDirectionType(direction)); + } + + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType + 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, + }; + } +} diff --git a/Battleship/Battleship/MovementStrategy/MovementDirection.cs b/Battleship/Battleship/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..8fc13f9 --- /dev/null +++ b/Battleship/Battleship/MovementStrategy/MovementDirection.cs @@ -0,0 +1,27 @@ +namespace Battleship.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влево + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} \ No newline at end of file diff --git a/Battleship/Battleship/MovementStrategy/ObjectParameters.cs b/Battleship/Battleship/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..bd90d26 --- /dev/null +++ b/Battleship/Battleship/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,72 @@ +namespace Battleship.MovementStrategy; + +/// +/// Параметры-координаты объекта +/// +public class ObjectParameters +{ + /// + /// Координата Х + /// + private readonly int _x; + + /// + /// Координата Y + /// + private readonly int _y; + + /// + /// Ширина объекта + /// + private readonly int _width; + + /// + /// Высота объекта + /// + private readonly int _height; + + /// + /// Левая граница + /// + public int LeftBorder => _x; + + /// + /// Верхняя граница + /// + public int TopBorder => _y; + + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + + /// + /// Середина объекта + /// + public int ObjectMiddleHorizontall => _x + _width / 2; + + /// + /// Середина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + + /// + /// Конструктор + /// + /// Координата Х + /// Координата Y + /// Ширина объекта + /// Высота объекта + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/Battleship/Battleship/MovementStrategy/StrategyStatus.cs b/Battleship/Battleship/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..4c2824b --- /dev/null +++ b/Battleship/Battleship/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace Battleship.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotIInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +}