diff --git a/ProjectBattleship/ProjectBattleship/AbstractStrategy.cs b/ProjectBattleship/ProjectBattleship/AbstractStrategy.cs
new file mode 100644
index 0000000..20d4956
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/AbstractStrategy.cs
@@ -0,0 +1,127 @@
+using ProjectBattleship.MovementStrategy;
+
+namespace ProjectBattleship.MovementStrategy;
+///
+/// Класс-стратегия перемещения объекта
+///
+public abstract class AbstractStrategy
+{
+ ///
+ /// Перемещаемый объект
+ ///
+ private IMoveableObject? _moveableObject;
+ ///
+ /// Статус перемещения
+ ///
+ private StrategyStatus _state = StrategyStatus.NotInit;
+ ///
+ /// Ширина поля
+ ///
+ protected int FieldWidth { get; private set; }
+ ///
+ /// Высота поля
+ ///
+ protected int FieldHeight { get; private set; }
+ ///
+ /// Статус перемещения
+ ///
+ public StrategyStatus GetStatus() { return _state; }
+ ///
+ /// Установка данных
+ ///
+ /// Перемещаемый объект
+ /// Ширина поля
+ /// Высота поля
+ 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;
+ }
+ ///
+ /// Шаг перемещения
+ ///
+ public void MakeStep()
+ {
+ if (_state != StrategyStatus.InProgress)
+ {
+ return;
+ }
+ if (IsTargetDestinaion())
+ {
+ _state = StrategyStatus.Finish;
+ return;
+ }
+ MoveToTarget();
+ }
+ ///
+ /// Перемещение влево
+ ///
+ /// Результат перемещения (true - удалось переместиться, false -
+ ///неудача)
+protected bool MoveLeft() => MoveTo(MovementDirection.Left);
+ ///
+ /// Перемещение вправо
+ ///
+ /// Результат перемещения (true - удалось переместиться, false -
+ ///неудача)
+protected bool MoveRight() => MoveTo(MovementDirection.Right);
+ ///
+ /// Перемещение вверх
+ ///
+ /// Результат перемещения (true - удалось переместиться, false -
+ ///неудача)
+protected bool MoveUp() => MoveTo(MovementDirection.Up);
+ ///
+ /// Перемещение вниз
+ ///
+ /// Результат перемещения (true - удалось переместиться, false -
+ ///неудача)
+protected bool MoveDown() => MoveTo(MovementDirection.Down);
+ ///
+ /// Параметры объекта
+ ///
+ protected ObjectParameters? GetObjectParameters =>
+ _moveableObject?.GetObjectPosition;
+ ///
+ /// Шаг объекта
+ ///
+ ///
+ protected int? GetStep()
+ {
+ if (_state != StrategyStatus.InProgress)
+ {
+ return null;
+ }
+ return _moveableObject?.GetStep;
+ }
+ ///
+ /// Перемещение к цели
+ ///
+ protected abstract void MoveToTarget();
+ ///
+ /// Достигнута ли цель
+ ///
+ ///
+ protected abstract bool IsTargetDestinaion();
+ ///
+ /// Попытка перемещения в требуемом направлении
+ ///
+ /// Направление
+ /// Результат попытки (true - удалось переместиться, false -
+ ///неудача)
+private bool MoveTo(MovementDirection movementDirection)
+ {
+ if (_state != StrategyStatus.InProgress)
+ {
+ return false;
+ }
+ return _moveableObject?.TryMoveObject(movementDirection) ?? false;
+ }
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/DirectionType.cs b/ProjectBattleship/ProjectBattleship/DirectionType.cs
index e1d9123..7a34dbb 100644
--- a/ProjectBattleship/ProjectBattleship/DirectionType.cs
+++ b/ProjectBattleship/ProjectBattleship/DirectionType.cs
@@ -4,6 +4,10 @@
///
public enum DirectionType
{
+ ///
+ /// Неизвестное направление
+ ///
+ Unknow = -1,
///
/// Вверх
///
diff --git a/ProjectBattleship/ProjectBattleship/DrawingBattleship.cs b/ProjectBattleship/ProjectBattleship/DrawingBattleship.cs
index 4f60cf7..43a6c39 100644
--- a/ProjectBattleship/ProjectBattleship/DrawingBattleship.cs
+++ b/ProjectBattleship/ProjectBattleship/DrawingBattleship.cs
@@ -1,228 +1,68 @@
-namespace ProjectBattleship;
+using ProjectBattleship.Entities;
+namespace ProjectBattleship.DrawingObject;
///
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
///
-public class DrawingBattleship
+public class DrawingBattleship : DrawingWarship
{
///
- /// Класс-сущность
- ///
- public EntityBattleship? EntityBattleship { get; private set; }
- ///
- /// Ширина окна
- ///
- private int? _pictureWidth;
- ///
- /// Высота окна
- ///
- private int? _pictureHeight;
- ///
- /// Левая координата прорисовки корабля
- ///
- private int? _startPosX;
- ///
- /// Верхняя кооридната прорисовки корабля
- ///
- private int? _startPosY;
- ///
- /// Ширина прорисовки корабля
- ///
- private readonly int _drawingWarshipWidth = 150;
- ///
- /// Высота прорисовки корабля
- ///
- private readonly int _drawingWarshipHeight = 50;
- ///
- /// Инициализация свойств
+ /// Конструктор
///
/// Скорость
/// Вес
/// Основной цвет
/// Дополнительный цвет
- /// Признак наличия отсека под ракеты
- /// Признак наличия орудийной башни
- public void Init(int speed, double weight, Color bodyColor, Color
- additionalColor, bool turret, bool rocketCompartment)
+ /// Признак наличия обвеса
+ /// Признак наличия антикрыла
+ /// Признак наличия гоночной полосы
+ public DrawingBattleship(int speed, double weight, Color bodyColor, Color
+ additionalColor, bool turret, bool rocketCompartment) : base(110, 60)
{
- EntityBattleship = new EntityBattleship();
- EntityBattleship.Init(speed, weight, bodyColor, additionalColor,
- turret, rocketCompartment);
- _pictureWidth = null;
- _pictureHeight = null;
- _startPosX = null;
- _startPosY = null;
+ EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor,
+ turret, rocketCompartment);
}
- ///
- /// Установка границ поля
- ///
- /// Ширина поля
- /// Высота поля
- /// true - границы заданы, false - проверка не пройдена,
- /// нельзя разместить объект в этих размерах
- public bool SetPictureSize(int width, int height)
+ public override void DrawTransport(Graphics g)
{
- if (_drawingWarshipWidth < width && _drawingWarshipHeight < height)
- {
- _pictureWidth = width;
- _pictureHeight = height;
- if (_startPosX.HasValue && _startPosY.HasValue)
- {
- SetPosition(_startPosX.Value, _startPosY.Value);
- }
-
- return true;
- }
- else
- {
- return false;
- }
- }
-
- ///
- /// Установка позиции
- ///
- /// Координата X
- /// Координата Y
- public void SetPosition(int x, int y)
- {
- if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
- {
- return;
- }
- if (x > 0 && y > 0 && x + _drawingWarshipWidth < _pictureWidth
- && y + _drawingWarshipHeight < _pictureHeight)
- {
- _startPosX = x;
- _startPosY = y;
- }
- else
- {
- Random rnd = new();
- _startPosX = rnd.Next(0, _pictureWidth.Value -
- _drawingWarshipWidth);
- _startPosY = rnd.Next(0, _pictureHeight.Value -
- _drawingWarshipHeight);
- }
- }
- ///
- /// Изменение направления перемещения
- ///
- /// Направление
- /// true - перемещене выполнено, false - перемещение невозможно
- public bool MoveTransport(DirectionType direction)
- {
- if (EntityBattleship == null || !_startPosX.HasValue ||
- !_startPosY.HasValue)
- {
- return false;
- }
- switch (direction)
- {
- //влево
- case DirectionType.Left:
- if (_startPosX - EntityBattleship.Step > 0)
- {
- _startPosX -= (int)EntityBattleship.Step;
- }
- return true;
- //вверх
- case DirectionType.Up:
- if (_startPosY - EntityBattleship.Step > 0)
- {
- _startPosY -= (int)EntityBattleship.Step;
- }
- return true;
- //вправо
- case DirectionType.Right:
- if (_startPosX + _drawingWarshipWidth + EntityBattleship.Step < _pictureWidth)
- {
- _startPosX += (int)EntityBattleship.Step;
- }
- return true;
- //вниз
- case DirectionType.Down:
- if (_startPosY + _drawingWarshipHeight + EntityBattleship.Step < _pictureHeight)
- {
- _startPosY += (int)EntityBattleship.Step;
- }
- return true;
- default:
- return false;
- }
- }
- ///
- /// Прорисовка объекта
- ///
- ///
- public void DrawTransport(Graphics g)
- {
- if (EntityBattleship == null || !_startPosX.HasValue ||
- !_startPosY.HasValue)
+ if (EntityWarship == null || EntityWarship is not EntityBattleship sportWarship ||
+ !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
- Brush bodyBrush = new SolidBrush(EntityBattleship.BodyColor);
- Brush additionalBrush = new
- SolidBrush(EntityBattleship.AdditionalColor);
- //основная часть
- Point[] body = new Point[] {new Point(_startPosX.Value + 5,
- _startPosY.Value), new Point(_startPosX.Value + 100,
- _startPosY.Value), new Point(_startPosX.Value + 150,
- _startPosY.Value + 25), new Point(_startPosX.Value + 100,
- _startPosY.Value + 50), new Point(_startPosX.Value + 5,
- _startPosY.Value + 50)};
- g.FillPolygon(bodyBrush, body);
- g.DrawPolygon(pen, body);
- Brush brBlack = new SolidBrush(Color.Black);
- g.FillRectangle(brBlack, _startPosX.Value,
- _startPosY.Value + 6, 5, 13);
- g.FillRectangle(brBlack, _startPosX.Value,
- _startPosY.Value + 31, 5, 13);
- Brush brDark = new SolidBrush(Color.DarkGray);
- g.FillRectangle(brDark, _startPosX.Value + 39,
- _startPosY.Value + 20, 40, 10);
- g.DrawRectangle(pen, _startPosX.Value + 39,
- _startPosY.Value + 20, 40, 10);
- g.FillRectangle(brDark, _startPosX.Value + 70,
- _startPosY.Value + 12, 18, 26);
- g.DrawRectangle(pen, _startPosX.Value + 70,
- _startPosY.Value + 12, 18, 26);
- g.FillEllipse(brBlack, _startPosX.Value + 94,
- _startPosY.Value + 19, 12, 12);
+ Brush additionalBrush = new SolidBrush(sportWarship.AdditionalColor);
//отсек под ракеты
if (EntityBattleship.RocketCompartment)
{
- g.FillRectangle(additionalBrush, _startPosX.Value + 14,
+ g.FillRectangle(additionalBrush, _startPosX.Value + 14,
_startPosY.Value + 14, 10, 10);
- g.FillRectangle(additionalBrush, _startPosX.Value + 26,
+ g.FillRectangle(additionalBrush, _startPosX.Value + 26,
_startPosY.Value + 14, 10, 10);
- g.FillRectangle(additionalBrush, _startPosX.Value + 14,
+ g.FillRectangle(additionalBrush, _startPosX.Value + 14,
_startPosY.Value + 26, 10, 10);
- g.FillRectangle(additionalBrush, _startPosX.Value + 26,
+ g.FillRectangle(additionalBrush, _startPosX.Value + 26,
_startPosY.Value + 26, 10, 10);
- g.DrawRectangle(pen, _startPosX.Value + 14,
+ g.DrawRectangle(pen, _startPosX.Value + 14,
_startPosY.Value + 14, 10, 10);
- g.DrawRectangle(pen, _startPosX.Value + 26,
+ g.DrawRectangle(pen, _startPosX.Value + 26,
_startPosY.Value + 14, 10, 10);
- g.DrawRectangle(pen, _startPosX.Value + 14,
+ g.DrawRectangle(pen, _startPosX.Value + 14,
_startPosY.Value + 26, 10, 10);
- g.DrawRectangle(pen, _startPosX.Value + 26,
+ g.DrawRectangle(pen, _startPosX.Value + 26,
_startPosY.Value + 26, 10, 10);
}
//орудийная башня
if (EntityBattleship.Turret)
{
- Point[] turret = new Point[] {new Point(_startPosX.Value + 112,
- _startPosY.Value + 19), new Point(_startPosX.Value + 112,
- _startPosY.Value + 31), new Point(_startPosX.Value + 119,
- _startPosY.Value + 28), new Point(_startPosX.Value + 119,
+ Point[] turret = new Point[] {new Point(_startPosX.Value + 112,
+ _startPosY.Value + 19), new Point(_startPosX.Value + 112,
+ _startPosY.Value + 31), new Point(_startPosX.Value + 119,
+ _startPosY.Value + 28), new Point(_startPosX.Value + 119,
_startPosY.Value + 22)};
g.FillPolygon(additionalBrush, turret);
- g.FillRectangle(additionalBrush, _startPosX.Value + 119,
+ g.FillRectangle(additionalBrush, _startPosX.Value + 119,
_startPosY.Value + 24, 12, 2);
g.DrawPolygon(pen, turret);
- g.DrawRectangle(pen, _startPosX.Value + 119,
+ g.DrawRectangle(pen, _startPosX.Value + 119,
_startPosY.Value + 24, 12, 2);
}
}
diff --git a/ProjectBattleship/ProjectBattleship/DrawingWarship.cs b/ProjectBattleship/ProjectBattleship/DrawingWarship.cs
new file mode 100644
index 0000000..1ba0609
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/DrawingWarship.cs
@@ -0,0 +1,197 @@
+using ProjectBattleship;
+using ProjectBattleship.Entities;
+namespace ProjectBattleship.DrawingObject;
+///
+/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
+///
+public class DrawingWarship
+{
+ ///
+ /// Класс-сущность
+ ///
+ public EntityWarship? EntityWarship { get; protected set; }
+ ///
+ /// Ширина окна
+ ///
+ private int? _pictureWidth;
+ ///
+ /// Высота окна
+ ///
+ private int? _pictureHeight;
+ ///
+ /// Левая координата прорисовки военного корабля
+ ///
+ protected int? _startPosX;
+ ///
+ /// Верхняя кооридната прорисовки военного корабля
+ ///
+ protected int? _startPosY;
+ ///
+ /// Ширина прорисовки военного корабля
+ ///
+ private readonly int _drawningWarshipWidth = 90;
+ ///
+ /// Высота прорисовки военного корабля
+ ///
+ private readonly int _drawningWarshipHeight = 50;
+ ///
+ /// Пустой конструктор
+ ///
+ private DrawingWarship()
+ {
+ _pictureWidth = null;
+ _pictureHeight = null;
+ _startPosX = null;
+ _startPosY = null;
+ }
+ ///
+ /// Конструктор
+ ///
+ /// Скорость
+ /// Вес
+ /// Основной цвет
+ public DrawingWarship(int speed, double weight, Color bodyColor) : this()
+ {
+ EntityWarship = new EntityWarship(speed, weight, bodyColor);
+ }
+ ///
+ /// Конструктор для наследников
+ ///
+ /// Ширина прорисовки военного корабля
+ /// Высота прорисовки военного корабля
+ protected DrawingWarship(int drawningWarshipWidth, int drawningWarshipHeight) : this()
+ {
+ _drawningWarshipWidth = drawningWarshipWidth;
+ _pictureHeight = drawningWarshipHeight;
+ }
+ ///
+ /// Установка границ поля
+ ///
+ /// Ширина поля
+ /// Высота поля
+ /// true - границы заданы, false - проверка не пройдена, нельзя
+ //разместить объект в этих размерах
+public bool SetPictureSize(int width, int height)
+ {
+ // TODO проверка, что объект "влезает" в размеры поля
+ // если влезает, сохраняем границы и корректируем позицию объекта,
+ //если она была уже установлена
+ _pictureWidth = width;
+ _pictureHeight = height;
+ return true;
+ }
+ ///
+ /// Установка позиции
+ ///
+ /// Координата X
+ /// Координата Y
+ public void SetPosition(int x, int y)
+ {
+ if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
+ {
+ return;
+ }
+ // TODO если при установке объекта в эти координаты, он будет
+ //"выходить" за границы формы
+ // то надо изменить координаты, чтобы он оставался в этих границах
+ _startPosX = x;
+ _startPosY = y;
+ }
+ ///
+ /// Изменение направления перемещения
+ ///
+ /// Направление
+ /// true - перемещене выполнено, false - перемещение
+ ///невозможно
+public bool MoveTransport(DirectionType direction)
+ {
+ if (EntityWarship == null || !_startPosX.HasValue ||
+ !_startPosY.HasValue)
+ {
+ return false;
+ }
+ switch (direction)
+ {
+ //влево
+ case DirectionType.Left:
+ if (_startPosX.Value - EntityWarship.Step > 0)
+ {
+ _startPosX -= (int)EntityWarship.Step;
+ }
+ return true;
+ //вверх
+ case DirectionType.Up:
+ if (_startPosY.Value - EntityWarship.Step > 0)
+ {
+ _startPosY -= (int)EntityWarship.Step;
+ }
+ return true;
+ // вправо
+ case DirectionType.Right:
+ //TODO прописать логику сдвига в право
+ return true;
+ //вниз
+ case DirectionType.Down:
+ //TODO прописать логику сдвига в вниз
+ return true;
+ default:
+ return false;
+ }
+ }
+ ///
+ /// Прорисовка объекта
+ ///
+ ///
+ public virtual void DrawTransport(Graphics g)
+ {
+ if (EntityWarship == null || !_startPosX.HasValue ||
+ !_startPosY.HasValue)
+ {
+ return;
+ }
+ Pen pen = new(Color.Black);
+ Brush bodyBrush = new SolidBrush(EntityWarship.BodyColor);
+ //основная часть
+ Point[] body = new Point[] {new Point(_startPosX.Value + 5,
+ _startPosY.Value), new Point(_startPosX.Value + 100,
+ _startPosY.Value), new Point(_startPosX.Value + 150,
+ _startPosY.Value + 25), new Point(_startPosX.Value + 100,
+ _startPosY.Value + 50), new Point(_startPosX.Value + 5,
+ _startPosY.Value + 50)};
+ g.FillPolygon(bodyBrush, body);
+ g.DrawPolygon(pen, body);
+ Brush brBlack = new SolidBrush(Color.Black);
+ g.FillRectangle(brBlack, _startPosX.Value,
+ _startPosY.Value + 6, 5, 13);
+ g.FillRectangle(brBlack, _startPosX.Value,
+ _startPosY.Value + 31, 5, 13);
+ Brush brDark = new SolidBrush(Color.DarkGray);
+ g.FillRectangle(brDark, _startPosX.Value + 39,
+ _startPosY.Value + 20, 40, 10);
+ g.DrawRectangle(pen, _startPosX.Value + 39,
+ _startPosY.Value + 20, 40, 10);
+ g.FillRectangle(brDark, _startPosX.Value + 70,
+ _startPosY.Value + 12, 18, 26);
+ g.DrawRectangle(pen, _startPosX.Value + 70,
+ _startPosY.Value + 12, 18, 26);
+ g.FillEllipse(brBlack, _startPosX.Value + 94,
+ _startPosY.Value + 19, 12, 12);
+ }
+
+ ///
+ /// Координата X объекта
+ ///
+ public int? GetPosX => _startPosX;
+ ///
+ /// Координата Y объекта
+ ///
+ public int? GetPosY => _startPosY;
+ ///
+ /// Ширина объекта
+ ///
+ public int GetWidth => _drawningWarshipWidth;
+ ///
+ /// Высота объекта
+ ///
+ public int GetHeight => _drawningWarshipHeight;
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/EntityBattleship.cs b/ProjectBattleship/ProjectBattleship/EntityBattleship.cs
index 119f53c..3f98e5e 100644
--- a/ProjectBattleship/ProjectBattleship/EntityBattleship.cs
+++ b/ProjectBattleship/ProjectBattleship/EntityBattleship.cs
@@ -1,4 +1,6 @@
-namespace ProjectBattleship;
+using ProjectBattleship.Entities;
+
+namespace ProjectBattleship.Entities;
///
/// Класс-сущность "Линкор"
///
diff --git a/ProjectBattleship/ProjectBattleship/EntityWarship.cs b/ProjectBattleship/ProjectBattleship/EntityWarship.cs
new file mode 100644
index 0000000..0ddce52
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/EntityWarship.cs
@@ -0,0 +1,35 @@
+namespace ProjectBattleship.Entities;
+///
+/// Класс-сущность "Автомобиль"
+///
+public class EntityWarship
+{
+ ///
+ /// Скорость
+ ///
+ public int Speed { get; private set; }
+ ///
+ /// Вес
+ ///
+ public double Weight { get; private set; }
+ ///
+ /// Основной цвет
+ ///
+ public Color BodyColor { get; private set; }
+ ///
+ /// Шаг перемещения автомобиля
+ ///
+ public double Step => Speed * 100 / Weight;
+ ///
+ /// Конструктор сущности
+ ///
+ /// Скорость
+ /// Вес автомобиля
+ /// Основной цвет
+ public EntityWarship(int speed, double weight, Color bodyColor)
+ {
+ Speed = speed;
+ Weight = weight;
+ BodyColor = bodyColor;
+ }
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs b/ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs
index ff159fd..d9cc026 100644
--- a/ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs
+++ b/ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs
@@ -29,11 +29,14 @@
private void InitializeComponent()
{
pictureBoxBattleship = new PictureBox();
- buttonCreate = new Button();
+ buttonCreateBattleship = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonUp = new Button();
+ comboBoxStrategy = new ComboBox();
+ button1 = new Button();
+ buttonCreateWarship = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit();
SuspendLayout();
//
@@ -41,33 +44,33 @@
//
pictureBoxBattleship.Dock = DockStyle.Fill;
pictureBoxBattleship.Location = new Point(0, 0);
- pictureBoxBattleship.Margin = new Padding(2, 2, 2, 2);
+ pictureBoxBattleship.Margin = new Padding(2);
pictureBoxBattleship.Name = "pictureBoxBattleship";
- pictureBoxBattleship.Size = new Size(730, 363);
+ pictureBoxBattleship.Size = new Size(876, 436);
pictureBoxBattleship.TabIndex = 0;
pictureBoxBattleship.TabStop = false;
//
- // buttonCreate
+ // buttonCreateBattleship
//
- buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
- buttonCreate.Location = new Point(10, 320);
- buttonCreate.Margin = new Padding(2, 2, 2, 2);
- buttonCreate.Name = "buttonCreate";
- buttonCreate.Size = new Size(109, 33);
- buttonCreate.TabIndex = 1;
- buttonCreate.Text = "Создать ";
- buttonCreate.UseVisualStyleBackColor = true;
- buttonCreate.Click += ButtonCreateBattleship_Click;
+ buttonCreateBattleship.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
+ buttonCreateBattleship.Location = new Point(11, 384);
+ buttonCreateBattleship.Margin = new Padding(2);
+ buttonCreateBattleship.Name = "buttonCreateBattleship";
+ buttonCreateBattleship.Size = new Size(201, 40);
+ buttonCreateBattleship.TabIndex = 1;
+ buttonCreateBattleship.Text = "Создать Линкор";
+ buttonCreateBattleship.UseVisualStyleBackColor = true;
+ buttonCreateBattleship.Click += ButtonCreateBattleship_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
- buttonLeft.Location = new Point(616, 324);
- buttonLeft.Margin = new Padding(2, 2, 2, 2);
+ buttonLeft.Location = new Point(739, 389);
+ buttonLeft.Margin = new Padding(2);
buttonLeft.Name = "buttonLeft";
- buttonLeft.Size = new Size(29, 29);
+ buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
@@ -77,10 +80,10 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
- buttonDown.Location = new Point(650, 324);
- buttonDown.Margin = new Padding(2, 2, 2, 2);
+ buttonDown.Location = new Point(780, 389);
+ buttonDown.Margin = new Padding(2);
buttonDown.Name = "buttonDown";
- buttonDown.Size = new Size(29, 29);
+ buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
@@ -90,10 +93,10 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
- buttonRight.Location = new Point(684, 324);
- buttonRight.Margin = new Padding(2, 2, 2, 2);
+ buttonRight.Location = new Point(821, 389);
+ buttonRight.Margin = new Padding(2);
buttonRight.Name = "buttonRight";
- buttonRight.Size = new Size(29, 29);
+ buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
@@ -103,26 +106,56 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
- buttonUp.Location = new Point(650, 290);
- buttonUp.Margin = new Padding(2, 2, 2, 2);
+ buttonUp.Location = new Point(780, 348);
+ buttonUp.Margin = new Padding(2);
buttonUp.Name = "buttonUp";
- buttonUp.Size = new Size(29, 29);
+ buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 5;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
+ // comboBoxStrategy
+ //
+ comboBoxStrategy.FormattingEnabled = true;
+ comboBoxStrategy.Location = new Point(652, 12);
+ comboBoxStrategy.Name = "comboBoxStrategy";
+ comboBoxStrategy.Size = new Size(212, 38);
+ comboBoxStrategy.TabIndex = 6;
+ //
+ // button1
+ //
+ button1.Location = new Point(752, 72);
+ button1.Name = "button1";
+ button1.Size = new Size(104, 43);
+ button1.TabIndex = 7;
+ button1.Text = "шаг";
+ button1.TextAlign = ContentAlignment.TopCenter;
+ button1.UseVisualStyleBackColor = true;
+ //
+ // buttonCreateWarship
+ //
+ buttonCreateWarship.Location = new Point(217, 384);
+ buttonCreateWarship.Name = "buttonCreateWarship";
+ buttonCreateWarship.Size = new Size(200, 40);
+ buttonCreateWarship.TabIndex = 8;
+ buttonCreateWarship.Text = "Создать корабль";
+ buttonCreateWarship.UseVisualStyleBackColor = true;
+ //
// FormBattleship
//
- AutoScaleDimensions = new SizeF(10F, 25F);
+ AutoScaleDimensions = new SizeF(12F, 30F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(730, 363);
+ ClientSize = new Size(876, 436);
+ Controls.Add(buttonCreateWarship);
+ Controls.Add(button1);
+ Controls.Add(comboBoxStrategy);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
- Controls.Add(buttonCreate);
+ Controls.Add(buttonCreateBattleship);
Controls.Add(pictureBoxBattleship);
- Margin = new Padding(2, 2, 2, 2);
+ Margin = new Padding(2);
Name = "FormBattleship";
StartPosition = FormStartPosition.CenterScreen;
Text = "Линкор";
@@ -134,10 +167,13 @@
#endregion
private PictureBox pictureBoxBattleship;
- private Button buttonCreate;
+ private Button buttonCreateBattleship;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonUp;
+ private ComboBox comboBoxStrategy;
+ private Button button1;
+ private Button buttonCreateWarship;
}
}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/FormBattleship.cs b/ProjectBattleship/ProjectBattleship/FormBattleship.cs
index 2e191eb..b8f3629 100644
--- a/ProjectBattleship/ProjectBattleship/FormBattleship.cs
+++ b/ProjectBattleship/ProjectBattleship/FormBattleship.cs
@@ -1,55 +1,93 @@
+using ProjectBattleship.MovementStrategy;
+using ProjectBattleship;
+using ProjectBattleship.DrawingObject;
+using ProjectBattleship.MovementStrategy;
namespace ProjectBattleship;
///
-/// " "
+/// " "
///
public partial class FormBattleship : Form
{
///
/// -
///
- private DrawingBattleship? _drawingBattleship;
+ private DrawingWarship? _drawningWarship;
+ ///
+ ///
+ ///
+ private AbstractStrategy? _strategy;
///
///
///
public FormBattleship()
{
InitializeComponent();
+ _strategy = null;
}
///
- ///
+ ///
///
private void Draw()
{
- if (_drawingBattleship == null)
+ if (_drawningWarship == null)
{
return;
}
Bitmap bmp = new(pictureBoxBattleship.Width,
- pictureBoxBattleship.Height);
+ pictureBoxBattleship.Height);
Graphics gr = Graphics.FromImage(bmp);
- _drawingBattleship.DrawTransport(gr);
+ _drawningWarship.DrawTransport(gr);
pictureBoxBattleship.Image = bmp;
}
///
- /// ""
+ /// -
+ ///
+ ///
+ private void CreateObject(string type)
+ {
+ Random random = new();
+ switch (type)
+ {
+ case nameof(DrawingWarship):
+ _drawningWarship = new DrawingWarship(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(DrawingBattleship):
+ _drawningWarship = new DrawingBattleship(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;
+ }
+ _drawningWarship.SetPictureSize(pictureBoxBattleship.Width,
+ pictureBoxBattleship.Height);
+ _drawningWarship.SetPosition(random.Next(10, 100), random.Next(10, 100));
+ _strategy = null;
+ comboBoxStrategy.Enabled = true;
+ Draw();
+ }
+ ///
+ /// " "
///
///
///
- private void ButtonCreateBattleship_Click(object sender, EventArgs e)
- {
- Random random = new();
- _drawingBattleship = new DrawingBattleship();
- _drawingBattleship.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)));
- _drawingBattleship.SetPictureSize(pictureBoxBattleship.Width,
- pictureBoxBattleship.Height);
- _drawingBattleship.SetPosition(random.Next(10, 100),
- random.Next(10, 100));
- Draw();
- }
+ private void ButtonCreateBattleship_Click(object sender, EventArgs e) =>
+ CreateObject(nameof(DrawingBattleship));
+ ///
+ /// " "
+ ///
+ ///
+ ///
+ private void ButtonCreateWarship_Click(object sender, EventArgs e) =>
+ CreateObject(nameof(DrawingWarship));
///
/// ( )
///
@@ -57,7 +95,7 @@ public partial class FormBattleship : Form
///
private void ButtonMove_Click(object sender, EventArgs e)
{
- if (_drawingBattleship == null)
+ if (_drawningWarship == null)
{
return;
}
@@ -66,20 +104,17 @@ public partial class FormBattleship : Form
switch (name)
{
case "buttonUp":
- result =
- _drawingBattleship.MoveTransport(DirectionType.Up);
+ result = _drawningWarship.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
- result =
- _drawingBattleship.MoveTransport(DirectionType.Down);
+ result = _drawningWarship.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
- result =
- _drawingBattleship.MoveTransport(DirectionType.Left);
+ result = _drawningWarship.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
- _drawingBattleship.MoveTransport(DirectionType.Right);
+ _drawningWarship.MoveTransport(DirectionType.Right);
break;
}
if (result)
@@ -87,4 +122,45 @@ public partial class FormBattleship : Form
Draw();
}
}
+ ///
+ /// ""
+ ///
+ ///
+ ///
+ private void ButtonStrategyStep_Click(object sender, EventArgs e)
+ {
+ if (_drawningWarship == null)
+ {
+ return;
+ }
+ if (comboBoxStrategy.Enabled)
+ {
+ _strategy = comboBoxStrategy.SelectedIndex switch
+ {
+ 0 => new MoveToCenter(),
+ 1 => new MoveToBorder(),
+ _ => null,
+ };
+ if (_strategy == null)
+ {
+ return;
+ }
+ _strategy.SetData(new MoveableWarship(_drawningWarship),
+ pictureBoxBattleship.Width, pictureBoxBattleship.Height);
+ }
+ if (_strategy == null)
+ {
+ return;
+ }
+ comboBoxStrategy.Enabled = false;
+ _strategy.MakeStep();
+ Draw();
+ if (_strategy.GetStatus() == StrategyStatus.Finish)
+ {
+ comboBoxStrategy.Enabled = true;
+ _strategy = null;
+ }
+ }
+
+
}
diff --git a/ProjectBattleship/ProjectBattleship/IMoveableObject.cs b/ProjectBattleship/ProjectBattleship/IMoveableObject.cs
new file mode 100644
index 0000000..1916e77
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/IMoveableObject.cs
@@ -0,0 +1,24 @@
+using ProjectBattleship.MovementStrategy;
+
+namespace ProjectBattleship.MovementStrategy;
+///
+/// Интерфейс для работы с перемещаемым объектом
+///
+public interface IMoveableObject
+{
+ ///
+ /// Получение координаты объекта
+ ///
+ ObjectParameters? GetObjectPosition { get; }
+ ///
+ /// Шаг объекта
+ ///
+ int GetStep { get; }
+ ///
+ /// Попытка переместить объект в указанном направлении
+ ///
+ /// Направление
+ /// true - объект перемещен, false - перемещение
+ ///невозможно
+bool TryMoveObject(MovementDirection direction);
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/MoveToCenter.cs b/ProjectBattleship/ProjectBattleship/MoveToCenter.cs
new file mode 100644
index 0000000..c52bed1
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/MoveToCenter.cs
@@ -0,0 +1,53 @@
+using ProjectBattleship.MovementStrategy;
+
+namespace ProjectBattleship.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();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/MoveableWarship.cs b/ProjectBattleship/ProjectBattleship/MoveableWarship.cs
new file mode 100644
index 0000000..8fbc1f0
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/MoveableWarship.cs
@@ -0,0 +1,58 @@
+using ProjectBattleship.DrawingObject;
+namespace ProjectBattleship.MovementStrategy;
+///
+/// Класс-реализация IMoveableObject с использованием DrawingWarship
+///
+public class MoveableWarship : IMoveableObject
+{
+ ///
+ /// Поле-объект класса DrawingWarship или его наследника
+ ///
+ private readonly DrawingWarship? _warship = null;
+ ///
+ /// Конструктор
+ ///
+ /// Объект класса DrawingWarship
+ 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,
+ };
+ }
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/MovementDirection.cs b/ProjectBattleship/ProjectBattleship/MovementDirection.cs
new file mode 100644
index 0000000..03a3f4d
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/MovementDirection.cs
@@ -0,0 +1,23 @@
+namespace ProjectBattleship.MovementStrategy;
+///
+/// Направление перемещения
+///
+public enum MovementDirection
+{
+ ///
+ /// Вверх
+ ///
+ Up = 1,
+ ///
+ /// Вниз
+ ///
+ Down = 2,
+ ///
+ /// Влево
+ ///
+ Left = 3,
+ ///
+ /// Вправо
+ ///
+ Right = 4
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/ObjectParameters.cs b/ProjectBattleship/ProjectBattleship/ObjectParameters.cs
new file mode 100644
index 0000000..b56fd34
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/ObjectParameters.cs
@@ -0,0 +1,61 @@
+namespace ProjectBattleship.MovementStrategy;
+///
+/// Параметры-координаты объекта
+///
+public class ObjectParameters
+{
+ ///
+ /// Координата X
+ ///
+ 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 ObjectMiddleHorizontal => _x + _width / 2;
+ ///
+ /// Середина объекта
+ ///
+ public int ObjectMiddleVertical => _y + _height / 2;
+ ///
+ /// Конструктор
+ ///
+ /// Координата X
+ /// Координата Y
+ /// Ширина объекта
+ /// Высота объекта
+ public ObjectParameters(int x, int y, int width, int height)
+ {
+ _x = x;
+ _y = y;
+ _width = width;
+ _height = height;
+ }
+}
\ No newline at end of file
diff --git a/ProjectBattleship/ProjectBattleship/StrategyStatus.cs b/ProjectBattleship/ProjectBattleship/StrategyStatus.cs
new file mode 100644
index 0000000..747b111
--- /dev/null
+++ b/ProjectBattleship/ProjectBattleship/StrategyStatus.cs
@@ -0,0 +1,19 @@
+namespace ProjectBattleship.MovementStrategy;
+///
+/// Статус выполнения операции перемещения
+///
+public enum StrategyStatus
+{
+ ///
+ /// Все готово к началу
+ ///
+ NotInit,
+ ///
+ /// Выполняется
+ ///
+ InProgress,
+ ///
+ /// Завершено
+ ///
+ Finish
+}
\ No newline at end of file