PIbd-11_Gulina_V.S._LabWork02_Simple #2

Closed
victinass wants to merge 4 commits from LabWork02 into LabWork01
15 changed files with 853 additions and 132 deletions

View File

@ -1,9 +1,14 @@
namespace Battleship;
namespace Battleship.Drawings;
/// <summary>
/// класс, отвечающий за лево/право/верх/низ
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -0,0 +1,108 @@
using Battleship.Entities;
//using System.Drawings;
namespace Battleship.Drawings;
/// <summary>
/// Класс, отвечающий за отрисовку и перемещение объекта-сущности
/// </summary>
public class DrawingBattleship : DrawingWarship
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyDeck">Признак наличия палубы</param>
/// <param name="compartment">Признак наличия отсека для ракет</param>
/// <param name="tower">Признак наличия башни</param>
///
public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 60)
{
EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor);
}
public override void DrawTransport(Graphics g)
{
if (EntityWarship == null || EntityWarship is not EntityBattleship battleship || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(battleship.AdditionalColor);
//отсек для ракет
if (battleship.BodyDeck)
{
//заливка линкора
Brush br = new SolidBrush(EntityWarship.BodyColor);
g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value, 80, 40);
//границы линкора
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value, 80, 40); //ширина высота (сама палуба)
//заливка двигателей (2 фигни сзади)
Brush brBlack = new SolidBrush(Color.Black);
g.FillRectangle(brBlack, _startPosX.Value + 5, _startPosY.Value + 7, 5, 10); //верхний
g.FillRectangle(brBlack, _startPosX.Value + 5, _startPosY.Value + 22, 5, 10); //нижний
//границы двигателей
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 7, 5, 10); //двигатель верхний
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 22, 5, 10); //двигатель нижний
//прямоугольник левый на палубе (горизонтальный)
Brush brLightSteelBlue = new SolidBrush(Color.LightSteelBlue);
g.FillRectangle(brLightSteelBlue, _startPosX.Value + 32, _startPosY.Value + 13, 21, 12);
g.DrawRectangle(pen, _startPosX.Value + 32, _startPosY.Value + 13, 21, 12);
//прямоугольник правый на палубе (вертикальный)
Brush brGray = new SolidBrush(Color.Gray);
g.FillRectangle(brGray, _startPosX.Value + 53, _startPosY.Value + 7, 16, 24);
g.DrawRectangle(pen, _startPosX.Value + 53, _startPosY.Value + 7, 16, 24);
//линии для треугольника
Point[] pointsNOS =
{
new Point(_startPosX.Value + 90, _startPosY.Value),
new Point(_startPosX.Value + 120, _startPosY.Value + 20),
new Point(_startPosX.Value + 90, _startPosY.Value + 40),
};
g.DrawPolygon(pen, pointsNOS);
g.FillPolygon(br, pointsNOS);
//заливка круга
Brush brLightSlateGray = new SolidBrush(Color.LightSlateGray);
g.FillEllipse(brLightSlateGray, _startPosX.Value + 78, _startPosY.Value + 12, 15, 15);
//круг на палубе
g.DrawEllipse(pen, _startPosX.Value + 78, _startPosY.Value + 12, 15, 15);
}
base.DrawTransport(g);
//башня
if (battleship.Tower)
{
//заливка башни
g.FillEllipse(additionalBrush, _startPosX.Value + 98, _startPosY.Value + 15, 10, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 107, _startPosY.Value + 17, 30, 5);
//границы башни
g.DrawEllipse(pen, _startPosX.Value + 98, _startPosY.Value + 15, 10, 10);
g.DrawRectangle(pen, _startPosX.Value + 107, _startPosY.Value + 17, 30, 5);
}
//отсек
if (battleship.Compartment)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 15, _startPosY.Value + 5, 27, 5); //верхний отсек для ракет
g.FillRectangle(additionalBrush, _startPosX.Value + 15, _startPosY.Value + 28, 27, 5); //нижний отсек для ракет
//границы отсеков
g.DrawRectangle(pen, _startPosX.Value + 15, _startPosY.Value + 5, 27, 5); //верхний отсек
g.DrawRectangle(pen, _startPosX.Value + 15, _startPosY.Value + 28, 27, 5); //нижний отсек
}
}
}

View File

@ -1,13 +1,13 @@
namespace Battleship;
/// <summary>
/// Класс, отвечающий за отрисовку и перемещение объекта-сущности
/// </summary>
public class DrawingBattleship
using Battleship.Entities;
namespace Battleship.Drawings;
public class DrawingWarship
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBattleship? EntityBattleship { get; private set; }
public EntityWarship? EntityWarship { get; protected set; }
/// <summary>
/// Ширина
@ -20,45 +20,77 @@ public class DrawingBattleship
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки линкора
/// Левая координата прорисовки военного корабля
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки линкора
/// Верхняя координата прорисовки военного корабля
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки линкора
/// Ширина прорисовки военного корабля
/// </summary>
private readonly int _drawingBattleshipWidth = 129;
private readonly int _drawingWarshipWidth = 129;
/// <summary>
/// Высота прорисовки линкора
/// Высота прорисовки военного корабля
/// </summary>
private readonly int _drawingBattleshipHeight = 40;
private readonly int _drawingWarshipHeight = 40;
/// <summary>
/// Инициализация свойств
/// Координата Х объекта
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyDeck">Признак наличия палубы</param>
/// <param name="compartment">Признак наличия отсека для ракет</param>
/// <param name="tower">Признак наличия башни</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower)
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawingWarshipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawingWarshipHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawingWarship()
{
EntityBattleship = new EntityBattleship();
EntityBattleship.Init(speed, weight, bodyColor, additionalColor, bodyDeck, compartment, tower);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawingWarship(int speed, double weight, Color bodyColor) : this()
{
EntityWarship = new EntityWarship(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawingWarshipWidth">Ширина прорисовки военного корабля</param>
/// <param name="drawingWarshipHeight">Высота прорисовки военного корабля</param>
protected DrawingWarship(int drawingWarshipWidth, int drawingWarshipHeight) : this()
{
_drawingWarshipWidth = drawingWarshipWidth;
_drawingWarshipHeight = drawingWarshipHeight;
}
/// <summary>
/// Установка границ поля
@ -71,25 +103,25 @@ public class DrawingBattleship
{
//TODO проверка, что объект "влезает" в размеры поля
//если влезает, сохраняем границы и корректируем позицию объекта, если она уже была установлена
if (_drawingBattleshipWidth > width || _drawingBattleshipHeight > height)
if (_drawingWarshipWidth > width || _drawingWarshipHeight > height)
{
return false;
}
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue || _startPosY.HasValue)
{
if (_startPosX + _drawingBattleshipWidth > _pictureWidth)
if (_startPosX + _drawingWarshipWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawingBattleshipWidth;
_startPosX = _pictureWidth - _drawingWarshipWidth;
}
else if (_startPosX < 0) _startPosX = 0;
if (_startPosY + _drawingBattleshipHeight > _pictureHeight)
if (_startPosY + _drawingWarshipHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawingBattleshipHeight;
_startPosY = _pictureHeight - _drawingWarshipHeight;
}
else if (_startPosY < 0) _startPosY = 0;
}
@ -102,7 +134,7 @@ public class DrawingBattleship
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y, int width, int height)
{
if (!_pictureWidth.HasValue || !_pictureHeight.HasValue)
@ -112,17 +144,17 @@ public class DrawingBattleship
// TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
if (x + _drawingBattleshipWidth > _pictureWidth)
if (x + _drawingWarshipWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawingBattleshipWidth;
_startPosX = _pictureWidth - _drawingWarshipWidth;
}
else if (x < 0) _startPosX = 0;
else if (x < 0) _startPosX = 0;
else _startPosX = x;
if (y + _drawingBattleshipHeight > _pictureHeight)
if (y + _drawingWarshipHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawingBattleshipHeight;
_startPosY = _pictureHeight - _drawingWarshipHeight;
}
else if (y < 0) _startPosY = 0;
else _startPosY = y;
@ -137,49 +169,49 @@ public class DrawingBattleship
public bool MoveTransport(DirectionType direction)
{
if (EntityBattleship == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityWarship == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityBattleship.Step > 0)
if (_startPosX.Value - EntityWarship.Step > 0)
{
_startPosX -= (int)EntityBattleship.Step;
_startPosX -= (int)EntityWarship.Step;
}
return true;
//вправо
case DirectionType.Right:
if (_startPosX.Value + EntityBattleship.Step + _drawingBattleshipWidth < _pictureWidth)
if (_startPosX.Value + EntityWarship.Step + _drawingWarshipWidth < _pictureWidth)
{
_startPosX += (int)EntityBattleship.Step;
_startPosX += (int)EntityWarship.Step;
}
return true;
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityBattleship.Step > 0)
if (_startPosY.Value - EntityWarship.Step > 0)
{
_startPosY -= (int)EntityBattleship.Step;
_startPosY -= (int)EntityWarship.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityBattleship.Step + _drawingBattleshipHeight < _pictureHeight) //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (_startPosY.Value + EntityWarship.Step + _drawingWarshipHeight < _pictureHeight) //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{
_startPosY += (int)EntityBattleship.Step;
_startPosY += (int)EntityWarship.Step;
}
return true;
default:
return false;
default:
return false;
}
}
/// <summary>
@ -187,18 +219,17 @@ public class DrawingBattleship
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityBattleship == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityWarship == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityBattleship.AdditionalColor);
//заливка линкора
Brush br = new SolidBrush(EntityBattleship.BodyColor);
Brush br = new SolidBrush(EntityWarship.BodyColor);
g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value, 80, 40);
//границы линкора
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value, 80, 40); //ширина высота (сама палуба)
@ -227,7 +258,7 @@ public class DrawingBattleship
new Point(_startPosX.Value + 90, _startPosY.Value),
new Point(_startPosX.Value + 120, _startPosY.Value + 20),
new Point(_startPosX.Value + 90, _startPosY.Value + 40),
};
g.DrawPolygon(pen, pointsNOS);
g.FillPolygon(br, pointsNOS);
@ -237,32 +268,5 @@ public class DrawingBattleship
g.FillEllipse(brLightSlateGray, _startPosX.Value + 78, _startPosY.Value + 12, 15, 15);
//круг на палубе
g.DrawEllipse(pen, _startPosX.Value + 78, _startPosY.Value + 12, 15, 15);
//ПРОВЕРКА
if (EntityBattleship.Compartment)
{
//отсеки для ракет
//заливка отсеков
g.FillRectangle(additionalBrush, _startPosX.Value + 15, _startPosY.Value + 5, 27, 5); //верхний отсек для ракет
g.FillRectangle(additionalBrush, _startPosX.Value + 15, _startPosY.Value + 28, 27, 5); //нижний отсек для ракет
//границы отсеков
g.DrawRectangle(pen, _startPosX.Value + 15, _startPosY.Value + 5, 27, 5); //верхний отсек
g.DrawRectangle(pen, _startPosX.Value + 15, _startPosY.Value + 28, 27, 5); //нижний отсек
}
if (EntityBattleship.Tower)
{
//заливка башни
g.FillEllipse(additionalBrush, _startPosX.Value + 98, _startPosY.Value + 15, 10, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 107, _startPosY.Value + 17, 30, 5);
//границы башни
g.DrawEllipse(pen, _startPosX.Value + 98, _startPosY.Value + 15, 10, 10);
g.DrawRectangle(pen, _startPosX.Value + 107, _startPosY.Value + 17, 30, 5);
}
}
}

View File

@ -1,14 +1,14 @@
namespace Battleship;
namespace Battleship.Entities;
/// <summary>
/// Класс-сущность Линкор
/// </summary>
public class EntityBattleship
public class EntityBattleship : EntityWarship
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
@ -17,23 +17,23 @@ public class EntityBattleship
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// /// <summary>
/// Признак (опция) отсека для ракет
/// </summary>
public bool Compartment { get; private set; }
/// <summary>
/// Признак (опция) наличия башни
/// </summary>
public bool Tower { get; private set; }
/// <summary>
/// Признак (опция) наличия палубы
/// </summary>
public bool BodyDeck { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия палубы
/// </summary>
public bool BodyDeck { get; private set; }
/// <summary>
/// Признак (опция) отсека для ракет
/// </summary>
public bool Compartment { get; private set; }
/// <summary>
/// Признак (опция) наличия башни
/// </summary>
public bool Tower { get; private set; }
/// <summary>
/// Перемещение линкора
/// </summary>
public double Step => Speed * 100 / Weight;
@ -44,18 +44,14 @@ public class EntityBattleship
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="bodyDeck"></param>
/// <param name="compartment"></param>
/// <param name="tower"></param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower)
public EntityBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
BodyDeck = bodyDeck;
Compartment = compartment;
Tower = tower;
BodyDeck = bodyDeck;
AdditionalColor = additionalColor;
}
}

View File

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

View File

@ -34,6 +34,9 @@ partial class FormBattleship
buttonDown = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonCreateWarshit = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit();
SuspendLayout();
//
@ -50,9 +53,9 @@ partial class FormBattleship
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 518);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29);
buttonCreate.Size = new Size(267, 29);
buttonCreate.TabIndex = 0;
buttonCreate.Text = "Создать";
buttonCreate.Text = "Создать линкор";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
@ -104,11 +107,47 @@ partial class FormBattleship
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// buttonCreateWarshit
//
buttonCreateWarshit.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateWarshit.Location = new Point(316, 518);
buttonCreateWarshit.Name = "buttonCreateWarshit";
buttonCreateWarshit.Size = new Size(267, 29);
buttonCreateWarshit.TabIndex = 5;
buttonCreateWarshit.Text = "Создать военный корабль";
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);
Controls.Add(buttonDown);
@ -129,4 +168,7 @@ partial class FormBattleship
private Button buttonRight;
private Button buttonUp;
private Button buttonLeft;
private Button buttonCreateWarshit;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}

View File

@ -1,4 +1,7 @@
namespace Battleship;
using Battleship.Drawings;
using Battleship.MovementStrategy;
namespace Battleship;
/// <summary>
/// Форма работы с объектом Линкор
/// </summary>
@ -7,11 +10,20 @@ public partial class FormBattleship : Form
/// <summary>
/// Поле/объект для прорисовки объекта
/// </summary>
private DrawingBattleship? _drawingBattleship; //поля с нижнего подчеркивания
private DrawingWarship? _drawingWarship; //поля с нижнего подчеркивания
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormBattleship()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки машины
@ -19,17 +31,44 @@ public partial class FormBattleship : Form
//создаем отдельный метод
private void Draw()
{
if (_drawingBattleship == null)
if (_drawingWarship == null)
{
return;
}
Bitmap bmp = new(pictureBoxBattleship.Width, pictureBoxBattleship.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingBattleship.DrawTransport(gr);
_drawingWarship.DrawTransport(gr);
pictureBoxBattleship.Image = bmp;
}
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawingWarship):
_drawingWarship = 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):
_drawingWarship = 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)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_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();
}
/// <summary>
/// обработка нажатия кнопки "создать линкор"
/// </summary>
@ -37,27 +76,29 @@ public partial class FormBattleship : Form
/// <param name="e"></param>
private void buttonCreate_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)), Convert.ToBoolean(random.Next(0, 2)));
_drawingBattleship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height);
_drawingBattleship.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxBattleship.Width, pictureBoxBattleship.Height);
Draw();
CreateObject(nameof(DrawingBattleship));
}
/// <summary>
/// обработка нажатия кнопок "вверх/вниз/влево/вправо"
/// обработка нажатия кнопки "создать военный корабль"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateWarshit_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawingWarship));
}
/// <summary>
/// кнопки вверх/вниз/влево/вправо
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingBattleship == null)
if (_drawingWarship == null)
{
return;
}
@ -67,16 +108,16 @@ public partial class FormBattleship : Form
switch (name)
{
case "buttonUp":
result = _drawingBattleship.MoveTransport(DirectionType.Up);
result = _drawingWarship.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawingBattleship.MoveTransport(DirectionType.Down);
result = _drawingWarship.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawingBattleship.MoveTransport(DirectionType.Left);
result = _drawingWarship.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawingBattleship.MoveTransport(DirectionType.Right);
result = _drawingWarship.MoveTransport(DirectionType.Right);
break;
}
@ -85,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;
}
}
}

View File

@ -0,0 +1,137 @@
namespace Battleship.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObjectcs? _moveableObjects;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotIInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set;}
/// <summary>
/// Статус перемещения
/// </summary>
/// <returns></returns>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
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;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns></returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns></returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns></returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns></returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObjects?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObjects?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestination();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection"></param>
/// <returns></returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObjects?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -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; }
/// <summary>
/// Шаг объекта
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,52 @@
using System;
namespace Battleship.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
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,54 @@
namespace Battleship.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
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();
}
}
}
}

View File

@ -0,0 +1,64 @@
using Battleship.Drawings;
namespace Battleship.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObjectcs с использованием DrawingWarship
/// </summary>
public class MoveableWarship : IMoveableObjectcs
{
/// <summary>
/// Gле-объект класса DrawingWarship или его наследника
/// </summary>
private DrawingWarship? _warship = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="warship"></param>
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));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,27 @@
namespace Battleship.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,72 @@
namespace Battleship.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координата Х
/// </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 ObjectMiddleHorizontall => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата Х</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина объекта</param>
/// <param name="height">Высота объекта</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

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