From 83a063cde7614a45ec054c14615b30dd7eb2d2a8 Mon Sep 17 00:00:00 2001 From: safia Date: Thu, 21 Mar 2024 01:52:26 +0300 Subject: [PATCH] LabWork02 --- .../ProjectBattleship/AbstractStrategy.cs | 14 ++-- .../ProjectBattleship/DrawingBattleship.cs | 17 ++-- .../ProjectBattleship/DrawingWarship.cs | 77 ++++++++++++------- .../ProjectBattleship/EntityBattleship.cs | 31 ++------ .../ProjectBattleship/EntityWarship.cs | 23 ++++-- .../FormBattleship.Designer.cs | 6 +- .../ProjectBattleship/FormBattleship.cs | 30 ++++---- .../ProjectBattleship/IMoveableObject.cs | 4 +- .../ProjectBattleship/MoveToBorder.cs | 53 +++++++++++++ .../ProjectBattleship/MoveToCenter.cs | 4 +- 10 files changed, 160 insertions(+), 99 deletions(-) create mode 100644 ProjectBattleship/ProjectBattleship/MoveToBorder.cs diff --git a/ProjectBattleship/ProjectBattleship/AbstractStrategy.cs b/ProjectBattleship/ProjectBattleship/AbstractStrategy.cs index 20d4956..2a6a5f3 100644 --- a/ProjectBattleship/ProjectBattleship/AbstractStrategy.cs +++ b/ProjectBattleship/ProjectBattleship/AbstractStrategy.cs @@ -1,6 +1,4 @@ -using ProjectBattleship.MovementStrategy; - -namespace ProjectBattleship.MovementStrategy; +namespace ProjectBattleship.MovementStrategy; /// /// Класс-стратегия перемещения объекта /// @@ -65,25 +63,25 @@ public abstract class AbstractStrategy /// /// Результат перемещения (true - удалось переместиться, false - ///неудача) -protected bool MoveLeft() => MoveTo(MovementDirection.Left); + protected bool MoveLeft() => MoveTo(MovementDirection.Left); /// /// Перемещение вправо /// /// Результат перемещения (true - удалось переместиться, false - ///неудача) -protected bool MoveRight() => MoveTo(MovementDirection.Right); + protected bool MoveRight() => MoveTo(MovementDirection.Right); /// /// Перемещение вверх /// /// Результат перемещения (true - удалось переместиться, false - ///неудача) -protected bool MoveUp() => MoveTo(MovementDirection.Up); + protected bool MoveUp() => MoveTo(MovementDirection.Up); /// /// Перемещение вниз /// /// Результат перемещения (true - удалось переместиться, false - ///неудача) -protected bool MoveDown() => MoveTo(MovementDirection.Down); + protected bool MoveDown() => MoveTo(MovementDirection.Down); /// /// Параметры объекта /// @@ -116,7 +114,7 @@ protected bool MoveDown() => MoveTo(MovementDirection.Down); /// Направление /// Результат попытки (true - удалось переместиться, false - ///неудача) -private bool MoveTo(MovementDirection movementDirection) + private bool MoveTo(MovementDirection movementDirection) { if (_state != StrategyStatus.InProgress) { diff --git a/ProjectBattleship/ProjectBattleship/DrawingBattleship.cs b/ProjectBattleship/ProjectBattleship/DrawingBattleship.cs index 43a6c39..d465ed8 100644 --- a/ProjectBattleship/ProjectBattleship/DrawingBattleship.cs +++ b/ProjectBattleship/ProjectBattleship/DrawingBattleship.cs @@ -12,26 +12,25 @@ public class DrawingBattleship : DrawingWarship /// Вес /// Основной цвет /// Дополнительный цвет - /// Признак наличия обвеса - /// Признак наличия антикрыла - /// Признак наличия гоночной полосы + /// Признак наличия обвеса + /// Признак наличия антикрыла public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool turret, bool rocketCompartment) : base(110, 60) { - EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor, - turret, rocketCompartment); + EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketCompartment); } public override void DrawTransport(Graphics g) { - if (EntityWarship == null || EntityWarship is not EntityBattleship sportWarship || + if (EntityWarship == null || EntityWarship is not EntityBattleship battleship || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush additionalBrush = new SolidBrush(sportWarship.AdditionalColor); + Brush additionalBrush = new SolidBrush(battleship.AdditionalColor); + base.DrawTransport(g); //отсек под ракеты - if (EntityBattleship.RocketCompartment) + if (battleship.RocketCompartment) { g.FillRectangle(additionalBrush, _startPosX.Value + 14, _startPosY.Value + 14, 10, 10); @@ -51,7 +50,7 @@ public class DrawingBattleship : DrawingWarship _startPosY.Value + 26, 10, 10); } //орудийная башня - if (EntityBattleship.Turret) + if (battleship.Turret) { Point[] turret = new Point[] {new Point(_startPosX.Value + 112, _startPosY.Value + 19), new Point(_startPosX.Value + 112, diff --git a/ProjectBattleship/ProjectBattleship/DrawingWarship.cs b/ProjectBattleship/ProjectBattleship/DrawingWarship.cs index 1ba0609..dfa7efd 100644 --- a/ProjectBattleship/ProjectBattleship/DrawingWarship.cs +++ b/ProjectBattleship/ProjectBattleship/DrawingWarship.cs @@ -1,5 +1,4 @@ -using ProjectBattleship; -using ProjectBattleship.Entities; +using ProjectBattleship.Entities; namespace ProjectBattleship.DrawingObject; /// /// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности @@ -29,11 +28,11 @@ public class DrawingWarship /// /// Ширина прорисовки военного корабля /// - private readonly int _drawningWarshipWidth = 90; + private readonly int _drawingWarshipWidth = 90; /// /// Высота прорисовки военного корабля /// - private readonly int _drawningWarshipHeight = 50; + private readonly int _drawingWarshipHeight = 50; /// /// Пустой конструктор /// @@ -57,12 +56,12 @@ public class DrawingWarship /// /// Конструктор для наследников /// - /// Ширина прорисовки военного корабля - /// Высота прорисовки военного корабля - protected DrawingWarship(int drawningWarshipWidth, int drawningWarshipHeight) : this() + /// Ширина прорисовки военного корабля + /// Высота прорисовки военного корабля + protected DrawingWarship(int drawingWarshipWidth, int drawingWarshipHeight) : this() { - _drawningWarshipWidth = drawningWarshipWidth; - _pictureHeight = drawningWarshipHeight; + _drawingWarshipWidth = drawingWarshipWidth; + _pictureHeight = drawingWarshipHeight; } /// /// Установка границ поля @@ -71,14 +70,23 @@ public class DrawingWarship /// Высота поля /// true - границы заданы, false - проверка не пройдена, нельзя //разместить объект в этих размерах -public bool SetPictureSize(int width, int height) + public bool SetPictureSize(int width, int height) { - // TODO проверка, что объект "влезает" в размеры поля - // если влезает, сохраняем границы и корректируем позицию объекта, - //если она была уже установлена - _pictureWidth = width; - _pictureHeight = height; - return true; + if (_drawingWarshipWidth < width && _drawingWarshipHeight < height) + { + _pictureWidth = width; + _pictureHeight = height; + if (_startPosX.HasValue && _startPosY.HasValue) + { + SetPosition(_startPosX.Value, _startPosY.Value); + } + + return true; + } + else + { + return false; + } } /// /// Установка позиции @@ -91,11 +99,20 @@ public bool SetPictureSize(int width, int height) { return; } - // TODO если при установке объекта в эти координаты, он будет - //"выходить" за границы формы - // то надо изменить координаты, чтобы он оставался в этих границах - _startPosX = x; - _startPosY = y; + if (x > 0 && y > 0 && x + _drawingWarshipWidth < _pictureWidth + && y + _drawingWarshipHeight < _pictureHeight) + { + _startPosX = x; + _startPosY = y; + } + else + { + Random rnd = new(); + _startPosX = rnd.Next(0, _pictureWidth.Value - + _drawingWarshipWidth); + _startPosY = rnd.Next(0, _pictureHeight.Value - + _drawingWarshipHeight); + } } /// /// Изменение направления перемещения @@ -103,7 +120,7 @@ public bool SetPictureSize(int width, int height) /// Направление /// true - перемещене выполнено, false - перемещение ///невозможно -public bool MoveTransport(DirectionType direction) + public bool MoveTransport(DirectionType direction) { if (EntityWarship == null || !_startPosX.HasValue || !_startPosY.HasValue) @@ -126,13 +143,19 @@ public bool MoveTransport(DirectionType direction) _startPosY -= (int)EntityWarship.Step; } return true; - // вправо + //вправо case DirectionType.Right: - //TODO прописать логику сдвига в право + if (_startPosX + _drawingWarshipWidth + EntityWarship.Step < _pictureWidth) + { + _startPosX += (int)EntityWarship.Step; + } return true; //вниз case DirectionType.Down: - //TODO прописать логику сдвига в вниз + if (_startPosY + _drawingWarshipHeight + EntityWarship.Step < _pictureHeight) + { + _startPosY += (int)EntityWarship.Step; + } return true; default: return false; @@ -189,9 +212,9 @@ public bool MoveTransport(DirectionType direction) /// /// Ширина объекта /// - public int GetWidth => _drawningWarshipWidth; + public int GetWidth => _drawingWarshipWidth; /// /// Высота объекта /// - public int GetHeight => _drawningWarshipHeight; + public int GetHeight => _drawingWarshipHeight; } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/EntityBattleship.cs b/ProjectBattleship/ProjectBattleship/EntityBattleship.cs index 3f98e5e..1b1e7fa 100644 --- a/ProjectBattleship/ProjectBattleship/EntityBattleship.cs +++ b/ProjectBattleship/ProjectBattleship/EntityBattleship.cs @@ -4,27 +4,9 @@ namespace ProjectBattleship.Entities; /// /// Класс-сущность "Линкор" /// -public class EntityBattleship +public class EntityBattleship : EntityWarship { - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// - /// Дополнительный цвет (для опциональных элементов) - /// public Color AdditionalColor { get; private set; } - /// - /// Признак (опция) наличия орудийной башни - /// public bool Turret { get; private set; } /// /// Признак (опция) наличия отсека под ракеты @@ -33,7 +15,8 @@ public class EntityBattleship /// /// Шаг перемещения корабля /// - public double Step => Speed * 100 / Weight; + + /// /// Инициализация полей объекта-класса спортивного автомобиля /// @@ -43,12 +26,10 @@ public class EntityBattleship /// Дополнительный цвет /// Признак наличия орудийной башни /// Признак наличия отсека под ракеты - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool turret, bool rocketCompartment) + + + public EntityBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool turret, bool rocketCompartment) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; Turret = turret; RocketCompartment = rocketCompartment; diff --git a/ProjectBattleship/ProjectBattleship/EntityWarship.cs b/ProjectBattleship/ProjectBattleship/EntityWarship.cs index 0ddce52..7faeff8 100644 --- a/ProjectBattleship/ProjectBattleship/EntityWarship.cs +++ b/ProjectBattleship/ProjectBattleship/EntityWarship.cs @@ -17,19 +17,28 @@ public class EntityWarship /// public Color BodyColor { get; private set; } /// - /// Шаг перемещения автомобиля + /// Дополнительный цвет (для опциональных элементов) + /// + + /// + /// Признак (опция) наличия орудийной башни + /// + public Color AdditionalColor { get; private set; } + public bool Turret { get; private set; } + /// + /// Признак (опция) наличия отсека под ракеты + /// + public bool RocketCompartment { get; private set; } + /// + /// Шаг перемещения корабля /// public double Step => Speed * 100 / Weight; - /// - /// Конструктор сущности - /// - /// Скорость - /// Вес автомобиля - /// Основной цвет public EntityWarship(int speed, double weight, Color bodyColor) { Speed = speed; Weight = weight; BodyColor = bodyColor; + } + } \ No newline at end of file diff --git a/ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs b/ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs index d9cc026..152b317 100644 --- a/ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs +++ b/ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs @@ -58,7 +58,7 @@ buttonCreateBattleship.Name = "buttonCreateBattleship"; buttonCreateBattleship.Size = new Size(201, 40); buttonCreateBattleship.TabIndex = 1; - buttonCreateBattleship.Text = "Создать Линкор"; + buttonCreateBattleship.Text = "Создать линкор"; buttonCreateBattleship.UseVisualStyleBackColor = true; buttonCreateBattleship.Click += ButtonCreateBattleship_Click; // @@ -116,7 +116,9 @@ // // comboBoxStrategy // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру ", "К краю" }); comboBoxStrategy.Location = new Point(652, 12); comboBoxStrategy.Name = "comboBoxStrategy"; comboBoxStrategy.Size = new Size(212, 38); @@ -131,6 +133,7 @@ button1.Text = "шаг"; button1.TextAlign = ContentAlignment.TopCenter; button1.UseVisualStyleBackColor = true; + button1.Click += ButtonStrategyStep_Click; // // buttonCreateWarship // @@ -140,6 +143,7 @@ buttonCreateWarship.TabIndex = 8; buttonCreateWarship.Text = "Создать корабль"; buttonCreateWarship.UseVisualStyleBackColor = true; + buttonCreateWarship.Click += ButtonCreateWarship_Click; // // FormBattleship // diff --git a/ProjectBattleship/ProjectBattleship/FormBattleship.cs b/ProjectBattleship/ProjectBattleship/FormBattleship.cs index b8f3629..8e6e7ca 100644 --- a/ProjectBattleship/ProjectBattleship/FormBattleship.cs +++ b/ProjectBattleship/ProjectBattleship/FormBattleship.cs @@ -1,7 +1,5 @@ using ProjectBattleship.MovementStrategy; -using ProjectBattleship; using ProjectBattleship.DrawingObject; -using ProjectBattleship.MovementStrategy; namespace ProjectBattleship; /// /// " " @@ -11,7 +9,7 @@ public partial class FormBattleship : Form /// /// - /// - private DrawingWarship? _drawningWarship; + private DrawingWarship? _drawingWarship; /// /// /// @@ -29,14 +27,14 @@ public partial class FormBattleship : Form /// private void Draw() { - if (_drawningWarship == null) + if (_drawingWarship == null) { return; } Bitmap bmp = new(pictureBoxBattleship.Width, pictureBoxBattleship.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningWarship.DrawTransport(gr); + _drawingWarship.DrawTransport(gr); pictureBoxBattleship.Image = bmp; } /// @@ -49,13 +47,13 @@ public partial class FormBattleship : Form switch (type) { case nameof(DrawingWarship): - _drawningWarship = new DrawingWarship(random.Next(100, 300), + _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): - _drawningWarship = new DrawingBattleship(random.Next(100, + _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)), @@ -67,9 +65,9 @@ public partial class FormBattleship : Form default: return; } - _drawningWarship.SetPictureSize(pictureBoxBattleship.Width, + _drawingWarship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height); - _drawningWarship.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _drawingWarship.SetPosition(random.Next(10, 100), random.Next(10, 100)); _strategy = null; comboBoxStrategy.Enabled = true; Draw(); @@ -95,7 +93,7 @@ public partial class FormBattleship : Form /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningWarship == null) + if (_drawingWarship == null) { return; } @@ -104,17 +102,17 @@ public partial class FormBattleship : Form switch (name) { case "buttonUp": - result = _drawningWarship.MoveTransport(DirectionType.Up); + result = _drawingWarship.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = _drawningWarship.MoveTransport(DirectionType.Down); + result = _drawingWarship.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = _drawningWarship.MoveTransport(DirectionType.Left); + result = _drawingWarship.MoveTransport(DirectionType.Left); break; case "buttonRight": result = - _drawningWarship.MoveTransport(DirectionType.Right); + _drawingWarship.MoveTransport(DirectionType.Right); break; } if (result) @@ -129,7 +127,7 @@ public partial class FormBattleship : Form /// private void ButtonStrategyStep_Click(object sender, EventArgs e) { - if (_drawningWarship == null) + if (_drawingWarship == null) { return; } @@ -145,7 +143,7 @@ public partial class FormBattleship : Form { return; } - _strategy.SetData(new MoveableWarship(_drawningWarship), + _strategy.SetData(new MoveableWarship(_drawingWarship), pictureBoxBattleship.Width, pictureBoxBattleship.Height); } if (_strategy == null) diff --git a/ProjectBattleship/ProjectBattleship/IMoveableObject.cs b/ProjectBattleship/ProjectBattleship/IMoveableObject.cs index 1916e77..f12339c 100644 --- a/ProjectBattleship/ProjectBattleship/IMoveableObject.cs +++ b/ProjectBattleship/ProjectBattleship/IMoveableObject.cs @@ -1,6 +1,4 @@ -using ProjectBattleship.MovementStrategy; - -namespace ProjectBattleship.MovementStrategy; +namespace ProjectBattleship.MovementStrategy; /// /// Интерфейс для работы с перемещаемым объектом /// diff --git a/ProjectBattleship/ProjectBattleship/MoveToBorder.cs b/ProjectBattleship/ProjectBattleship/MoveToBorder.cs new file mode 100644 index 0000000..5962022 --- /dev/null +++ b/ProjectBattleship/ProjectBattleship/MoveToBorder.cs @@ -0,0 +1,53 @@ +namespace ProjectBattleship.MovementStrategy +{ + /// + /// Стратегия перемещения объекта к краю экрана + /// + internal class MoveToBorder : AbstractStrategy + { + protected override bool IsTargetDestinaion() + { + 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(); + } + } + } + } +} diff --git a/ProjectBattleship/ProjectBattleship/MoveToCenter.cs b/ProjectBattleship/ProjectBattleship/MoveToCenter.cs index c52bed1..ddf375b 100644 --- a/ProjectBattleship/ProjectBattleship/MoveToCenter.cs +++ b/ProjectBattleship/ProjectBattleship/MoveToCenter.cs @@ -1,6 +1,4 @@ -using ProjectBattleship.MovementStrategy; - -namespace ProjectBattleship.MovementStrategy; +namespace ProjectBattleship.MovementStrategy; /// /// Стратегия перемещения объекта в центр экрана ///