diff --git a/ProjectTank/ProjectTank/Drawnings/DirectionType.cs b/ProjectTank/ProjectTank/Drawnings/DirectionType.cs new file mode 100644 index 0000000..05a951b --- /dev/null +++ b/ProjectTank/ProjectTank/Drawnings/DirectionType.cs @@ -0,0 +1,27 @@ +namespace ProjectTank.Drawnings; +/// +/// Направление перемещения +/// +public enum DirectionType +{ + /// + /// Неизвестное направление + /// + Unknow = -1, + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/ProjectTank/ProjectTank/Drawnings/DrawningTank.cs b/ProjectTank/ProjectTank/Drawnings/DrawningTank.cs new file mode 100644 index 0000000..bcc32c6 --- /dev/null +++ b/ProjectTank/ProjectTank/Drawnings/DrawningTank.cs @@ -0,0 +1,63 @@ +using ProjectTank.Entities; + +namespace ProjectTank.Drawnings; +/// +/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// +public class DrawningTank : DrawningTank2 +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес автомобиля + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия башни с орудием + /// Признак наличия пулемёта + public DrawningTank(int speed, double weight, Color bodyColor, Color additionalColor, bool gunTurret, bool machineGun) : base(200, 100) + { + EntityTank2 = new EntityTank(speed, weight, bodyColor, additionalColor, gunTurret, machineGun); + } + + public override void DrawTransport(Graphics g) + { + if (EntityTank2 == null || EntityTank2 is not EntityTank tank || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black); + Brush additionalBrush = new SolidBrush(tank.AdditionalColor); + + + + _startPosX += 37; + _startPosY += 0; + base.DrawTransport(g); + _startPosX -= 37; + _startPosY -= 0; + + if (tank.GunTurret) + { + g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 42, 85, 8); + g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 42, 85, 8); + } + + if (tank.MachineGun) + { + g.DrawRectangle(pen, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12); + g.DrawRectangle(pen, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18); + g.DrawRectangle(pen, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5); + + g.FillRectangle(additionalBrush, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12); + g.FillRectangle(additionalBrush, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18); + g.FillRectangle(additionalBrush, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5); + + } + + + + + } +} diff --git a/ProjectTank/ProjectTank/DrawningTank.cs b/ProjectTank/ProjectTank/Drawnings/DrawningTank2.cs similarity index 50% rename from ProjectTank/ProjectTank/DrawningTank.cs rename to ProjectTank/ProjectTank/Drawnings/DrawningTank2.cs index 5bc9243..7c16542 100644 --- a/ProjectTank/ProjectTank/DrawningTank.cs +++ b/ProjectTank/ProjectTank/Drawnings/DrawningTank2.cs @@ -1,13 +1,16 @@ -namespace ProjectTank; +using ProjectTank.Entities; + +namespace ProjectTank.Drawnings; + /// -/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности /// -public class DrawningTank +public class DrawningTank2 { /// /// Класс-сущность /// - public EntityTank? EntityTank { get; private set; } + public EntityTank2? EntityTank2 { get; protected set; } /// /// Ширина окна /// @@ -19,39 +22,70 @@ public class DrawningTank /// /// Левая координата прорисовки танка /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя кооридната прорисовки танка /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки танка /// - private readonly int _drawningTankWidth = 200; + private readonly int _drawningTankWidth = 160; /// /// Высота прорисовки танка /// - private readonly int _drawningTankHeight = 100; + private readonly int _drawningTankHeight = 94; + /// - /// Инициализация свойств + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта /// - /// Скорость - /// Вес автомобиля - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия башни с орудием - /// Признак наличия пулемёта - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool gunTurret, bool machineGun, bool v) + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningTankWidth; + + /// + /// Высота объекта + /// + public int GetHeight => _drawningTankHeight; + + /// + /// Пустой конструктор + /// + private DrawningTank2() { - EntityTank = new EntityTank(); - EntityTank.Init(speed, weight, bodyColor, additionalColor, - gunTurret, machineGun); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawningTank2(int speed, double weight, Color bodyColor) : this() + { + EntityTank2 = new EntityTank2(speed, weight, bodyColor); + } + /// + /// Конструктор для наследования + /// + /// Ширина прорисовки танка + /// Высота прорисовки танка + protected DrawningTank2(int drawningTankWidth,int drawningTankHeight) : this() + { + _drawningTankWidth = drawningTankWidth; + _drawningTankHeight = drawningTankHeight; + } /// /// Установка границ поля @@ -64,19 +98,16 @@ public class DrawningTank if (_drawningTankWidth < width && _drawningTankHeight < height) { _pictureWidth = width; _pictureHeight = height; - - { - if (_startPosX.HasValue&&_startPosY.HasValue) - + + { + if (_startPosX.HasValue && _startPosY.HasValue) + SetPosition(_startPosX.Value, _startPosY.Value); - } - return true; } - return false; + return true; } - - - + return false; + } /// /// Установка позиции @@ -91,10 +122,11 @@ public class DrawningTank { return; } - if (x < 0 || x + _drawningTankWidth > _pictureWidth || y < 0 || y + _drawningTankHeight > _pictureHeight) - { + if (x < 0 || x + _drawningTankWidth > _pictureWidth || y < 0 || y + _drawningTankHeight > _pictureHeight) + { _startPosX = _pictureWidth - _drawningTankWidth; _startPosY = _pictureHeight - _drawningTankHeight; - } else + } + else { _startPosX = x; _startPosY = y; @@ -108,7 +140,7 @@ public class DrawningTank public bool MoveTransport(DirectionType direction) { - if (EntityTank == null || !_startPosX.HasValue || + if (EntityTank2 == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; @@ -117,32 +149,32 @@ public class DrawningTank { //влево case DirectionType.Left: - if (_startPosX.Value - EntityTank.Step > 0) + if (_startPosX.Value - EntityTank2.Step > 0) { - _startPosX -= (int)EntityTank.Step; + _startPosX -= (int)EntityTank2.Step; } return true; //вверх case DirectionType.Up: - if (_startPosY.Value - EntityTank.Step > 0) + if (_startPosY.Value - EntityTank2.Step > 0) { - _startPosY -= (int)EntityTank.Step; + _startPosY -= (int)EntityTank2.Step; } return true; // вниз case DirectionType.Down: - if (_startPosY.Value + EntityTank.Step + _drawningTankHeight < _pictureHeight) + if (_startPosY.Value + EntityTank2.Step + _drawningTankHeight < _pictureHeight) { - _startPosY += (int)EntityTank.Step; + _startPosY += (int)EntityTank2.Step; } return true; // вправо case DirectionType.Right: - if (_startPosX.Value + EntityTank.Step + _drawningTankWidth < _pictureWidth) + if (_startPosX.Value + EntityTank2.Step + _drawningTankWidth < _pictureWidth) { - _startPosX += (int)EntityTank.Step; + _startPosX += (int)EntityTank2.Step; } return true; default: @@ -153,65 +185,45 @@ public class DrawningTank /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityTank == null || !_startPosX.HasValue || + if (EntityTank2 == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush additionalBrush = new - SolidBrush(EntityTank.AdditionalColor); - + //границы танка + гусеницы + пулемёт + башня с оружием - g.DrawRectangle(pen, _startPosX.Value + 85, _startPosY.Value + 39, 55, 17); - g.DrawRectangle(pen, _startPosX.Value + 49, _startPosY.Value + 56, 137, 13); + g.DrawRectangle(pen, _startPosX.Value + 48, _startPosY.Value + 39, 55, 17); + g.DrawRectangle(pen, _startPosX.Value + 12, _startPosY.Value + 56, 137, 13); - g.DrawEllipse(pen, _startPosX.Value + 37, _startPosY.Value + 59, 160, 35); - g.DrawEllipse(pen, _startPosX.Value + 88, _startPosY.Value + 65, 29, 23); - g.DrawEllipse(pen, _startPosX.Value + 148, _startPosY.Value + 65, 29, 23); - g.DrawEllipse(pen, _startPosX.Value + 128, _startPosY.Value + 73, 18, 15); - g.DrawEllipse(pen, _startPosX.Value + 108, _startPosY.Value + 73, 18, 15); - g.DrawEllipse(pen, _startPosX.Value + 88, _startPosY.Value + 73, 18, 15); + g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 59, 160, 35); + g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 65, 29, 23); + g.DrawEllipse(pen, _startPosX.Value + 111, _startPosY.Value + 65, 29, 23); + g.DrawEllipse(pen, _startPosX.Value + 91, _startPosY.Value + 73, 18, 15); + g.DrawEllipse(pen, _startPosX.Value + 71, _startPosY.Value + 73, 18, 15); + g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 73, 18, 15); - g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 42, 85, 8); + - g.DrawRectangle(pen, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12); - g.DrawRectangle(pen, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18); - g.DrawRectangle(pen, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5); - - //танк - Brush br = new SolidBrush(EntityTank.BodyColor); - g.FillRectangle(br, _startPosX.Value + 85, _startPosY.Value + 39, 55, 17); - g.FillRectangle(br, _startPosX.Value + 49, _startPosY.Value + 56, 137, 13); - + Brush br = new SolidBrush(EntityTank2.BodyColor); + g.FillRectangle(br, _startPosX.Value + 48, _startPosY.Value + 39, 55, 17); + g.FillRectangle(br, _startPosX.Value + 12, _startPosY.Value + 56, 137, 13); + Brush brDBlue = new SolidBrush(Color.DarkBlue); - g.FillEllipse(brDBlue, _startPosX.Value + 37, _startPosY.Value + 59, 160, 35); + g.FillEllipse(brDBlue, _startPosX.Value, _startPosY.Value + 59, 160, 35); - - - //гусеницы Brush brBlue = new SolidBrush(Color.LightBlue); - g.FillEllipse(brBlue, _startPosX.Value + 56, _startPosY.Value + 65, 29, 23); - g.FillEllipse(brBlue, _startPosX.Value + 148, _startPosY.Value + 65, 29, 23); - g.FillEllipse(brBlue, _startPosX.Value + 128, _startPosY.Value + 73, 18, 15); - g.FillEllipse(brBlue, _startPosX.Value + 108, _startPosY.Value + 73, 18, 15); - g.FillEllipse(brBlue, _startPosX.Value + 88, _startPosY.Value + 73, 18, 15); + g.FillEllipse(brBlue, _startPosX.Value + 19, _startPosY.Value + 65, 29, 23); + g.FillEllipse(brBlue, _startPosX.Value + 111, _startPosY.Value + 65, 29, 23); + g.FillEllipse(brBlue, _startPosX.Value + 91, _startPosY.Value + 73, 18, 15); + g.FillEllipse(brBlue, _startPosX.Value + 71, _startPosY.Value + 73, 18, 15); + g.FillEllipse(brBlue, _startPosX.Value + 51, _startPosY.Value + 73, 18, 15); - if (EntityTank.GunTurret) - { - g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 42, 85, 8); - } - if (EntityTank.MachineGun) - { - g.FillRectangle(additionalBrush, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12); - g.FillRectangle(additionalBrush, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18); - g.FillRectangle(additionalBrush, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5); - } } -} \ No newline at end of file +} diff --git a/ProjectTank/ProjectTank/EntityTank.cs b/ProjectTank/ProjectTank/Entities/EntityTank.cs similarity index 65% rename from ProjectTank/ProjectTank/EntityTank.cs rename to ProjectTank/ProjectTank/Entities/EntityTank.cs index 0692b70..313b17d 100644 --- a/ProjectTank/ProjectTank/EntityTank.cs +++ b/ProjectTank/ProjectTank/Entities/EntityTank.cs @@ -1,24 +1,16 @@ -using System.Net.NetworkInformation; +using ProjectTank.Entities; namespace ProjectTank; /// /// Класс-сущность "Танк" /// -public class EntityTank +public class EntityTank : EntityTank2 { - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } + public EntityTank(int speed, double weight, Color bodyColor) : base(speed, weight, bodyColor) + { + } + /// /// Дополнительный цвет (для опциональных элементов) /// @@ -32,10 +24,6 @@ public class EntityTank /// public bool MachineGun { get; private set; } /// - /// Шаг перемещения танка - /// - public double Step => Speed * 100 / Weight; - /// /// Инициализация полей объекта-класса спортивного автомобиля /// /// Скорость @@ -44,12 +32,10 @@ public class EntityTank /// Дополнительный цвет /// Признак наличия башни с орудием /// Признак наличия пулемёта - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool gunTurret, bool machineGun) + public EntityTank(int speed, double weight, Color bodyColor, Color + additionalColor, bool gunTurret, bool machineGun) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; + AdditionalColor = additionalColor; GunTurret = gunTurret; MachineGun = machineGun; @@ -59,7 +45,7 @@ public class MyClass { private int PrivateField; - public int PublicProperty {private get; set; } + public int PublicProperty { private get; set; } public void PublicMethod() { diff --git a/ProjectTank/ProjectTank/Entities/EntityTank2.cs b/ProjectTank/ProjectTank/Entities/EntityTank2.cs new file mode 100644 index 0000000..b56e9b8 --- /dev/null +++ b/ProjectTank/ProjectTank/Entities/EntityTank2.cs @@ -0,0 +1,40 @@ +namespace ProjectTank.Entities; + +/// +/// Класс-сущность "Автомобиль" +/// +public class EntityTank2 +{ + /// + /// Скорость + /// + 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 EntityTank2(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/FormTank.Designer.cs b/ProjectTank/ProjectTank/FormTank.Designer.cs index 8cea8af..63b89a0 100644 --- a/ProjectTank/ProjectTank/FormTank.Designer.cs +++ b/ProjectTank/ProjectTank/FormTank.Designer.cs @@ -1,4 +1,8 @@ -namespace ProjectTank +using static System.Net.Mime.MediaTypeNames; +using System.Windows.Forms; +using System.Xml.Linq; + +namespace ProjectTank { partial class FormTank { @@ -29,11 +33,14 @@ private void InitializeComponent() { pictureBoxTank = new PictureBox(); - buttonCreate = new Button(); + buttonCreateTank = new Button(); buttonLeft = new Button(); + buttonUp = new Button(); buttonDown = new Button(); buttonRight = new Button(); - buttonUp = new Button(); + buttonCreateTank2 = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit(); SuspendLayout(); // @@ -42,42 +49,54 @@ pictureBoxTank.Dock = DockStyle.Fill; pictureBoxTank.Location = new Point(0, 0); pictureBoxTank.Name = "pictureBoxTank"; - pictureBoxTank.Size = new Size(800, 450); + pictureBoxTank.Size = new Size(923, 597); pictureBoxTank.TabIndex = 0; pictureBoxTank.TabStop = false; // - // buttonCreate + // buttonCreateTank // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(12, 415); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(94, 29); - buttonCreate.TabIndex = 1; - buttonCreate.Text = "Создать"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += ButtonCreateTank_Click; + buttonCreateTank.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateTank.Location = new Point(12, 562); + buttonCreateTank.Name = "buttonCreateTank"; + buttonCreateTank.Size = new Size(223, 23); + buttonCreateTank.TabIndex = 1; + buttonCreateTank.Text = "Создать танк с пулемётом"; + buttonCreateTank.UseVisualStyleBackColor = true; + buttonCreateTank.Click += ButtonCreateTank_Click; // // buttonLeft // buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.BackgroundImage = Properties.Resources.Left; buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; - buttonLeft.Location = new Point(671, 409); + buttonLeft.Location = new Point(787, 550); buttonLeft.Name = "buttonLeft"; buttonLeft.Size = new Size(35, 35); buttonLeft.TabIndex = 2; buttonLeft.UseVisualStyleBackColor = true; buttonLeft.Click += ButtonMove_Click; // + // buttonUp + // + buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonUp.BackgroundImage = Properties.Resources.Up; + buttonUp.BackgroundImageLayout = ImageLayout.Stretch; + buttonUp.Location = new Point(828, 509); + buttonUp.Name = "buttonUp"; + buttonUp.Size = new Size(35, 35); + buttonUp.TabIndex = 3; + buttonUp.UseVisualStyleBackColor = true; + buttonUp.Click += ButtonMove_Click; + // // buttonDown // buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.BackgroundImage = Properties.Resources.Down; buttonDown.BackgroundImageLayout = ImageLayout.Stretch; - buttonDown.Location = new Point(712, 409); + buttonDown.Location = new Point(828, 550); buttonDown.Name = "buttonDown"; buttonDown.Size = new Size(35, 35); - buttonDown.TabIndex = 3; + buttonDown.TabIndex = 4; buttonDown.UseVisualStyleBackColor = true; buttonDown.Click += ButtonMove_Click; // @@ -86,38 +105,60 @@ buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.BackgroundImage = Properties.Resources.Right; buttonRight.BackgroundImageLayout = ImageLayout.Stretch; - buttonRight.Location = new Point(753, 409); + buttonRight.Location = new Point(869, 550); buttonRight.Name = "buttonRight"; buttonRight.Size = new Size(35, 35); - buttonRight.TabIndex = 4; + buttonRight.TabIndex = 5; buttonRight.UseVisualStyleBackColor = true; buttonRight.Click += ButtonMove_Click; // - // buttonUp + // buttonCreateTank2 // - buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - buttonUp.BackgroundImage = Properties.Resources.Up; - buttonUp.BackgroundImageLayout = ImageLayout.Stretch; - buttonUp.Location = new Point(712, 368); - buttonUp.Name = "buttonUp"; - buttonUp.Size = new Size(35, 35); - buttonUp.TabIndex = 5; - buttonUp.UseVisualStyleBackColor = true; - buttonUp.Click += ButtonMove_Click; + buttonCreateTank2.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateTank2.Location = new Point(250, 562); + buttonCreateTank2.Name = "buttonCreateTank2"; + buttonCreateTank2.Size = new Size(223, 23); + buttonCreateTank2.TabIndex = 6; + buttonCreateTank2.Text = "Создать обычный танк"; + buttonCreateTank2.UseVisualStyleBackColor = true; + buttonCreateTank2.Click += ButtonCreateTank2_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(790, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(836, 41); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(75, 23); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; // // FormTank // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); - Controls.Add(buttonUp); + ClientSize = new Size(923, 597); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateTank2); Controls.Add(buttonRight); Controls.Add(buttonDown); + Controls.Add(buttonUp); Controls.Add(buttonLeft); - Controls.Add(buttonCreate); + Controls.Add(buttonCreateTank); Controls.Add(pictureBoxTank); Name = "FormTank"; - Text = "Танк"; + Text = "Танк с пулемётом"; ((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit(); ResumeLayout(false); } @@ -125,10 +166,13 @@ #endregion private PictureBox pictureBoxTank; - private Button buttonCreate; + private Button buttonCreateTank; private Button buttonLeft; + private Button buttonUp; private Button buttonDown; private Button buttonRight; - private Button buttonUp; + private Button buttonCreateTank2; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectTank/ProjectTank/FormTank.cs b/ProjectTank/ProjectTank/FormTank.cs index a80a840..3e3ff92 100644 --- a/ProjectTank/ProjectTank/FormTank.cs +++ b/ProjectTank/ProjectTank/FormTank.cs @@ -1,10 +1,26 @@ -namespace ProjectTank; +using ProjectTank.Drawnings; +using ProjectTank.MovementStrategy; + +namespace ProjectTank; public partial class FormTank : Form { - private DrawningTank? _drawningTank; + /// + /// Поле-объект для прорисовки объекта + /// + private DrawningTank2? _drawningTank2; + + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + + /// + /// Конструктор формы + /// public FormTank() { InitializeComponent(); + _strategy = null; } /// @@ -12,32 +28,59 @@ public partial class FormTank : Form /// private void Draw() { - if (_drawningTank == null) + if (_drawningTank2 == null) { return; } Bitmap bmp = new(pictureBoxTank.Width, pictureBoxTank.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningTank.DrawTransport(gr); + _drawningTank2.DrawTransport(gr); pictureBoxTank.Image = bmp; } + /// - /// Обработка нажатия кнопки "Создать" + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningTank2): + _drawningTank2 = new DrawningTank2(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(DrawningTank): + _drawningTank2 = new DrawningTank(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))); + break; + default: + return; + } + + _drawningTank2.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height); + _drawningTank2.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _strategy = null; + comboBoxStrategy.Enabled = true; + Draw(); + } + /// + /// Обработка нажатия кнопки "Создать танк с пулемётом" + /// + /// + /// + private void ButtonCreateTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank)); + + /// + /// Обработка нажатия кнопки "Создать обычный танк" /// /// /// - private void ButtonCreateTank_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningTank = new DrawningTank(); - _drawningTank.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))); - _drawningTank.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height); - _drawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100)); - Draw(); - } + private void ButtonCreateTank2_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank2)); + /// /// Перемещение объекта по форме (нажатие кнопок навигации) /// @@ -45,36 +88,82 @@ public partial class FormTank : Form /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningTank == null) + if (_drawningTank2 == null) { return; } + string name = ((Button)sender)?.Name ?? string.Empty; bool result = false; switch (name) { case "buttonUp": - result = - _drawningTank.MoveTransport(DirectionType.Up); + result = _drawningTank2.MoveTransport(DirectionType.Up); break; case "buttonDown": - result = - _drawningTank.MoveTransport(DirectionType.Down); + result = _drawningTank2.MoveTransport(DirectionType.Down); break; case "buttonLeft": - result = - _drawningTank.MoveTransport(DirectionType.Left); + result = _drawningTank2.MoveTransport(DirectionType.Left); break; case "buttonRight": - result = - _drawningTank.MoveTransport(DirectionType.Right); + result = _drawningTank2.MoveTransport(DirectionType.Right); break; } + if (result) { Draw(); } } + + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningTank2 == null) + { + return; + } + + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableTank2(_drawningTank2), pictureBoxTank.Width, pictureBoxTank.Height); + } + + if (_strategy == null) + { + return; + } + + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } + + private void button1_Click(object sender, EventArgs e) + { + + } } diff --git a/ProjectTank/ProjectTank/MovementStrategy/AbstractStrategy.cs b/ProjectTank/ProjectTank/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..ed6eb79 --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,139 @@ +namespace ProjectTank.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; + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/MovementStrategy/IMoveableObject.cs b/ProjectTank/ProjectTank/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..63e7699 --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,24 @@ +namespace ProjectTank.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемым объектом +/// +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/MovementStrategy/MoveToBorder.cs b/ProjectTank/ProjectTank/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..d8edc5a --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,54 @@ +using ProjectTank.MovementStrategy; + +namespace ProjectTank.MovementStrategy; + +public 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.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(); + } + } + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/MovementStrategy/MoveToCenter.cs b/ProjectTank/ProjectTank/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..6b4b22a --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,53 @@ +using ProjectTank.MovementStrategy; + +namespace ProjectTank.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(); + } + } + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/MovementStrategy/MoveableTank2.cs b/ProjectTank/ProjectTank/MovementStrategy/MoveableTank2.cs new file mode 100644 index 0000000..02d4498 --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/MoveableTank2.cs @@ -0,0 +1,63 @@ +using ProjectTank.Drawnings; +namespace ProjectTank.MovementStrategy; + +/// +/// Класс-реализация IMoveableObject с использованием DrawningCar +/// +public class MoveableTank2 : IMoveableObject +{ + /// + /// Поле-объект класса DrawningCar или его наследника + /// + private readonly DrawningTank2? _tank = null; + + /// + /// Конструктор + /// + /// Объект класса DrawningCar + public MoveableTank2(DrawningTank2 tank) + { + _tank = tank; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_tank == null || _tank.EntityTank2 == null || !_tank.GetPosX.HasValue || !_tank.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_tank.GetPosX.Value, _tank.GetPosY.Value, _tank.GetWidth, _tank.GetHeight); + } + } + + public int GetStep => (int)(_tank?.EntityTank2?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_tank == null || _tank.EntityTank2 == null) + { + return false; + } + + return _tank.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, + }; + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/DirectionType.cs b/ProjectTank/ProjectTank/MovementStrategy/MovementDirection.cs similarity index 82% rename from ProjectTank/ProjectTank/DirectionType.cs rename to ProjectTank/ProjectTank/MovementStrategy/MovementDirection.cs index 31f8f61..6c3815a 100644 --- a/ProjectTank/ProjectTank/DirectionType.cs +++ b/ProjectTank/ProjectTank/MovementStrategy/MovementDirection.cs @@ -1,23 +1,27 @@ -namespace ProjectTank; +namespace ProjectTank.MovementStrategy; + /// /// Направление перемещения /// -public enum DirectionType +public enum MovementDirection { /// /// Вверх /// Up = 1, + /// /// Вниз /// Down = 2, + /// /// Влево /// Left = 3, + /// /// Вправо /// Right = 4 -} +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/MovementStrategy/ObjectParameters.cs b/ProjectTank/ProjectTank/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..74dcf8e --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,72 @@ +namespace ProjectTank.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; + } +} \ No newline at end of file diff --git a/ProjectTank/ProjectTank/MovementStrategy/StrategyStatus.cs b/ProjectTank/ProjectTank/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..2905125 --- /dev/null +++ b/ProjectTank/ProjectTank/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,22 @@ +namespace ProjectTank.MovementStrategy; + +/// +/// Статус выполнения операции перемещения +/// +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + + /// + /// Выполняется + /// + InProgress, + + /// + /// Завершено + /// + Finish +} \ No newline at end of file