diff --git a/Tank/Tank/DrawningtTank.cs b/Tank/Tank/DrawningTank.cs similarity index 51% rename from Tank/Tank/DrawningtTank.cs rename to Tank/Tank/DrawningTank.cs index dead204..70c7430 100644 --- a/Tank/Tank/DrawningtTank.cs +++ b/Tank/Tank/DrawningTank.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace Tank; -public class DrawningtTank +public class DrawningTank { /// /// Класс-сущность @@ -31,11 +31,11 @@ public class DrawningtTank /// /// Ширина прорисовки автомобиля /// - private readonly int _drawningCarWidth = 110; + private readonly int _drawningTankWidth = 145; /// /// Высота прорисовки автомобиля /// - private readonly int _drawningCarHeight = 60; + private readonly int _drawningTankHeight = 105; /// /// Инициализация свойств /// @@ -43,15 +43,13 @@ public class DrawningtTank /// Вес /// Основной цвет /// Дополнительный цвет - /// Признак наличия обвеса - /// Признак наличия антикрыла - /// Признак наличия гоночной полосы - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool bodyKit, bool wing, bool sportLine) + /// Признак наличия обвеса + /// Признак наличия антикрыла + + public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool pushka, bool pulemet) { EntityTank = new EntityTank(); - EntityTank.Init(speed, weight, bodyColor, additionalColor, - bodyKit, wing, sportLine); + EntityTank.Init(speed, weight, bodyColor, additionalColor,pushka, pulemet); _pictureWidth = null; _pictureHeight = null; _startPosX = null; @@ -63,13 +61,33 @@ public class DrawningtTank /// Ширина поля /// Высота поля /// true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах -public bool SetPictureSize(int width, int height) + /// + /// Установка границ поля + /// + /// Ширина поля + /// Высота поля + /// true - границы заданы, false - проверка не пройдена, нельзя + public bool SetPictureSize(int width, int height) { - // TODO проверка, что объект "влезает" в размеры поля - // если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена - _pictureWidth = width; - _pictureHeight = height; - return true; + if (_drawningTankWidth <= width && _drawningTankHeight <= height) + { + _pictureWidth = width; + _pictureHeight = height; + if (_startPosX.HasValue && _startPosY.HasValue) + { + if (_startPosX + _drawningTankWidth > _pictureWidth) + { + _startPosX = _pictureWidth - _drawningTankWidth; + } + + if (_startPosY + _drawningTankHeight > _pictureHeight) + { + _startPosY = _pictureHeight - _drawningTankHeight; + } + } + return true; + } + return false; } /// /// Установка позиции @@ -82,8 +100,11 @@ public bool SetPictureSize(int width, int height) { return; } - // TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы - // то надо изменить координаты, чтобы он оставался в этих границах + if (x < 0) x = 0; + else if (x + _drawningTankWidth > _pictureWidth) x = _pictureWidth.Value - _drawningTankWidth; + + if (y < 0) y = 0; + else if (y + _drawningTankHeight > _pictureHeight) y = _pictureHeight.Value - _drawningTankHeight; _startPosX = x; _startPosY = y; } @@ -92,7 +113,7 @@ public bool SetPictureSize(int width, int height) /// /// Направление /// true - перемещене выполнено, false - перемещение невозможно -public bool MoveTransport(DirectionType direction) + public bool MoveTransport(DirectionType direction) { if (EntityTank == null || !_startPosX.HasValue || !_startPosY.HasValue) @@ -104,24 +125,22 @@ public bool MoveTransport(DirectionType direction) //влево case DirectionType.Left: if (_startPosX.Value - EntityTank.Step > 0) - { _startPosX -= (int)EntityTank.Step; - } return true; //вверх case DirectionType.Up: if (_startPosY.Value - EntityTank.Step > 0) - { _startPosY -= (int)EntityTank.Step; - } return true; // вправо case DirectionType.Right: - //TODO прописать логику сдвига в право + if (_startPosX.Value + _drawningTankWidth + EntityTank.Step < _pictureWidth) + _startPosX += (int)EntityTank.Step; return true; //вниз case DirectionType.Down: - //TODO прописать логику сдвига в вниз + if (_startPosY.Value + _drawningTankHeight + EntityTank.Step < _pictureHeight) + _startPosY += (int)EntityTank.Step; return true; default: return false; @@ -139,12 +158,35 @@ public bool MoveTransport(DirectionType direction) return; } Pen pen = new(Color.Black); - Brush additionalBrush = new - SolidBrush(EntityTank.AdditionalColor); - // обвесы - if (EntityTank.BodyKit) + Brush additionalBrush = new SolidBrush(EntityTank.AdditionalColor); + Brush bodyBrush = new SolidBrush(EntityTank.BodyColor); + + g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 45, 150, 60); + g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 60, 33, 33); + g.DrawEllipse(pen, _startPosX.Value + 110, _startPosY.Value + 60, 33, 33); + g.DrawEllipse(pen, _startPosX.Value + 35, _startPosY.Value + 80, 16, 16); + g.DrawEllipse(pen, _startPosX.Value + 55, _startPosY.Value + 83, 16, 16); + g.DrawEllipse(pen, _startPosX.Value + 75, _startPosY.Value + 83, 16, 16); + g.DrawEllipse(pen, _startPosX.Value + 95, _startPosY.Value + 80, 16, 16); + + g.FillEllipse(bodyBrush, _startPosX.Value + 45, _startPosY.Value + 55, 15, 15); + g.FillEllipse(bodyBrush, _startPosX.Value + 65, _startPosY.Value + 55, 15, 15); + g.FillEllipse(bodyBrush, _startPosX.Value + 85, _startPosY.Value + 55, 15, 15); + + g.FillRectangle(bodyBrush, _startPosX.Value + 30, _startPosY.Value + 10, 100, 30); + g.FillRectangle(bodyBrush, _startPosX.Value + 5, _startPosY.Value + 40, 140, 25); + + if(EntityTank.Pushka) + g.FillRectangle(additionalBrush, _startPosX.Value + 120, _startPosY.Value + 20, 100, 15); + + if (EntityTank.Pulemet) { - return; + Point p = new Point(_startPosX.Value + 75, _startPosY.Value + 10); + Point p1 = new Point(_startPosX.Value + 80, _startPosY.Value + 1); + Point p2 = new Point(_startPosX.Value + 87, _startPosY.Value + 2); + Point p3 = new Point(_startPosX.Value + 80, _startPosY.Value + 10); + Point[] p_pulemet = { p, p1, p2, p3 }; + g.FillPolygon(additionalBrush, p_pulemet); } } } diff --git a/Tank/Tank/EntityTank.cs b/Tank/Tank/EntityTank.cs index f3512d3..39a4618 100644 --- a/Tank/Tank/EntityTank.cs +++ b/Tank/Tank/EntityTank.cs @@ -21,15 +21,11 @@ public class EntityTank /// /// Признак (опция) наличия обвеса /// - public bool BodyKit { get; private set; } + public bool Pushka { get; private set; } /// /// Признак (опция) наличия антикрыла /// - public bool Wing { get; private set; } - /// - /// Признак (опция) наличия гоночной полосы - /// - public bool SportLine { get; private set; } + public bool Pulemet { get; private set; } /// /// Шаг перемещения автомобиля /// @@ -41,17 +37,17 @@ public class EntityTank /// Вес автомобиля /// Основной цвет /// Дополнительный цвет - /// Признак наличия обвеса - /// Признак наличия антикрыла + /// Признак наличия обвеса + /// Признак наличия антикрыла /// Признак наличия гоночной полосы - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool wing, bool sportLine) + public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool pushka, bool pulemet) { Speed = speed; Weight = weight; BodyColor = bodyColor; AdditionalColor = additionalColor; - BodyKit = bodyKit; - Wing = wing; - SportLine = sportLine; + Pushka = pushka; + Pulemet = pulemet; + } } \ No newline at end of file diff --git a/Tank/Tank/FormTank.Designer.cs b/Tank/Tank/FormTank.Designer.cs index 90da2fa..ef5db72 100644 --- a/Tank/Tank/FormTank.Designer.cs +++ b/Tank/Tank/FormTank.Designer.cs @@ -28,31 +28,110 @@ /// private void InitializeComponent() { - button1 = new Button(); + pictureBoxTank = new PictureBox(); + buttonCreate = new Button(); + buttonLeft = new Button(); + buttonUp = new Button(); + buttonRight = new Button(); + buttonDown = new Button(); + ((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit(); SuspendLayout(); // - // button1 + // pictureBoxTank // - button1.Location = new Point(51, 65); - button1.Name = "button1"; - button1.Size = new Size(150, 46); - button1.TabIndex = 0; - button1.Text = "button1"; - button1.UseVisualStyleBackColor = true; + pictureBoxTank.AccessibleRole = AccessibleRole.None; + pictureBoxTank.Dock = DockStyle.Fill; + pictureBoxTank.Location = new Point(0, 0); + pictureBoxTank.Name = "pictureBoxTank"; + pictureBoxTank.Size = new Size(1235, 854); + pictureBoxTank.SizeMode = PictureBoxSizeMode.AutoSize; + pictureBoxTank.TabIndex = 1; + pictureBoxTank.TabStop = false; + pictureBoxTank.Click += ButtonMove_Click; + // + // buttonCreate + // + buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreate.Location = new Point(12, 796); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(150, 46); + buttonCreate.TabIndex = 2; + buttonCreate.Text = "Создать"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += ButtonCreateTank_Click; + // + // buttonLeft + // + buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonLeft.BackgroundImage = Properties.Resources.left; + buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; + buttonLeft.Location = new Point(1021, 786); + buttonLeft.Name = "buttonLeft"; + buttonLeft.Size = new Size(45, 45); + buttonLeft.TabIndex = 3; + 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(1072, 735); + buttonUp.Name = "buttonUp"; + buttonUp.Size = new Size(45, 45); + buttonUp.TabIndex = 4; + buttonUp.UseVisualStyleBackColor = true; + buttonUp.Click += ButtonMove_Click; + // + // buttonRight + // + buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonRight.BackgroundImage = Properties.Resources.right; + buttonRight.BackgroundImageLayout = ImageLayout.Stretch; + buttonRight.Location = new Point(1123, 786); + buttonRight.Name = "buttonRight"; + buttonRight.Size = new Size(45, 45); + buttonRight.TabIndex = 5; + buttonRight.UseVisualStyleBackColor = true; + buttonRight.Click += ButtonMove_Click; + // + // buttonDown + // + buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonDown.BackgroundImage = Properties.Resources.down; + buttonDown.BackgroundImageLayout = ImageLayout.Stretch; + buttonDown.Location = new Point(1072, 786); + buttonDown.Name = "buttonDown"; + buttonDown.Size = new Size(45, 45); + buttonDown.TabIndex = 6; + buttonDown.UseVisualStyleBackColor = true; + buttonDown.Click += ButtonMove_Click; // // FormTank // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); - Controls.Add(button1); + ClientSize = new Size(1235, 854); + Controls.Add(buttonDown); + Controls.Add(buttonRight); + Controls.Add(buttonUp); + Controls.Add(buttonLeft); + Controls.Add(buttonCreate); + Controls.Add(pictureBoxTank); Name = "FormTank"; Text = "Танк"; + ((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit(); ResumeLayout(false); + PerformLayout(); } #endregion - - private Button button1; + private PictureBox pictureBoxTank; + private Button buttonCreate; + private Button buttonLeft; + private Button buttonUp; + private Button buttonRight; + private Button buttonDown; } } \ No newline at end of file diff --git a/Tank/Tank/FormTank.cs b/Tank/Tank/FormTank.cs index d9a07a7..f92df8d 100644 --- a/Tank/Tank/FormTank.cs +++ b/Tank/Tank/FormTank.cs @@ -12,9 +12,92 @@ namespace Tank { public partial class FormTank : Form { + /// + /// Поле-объект для прорисовки объекта + /// + private DrawningTank? _drawningTank; + /// + /// Конструктор формы + /// public FormTank() { InitializeComponent(); } + /// + /// Метод прорисовки машины + /// + private void Draw() + { + if (_drawningTank == null) + { + return; + } + Bitmap bmp = new(pictureBoxTank.Width, + pictureBoxTank.Height); + Graphics gr = Graphics.FromImage(bmp); + _drawningTank.DrawTransport(gr); + pictureBoxTank.Image = bmp; + } + /// + /// Обработка нажатия кнопки "Создать" + /// + /// + /// + 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))); + _drawningTank.SetPictureSize(pictureBoxTank.Width, + pictureBoxTank.Height); + _drawningTank.SetPosition(random.Next(10, 100), random.Next(10, + 100)); + Draw(); + } + /// + /// Перемещение объекта по форме (нажатие кнопок навигации) + /// + /// + /// + private void ButtonMove_Click(object sender, EventArgs e) + { + if (_drawningTank == null) + { + return; + } + string name = ((Button)sender)?.Name ?? string.Empty; + bool result = false; + switch (name) + { + case "buttonUp": + result = + _drawningTank.MoveTransport(DirectionType.Up); + break; + case "buttonDown": + result = + _drawningTank.MoveTransport(DirectionType.Down); + break; + case "buttonLeft": + result = + _drawningTank.MoveTransport(DirectionType.Left); + break; + case "buttonRight": + result = + _drawningTank.MoveTransport(DirectionType.Right); + break; + } + if (result) + { + Draw(); + } + } } } diff --git a/Tank/Tank/Properties/Resources.Designer.cs b/Tank/Tank/Properties/Resources.Designer.cs new file mode 100644 index 0000000..adfd17a --- /dev/null +++ b/Tank/Tank/Properties/Resources.Designer.cs @@ -0,0 +1,103 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace Tank.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("Tank.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 down { + get { + object obj = ResourceManager.GetObject("down", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap left { + get { + object obj = ResourceManager.GetObject("left", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap right { + get { + object obj = ResourceManager.GetObject("right", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap up { + get { + object obj = ResourceManager.GetObject("up", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/Tank/Tank/Properties/Resources.resx b/Tank/Tank/Properties/Resources.resx new file mode 100644 index 0000000..02616cd --- /dev/null +++ b/Tank/Tank/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\left.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\down.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\right.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\up.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/Tank/Tank/Resources/down.png b/Tank/Tank/Resources/down.png new file mode 100644 index 0000000..2a4910d Binary files /dev/null and b/Tank/Tank/Resources/down.png differ diff --git a/Tank/Tank/Resources/left.png b/Tank/Tank/Resources/left.png new file mode 100644 index 0000000..5489fb2 Binary files /dev/null and b/Tank/Tank/Resources/left.png differ diff --git a/Tank/Tank/Resources/right.png b/Tank/Tank/Resources/right.png new file mode 100644 index 0000000..980696d Binary files /dev/null and b/Tank/Tank/Resources/right.png differ diff --git a/Tank/Tank/Resources/up.png b/Tank/Tank/Resources/up.png new file mode 100644 index 0000000..b1f4345 Binary files /dev/null and b/Tank/Tank/Resources/up.png differ diff --git a/Tank/Tank/Tank.csproj b/Tank/Tank/Tank.csproj index b57c89e..13ee123 100644 --- a/Tank/Tank/Tank.csproj +++ b/Tank/Tank/Tank.csproj @@ -8,4 +8,19 @@ enable + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + \ No newline at end of file