diff --git a/ProjectCruiser/ProjectCruiser/Drawings/DirectionType.cs b/ProjectCruiser/ProjectCruiser/Drawings/DirectionType.cs new file mode 100644 index 0000000..4f4876b --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/Drawings/DirectionType.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.Drawings; + +/// +/// Направление перемещения +/// +public enum DirectionType +{ + /// + /// Неизвестное направление + /// + Unknow = -1, + + /// + /// Вверх + /// + Up = 1, + + /// + /// Вниз + /// + Down = 2, + + /// + /// Влева + /// + Left = 3, + + /// + /// Вправо + /// + Right = 4 +} + diff --git a/ProjectCruiser/ProjectCruiser/Drawings/DrawningCruiser.cs b/ProjectCruiser/ProjectCruiser/Drawings/DrawningCruiser.cs new file mode 100644 index 0000000..e3cdcbb --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/Drawings/DrawningCruiser.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectCruiser.Entities; + +namespace ProjectCruiser.Drawings; + +public class DrawningCruiser +{ + /// + /// Класс-сущность + /// + public EntityCruiser? EntityCruiser { get; protected set; } + /// + /// Ширина окна + /// + private int? _pictureWidth; + /// + /// Высота окна + /// + private int? _pictureHeight; + /// + /// Левая координата прорисовки крейсера + /// + + protected int? _startPosX; + /// + /// Верхняя координата прорисовки крейсера + /// + protected int? _startPosY; + + /// + /// Ширина прорисовки крейсера + /// + private readonly int _drawningCruiserWidth = 180; + /// + /// Высота прорисовки крейсера + /// + private readonly int _drawingCruiserHeight = 70; + + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningCruiserWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawingCruiserHeight; + + /// + /// Пустой конструктор + /// + private DrawningCruiser() { + _pictureWidth = null; + _pictureHeight = null; + _startPosX = null; + _startPosY = null; + } + + /// + /// Констуктор + /// + /// Скорость + /// Вес крейсера + /// Скорость + public DrawningCruiser(int speed, double weigth, Color bodyColor): this() + { + EntityCruiser = new EntityCruiser(speed, weigth, bodyColor); + } + + /// + /// Констуктор для наследников + /// + /// Ширина прорисовки крейсера + /// Высота прорисовки крейсера + protected DrawningCruiser(int drawningCruiserWidth, int drawingCruiserHeight) : this() + { + _drawningCruiserWidth = drawningCruiserWidth; + _drawingCruiserHeight = drawingCruiserHeight; + } + + public bool SetPictireSize(int width, int height) + { + _pictureWidth = width; + _pictureHeight = height; + return true; + } + + public void SetPosition(int x, int y) + { + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) + { + return; + } + + _startPosX = x; + _startPosY = y; + } + + public bool MoveTransport(DirectionType direction) + { + if (EntityCruiser == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return false; + } + + switch (direction) + { + case DirectionType.Left: + if (_startPosX.Value - EntityCruiser.Step > 0) + { + _startPosX -= (int)EntityCruiser.Step; + } + return true; + + case DirectionType.Up: + if (_startPosY.Value - EntityCruiser.Step > 0) + { + _startPosY -= (int)EntityCruiser.Step; + } + return true; + case DirectionType.Right: + if (_startPosX.Value + _drawningCruiserWidth + EntityCruiser.Step < _pictureWidth) + { + _startPosX += (int)EntityCruiser.Step; + } + return true; + case DirectionType.Down: + if (_startPosY.Value + _drawingCruiserHeight + EntityCruiser.Step < _pictureHeight) + { + _startPosY += (int)EntityCruiser.Step; + } + return true; + default: + return false; + } + } + + public virtual void DrawTransport(Graphics g) + { + if (EntityCruiser == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black); + + // Основной корпус крейсера + Brush Brush = new + SolidBrush(EntityCruiser.BodyColor); + + Point[] hull = new Point[] + { + new Point((int)(_startPosX + 5), (int)(_startPosY + 10)), + new Point((int)(_startPosX + 110), (int)(_startPosY + 10)), + new Point((int)(_startPosX + 170), (int)(_startPosY + 40)), + new Point((int)(_startPosX + 110), (int)(_startPosY + 60)), + new Point((int)(_startPosX + 5), (int)(_startPosY + 60)) + }; + g.FillPolygon(Brush, hull); + g.DrawPolygon(pen, hull); + + } +} diff --git a/ProjectCruiser/ProjectCruiser/Drawings/DrawningMilitaryCruiser.cs b/ProjectCruiser/ProjectCruiser/Drawings/DrawningMilitaryCruiser.cs new file mode 100644 index 0000000..9409d28 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/Drawings/DrawningMilitaryCruiser.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectCruiser.Entities; + +namespace ProjectCruiser.Drawings; + +public class DrawningMilitaryCruiser: DrawningCruiser +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес крейсера + /// Скорость + /// Дополнительный цвет + /// Признак наличия обвеса + /// Признак наличия брони + /// Признак наличия оружия + public DrawningMilitaryCruiser(int speed, double weigth, Color bodyColor, Color additionalColor, bool bodyKit, bool armor, bool weapon): base(180, 70) + { + EntityCruiser = new EntityMilitaryCruiser(speed, weigth, bodyColor, additionalColor, bodyKit, armor, weapon); + } + + public override void DrawTransport(Graphics g) + { + + if (EntityCruiser == null || EntityCruiser is not EntityMilitaryCruiser militaryCruiser || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black); + + // Основной корпус парусника + Brush brush = new SolidBrush(militaryCruiser.BodyColor); + + Point[] hull = new Point[] + { + new Point((int)(_startPosX + 5), (int)(_startPosY + 10)), + new Point((int)(_startPosX + 110), (int)(_startPosY + 10)), + new Point((int)(_startPosX + 170), (int)(_startPosY + 40)), + new Point((int)(_startPosX + 110), (int)(_startPosY + 60)), + new Point((int)(_startPosX + 5), (int)(_startPosY + 60)) + }; + g.FillPolygon(brush, hull); + g.DrawPolygon(pen, hull); + base.DrawTransport(g); + + //Взлетная полоса + Brush additionalBrush = new SolidBrush(militaryCruiser.AdditionalColor); + g.FillEllipse(additionalBrush, (int)(_startPosX + 100), (int)(_startPosY + 25), 20, 20); + g.DrawEllipse(pen, (int)(_startPosX + 100), (int)(_startPosY + 25), 20, 20); + + //Рокетная шахта + g.FillRectangle(additionalBrush, (int)(_startPosX + 70), (int)(_startPosY + 20), 20, 30); + g.FillRectangle(additionalBrush, (int)(_startPosX + 40), (int)(_startPosY + 27), 30, 15); + + } +} diff --git a/ProjectCruiser/ProjectCruiser/Entities/EntityCruiser.cs b/ProjectCruiser/ProjectCruiser/Entities/EntityCruiser.cs new file mode 100644 index 0000000..0f9bcb5 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/Entities/EntityCruiser.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.Entities; + +/// +/// Класс-сущность "Крейсер" Вариант 18 +/// +public class EntityCruiser +{ + /// + /// Скорость + /// + public int Speed { get; protected set; } + + /// + /// Вес + /// + public double Weigth { get; protected set; } + + /// + /// Основной цвет + /// + public Color BodyColor { get; protected set; } + + /// + /// Шаг перемещения крейсера + /// + public double Step => Speed * 100 / Weigth; + + /// + /// Конструктор сущности + /// + /// Скорость + /// Вес крейсера + /// Скорость + public EntityCruiser(int speed, double weigth, Color bodyColor) + { + Speed = speed; + Weigth = weigth; + BodyColor = bodyColor; + } +} diff --git a/ProjectCruiser/ProjectCruiser/Entities/EntityMilitaryCruiser.cs b/ProjectCruiser/ProjectCruiser/Entities/EntityMilitaryCruiser.cs new file mode 100644 index 0000000..eb780c0 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/Entities/EntityMilitaryCruiser.cs @@ -0,0 +1,49 @@ +namespace ProjectCruiser.Entities +{ + /// + /// Класс-сущность "Военный Крейсер" Вариант 18 + /// + public class EntityMilitaryCruiser: EntityCruiser + { + /// + /// Дополнительный цвет (для опциональных элементов) + /// + public Color AdditionalColor { get; private set; } + + /// + /// Признак (опция) наличие обвеса + /// + public bool BodyKit { get; private set; } + + /// + /// Признак (опция) брони + /// + public bool Armor { get; private set; } + + /// + /// Признак (опция) оружия + /// + public bool Weapon { get; private set; } + + /// + /// Инициализация полей объекта класса крейсера + /// + /// Скорость + /// Вес крейсера + /// Скорость + /// Дополнительный цвет + /// Признак наличия обвеса + /// Признак наличия брони + /// Признак наличия оружия + public EntityMilitaryCruiser(int speed, double weigth, Color bodyColor, Color additionalColor, bool bodyKit, bool armor, bool weapon): base(speed, weigth, bodyColor) + { + Speed = speed; + Weigth = weigth; + BodyColor = bodyColor; + AdditionalColor = additionalColor; + BodyKit = bodyKit; + Armor = armor; + Weapon = weapon; + } + } +} diff --git a/ProjectCruiser/ProjectCruiser/Form1.Designer.cs b/ProjectCruiser/ProjectCruiser/Form1.Designer.cs deleted file mode 100644 index a813ab1..0000000 --- a/ProjectCruiser/ProjectCruiser/Form1.Designer.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace ProjectCruiser -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - SuspendLayout(); - // - // Form1 - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); - Name = "Form1"; - Text = "Form1"; - ResumeLayout(false); - } - - #endregion - } -} diff --git a/ProjectCruiser/ProjectCruiser/Form1.cs b/ProjectCruiser/ProjectCruiser/Form1.cs deleted file mode 100644 index 99d4497..0000000 --- a/ProjectCruiser/ProjectCruiser/Form1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ProjectCruiser -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - } -} diff --git a/ProjectCruiser/ProjectCruiser/FormCruiser.Designer.cs b/ProjectCruiser/ProjectCruiser/FormCruiser.Designer.cs new file mode 100644 index 0000000..9b8c644 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/FormCruiser.Designer.cs @@ -0,0 +1,176 @@ +namespace ProjectCruiser +{ + partial class FormCruiser + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + pictureBoxCruiser = new PictureBox(); + buttonCreateMilitaryCruiser = new Button(); + buttonDown = new Button(); + buttonUp = new Button(); + buttonRight = new Button(); + buttonLeft = new Button(); + buttonCreateCruiser = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); + ((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit(); + SuspendLayout(); + // + // pictureBoxCruiser + // + pictureBoxCruiser.Dock = DockStyle.Fill; + pictureBoxCruiser.Location = new Point(0, 0); + pictureBoxCruiser.Name = "pictureBoxCruiser"; + pictureBoxCruiser.Size = new Size(800, 450); + pictureBoxCruiser.TabIndex = 0; + pictureBoxCruiser.TabStop = false; + // + // buttonCreateMilitaryCruiser + // + buttonCreateMilitaryCruiser.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateMilitaryCruiser.Location = new Point(12, 409); + buttonCreateMilitaryCruiser.Name = "buttonCreateMilitaryCruiser"; + buttonCreateMilitaryCruiser.Size = new Size(216, 29); + buttonCreateMilitaryCruiser.TabIndex = 1; + buttonCreateMilitaryCruiser.Text = "Создать военный крейсер"; + buttonCreateMilitaryCruiser.UseVisualStyleBackColor = true; + buttonCreateMilitaryCruiser.Click += ButtonCreateMilitaryCruiser_Click; + // + // buttonDown + // + buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonDown.BackgroundImage = Properties.Resources.arrowDown; + buttonDown.BackgroundImageLayout = ImageLayout.Stretch; + buttonDown.Location = new Point(682, 392); + buttonDown.Name = "buttonDown"; + buttonDown.Size = new Size(35, 35); + buttonDown.TabIndex = 2; + buttonDown.UseVisualStyleBackColor = true; + buttonDown.Click += ButtonMove_Click; + // + // buttonUp + // + buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonUp.BackgroundImage = Properties.Resources.arrowUp; + buttonUp.BackgroundImageLayout = ImageLayout.Stretch; + buttonUp.Location = new Point(682, 351); + buttonUp.Name = "buttonUp"; + buttonUp.Size = new Size(35, 35); + buttonUp.TabIndex = 3; + buttonUp.UseVisualStyleBackColor = true; + buttonUp.Click += ButtonMove_Click; + // + // buttonRight + // + buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonRight.BackgroundImage = Properties.Resources.arrowRight; + buttonRight.BackgroundImageLayout = ImageLayout.Stretch; + buttonRight.Location = new Point(723, 392); + buttonRight.Name = "buttonRight"; + buttonRight.Size = new Size(35, 35); + buttonRight.TabIndex = 4; + buttonRight.UseVisualStyleBackColor = true; + buttonRight.Click += ButtonMove_Click; + // + // buttonLeft + // + buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonLeft.BackgroundImage = Properties.Resources.arrowLeft; + buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; + buttonLeft.Location = new Point(641, 392); + buttonLeft.Name = "buttonLeft"; + buttonLeft.Size = new Size(35, 35); + buttonLeft.TabIndex = 5; + buttonLeft.UseVisualStyleBackColor = true; + buttonLeft.Click += ButtonMove_Click; + // + // buttonCreateCruiser + // + buttonCreateCruiser.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateCruiser.Location = new Point(234, 409); + buttonCreateCruiser.Name = "buttonCreateCruiser"; + buttonCreateCruiser.Size = new Size(179, 29); + buttonCreateCruiser.TabIndex = 6; + buttonCreateCruiser.Text = "Создать крейсер"; + buttonCreateCruiser.UseVisualStyleBackColor = true; + buttonCreateCruiser.Click += buttonCreateCruiser_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(637, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(151, 28); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonStrategyStep.Location = new Point(694, 46); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(94, 29); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // + // FormCruiser + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateCruiser); + Controls.Add(buttonLeft); + Controls.Add(buttonRight); + Controls.Add(buttonUp); + Controls.Add(buttonDown); + Controls.Add(buttonCreateMilitaryCruiser); + Controls.Add(pictureBoxCruiser); + Name = "FormCruiser"; + Text = "Крейсер"; + ((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).EndInit(); + ResumeLayout(false); + } + + #endregion + + private PictureBox pictureBoxCruiser; + private Button buttonCreateMilitaryCruiser; + private Button buttonDown; + private Button buttonUp; + private Button buttonRight; + private Button buttonLeft; + private Button buttonCreateCruiser; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; + } +} \ No newline at end of file diff --git a/ProjectCruiser/ProjectCruiser/FormCruiser.cs b/ProjectCruiser/ProjectCruiser/FormCruiser.cs new file mode 100644 index 0000000..1cce72e --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/FormCruiser.cs @@ -0,0 +1,150 @@ +using ProjectCruiser.Drawings; +using ProjectCruiser.MovementStrategy; + +namespace ProjectCruiser +{ + public partial class FormCruiser : Form + { + + private DrawningCruiser? _drawingCruiser; + + private AbstactStrategy? _strategy; + public FormCruiser() + { + InitializeComponent(); + _strategy = null; + } + + private void Draw() + { + if (_drawingCruiser == null) + { + return; + } + + Bitmap bmp = new(pictureBoxCruiser.Width, pictureBoxCruiser.Height); + Graphics gr = Graphics.FromImage(bmp); + _drawingCruiser.DrawTransport(gr); + pictureBoxCruiser.Image = bmp; + } + + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningCruiser): + + _drawingCruiser = new DrawningCruiser(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(DrawningMilitaryCruiser): + + _drawingCruiser = new DrawningMilitaryCruiser(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; + } + + _drawingCruiser.SetPictireSize(pictureBoxCruiser.Width, pictureBoxCruiser.Height); + _drawingCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + + /// + /// Обработка нажатия кнопки "Создать военный крейсер" + /// + /// + /// + private void ButtonCreateMilitaryCruiser_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMilitaryCruiser)); + + /// + /// Обработка нажатия кнопки "Создать крейсер" + /// + /// + /// + private void buttonCreateCruiser_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningCruiser)); + + private void ButtonMove_Click(object sender, EventArgs e) + { + if (_drawingCruiser == null) + { + return; + } + + string name = ((Button)sender)?.Name ?? string.Empty; + bool result = false; + switch (name) + { + case "buttonUp": + result = _drawingCruiser.MoveTransport(DirectionType.Up); + break; + case "buttonDown": + result = _drawingCruiser.MoveTransport(DirectionType.Down); + break; + case "buttonLeft": + result = _drawingCruiser.MoveTransport(DirectionType.Left); + break; + case "buttonRight": + result = _drawingCruiser.MoveTransport(DirectionType.Right); + break; + } + + if (result) + { + Draw(); + } + } + + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawingCruiser == null) { return; } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return ; + } + _strategy.SetData(new MoveableCruiser(_drawingCruiser), pictureBoxCruiser.Width, pictureBoxCruiser.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } + } +} diff --git a/ProjectCruiser/ProjectCruiser/Form1.resx b/ProjectCruiser/ProjectCruiser/FormCruiser.resx similarity index 100% rename from ProjectCruiser/ProjectCruiser/Form1.resx rename to ProjectCruiser/ProjectCruiser/FormCruiser.resx diff --git a/ProjectCruiser/ProjectCruiser/MovementStrategy/AbstactStrategy.cs b/ProjectCruiser/ProjectCruiser/MovementStrategy/AbstactStrategy.cs new file mode 100644 index 0000000..b38a124 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/MovementStrategy/AbstactStrategy.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.MovementStrategy; + +/// +/// Класс-стратегия перемещения объекта +/// +public abstract class AbstactStrategy +{ + /// + /// Перемещаемы объект + /// + private IMoveableObject? _moveableObject; + + /// + /// Статус перемещения + /// + private StrategyStatus _state = StrategyStatus.NotInit; + + /// + /// Ширина перемещения + /// + protected int FieldWidth { get; private set; } + + /// + /// Высота перемещения + /// + protected int FieldHeight { get; private set; } + + /// + /// Статус перемещения + /// + public StrategyStatus GetStatus() { return _state; } + + /// + /// Установка данных + /// + /// Перемещаемы объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObject moveableObject, int width, int height) + { + if (moveableObject == null) + { + _state = StrategyStatus.NotInit; + return; + } + + _state = StrategyStatus.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + + if (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 => _moveableObject?.GetObjectPosition; + + + protected int? GetStep() + { + if (_state != StrategyStatus.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + + + + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestination(); + + + private bool MoveTo(MovementDirection direction) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + return _moveableObject?.TryMoveObject(direction) ?? false; + } + +} diff --git a/ProjectCruiser/ProjectCruiser/MovementStrategy/IMoveableObject.cs b/ProjectCruiser/ProjectCruiser/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..fd23511 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.MovementStrategy; + +/// +/// Интерфейс для работы с перемещением объектов +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveToBorder.cs b/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..8469f08 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,50 @@ +namespace ProjectCruiser.MovementStrategy; + +public class MoveToBorder : AbstactStrategy +{ + protected override bool IsTargetDestination() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth && + objParams.ObjectMiddleVertical - GetStep() <= FieldHeight && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + int diffX = objParams.ObjectMiddleHorizontal - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + + int diffY = objParams.ObjectMiddleVertical - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} diff --git a/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveToCenter.cs b/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..c88b51e --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.MovementStrategy; + +public class MoveToCenter : AbstactStrategy +{ + protected override bool IsTargetDestination() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && + objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; + } + + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + + int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } else + { + MoveRight(); + } + } + + int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } else + { + MoveDown(); + } + } + } +} diff --git a/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveableCruiser.cs b/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveableCruiser.cs new file mode 100644 index 0000000..4755f4d --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/MovementStrategy/MoveableCruiser.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectCruiser.Drawings; + +namespace ProjectCruiser.MovementStrategy; + +/// +/// Класс реализация IMoveableObject с использованием DrawningCruiser +/// +public class MoveableCruiser : IMoveableObject +{ + /// + /// Поле-объект класса DrawningCruiser или его наследника + /// + private readonly DrawningCruiser? _cruiser = null; + + /// + /// Конструктор + /// + /// + public MoveableCruiser(DrawningCruiser? cruiser) + { + _cruiser = cruiser; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_cruiser == null || _cruiser.EntityCruiser == null || !_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_cruiser.GetPosX.Value, _cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight); + } + } + + public int GetStep => (int)(_cruiser?.EntityCruiser?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_cruiser == null || _cruiser.EntityCruiser == null) + { + return false; + } + return _cruiser.MoveTransport(GetDirectionType(direction)); + } + + /// + /// Конвертация из 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/ProjectCruiser/ProjectCruiser/MovementStrategy/MovementDirection.cs b/ProjectCruiser/ProjectCruiser/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..2d6fe5f --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/MovementStrategy/MovementDirection.cs @@ -0,0 +1,24 @@ +namespace ProjectCruiser.MovementStrategy; + +/// +/// Направление перемещения +/// +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влева + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/ProjectCruiser/ProjectCruiser/MovementStrategy/ObjectParameters.cs b/ProjectCruiser/ProjectCruiser/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..dd28ac0 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.MovementStrategy; +/// +/// Параметры координаты объекта +/// +public class ObjectParameters +{ + /// + /// Координата X + /// + private readonly int _x; + + /// + /// Координата Y + /// + private readonly int _y; + + /// + /// Ширина объекта + /// + private readonly int _width; + + /// + /// Высота объекта + /// + private readonly int _height; + + /// + /// Левая граница + /// + public int LeftBorder => _x; + + /// + /// Верхняя граница + /// + public int TopBorder => _y; + + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + + /// + /// Середина объекта + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + + /// + /// Середина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + + /// + /// Конструктор + /// + /// + /// + /// + /// + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/ProjectCruiser/ProjectCruiser/MovementStrategy/StrategyStatus.cs b/ProjectCruiser/ProjectCruiser/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..d769b40 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish +} diff --git a/ProjectCruiser/ProjectCruiser/Program.cs b/ProjectCruiser/ProjectCruiser/Program.cs index 2ddf3fc..4e00cd8 100644 --- a/ProjectCruiser/ProjectCruiser/Program.cs +++ b/ProjectCruiser/ProjectCruiser/Program.cs @@ -11,7 +11,7 @@ namespace ProjectCruiser // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); + Application.Run(new FormCruiser()); } } } \ No newline at end of file diff --git a/ProjectCruiser/ProjectCruiser/ProjectCruiser.csproj b/ProjectCruiser/ProjectCruiser/ProjectCruiser.csproj index 663fdb8..af03d74 100644 --- a/ProjectCruiser/ProjectCruiser/ProjectCruiser.csproj +++ b/ProjectCruiser/ProjectCruiser/ProjectCruiser.csproj @@ -8,4 +8,19 @@ enable + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + \ No newline at end of file diff --git a/ProjectCruiser/ProjectCruiser/Properties/Resources.Designer.cs b/ProjectCruiser/ProjectCruiser/Properties/Resources.Designer.cs new file mode 100644 index 0000000..724a88c --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/Properties/Resources.Designer.cs @@ -0,0 +1,103 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace ProjectCruiser.Properties { + using System; + + + /// + /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. + /// + // Этот класс создан автоматически классом StronglyTypedResourceBuilder + // с помощью такого средства, как ResGen или Visual Studio. + // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen + // с параметром /str или перестройте свой проект VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectCruiser.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Перезаписывает свойство CurrentUICulture текущего потока для всех + /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap arrowDown { + get { + object obj = ResourceManager.GetObject("arrowDown", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap arrowLeft { + get { + object obj = ResourceManager.GetObject("arrowLeft", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap arrowRight { + get { + object obj = ResourceManager.GetObject("arrowRight", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap arrowUp { + get { + object obj = ResourceManager.GetObject("arrowUp", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/ProjectCruiser/ProjectCruiser/Properties/Resources.resx b/ProjectCruiser/ProjectCruiser/Properties/Resources.resx new file mode 100644 index 0000000..b4f1385 --- /dev/null +++ b/ProjectCruiser/ProjectCruiser/Properties/Resources.resx @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + Resources\arrowDown.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + Resources\arrowLeft.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + Resources\arrowRight.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + Resources\arrowUp.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowDown.png b/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowDown.png new file mode 100644 index 0000000..fec3972 Binary files /dev/null and b/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowDown.png differ diff --git a/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowLeft.png b/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowLeft.png new file mode 100644 index 0000000..0a1d82c Binary files /dev/null and b/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowLeft.png differ diff --git a/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowRight.png b/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowRight.png new file mode 100644 index 0000000..eecf7b0 Binary files /dev/null and b/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowRight.png differ diff --git a/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowUp.png b/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowUp.png new file mode 100644 index 0000000..e2a4a93 Binary files /dev/null and b/ProjectCruiser/ProjectCruiser/Properties/Resources/arrowUp.png differ