diff --git a/Battleship/Battleship/AbstractStrategy.cs b/Battleship/Battleship/AbstractStrategy.cs
new file mode 100644
index 0000000..a0ef782
--- /dev/null
+++ b/Battleship/Battleship/AbstractStrategy.cs
@@ -0,0 +1,138 @@
+using Battleship.MovementStrategy;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Battleship.MovementStrategy
+{
+ ///
+ /// Класс-стратегия перемещения объекта
+ ///
+ public abstract class AbstractStrategy
+ {
+ ///
+ /// Перемещаемый объект
+ ///
+ private IMoveableObject? _moveableObject;
+ ///
+ /// Статус перемещения
+ ///
+ private Status _state = Status.NotInit;
+ ///
+ /// Ширина поля
+ ///
+ protected int FieldWidth { get; private set; }
+ ///
+ /// Высота поля
+ ///
+ protected int FieldHeight { get; private set; }
+ ///
+ /// Статус перемещения
+ ///
+ public Status GetStatus() { return _state; }
+ ///
+ /// Установка данных
+ ///
+ /// Перемещаемый объект
+ /// Ширина поля
+ /// Высота поля
+ public void SetData(IMoveableObject moveableObject, int width, int
+ height)
+ {
+ if (moveableObject == null)
+ {
+ _state = Status.NotInit;
+ return;
+ }
+ _state = Status.InProgress;
+ _moveableObject = moveableObject;
+ FieldWidth = width;
+ FieldHeight = height;
+ }
+ ///
+ /// Шаг перемещения
+ ///
+ public void MakeStep()
+ {
+ if (_state != Status.InProgress)
+ {
+ return;
+ }
+ if (IsTargetDestinaion())
+ {
+ _state = Status.Finish;
+ return;
+ }
+ MoveToTarget();
+ }
+ ///
+ /// Перемещение влево
+ ///
+ /// Результат перемещения (true - удалось переместиться, false - неудача)
+ protected bool MoveLeft() => MoveTo(DirectionType.Left);
+ ///
+ /// Перемещение вправо
+ ///
+ /// Результат перемещения (true - удалось переместиться, false - неудача)
+ protected bool MoveRight() => MoveTo(DirectionType.Right);
+ ///
+ /// Перемещение вверх
+ ///
+ /// Результат перемещения (true - удалось переместиться, false - неудача)
+ protected bool MoveUp() => MoveTo(DirectionType.Up);
+ ///
+ /// Перемещение вниз
+ ///
+ /// Результат перемещения (true - удалось переместиться, false - неудача)
+ protected bool MoveDown() => MoveTo(DirectionType.Down);
+ ///
+ /// Параметры объекта
+ ///
+
+ // protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectParametrs;
+ protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
+
+ ///
+ /// Шаг объекта
+ ///
+ ///
+ protected int? GetStep()
+ {
+ if (_state != Status.InProgress)
+ {
+ return null;
+ }
+ return _moveableObject?.GetStep;
+ }
+ ///
+ /// Перемещение к цели
+ ///
+ protected abstract void MoveToTarget();
+ ///
+ /// Достигнута ли цель
+ ///
+ ///
+ protected abstract bool IsTargetDestinaion();
+ ///
+ /// Попытка перемещения в требуемом направлении
+ ///
+ /// Направление
+ /// Результат попытки (true - удалось переместиться, false - неудача)
+ private bool MoveTo(DirectionType directionType)
+ {
+ if (_state != Status.InProgress)
+ {
+ return false;
+ }
+ if (_moveableObject?.CheckCanMove(directionType) ?? false)
+ {
+ _moveableObject.MoveObject(directionType);
+ return true;
+ }
+ return false;
+ }
+ }
+}
+
diff --git a/Battleship/Battleship/Battleship.Designer.cs b/Battleship/Battleship/Battleship.Designer.cs
index a6a444d..0808631 100644
--- a/Battleship/Battleship/Battleship.Designer.cs
+++ b/Battleship/Battleship/Battleship.Designer.cs
@@ -34,6 +34,9 @@
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
+ this.buttonCreateAdd = new System.Windows.Forms.Button();
+ this.buttonStep = new System.Windows.Forms.Button();
+ this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxBattleship)).BeginInit();
this.SuspendLayout();
//
@@ -51,9 +54,9 @@
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(12, 415);
this.buttonCreate.Name = "buttonCreate";
- this.buttonCreate.Size = new System.Drawing.Size(75, 23);
+ this.buttonCreate.Size = new System.Drawing.Size(114, 23);
this.buttonCreate.TabIndex = 6;
- this.buttonCreate.Text = "Создать";
+ this.buttonCreate.Text = "Создать корабль";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
@@ -105,11 +108,48 @@
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
+ // buttonCreateAdd
+ //
+ this.buttonCreateAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
+ this.buttonCreateAdd.Location = new System.Drawing.Point(132, 415);
+ this.buttonCreateAdd.Name = "buttonCreateAdd";
+ this.buttonCreateAdd.Size = new System.Drawing.Size(159, 23);
+ this.buttonCreateAdd.TabIndex = 11;
+ this.buttonCreateAdd.Text = "Создать военный корабль";
+ this.buttonCreateAdd.UseVisualStyleBackColor = true;
+ this.buttonCreateAdd.Click += new System.EventHandler(this.buttonCreateAdd_Click);
+ //
+ // buttonStep
+ //
+ this.buttonStep.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
+ this.buttonStep.Location = new System.Drawing.Point(713, 48);
+ this.buttonStep.Name = "buttonStep";
+ this.buttonStep.Size = new System.Drawing.Size(75, 23);
+ this.buttonStep.TabIndex = 12;
+ this.buttonStep.Text = "Шаг";
+ this.buttonStep.UseVisualStyleBackColor = true;
+ this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
+ //
+ // comboBoxStrategy
+ //
+ this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
+ this.comboBoxStrategy.FormattingEnabled = true;
+ this.comboBoxStrategy.Items.AddRange(new object[] {
+ "В центр",
+ "К границе"});
+ this.comboBoxStrategy.Location = new System.Drawing.Point(667, 12);
+ this.comboBoxStrategy.Name = "comboBoxStrategy";
+ this.comboBoxStrategy.Size = new System.Drawing.Size(121, 23);
+ this.comboBoxStrategy.TabIndex = 13;
+ //
// Battleship
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
+ this.Controls.Add(this.comboBoxStrategy);
+ this.Controls.Add(this.buttonStep);
+ this.Controls.Add(this.buttonCreateAdd);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
@@ -130,5 +170,8 @@
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
+ private Button buttonCreateAdd;
+ private Button buttonStep;
+ private ComboBox comboBoxStrategy;
}
}
\ No newline at end of file
diff --git a/Battleship/Battleship/Battleship.cs b/Battleship/Battleship/Battleship.cs
index 36ee80e..c2458df 100644
--- a/Battleship/Battleship/Battleship.cs
+++ b/Battleship/Battleship/Battleship.cs
@@ -1,3 +1,6 @@
+using Battleship.DrawningObjects;
+using Battleship.MovementStrategy;
+
namespace Battleship
{
public partial class Battleship : Form
@@ -5,10 +8,11 @@ namespace Battleship
///
/// -
///
- private DrawningBattleship? _drawningBattleship;
+ private DrawningShip? _drawningShip;
///
///
///
+ private AbstractStrategy? _abstractStrategy;
public Battleship()
{
InitializeComponent();
@@ -17,35 +21,47 @@ namespace Battleship
///
private void Draw()
{
- if (_drawningBattleship == null)
+ if (_drawningShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxBattleship.Width,
pictureBoxBattleship.Height);
Graphics gr = Graphics.FromImage(bmp);
- _drawningBattleship.DrawTransport(gr);
+ _drawningShip.DrawTransport(gr);
pictureBoxBattleship.Image = bmp;
}
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
- _drawningBattleship = new DrawningBattleship();
- _drawningBattleship.Init(random.Next(100, 300),
+ _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)),
- 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)),
+ Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
+ random.Next(0, 256)),
pictureBoxBattleship.Width, pictureBoxBattleship.Height);
- _drawningBattleship.SetPosition(random.Next(10, 100),
- random.Next(10, 100));
+ _drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
+ Draw();
+ }
+ private void buttonCreateAdd_Click(object sender, EventArgs e)
+ {
+ Random random = new();
+ _drawningShip = new DrawningBattleship(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)),
+ pictureBoxBattleship.Width, pictureBoxBattleship.Height);
+ _drawningShip.SetPosition(random.Next(10, 100), random.Next(10,100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
- if (_drawningBattleship == null)
+ if (_drawningShip == null)
{
return;
}
@@ -53,20 +69,56 @@ namespace Battleship
switch (name)
{
case "buttonUp":
- _drawningBattleship.MoveTransport(DirectionType.Up);
+ _drawningShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
- _drawningBattleship.MoveTransport(DirectionType.Down);
+ _drawningShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
- _drawningBattleship.MoveTransport(DirectionType.Left);
+ _drawningShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
- _drawningBattleship.MoveTransport(DirectionType.Right);
+ _drawningShip.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
+ private void buttonStep_Click(object sender, EventArgs e)
+ {
+ if (_drawningShip == null)
+ {
+ return;
+ }
+ if (comboBoxStrategy.Enabled)
+ {
+ _abstractStrategy = comboBoxStrategy.SelectedIndex
+ switch
+ {
+ 0 => new MoveToCenter(),
+ 1 => new MoveToBorder(),
+ _ => null,
+ };
+ if (_abstractStrategy == null)
+ {
+ return;
+ }
+ _abstractStrategy.SetData(new
+ DrawningObjectShip(_drawningShip), pictureBoxBattleship.Width,
+ pictureBoxBattleship.Height);
+ comboBoxStrategy.Enabled = false;
+ }
+ if (_abstractStrategy == null)
+ {
+ return;
+ }
+ _abstractStrategy.MakeStep();
+ Draw();
+ if (_abstractStrategy.GetStatus() == Status.Finish)
+ {
+ comboBoxStrategy.Enabled = true;
+ _abstractStrategy = null;
+ }
+ }
}
}
\ No newline at end of file
diff --git a/Battleship/Battleship/DrawningBattleship.cs b/Battleship/Battleship/DrawningBattleship.cs
index 80f2e97..f2b792d 100644
--- a/Battleship/Battleship/DrawningBattleship.cs
+++ b/Battleship/Battleship/DrawningBattleship.cs
@@ -1,176 +1,37 @@
-using System;
+using Battleship;
+using Battleship.Entities;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
-namespace Battleship
+namespace Battleship.DrawningObjects
{
- ///
- /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
- ///
- public class DrawningBattleship
+ public class DrawningBattleship : DrawningShip
{
- ///
- /// Класс-сущность
- ///
- public EntityBattleship? EntityBattleship { get; private set; }
- ///
- /// Ширина окна
- ///
- private int _pictureWidth;
- ///
- /// Высота окна
- ///
- private int _pictureHeight;
- ///
- /// Левая координата прорисовки
- ///
- private int _startPosX;
- ///
- /// Верхняя кооридната прорисовки
- ///
- private int _startPosY;
- ///
- /// Ширина прорисовки
- ///
- private readonly int _buttleshipWidth = 175;
- ///
- /// Высота прорисовки
- ///
- private readonly int _buttleshipHeight = 80;
- ///
- /// Инициализация свойств
- ///
- /// Скорость
- /// Вес
- /// Цвет основы
- /// Дополнительный цвет
- /// Признак наличия орудийной башни
- /// Признак наличия отсека под ракеты
- /// Ширина картинки
- /// Высота картинки
- /// true - объект создан, false - проверка не пройдена,
- ///нельзя создать объект в этих размерах
-
- public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool tower, bool section, int width, int height)
+ public DrawningBattleship(int speed, double weight, Color bodyColor, Color
+ additionalColor, bool tower, bool section, int width, int height)
+ : base(speed, weight, bodyColor, width, height, 175, 80)
{
- if (width < _buttleshipWidth || height < _buttleshipHeight)
+ if(EntityShip != null)
{
- return false;
- }
- _pictureWidth = width;
- _pictureHeight = height;
- EntityBattleship = new EntityBattleship();
- EntityBattleship.Init(speed, weight, bodyColor, additionalColor,
- tower, section);
- return true;
- }
-
- ///
- /// Установка позиции
- ///
- /// Координата X
- /// Координата Y
- public void SetPosition(int x, int y)
- {
- if (x >= 0 && x + _buttleshipWidth <= _pictureWidth && y >= 0 && y + _buttleshipHeight <= _pictureHeight)
- {
- _startPosX = x;
- _startPosY = y;
+ EntityShip = new EntityBattleship(speed, weight, bodyColor, additionalColor, tower, section);
}
}
- ///
- /// Изменение направления перемещения
- ///
- /// Направление
- public void MoveTransport(DirectionType direction)
+ public override void DrawTransport(Graphics g)
{
- if (EntityBattleship == null)
- {
- return;
- }
- switch (direction)
- {
- //влево
- case DirectionType.Left:
- if (_startPosX - EntityBattleship.Step > 0)
- {
- _startPosX -= (int)EntityBattleship.Step;
- }
- break;
- //вверх
- case DirectionType.Up:
- if (_startPosY - EntityBattleship.Step > 0)
- {
- _startPosY -= (int)EntityBattleship.Step;
- }
- break;
- // вправо
- case DirectionType.Right:
- if (_startPosX + _buttleshipWidth + EntityBattleship.Step < _pictureWidth)
- {
- _startPosX += (int)EntityBattleship.Step;
- }
- break;
- //вниз
- case DirectionType.Down:
- if (_startPosY + _buttleshipHeight + EntityBattleship.Step < _pictureHeight)
- {
- _startPosY += (int)EntityBattleship.Step;
- }
- break;
- }
- }
- ///
- /// Прорисовка объекта
- ///
- ///
- public void DrawTransport(Graphics g)
- {
- if (EntityBattleship == null)
+ if (EntityShip is not EntityBattleship battleShip)
{
return;
}
Pen pen = new(Color.Black, 2);
Brush additionalBrush = new
- SolidBrush(EntityBattleship.AdditionalColor);
-
- //основа
- Brush mainBrush = new SolidBrush(EntityBattleship.BodyColor);
- Point[] hull = new Point[]
- {
- new Point(_startPosX + 5, _startPosY + 0),
- new Point(_startPosX + 120, _startPosY + 0),
- new Point(_startPosX + 160, _startPosY + 35),
- new Point(_startPosX + 120, _startPosY + 70),
- new Point(_startPosX + 5, _startPosY + 70),
- };
- g.FillPolygon(mainBrush, hull);
- g.DrawPolygon(pen, hull);
-
- //блоки
- Brush blockBrush = new
- SolidBrush(Color.DimGray);
- g.FillRectangle(blockBrush, _startPosX + 70, _startPosY + 15, 20, 40);
- g.DrawRectangle(pen, _startPosX + 70, _startPosY + 15, 20, 40);
-
- g.FillRectangle(additionalBrush, _startPosX + 40, _startPosY + 25, 30, 20);
- g.DrawRectangle(pen, _startPosX + 40, _startPosY + 25, 30, 20);
-
- g.FillEllipse(additionalBrush, _startPosX + 100, _startPosY + 20, 30, 30);
- g.DrawEllipse(pen, _startPosX + 100, _startPosY + 20, 30, 30);
-
- //для ускорения
- Brush speedBrush = new
- SolidBrush(Color.Gold);
- g.FillRectangle(speedBrush, _startPosX + 0, _startPosY + 10, 5, 20);
- g.DrawRectangle(pen, _startPosX + 0, _startPosY + 10, 5, 20);
- g.FillRectangle(speedBrush, _startPosX + 0, _startPosY + 40, 5, 20);
- g.DrawRectangle(pen, _startPosX + 0, _startPosY + 40, 5, 20);
+ SolidBrush(battleShip.AdditionalColor);
+ base.DrawTransport(g);
//орудийная башня
- if (EntityBattleship.Tower)
+ if (battleShip.Tower)
{
Brush baseBrush = new SolidBrush(Color.White);
g.FillRectangle(baseBrush, _startPosX + 108, _startPosY + 28, 15, 15);
@@ -180,7 +41,7 @@ namespace Battleship
g.DrawRectangle(pen, _startPosX + 123, _startPosY + 32, 55, 6);
}
//отсеки под ракеты
- if (EntityBattleship.Section)
+ if (battleShip.Section)
{
Brush sectionBrush = new
SolidBrush(Color.Gray);
@@ -192,4 +53,3 @@ namespace Battleship
}
}
}
-
diff --git a/Battleship/Battleship/DrawningObjectShip.cs b/Battleship/Battleship/DrawningObjectShip.cs
new file mode 100644
index 0000000..1a7fb51
--- /dev/null
+++ b/Battleship/Battleship/DrawningObjectShip.cs
@@ -0,0 +1,41 @@
+using Battleship.DrawningObjects;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Battleship;
+
+
+namespace Battleship.MovementStrategy
+{
+ ///
+ /// Реализация интерфейса IDrawningObject для работы с объектом DrawningCar (паттерн Adapter)
+ ///
+ public class DrawningObjectShip : IMoveableObject
+ {
+ private readonly DrawningShip? _drawningShip = null;
+ public DrawningObjectShip(DrawningShip drawningShip)
+ {
+ _drawningShip = drawningShip;
+ }
+ public ObjectParameters? GetObjectPosition
+ {
+ get
+ {
+ if (_drawningShip == null || _drawningShip.EntityShip == null)
+ {
+ return null;
+ }
+ return new ObjectParameters(_drawningShip.GetPosX,
+ _drawningShip.GetPosY, _drawningShip.GetWidth, _drawningShip.GetHeight);
+ }
+ }
+ public int GetStep => (int)(_drawningShip?.EntityShip?.Step ?? 0);
+ public bool CheckCanMove(DirectionType direction) =>
+ _drawningShip?.CanMove(direction) ?? false;
+ public void MoveObject(DirectionType direction) =>
+ _drawningShip?.MoveTransport(direction);
+ }
+}
+
diff --git a/Battleship/Battleship/DrawningShip.cs b/Battleship/Battleship/DrawningShip.cs
new file mode 100644
index 0000000..d6c291b
--- /dev/null
+++ b/Battleship/Battleship/DrawningShip.cs
@@ -0,0 +1,223 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Battleship.Entities;
+
+namespace Battleship.DrawningObjects
+{
+ ///
+ /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
+ ///
+ public class DrawningShip
+ {
+ ///
+ /// Класс-сущность
+ ///
+ public EntityShip? EntityShip { get; protected set; }
+ ///
+ /// Ширина окна
+ ///
+ private int _pictureWidth;
+ ///
+ /// Высота окна
+ ///
+ private int _pictureHeight;
+ ///
+ /// Левая координата прорисовки
+ ///
+ protected int _startPosX;
+ ///
+ /// Верхняя кооридната прорисовки
+ ///
+ protected int _startPosY;
+ ///
+ /// Ширина прорисовки
+ ///
+ protected readonly int _buttleshipWidth = 175;
+ ///
+ /// Высота прорисовки
+ ///
+ protected readonly int _buttleshipHeight = 80;
+ ///
+ /// Инициализация свойств
+ ///
+ /// Скорость
+ /// Вес
+ /// Цвет основы
+ /// Ширина картинки
+ /// Высота картинки
+ /// true - объект создан, false - проверка не пройдена,
+ ///нельзя создать объект в этих размерах
+
+ public DrawningShip(int speed, double weight, Color bodyColor, int width, int height)
+ {
+ if (width < _buttleshipWidth || height < _buttleshipHeight)
+ {
+ return;
+ }
+ _pictureWidth = width;
+ _pictureHeight = height;
+ EntityShip = new EntityShip(speed, weight, bodyColor);
+
+ }
+ ///
+ /// Конструктор
+ ///
+ /// Скорость
+ /// Вес
+ /// Основной цвет
+ /// Ширина картинки
+ /// Высота картинки
+ /// Ширина прорисовки автомобиля
+ /// Высота прорисовки автомобиля
+ protected DrawningShip(int speed, double weight, Color bodyColor, int
+ width, int height, int buttleshipWidth, int buttleshipHeight)
+ {
+ if (width <= _buttleshipWidth || height <= _buttleshipHeight)
+ return;
+ _pictureWidth = width;
+ _pictureHeight = height;
+ _buttleshipWidth = buttleshipWidth;
+ _buttleshipHeight = buttleshipHeight;
+ EntityShip = new EntityShip(speed, weight, bodyColor);
+ }
+ ///
+ /// Установка позиции
+ ///
+ /// Координата X
+ /// Координата Y
+ public void SetPosition(int x, int y)
+ {
+ if (x >= 0 && x + _buttleshipWidth <= _pictureWidth && y >= 0 && y + _buttleshipHeight <= _pictureHeight)
+ {
+ _startPosX = x;
+ _startPosY = y;
+ }
+ }
+ ///
+ /// Изменение направления перемещения
+ ///
+ /// Направление
+
+ ///
+ /// Прорисовка объекта
+ ///
+ ///
+ public virtual void DrawTransport(Graphics g)
+ {
+ if (EntityShip == null)
+ {
+ return;
+ }
+ Pen pen = new(Color.Black, 2);
+
+ //основа
+ Brush mainBrush = new SolidBrush(EntityShip.BodyColor);
+ Point[] hull = new Point[]
+ {
+ new Point(_startPosX + 5, _startPosY + 0),
+ new Point(_startPosX + 120, _startPosY + 0),
+ new Point(_startPosX + 160, _startPosY + 35),
+ new Point(_startPosX + 120, _startPosY + 70),
+ new Point(_startPosX + 5, _startPosY + 70),
+ };
+ g.FillPolygon(mainBrush, hull);
+ g.DrawPolygon(pen, hull);
+
+ //блоки
+ Brush blockBrush = new
+ SolidBrush(Color.DimGray);
+ g.FillRectangle(blockBrush, _startPosX + 70, _startPosY + 15, 20, 40);
+ g.DrawRectangle(pen, _startPosX + 70, _startPosY + 15, 20, 40);
+
+ g.FillRectangle(blockBrush, _startPosX + 40, _startPosY + 25, 30, 20);
+ g.DrawRectangle(pen, _startPosX + 40, _startPosY + 25, 30, 20);
+
+ g.FillEllipse(blockBrush, _startPosX + 100, _startPosY + 20, 30, 30);
+ g.DrawEllipse(pen, _startPosX + 100, _startPosY + 20, 30, 30);
+
+ //для ускорения
+ Brush speedBrush = new
+ SolidBrush(Color.Gold);
+ g.FillRectangle(speedBrush, _startPosX + 0, _startPosY + 10, 5, 20);
+ g.DrawRectangle(pen, _startPosX + 0, _startPosY + 10, 5, 20);
+ g.FillRectangle(speedBrush, _startPosX + 0, _startPosY + 40, 5, 20);
+ g.DrawRectangle(pen, _startPosX + 0, _startPosY + 40, 5, 20);
+ }
+ ///
+ /// Координата X объекта
+ ///
+ public int GetPosX => _startPosX;
+ ///
+ /// Координата Y объекта
+ /// ///
+ public int GetPosY => _startPosY;
+ ///
+ /// Ширина объекта
+ ///
+ public int GetWidth => _buttleshipWidth;
+ ///
+ /// Высота объекта
+ ///
+ public int GetHeight => _buttleshipHeight;
+ ///
+ /// Проверка, что объект может переместится по указанному направлению
+ ///
+ /// Направление
+ /// true - можно переместится по указанному направлению
+ public bool CanMove(DirectionType direction)
+ {
+ if (EntityShip == null)
+ {
+ return false;
+ }
+ return direction switch
+ {
+ //влево
+ DirectionType.Left => _startPosX - EntityShip.Step > 0,
+ //вверх
+ DirectionType.Up => _startPosY - EntityShip.Step > 0,
+ //вправо
+ DirectionType.Right => _startPosX + EntityShip.Step + _buttleshipWidth < _pictureWidth,
+ //вниз
+ DirectionType.Down => _startPosY + EntityShip.Step + _buttleshipHeight < _pictureHeight,
+ _ => false,
+ };
+ }
+ ///
+ /// Изменение направления перемещения
+ ///
+ /// Направление
+ public void MoveTransport(DirectionType direction)
+ {
+ if (!CanMove(direction) || EntityShip == null)
+ {
+ return;
+ }
+ switch (direction)
+ {
+ //влево
+ case DirectionType.Left:
+ _startPosX -= (int)EntityShip.Step;
+ break;
+ //вверх
+ case DirectionType.Up:
+ _startPosY -= (int)EntityShip.Step;
+ break;
+ // вправо
+ case DirectionType.Right:
+ _startPosX += (int)EntityShip.Step;
+ break;
+ //вниз
+ case DirectionType.Down:
+ _startPosY += (int)EntityShip.Step;
+ break;
+ }
+ }
+ }
+}
+
+
+
diff --git a/Battleship/Battleship/EntityBattleship.cs b/Battleship/Battleship/EntityBattleship.cs
index 425529a..999b563 100644
--- a/Battleship/Battleship/EntityBattleship.cs
+++ b/Battleship/Battleship/EntityBattleship.cs
@@ -1,28 +1,15 @@
-using System;
+using Battleship.Entities;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
-namespace Battleship
+namespace Battleship.Entities
{
- public class EntityBattleship
+ internal class EntityBattleship: EntityShip
{
- ///
- /// Скорость
- ///
- public int Speed { get; private set; }
- ///
- /// Вес
- ///
- public double Weight { get; private set; }
- ///
- /// Основной цвет
- ///
- public Color BodyColor { get; private set; }
- ///
- /// Дополнительный цвет (для опциональных элементов)
- ///
+
public Color AdditionalColor { get; private set; }
///
/// Признак (опция) наличия башни
@@ -35,7 +22,7 @@ namespace Battleship
///
/// Шаг перемещения
///
- public double Step => (double)Speed * 100 / Weight;
+
///
/// Инициализация полей объекта-класса спортивного автомобиля
///
@@ -45,13 +32,10 @@ namespace Battleship
/// Дополнительный цвет
/// Признак наличия орудийной башни
/// Признак наличия отсека под ракеты
- public void Init(int speed, double weight, Color bodyColor, Color
- additionalColor, bool tower, bool section)
+ public EntityBattleship(int speed, double weight, Color bodyColor, Color
+ additionalColor, bool tower, bool section) : base(speed, weight, bodyColor)
{
- Speed = speed;
- Weight = weight;
- BodyColor = bodyColor;
- AdditionalColor = additionalColor;
+ AdditionalColor = additionalColor;
Tower = tower;
Section = section;
}
diff --git a/Battleship/Battleship/EntityShip.cs b/Battleship/Battleship/EntityShip.cs
new file mode 100644
index 0000000..ec575b5
--- /dev/null
+++ b/Battleship/Battleship/EntityShip.cs
@@ -0,0 +1,41 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Battleship.Entities
+{
+ public class EntityShip
+ {
+ ///
+ /// Скорость
+ ///
+ public int Speed { get; private set; }
+ ///
+ /// Вес
+ ///
+ public double Weight { get; private set; }
+ ///
+ /// Основной цвет
+ ///
+ public Color BodyColor { get; private set; }
+ ///
+ /// Дополнительный цвет (для опциональных элементов)
+ ///
+
+ public double Step => (double)Speed * 100 / Weight;
+ ///
+ /// Инициализация полей объекта-класса спортивного автомобиля
+ ///
+ /// Скорость
+ /// Вес автомобиля
+ /// Основной цвет
+ public EntityShip(int speed, double weight, Color bodyColor)
+ {
+ Speed = speed;
+ Weight = weight;
+ BodyColor = bodyColor;
+ }
+ }
+}
diff --git a/Battleship/Battleship/IMoveableObject.cs b/Battleship/Battleship/IMoveableObject.cs
new file mode 100644
index 0000000..d6d57b3
--- /dev/null
+++ b/Battleship/Battleship/IMoveableObject.cs
@@ -0,0 +1,36 @@
+using Battleship.MovementStrategy;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Battleship;
+
+namespace Battleship.MovementStrategy
+{
+ ///
+ /// Интерфейс для работы с перемещаемым объектом
+ ///
+ public interface IMoveableObject
+ {
+ ///
+ /// Получение координаты X объекта
+ ///
+ ObjectParameters? GetObjectPosition { get; }
+ ///
+ /// Шаг объекта
+ ///
+ int GetStep { get; }
+ ///
+ /// Проверка, можно ли переместиться по нужному направлению
+ ///
+ ///
+ ///
+ bool CheckCanMove(DirectionType direction);
+ ///
+ /// Изменение направления пермещения объекта
+ ///
+ /// Направление
+ void MoveObject(DirectionType direction);
+ }
+}
diff --git a/Battleship/Battleship/MoveToBorder.cs b/Battleship/Battleship/MoveToBorder.cs
new file mode 100644
index 0000000..8971be9
--- /dev/null
+++ b/Battleship/Battleship/MoveToBorder.cs
@@ -0,0 +1,58 @@
+using Battleship.MovementStrategy;
+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 IsTargetDestinaion()
+ {
+ var objParams = GetObjectParameters;
+ if (objParams == null)
+ {
+ return false;
+ }
+ return objParams.RightBorder <= FieldWidth &&
+ objParams.RightBorder + GetStep() >= FieldWidth &&
+ objParams.DownBorder <= FieldHeight &&
+ objParams.DownBorder + GetStep() >= FieldHeight;
+
+ }
+ protected override void MoveToTarget()
+ {
+ var objParams = GetObjectParameters;
+ if (objParams == null)
+ {
+ return;
+ }
+ var diffX = objParams.RightBorder - FieldWidth;
+ if (Math.Abs(diffX) > GetStep())
+ {
+ if (diffX > 0)
+ {
+ MoveLeft();
+ }
+ else
+ {
+ MoveRight();
+ }
+ }
+ var diffY = objParams.DownBorder - FieldHeight;
+ if (Math.Abs(diffY) > GetStep())
+ {
+ if (diffY > 0)
+ {
+ MoveUp();
+ }
+ else
+ {
+ MoveDown();
+ }
+ }
+ }
+ }
+}
diff --git a/Battleship/Battleship/MoveToCenter.cs b/Battleship/Battleship/MoveToCenter.cs
new file mode 100644
index 0000000..abaabfb
--- /dev/null
+++ b/Battleship/Battleship/MoveToCenter.cs
@@ -0,0 +1,57 @@
+using Battleship.MovementStrategy;
+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 IsTargetDestinaion()
+ {
+ var objParams = GetObjectParameters;
+ if (objParams == null)
+ {
+ return false;
+ }
+ return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
+ objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
+ objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
+ objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
+ }
+ protected override void MoveToTarget()
+ {
+ var objParams = GetObjectParameters;
+ if (objParams == null)
+ {
+ return;
+ }
+ var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
+ if (Math.Abs(diffX) > GetStep())
+ {
+ if (diffX > 0)
+ {
+ MoveLeft();
+ }
+ else
+ {
+ MoveRight();
+ }
+ }
+ var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
+ if (Math.Abs(diffY) > GetStep())
+ {
+ if (diffY > 0)
+ {
+ MoveUp();
+ }
+ else
+ {
+ MoveDown();
+ }
+ }
+ }
+ }
+}
diff --git a/Battleship/Battleship/ObjectParameters.cs b/Battleship/Battleship/ObjectParameters.cs
new file mode 100644
index 0000000..ec3a35a
--- /dev/null
+++ b/Battleship/Battleship/ObjectParameters.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Battleship.MovementStrategy
+{
+ ///
+ /// Параметры-координаты объекта
+ ///
+ public class ObjectParameters
+ {
+ private readonly int _x;
+ 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;
+ }
+ }
+}
diff --git a/Battleship/Battleship/Status.cs b/Battleship/Battleship/Status.cs
new file mode 100644
index 0000000..70f04f0
--- /dev/null
+++ b/Battleship/Battleship/Status.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Battleship.MovementStrategy
+{
+ ///
+ /// Статус выполнения операции перемещения
+ ///
+ public enum Status
+ {
+ NotInit,
+ InProgress,
+ Finish
+ }
+}