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