diff --git a/ProjectCruiser/DirectionType.cs b/ProjectCruiser/Drawnings/DirectionType.cs similarity index 53% rename from ProjectCruiser/DirectionType.cs rename to ProjectCruiser/Drawnings/DirectionType.cs index 5d71959..1ef4846 100644 --- a/ProjectCruiser/DirectionType.cs +++ b/ProjectCruiser/Drawnings/DirectionType.cs @@ -1,13 +1,17 @@ -namespace ProjectCruiser; +namespace ProjectCruiser.Drawnings; /// /// /// public enum DirectionType { - /// - /// - /// - Up = 1, + /// + /// + /// + Unknow = -1, + /// + /// + /// + Up = 1, /// /// /// diff --git a/ProjectCruiser/DrawningCruiser.cs b/ProjectCruiser/Drawnings/DrawningCruiser.cs similarity index 72% rename from ProjectCruiser/DrawningCruiser.cs rename to ProjectCruiser/Drawnings/DrawningCruiser.cs index 5f6a85a..b8cbec0 100644 --- a/ProjectCruiser/DrawningCruiser.cs +++ b/ProjectCruiser/Drawnings/DrawningCruiser.cs @@ -1,6 +1,6 @@ -using System.Drawing.Drawing2D; +using ProjectCruiser.Entities; -namespace ProjectCruiser; +namespace ProjectCruiser.Drawnings; /// /// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// @@ -9,7 +9,7 @@ public class DrawningCruiser /// /// Класс-сущность /// - public EntityCruiser? EntityCruiser { get; private set; } + public EntityCruiser? EntityCruiser { get; protected set; } /// /// Ширина окна /// @@ -21,11 +21,11 @@ public class DrawningCruiser /// /// Левая координата прорисовки автомобиля /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя кооридната прорисовки автомобиля /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки крейсера @@ -36,27 +36,56 @@ public class DrawningCruiser /// private readonly int _drawningCruiserHeight = 50; private readonly int _drawningEnginesWidth = 3; + /// - /// Инициализация свойств + /// Координата X объекта /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия вертолетной площадки - /// Признак наличия шлюпок - /// Признак наличия пушки - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool helicopterArea, bool boat, bool wepon) + public int? GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningCruiserWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningCruiserHeight; + + /// + /// Пустой онструктор + /// + private DrawningCruiser() { - EntityCruiser = new EntityCruiser(); - EntityCruiser.Init(speed, weight, bodyColor, additionalColor, - helicopterArea, boat, wepon); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawningCruiser(int speed, double weight, Color bodyColor) : this() + { + EntityCruiser = new EntityCruiser(speed, weight, bodyColor); + } + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки автомобиля + /// Высота прорисовки автомобиля + protected DrawningCruiser(int drawningCarWidth, int drawningCarHeight) : this() + { + _drawningCruiserWidth = drawningCarWidth; + _pictureHeight = drawningCarHeight; + } + /// /// Установка границ поля /// @@ -96,7 +125,7 @@ public class DrawningCruiser return; } - if (x < 0 || x + _drawningCruiserWidth > _pictureWidth || y < 0 || y + _drawningCruiserHeight > _pictureHeight) + if (x < 0 || x + _drawningCruiserWidth > _pictureWidth || y < 0 || y + _drawningCruiserHeight > _pictureHeight) { _startPosX = _pictureWidth - _drawningCruiserWidth; _startPosY = _pictureHeight - _drawningCruiserHeight; @@ -158,7 +187,7 @@ public class DrawningCruiser /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { if (EntityCruiser == null || !_startPosX.HasValue || !_startPosY.HasValue) @@ -167,10 +196,6 @@ public class DrawningCruiser } Pen pen = new(EntityCruiser.BodyColor, 2); Brush additionalBrush = new SolidBrush(Color.Black); - Brush weaponBrush = new SolidBrush(Color.Black); - Brush weaponBrush2 = new SolidBrush(EntityCruiser.AdditionalColor); - Brush helicopterAreaBrush = new HatchBrush(HatchStyle.ZigZag, EntityCruiser.AdditionalColor, Color.FromArgb(163, 163, 163)); - Brush boatBrush = new SolidBrush(EntityCruiser.AdditionalColor); //границы круисера g.DrawLine(pen, _startPosX.Value, _startPosY.Value, _startPosX.Value + 105, _startPosY.Value); @@ -191,28 +216,5 @@ public class DrawningCruiser g.FillRectangle(additionalBrush, _startPosX.Value - 3, _startPosY.Value + 7, 3, 14); g.FillRectangle(additionalBrush, _startPosX.Value - 3, _startPosY.Value + 26, 3, 14); - if (EntityCruiser.HelicopterArea) - { - g.FillEllipse(helicopterAreaBrush, _startPosX.Value + 5, _startPosY.Value + 9, 25, 30); - g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 9, 25, 30); - } - - if (EntityCruiser.Boat) - { - g.DrawEllipse(pen, _startPosX.Value + 34, _startPosY.Value + 2, 30, 7); - g.FillEllipse(boatBrush, _startPosX.Value + 34, _startPosY.Value + 2, 30, 7); - - g.DrawEllipse(pen, _startPosX.Value + 34, _startPosY.Value + 39, 30, 7); - g.FillEllipse(boatBrush, _startPosX.Value + 34, _startPosY.Value + 39, 30, 7); - } - - if (EntityCruiser.Weapon) - { - g.DrawEllipse(pen, _startPosX.Value + 97, _startPosY.Value + 36, 10, 10); - g.FillEllipse(weaponBrush2, _startPosX.Value + 97, _startPosY.Value + 36, 10, 10); - - g.FillRectangle(weaponBrush, _startPosX.Value + 107, _startPosY.Value + 40, 15, 5); - } - } } \ No newline at end of file diff --git a/ProjectCruiser/Drawnings/DrawningMilitaryCruiser.cs b/ProjectCruiser/Drawnings/DrawningMilitaryCruiser.cs new file mode 100644 index 0000000..a21ade3 --- /dev/null +++ b/ProjectCruiser/Drawnings/DrawningMilitaryCruiser.cs @@ -0,0 +1,67 @@ +using System.Drawing.Drawing2D; +using ProjectCruiser.Entities; + +namespace ProjectCruiser.Drawnings +{ + public class DrawningMilitaryCruiser : DrawningCruiser + { + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия вертолетной площадки + /// Признак наличия шлюпок + /// Признак наличия пушки + + public DrawningMilitaryCruiser(int speed, double weight, Color bodyColor, Color additionalColor, bool helicopterArea, bool boat, bool weapon) + : base(150, 50) + { + EntityCruiser = new EntityMilitaryCruiser(speed, weight, bodyColor, additionalColor, helicopterArea, boat, weapon); + } + + public override void DrawTransport(Graphics g) + { + if (EntityCruiser == null || EntityCruiser is not EntityMilitaryCruiser entityMilitaryCruiser || !_startPosX.HasValue || + !_startPosY.HasValue) + { + return; + } + + Pen pen = new(entityMilitaryCruiser.BodyColor, 2); + Brush additionalBrush = new SolidBrush(Color.Black); + Brush weaponBrush = new SolidBrush(Color.Black); + Brush weaponBrush2 = new SolidBrush(entityMilitaryCruiser.AdditionalColor); + Brush helicopterAreaBrush = new HatchBrush(HatchStyle.ZigZag, entityMilitaryCruiser.AdditionalColor, Color.FromArgb(163, 163, 163)); + Brush boatBrush = new SolidBrush(entityMilitaryCruiser.AdditionalColor); + + base.DrawTransport(g); + + if (entityMilitaryCruiser.HelicopterArea) + { + g.FillEllipse(helicopterAreaBrush, _startPosX.Value + 5, _startPosY.Value + 9, 25, 30); + g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 9, 25, 30); + } + + if (entityMilitaryCruiser.Boat) + { + g.DrawEllipse(pen, _startPosX.Value + 34, _startPosY.Value + 2, 30, 7); + g.FillEllipse(boatBrush, _startPosX.Value + 34, _startPosY.Value + 2, 30, 7); + + g.DrawEllipse(pen, _startPosX.Value + 34, _startPosY.Value + 39, 30, 7); + g.FillEllipse(boatBrush, _startPosX.Value + 34, _startPosY.Value + 39, 30, 7); + } + + if (entityMilitaryCruiser.Weapon) + { + g.DrawEllipse(pen, _startPosX.Value + 97, _startPosY.Value + 36, 10, 10); + g.FillEllipse(weaponBrush2, _startPosX.Value + 97, _startPosY.Value + 36, 10, 10); + + g.FillRectangle(weaponBrush, _startPosX.Value + 107, _startPosY.Value + 40, 15, 5); + } + + } + } +} diff --git a/ProjectCruiser/Entities/EntityCruiser.cs b/ProjectCruiser/Entities/EntityCruiser.cs new file mode 100644 index 0000000..d7e81bc --- /dev/null +++ b/ProjectCruiser/Entities/EntityCruiser.cs @@ -0,0 +1,38 @@ +namespace ProjectCruiser.Entities; + +/// +/// Класс-сущность "крейсер" +/// +public class EntityCruiser +{ + //свойства + /// + /// Скорость + /// + 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 EntityCruiser(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} diff --git a/ProjectCruiser/Entities/EntityMilitaryCruiser.cs b/ProjectCruiser/Entities/EntityMilitaryCruiser.cs new file mode 100644 index 0000000..46925ff --- /dev/null +++ b/ProjectCruiser/Entities/EntityMilitaryCruiser.cs @@ -0,0 +1,30 @@ +namespace ProjectCruiser.Entities +{ + internal class EntityMilitaryCruiser : EntityCruiser + { + /// + /// Признак (опция) наличие вертолетной площадки + /// + public bool HelicopterArea { get; private set; } + /// + /// Признак (опция) наличие шлюпок + /// + public bool Boat { get; private set; } + /// + /// Признак (опция) наличие пушки + /// + public bool Weapon { get; private set; } + /// + /// Дополнительный цвет (для опциональных элементов) + /// + public Color AdditionalColor { get; private set; } + + public EntityMilitaryCruiser(int speed, double weight, Color bodyColor, Color additionalColor, bool helicopterArea, bool boat, bool weapon) : base(speed, weight, bodyColor) + { + AdditionalColor = additionalColor; + HelicopterArea = helicopterArea; + Boat = boat; + Weapon = weapon; + } + } +} diff --git a/ProjectCruiser/EntityCruiser.cs b/ProjectCruiser/EntityCruiser.cs deleted file mode 100644 index aaabd12..0000000 --- a/ProjectCruiser/EntityCruiser.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace ProjectCruiser; -/// -/// Класс-сущность "крейсер" -/// -public class EntityCruiser -{ - //свойства - /// - /// Скорость - /// - 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 HelicopterArea { get; private set; } - /// - /// Признак (опция) наличие шлюпок - /// - public bool Boat { get; private set; } - /// - /// Признак (опция) наличие пушки - /// - public bool Weapon { get; private set; } - //поле класса - /// - /// Шаг перемещения автомобиля - /// - public double Step => Speed * 100 / Weight; - /// - /// Инициализация полей объекта-класса крейсера - /// - /// скорость - /// вес - /// основной цвет - /// дополнительный цвет - /// вертолетная площадка - /// шлюпки - /// наличие пушки - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool helicopterArea, bool boat, bool wepon) - { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; - AdditionalColor = additionalColor; - HelicopterArea = helicopterArea; - Boat = boat; - Weapon = wepon; - } -} diff --git a/ProjectCruiser/FormCruiser.Designer.cs b/ProjectCruiser/FormCruiser.Designer.cs index 21bd8ec..652e1eb 100644 --- a/ProjectCruiser/FormCruiser.Designer.cs +++ b/ProjectCruiser/FormCruiser.Designer.cs @@ -29,33 +29,36 @@ private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormCruiser)); - pictureBox1 = new PictureBox(); + pictureBoxCruiser = new PictureBox(); button1 = new Button(); buttonUp = new Button(); buttonDown = new Button(); buttonRight = new Button(); buttonLeft = new Button(); - ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); + comboBoxStrategy = new ComboBox(); + buttonCretaeCruiser = new Button(); + buttonStrategyStep = new Button(); + ((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit(); SuspendLayout(); // - // pictureBox1 + // pictureBoxCruiser // - pictureBox1.Dock = DockStyle.Fill; - pictureBox1.Location = new Point(0, 0); - pictureBox1.Name = "pictureBox1"; - pictureBox1.Size = new Size(800, 450); - pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize; - pictureBox1.TabIndex = 0; - pictureBox1.TabStop = false; + pictureBoxCruiser.Dock = DockStyle.Fill; + pictureBoxCruiser.Location = new Point(0, 0); + pictureBoxCruiser.Name = "pictureBoxCruiser"; + pictureBoxCruiser.Size = new Size(800, 450); + pictureBoxCruiser.SizeMode = PictureBoxSizeMode.AutoSize; + pictureBoxCruiser.TabIndex = 0; + pictureBoxCruiser.TabStop = false; // // button1 // button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; button1.Location = new Point(12, 409); button1.Name = "button1"; - button1.Size = new Size(94, 29); + button1.Size = new Size(213, 29); button1.TabIndex = 1; - button1.Text = "создать"; + button1.Text = "создать военный крейсер"; button1.UseVisualStyleBackColor = true; button1.Click += ButtonCreateCruiser_Click; // @@ -107,32 +110,70 @@ buttonLeft.UseVisualStyleBackColor = true; buttonLeft.Click += ButtonMove_Click; // - // Form1 + // 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 = 6; + // + // buttonCretaeCruiser + // + buttonCretaeCruiser.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCretaeCruiser.Location = new Point(240, 410); + buttonCretaeCruiser.Name = "buttonCretaeCruiser"; + buttonCretaeCruiser.Size = new Size(213, 29); + buttonCretaeCruiser.TabIndex = 7; + buttonCretaeCruiser.Text = "создать крейсер"; + buttonCretaeCruiser.UseVisualStyleBackColor = true; + buttonCretaeCruiser.Click += buttonCretaeCruiser_Click; + // + // buttonStrategyStep + // + 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(buttonCretaeCruiser); + Controls.Add(comboBoxStrategy); Controls.Add(buttonLeft); Controls.Add(buttonRight); Controls.Add(buttonDown); Controls.Add(buttonUp); Controls.Add(button1); - Controls.Add(pictureBox1); - Name = "Form1"; + Controls.Add(pictureBoxCruiser); + Name = "FormCruiser"; Text = "FormCruiser"; Click += ButtonMove_Click; - ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); + ((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).EndInit(); ResumeLayout(false); PerformLayout(); } #endregion - private PictureBox pictureBox1; + private PictureBox pictureBoxCruiser; private Button button1; private Button buttonUp; private Button buttonDown; private Button buttonRight; private Button buttonLeft; + private ComboBox comboBoxStrategy; + private Button buttonCretaeCruiser; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectCruiser/FormCruiser.cs b/ProjectCruiser/FormCruiser.cs index b14b170..2696789 100644 --- a/ProjectCruiser/FormCruiser.cs +++ b/ProjectCruiser/FormCruiser.cs @@ -1,4 +1,7 @@ -namespace ProjectCruiser +using ProjectCruiser.Drawnings; +using ProjectCruiser.MovementStrategy; + +namespace ProjectCruiser { public partial class FormCruiser : Form { @@ -6,10 +9,16 @@ /// Поле-объект для прорисовки объекта /// private DrawningCruiser? _drawningCruiser; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + public FormCruiser() { InitializeComponent(); - + _strategy = null; } /// @@ -21,35 +30,64 @@ { return; } - Bitmap bmp = new(pictureBox1.Width, - pictureBox1.Height); + Bitmap bmp = new(pictureBoxCruiser.Width, + pictureBoxCruiser.Height); Graphics gr = Graphics.FromImage(bmp); _drawningCruiser.DrawTransport(gr); - pictureBox1.Image = bmp; + pictureBoxCruiser.Image = bmp; } + /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningCruiser): + _drawningCruiser = 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): + _drawningCruiser = 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; + } + _drawningCruiser.SetPictureSize(pictureBoxCruiser.Width, + pictureBoxCruiser.Height); + _drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + + /// + /// Обработка нажатия кнопки "Создать военный крейсер" /// /// /// - private void ButtonCreateCruiser_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningCruiser = new DrawningCruiser(); - _drawningCruiser.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))); - _drawningCruiser.SetPictureSize(pictureBox1.Width, - pictureBox1.Height); + private void ButtonCreateCruiser_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMilitaryCruiser)); + + /// + /// Обработка нажатия кнопки "Создать крейсер" + /// + /// + /// + private void buttonCretaeCruiser_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningCruiser)); + - //начальное положение круисера - _drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100)); - Draw(); - } /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -87,5 +125,50 @@ Draw(); } } + + /// + /// обработка нажатия кнопки шаг + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningCruiser == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableCruiser(_drawningCruiser), 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/FormCruiser.resx b/ProjectCruiser/FormCruiser.resx index 01513c1..8a26dc4 100644 --- a/ProjectCruiser/FormCruiser.resx +++ b/ProjectCruiser/FormCruiser.resx @@ -121,7 +121,7 @@ iVBORw0KGgoAAAANSUhEUgAABGsAAAZACAYAAADO3c9BAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - wAAADsABataJCQAAVu1JREFUeF7s3XHE5XXe//HcstZKkiRJMpIkSZIkSZJkJUmSlSRZK1lJxkokK0mS + vAAADrwBlbxySQAAVu1JREFUeF7s3XHE5XXe//HcstZKkiRJMpIkSZIkSZJkJUmSlSRZK1lJxkokK0mS JGtkJUmSJEkykiRJMpIkyRgjY4wxxhhjjN/v9dnd7rutz3xmrus61/uc8z2PJw+/2++/na7rnO/3dZ3z +Z4iSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk SZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk @@ -498,7 +498,7 @@ iVBORw0KGgoAAAANSUhEUgAABGsAAAZACAYAAADO3c9BAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - wAAADsABataJCQAAVmJJREFUeF7s3XGk5nX+//98ZK2VJEkykpEkSZKsJEmyspIkyUqSrJWsJGMlkpUk + vAAADrwBlbxySQAAVmJJREFUeF7s3XGk5nX+//98ZK2VJEkykpEkSZKsJEmyspIkyUqSrJWsJGMlkpUk SZKVrCRZSVYyVpIkSZKRJEnGGBljjDHGGGP8fo/37mc/36199WzOnHOe531d1+3Ozf69zTnX9X4/znW9 3qdJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJ kiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJkiRJ @@ -873,7 +873,7 @@ iVBORw0KGgoAAAANSUhEUgAABkAAAARrCAYAAADb+Gp7AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - wAAADsABataJCQAASClJREFUeF7s3Q+k3vX///F85SNJJjMzk0ySyXwkk8nMJEkyyWQySSaZZGYmGUmS + vAAADrwBlbxySQAASClJREFUeF7s3Q+k3vX///F85SNJJjMzk0ySyXwkk8nMJEkyyWQySSaZZGYmGUmS ZJJJZpLMJJlkJjOZj5mZmZmZyczMzBwzxxzHMcfv93hXq7ad/+d9Xdf7/Xrf7tx8vt+vjy/V2RXn4Xq+ 7pMkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk SZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk @@ -1187,7 +1187,7 @@ iVBORw0KGgoAAAANSUhEUgAABkAAAARrCAYAAADb+Gp7AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - wAAADsABataJCQAAUVNJREFUeF7s3X/E34X+//F85DiSTDKTSSbJJEcySZIkSZJkkiTJ5EiSZJJIkiRJ + vAAADrwBlbxySQAAUVNJREFUeF7s3X/E34X+//F85DiSTDKTSSbJJEcySZIkSZJkkiTJ5EiSZJJIkiRJ JpkkSZJMMpNM5pjMzMzMTGZmZmZmZuZymcv3+3idTufU9tyuX+8frx+3OzfO+bPrer9fF8+Hvd9XSZIk SZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk SZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIk diff --git a/ProjectCruiser/MovementStrategy/AbstractStrategy.cs b/ProjectCruiser/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..989cb90 --- /dev/null +++ b/ProjectCruiser/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,123 @@ +namespace ProjectCruiser.MovementStrategy +{ + /// + /// Класс-стратегия перемещения объекта + /// + public abstract class AbstractStrategy + { + /// + /// Перемещаемый объект + /// + 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 (IsTargetDestinaion()) + { + _state = StrategyStatus.Finish; + return; + } + MoveToTarget(); + } + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveRight() => MoveTo(MovementDirection.Right); + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveUp() => MoveTo(MovementDirection.Up); + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + 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 IsTargetDestinaion(); + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } + } + +} diff --git a/ProjectCruiser/MovementStrategy/IMoveableObject.cs b/ProjectCruiser/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..b6a27e5 --- /dev/null +++ b/ProjectCruiser/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace ProjectCruiser.MovementStrategy +{ + /// + /// Интерфейс для работы с перемещаемым объектом + /// + public interface IMoveableObject + { + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); + } + +} diff --git a/ProjectCruiser/MovementStrategy/MoveToBorder.cs b/ProjectCruiser/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..1e2d6ac --- /dev/null +++ b/ProjectCruiser/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,53 @@ +namespace ProjectCruiser.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/ProjectCruiser/MovementStrategy/MoveToCenter.cs b/ProjectCruiser/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..540208e --- /dev/null +++ b/ProjectCruiser/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,53 @@ +namespace ProjectCruiser.MovementStrategy +{ + /// + /// Стратегия перемещения объекта в центр экрана + /// + public class MoveToCenter : AbstractStrategy + { + protected override bool IsTargetDestinaion() + { + 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/MovementStrategy/MoveableCruiser.cs b/ProjectCruiser/MovementStrategy/MoveableCruiser.cs new file mode 100644 index 0000000..766c933 --- /dev/null +++ b/ProjectCruiser/MovementStrategy/MoveableCruiser.cs @@ -0,0 +1,62 @@ +using ProjectCruiser.Drawnings; + +namespace ProjectCruiser.MovementStrategy +{ + /// + /// класс реалтзация для IMoveableObject с использованием DrawningCruiser + /// + public class MoveableCruiser : IMoveableObject + { + /// + /// Поле-объект класса DrawningCruiser или его наследника + /// + private readonly DrawningCruiser? _cruiser = null; + /// + /// Конструктор + /// + /// Объект класса DrawningCruiser + 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 + /// + /// 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/MovementStrategy/MovementDirection.cs b/ProjectCruiser/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..d66685a --- /dev/null +++ b/ProjectCruiser/MovementStrategy/MovementDirection.cs @@ -0,0 +1,26 @@ +namespace ProjectCruiser.MovementStrategy +{ + /// + /// Направление перемещения + /// + public enum MovementDirection + { + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 + } + +} diff --git a/ProjectCruiser/MovementStrategy/ObjectParameters.cs b/ProjectCruiser/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..ac6715e --- /dev/null +++ b/ProjectCruiser/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,64 @@ +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; + /// + /// Конструктор + /// + /// Координата X + /// Координата Y + /// Ширина объекта + /// Высота объекта + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } + } + +} diff --git a/ProjectCruiser/MovementStrategy/StrategyStatus.cs b/ProjectCruiser/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..397e23e --- /dev/null +++ b/ProjectCruiser/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace ProjectCruiser.MovementStrategy +{ + /// + /// Статус выполнения операции перемещения + /// + public enum StrategyStatus + { + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish + } + +}