diff --git a/Battleship/Battleship/DirectionType.cs b/Battleship/Battleship/DirectionType.cs new file mode 100644 index 0000000..c1e811b --- /dev/null +++ b/Battleship/Battleship/DirectionType.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +namespace Battleship; +public enum DirectionType +{ + Up = 1, //Вверх + Down = 2,//Вниз + Right = 3,//Вправо + Left = 4 //Влево +} diff --git a/Battleship/Battleship/DrawningBattleship.cs b/Battleship/Battleship/DrawningBattleship.cs new file mode 100644 index 0000000..e7b2217 --- /dev/null +++ b/Battleship/Battleship/DrawningBattleship.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +namespace Battleship; +// класс прорисовки и пермещения +public class DrawningBattleship +{ + #region [Variables Initialization] + public EntityBattleship? EntityBattleship { get; private set; } //класс сущность + private int? _pictureWidth; //ширина окна + private int? _pictureHeight; //высота окна + private int? _startX; // Х начальной позиции + private int? _startY; // Y начальной позиции + private readonly int _drawningShipWidth = 143; // длина корабля + private readonly int _drawningShipHeight = 75; // высота корабля + #endregion + public void Init(EntityBattleship entityBattleship) //инициализация свойств корабля и параметров окна, позиции + { + EntityBattleship = entityBattleship; + _pictureWidth = null; + _pictureHeight = null; + _startX = null; + _startY = null; + } + public bool SetPictureSize(int width, int height) // установка размеров окна + { + if (width > _drawningShipWidth && height > _drawningShipHeight) //если размеры окна позволяют вместить корабль, то присваиваем + { + if (_startX.HasValue && _startY.HasValue) + { + if (_drawningShipHeight + _startY.Value > height) + { + _startY = height - _drawningShipHeight; + } + if (_drawningShipWidth + _startX.Value > width) + { + _startX = width - _drawningShipWidth; + } + } + _pictureWidth = width; + _pictureHeight = height; + return true; + } + return false; + } + public void SetPosition(int x, int y) // установка позиции корабля + { + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) // проверка инициализации размеров окна + return; + if (x < 0 || x + _drawningShipWidth > _pictureWidth) // если корабль не вмещается по Х - присваиваем 0 + x = 0; + if (y < 0 || y + _drawningShipHeight > _pictureHeight) // если корабль не вмещается по Y - присваиваем 0 + y = 0; + _startX = x; + _startY = y; + } + public bool MoveTransport(DirectionType direction) //метод движения корабля + { + if (EntityBattleship == null || !_startX.HasValue || !_startY.HasValue) //проверка наличия корабля и инициализации начальной позиции + return false; + switch (direction) + { + case DirectionType.Left: // Влево + if (_startX.Value - EntityBattleship.Step > 0) // Проверяем, есть ли место для шага (аналогично далее) + _startX -= (int)EntityBattleship.Step; + return true; + case DirectionType.Right: // Вправо + if (_startX.Value + EntityBattleship.Step + _drawningShipWidth < _pictureWidth) + _startX += (int)EntityBattleship.Step; + return true; + case DirectionType.Up: // Вверх + if (_startY.Value - EntityBattleship.Step > 0) + _startY -= (int)EntityBattleship.Step; + return true; + case DirectionType.Down: // Вниз + if (_startY.Value + _drawningShipHeight + EntityBattleship.Step < _pictureHeight) + _startY += (int)EntityBattleship.Step; + return true; + default: return false; + } + } + public void DrawTransport(Graphics g) //метод рисования корабля + { + if (EntityBattleship == null || !_startX.HasValue || !_startY.HasValue) //проверка наличия корабля и инициализации начальной позиции + return; + Pen pen = new(Color.Black, 3); + Brush addBr = new SolidBrush(EntityBattleship.AdditionalColor); + Brush br = new SolidBrush(EntityBattleship.BodyColor); + #region [Drawing] + // Гриницы Линкора + g.DrawLine(pen, _startX.Value + 3, _startY.Value + 15, _startX.Value + 93, _startY.Value + 15); + g.DrawLine(pen, _startX.Value + 93, _startY.Value + 15, _startX.Value + 143, _startY.Value + 15 + 30); + g.DrawLine(pen, _startX.Value + 143, _startY.Value + 15 + 30, _startX.Value + 93, _startY.Value + 15 + 60); + g.DrawLine(pen, _startX.Value + 93, _startY.Value + 15 + 60, _startX.Value + 3, _startY.Value + 15 + 60); + g.DrawLine(pen, _startX.Value + 3, _startY.Value + 15 + 60, _startX.Value + 3, _startY.Value + 15); + //Заливка + g.FillRectangle(br, _startX.Value + 3, _startY.Value + 15, 90, 60); + g.FillPolygon(br, new PointF[] { new PointF(_startX.Value + 93, _startY.Value + 15), new PointF(_startX.Value + 143, _startY.Value + 15 + 30), new PointF(_startX.Value + 93, _startY.Value + 15 + 60) }); + //Элементы палубы + g.DrawEllipse(pen, _startX.Value + 83, _startY.Value + 15 + 20, 20, 20); + g.DrawRectangle(pen, _startX.Value + 63, _startY.Value + 15 + 15, 15, 30); + g.DrawRectangle(pen, _startX.Value + 43, _startY.Value + 15 + 25, 20, 10); + Brush brBlack = new SolidBrush(Color.Black); + g.FillRectangle(brBlack, _startX.Value, _startY.Value + 15 + 10, 3, 15); + g.FillRectangle(brBlack, _startX.Value, _startY.Value + 15 + 35, 3, 15); + // Орудийная башня + if (EntityBattleship.Weapon) + { + g.FillPie(addBr, _startX.Value + 8, _startY.Value + 15, 30, 25, 180, 180); + g.FillRectangle(addBr, _startX.Value + 18, _startY.Value, 10, 20); + } + //Ракеты + if (EntityBattleship.Rockets) + { + g.FillRectangle(addBr, _startX.Value + 8, _startY.Value + 15 + 20, 30, 35); + g.DrawRectangle(pen, _startX.Value + 8, _startY.Value + 15 + 20, 30, 35); + g.DrawEllipse(pen, _startX.Value + 13, _startY.Value + 15 + 25, 10, 10); + g.DrawEllipse(pen, _startX.Value + 23, _startY.Value + 15 + 25, 10, 10); + g.DrawEllipse(pen, _startX.Value + 23, _startY.Value + 15 + 40, 10, 10); + g.DrawEllipse(pen, _startX.Value + 13, _startY.Value + 15 + 40, 10, 10); + } + #endregion + } +} \ No newline at end of file diff --git a/Battleship/Battleship/EntityBattleship.cs b/Battleship/Battleship/EntityBattleship.cs new file mode 100644 index 0000000..c72a1a6 --- /dev/null +++ b/Battleship/Battleship/EntityBattleship.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +namespace Battleship; + // класс-сущность "Боевой корабль" +public class EntityBattleship +{ + public int Speed; // скорость + public double Weight; //вес + public Color BodyColor; /*основной цвет*/ + public Color AdditionalColor; // дополнительный цвет + public bool Weapon { get; private set; } // оружие + public bool Rockets { get; set; } // рокеты + public double Step => Speed * 100 / Weight; // шаг перемещения корабля + public void Init(int speed, double weight, Color bodycolor, Color additionalcolor, bool weapon, bool rockets) // инициализация полей объекта-класса военного корабля + { + Speed = speed; + Weight = weight; + BodyColor = bodycolor; + AdditionalColor = additionalcolor; + Weapon = weapon; + Rockets = rockets; + } +} \ No newline at end of file diff --git a/Battleship/Battleship/Form1.Designer.cs b/Battleship/Battleship/Form1.Designer.cs deleted file mode 100644 index 18ae06a..0000000 --- a/Battleship/Battleship/Form1.Designer.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace Battleship -{ - 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() - { - this.components = new System.ComponentModel.Container(); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(800, 450); - this.Text = "Form1"; - } - - #endregion - } -} diff --git a/Battleship/Battleship/Form1.cs b/Battleship/Battleship/Form1.cs deleted file mode 100644 index 1d6c6e1..0000000 --- a/Battleship/Battleship/Form1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Battleship -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - } -} diff --git a/Battleship/Battleship/FormBattleship.Designer.cs b/Battleship/Battleship/FormBattleship.Designer.cs new file mode 100644 index 0000000..26234dd --- /dev/null +++ b/Battleship/Battleship/FormBattleship.Designer.cs @@ -0,0 +1,131 @@ +namespace Battleship +{ + partial class FormBattleship + { + /// + /// 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() + { + pictureBoxBattleship = new PictureBox(); + buttonCreate = new Button(); + buttonUp = new Button(); + buttonDown = new Button(); + buttonLeft = new Button(); + buttonRight = new Button(); + ((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit(); + SuspendLayout(); + // + // pictureBoxBattleship + // + pictureBoxBattleship.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + pictureBoxBattleship.Location = new Point(0, 0); + pictureBoxBattleship.Name = "pictureBoxBattleship"; + pictureBoxBattleship.Size = new Size(1259, 803); + pictureBoxBattleship.TabIndex = 0; + pictureBoxBattleship.TabStop = false; + // + // buttonCreate + // + buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreate.Location = new Point(12, 745); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(150, 46); + buttonCreate.TabIndex = 1; + buttonCreate.Text = "Создать"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += buttonCreate_Click; + // + // buttonUp + // + buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonUp.BackgroundImage = Properties.Resources.right_arrow; + buttonUp.BackgroundImageLayout = ImageLayout.Stretch; + buttonUp.Location = new Point(1152, 699); + buttonUp.Name = "buttonUp"; + buttonUp.Size = new Size(40, 40); + buttonUp.TabIndex = 2; + buttonUp.UseVisualStyleBackColor = true; + buttonUp.Click += ButtonMove_Click; + // + // buttonDown + // + buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonDown.BackgroundImage = Properties.Resources.right_arrow_2; + buttonDown.BackgroundImageLayout = ImageLayout.Stretch; + buttonDown.Location = new Point(1152, 745); + buttonDown.Name = "buttonDown"; + buttonDown.Size = new Size(40, 40); + buttonDown.TabIndex = 3; + buttonDown.UseVisualStyleBackColor = true; + buttonDown.Click += ButtonMove_Click; + // + // buttonLeft + // + buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonLeft.BackgroundImage = Properties.Resources.right_arrow_4; + buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; + buttonLeft.Location = new Point(1106, 745); + buttonLeft.Name = "buttonLeft"; + buttonLeft.Size = new Size(40, 40); + buttonLeft.TabIndex = 4; + buttonLeft.UseVisualStyleBackColor = true; + buttonLeft.Click += ButtonMove_Click; + // + // buttonRight + // + buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonRight.BackgroundImage = Properties.Resources.right_arrow_3; + buttonRight.BackgroundImageLayout = ImageLayout.Stretch; + buttonRight.Location = new Point(1198, 745); + buttonRight.Name = "buttonRight"; + buttonRight.Size = new Size(40, 40); + buttonRight.TabIndex = 5; + buttonRight.UseVisualStyleBackColor = true; + buttonRight.Click += ButtonMove_Click; + // + // FormBattleship + // + AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1259, 803); + Controls.Add(buttonRight); + Controls.Add(buttonLeft); + Controls.Add(buttonDown); + Controls.Add(buttonUp); + Controls.Add(buttonCreate); + Controls.Add(pictureBoxBattleship); + Name = "FormBattleship"; + Text = "Линкор"; + ((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).EndInit(); + ResumeLayout(false); + } + + #endregion + private PictureBox pictureBoxBattleship; + private Button buttonCreate; + private Button buttonUp; + private Button buttonDown; + private Button buttonLeft; + private Button buttonRight; + } +} \ No newline at end of file diff --git a/Battleship/Battleship/FormBattleship.cs b/Battleship/Battleship/FormBattleship.cs new file mode 100644 index 0000000..a787a28 --- /dev/null +++ b/Battleship/Battleship/FormBattleship.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +namespace Battleship +{ + public partial class FormBattleship : Form + { + private DrawningBattleship? _drawningBattleship; + private EntityBattleship? _entityBattleship; + public FormBattleship() + { + InitializeComponent(); + } + private void Draw() // метод рисования корабля + { + if (_drawningBattleship == null) + return; + Bitmap bmp = new(pictureBoxBattleship.Width, pictureBoxBattleship.Height); + Graphics gr = Graphics.FromImage(bmp); + _drawningBattleship.DrawTransport(gr); + pictureBoxBattleship.Image = bmp; + } + private void buttonCreate_Click(object sender, EventArgs e) // обработка кнопки "создать" + { + Random random = new Random(); + _drawningBattleship = new DrawningBattleship(); + _entityBattleship = new EntityBattleship(); + _entityBattleship.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))); + _drawningBattleship.Init(_entityBattleship); + _drawningBattleship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height); + _drawningBattleship.SetPosition(random.Next(10, 100), random.Next(10, 100)); + Draw(); + } + private void ButtonMove_Click(object sender, EventArgs e) // обработка кнопок движения + { + if (_drawningBattleship == null) + return; + string name = ((Button)sender)?.Name ?? string.Empty; + bool result = false; + switch (name) + { + case "buttonUp": + result = _drawningBattleship.MoveTransport(DirectionType.Up); + break; + case "buttonDown": + result = _drawningBattleship.MoveTransport(DirectionType.Down); + break; + case "buttonRight": + result = _drawningBattleship.MoveTransport(DirectionType.Right); + break; + case "buttonLeft": + result = _drawningBattleship.MoveTransport(DirectionType.Left); + break; + } + if (result) + Draw(); + } + } +} diff --git a/Battleship/Battleship/Form1.resx b/Battleship/Battleship/FormBattleship.resx similarity index 93% rename from Battleship/Battleship/Form1.resx rename to Battleship/Battleship/FormBattleship.resx index 1af7de1..af32865 100644 --- a/Battleship/Battleship/Form1.resx +++ b/Battleship/Battleship/FormBattleship.resx @@ -1,17 +1,17 @@  - diff --git a/Battleship/Battleship/Program.cs b/Battleship/Battleship/Program.cs index 48b33ea..4d0e539 100644 --- a/Battleship/Battleship/Program.cs +++ b/Battleship/Battleship/Program.cs @@ -11,7 +11,7 @@ namespace Battleship // 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 FormBattleship()); } } } \ No newline at end of file diff --git a/Battleship/Battleship/Properties/Resources.Designer.cs b/Battleship/Battleship/Properties/Resources.Designer.cs new file mode 100644 index 0000000..3ec26bc --- /dev/null +++ b/Battleship/Battleship/Properties/Resources.Designer.cs @@ -0,0 +1,103 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace Battleship.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("Battleship.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 right_arrow { + get { + object obj = ResourceManager.GetObject("right-arrow", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap right_arrow_2 { + get { + object obj = ResourceManager.GetObject("right-arrow-2", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap right_arrow_3 { + get { + object obj = ResourceManager.GetObject("right-arrow-3", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Поиск локализованного ресурса типа System.Drawing.Bitmap. + /// + internal static System.Drawing.Bitmap right_arrow_4 { + get { + object obj = ResourceManager.GetObject("right-arrow-4", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/Battleship/Battleship/Properties/Resources.resx b/Battleship/Battleship/Properties/Resources.resx new file mode 100644 index 0000000..d7db91e --- /dev/null +++ b/Battleship/Battleship/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\right-arrow-4.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\right-arrow-2.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\right-arrow-3.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\right-arrow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/Battleship/Battleship/Resources/right-arrow-2.png b/Battleship/Battleship/Resources/right-arrow-2.png new file mode 100644 index 0000000..bf1cb45 Binary files /dev/null and b/Battleship/Battleship/Resources/right-arrow-2.png differ diff --git a/Battleship/Battleship/Resources/right-arrow-3.png b/Battleship/Battleship/Resources/right-arrow-3.png new file mode 100644 index 0000000..d3fc6c6 Binary files /dev/null and b/Battleship/Battleship/Resources/right-arrow-3.png differ diff --git a/Battleship/Battleship/Resources/right-arrow-4.png b/Battleship/Battleship/Resources/right-arrow-4.png new file mode 100644 index 0000000..edbd20c Binary files /dev/null and b/Battleship/Battleship/Resources/right-arrow-4.png differ diff --git a/Battleship/Battleship/Resources/right-arrow.png b/Battleship/Battleship/Resources/right-arrow.png new file mode 100644 index 0000000..9907cdd Binary files /dev/null and b/Battleship/Battleship/Resources/right-arrow.png differ