diff --git a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs new file mode 100644 index 0000000..7136532 --- /dev/null +++ b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs @@ -0,0 +1,119 @@ +using Battleship.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Battleship.CollectionGenericObjects; +/// +/// Абстракция компании, хранящий коллекцию кораблей +/// +public abstract class AbstractCompany +{ + /// + /// Размер места (ширина) + /// + protected readonly int _placeSizeWidth = 210; + + /// + /// Размер места (высота) + /// + protected readonly int _placeSizeHeight = 100; + + /// + /// Ширина окна + /// + protected readonly int _pictureWidth; + + /// + /// Высота окна + /// + protected readonly int _pictureHeight; + + /// + /// Коллекция кораблей + /// + protected ICollectionGenericObjects? _collection = null; + /// + /// Вычисление максимального количества элементов, который можно разместить в окне + /// + private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + + /// + /// Конструктор + /// + /// Ширина окна + /// Высота окна + /// Коллекция кораблей + public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) + { + _pictureWidth = picWidth; + _pictureHeight = picHeight; + _collection = collection; + _collection.SetMaxCount = GetMaxCount; + } + + /// + /// Перегрузка оператора сложения для класса + /// + /// Компания + /// Добавляемый объект + /// + public static int operator +(AbstractCompany company, DrawningShip ship) + { + return company._collection.Insert(ship); + } + + /// + /// Перегрузка оператора удаления для класса + /// + /// Компания + /// Номер удаляемого объекта + /// + public static DrawningShip operator -(AbstractCompany company, int position) + { + return company._collection?.Remove(position); + } + + /// + /// Получение случайного объекта из коллекции + /// + /// + public DrawningShip? GetRandomObject() + { + Random rnd = new(); + return _collection?.Get(rnd.Next(GetMaxCount)); + } + + /// + /// Вывод всей коллекции + /// + /// + public Bitmap? Show() + { + Bitmap bitmap = new(_pictureWidth, _pictureHeight); + Graphics graphics = Graphics.FromImage(bitmap); + DrawBackground(graphics); + + SetObjectsPosition(); + for (int i = 0; i < (_collection?.Count ?? 0); ++i) + { + DrawningShip? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + + return bitmap; + } + + /// + /// Вывод заднего фона + /// + /// + protected abstract void DrawBackground(Graphics g); + + /// + /// Расстановка объектов + /// + protected abstract void SetObjectsPosition(); +} diff --git a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs new file mode 100644 index 0000000..c615b62 --- /dev/null +++ b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +namespace Battleship.CollectionGenericObjects; + +/// +/// Интерфейс описания действий для набора хранимых объектов +/// +/// Параметр: ограничение - ссылочный тип +public interface ICollectionGenericObjects + where T : class +{ + /// + /// Количество объектов в коллекции + /// + int Count { get; } + + /// + /// Установка максимального количества элементов + /// + int SetMaxCount { set; } + + /// + /// Добавление объекта в коллекцию + /// + /// Добавляемый объект + /// true - удачно, false - вставка не удалась + int Insert(T obj); + /// + /// Добавление объекта в коллекцию на конкретную позицию + /// + /// Добавляемый объект + /// Позиция + /// true - удачно, false - вставка не удалась + bool Insert(T obj, int position); + + /// + /// Удаление объекта из коллекции с конкретной позиции + /// + /// Позиция + /// true - удачно, false - удаление не удалось + T? Remove(int position); + + /// + /// Получение объекта по позиции + /// + /// Позиция + /// Объект + T? Get(int position); +} diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs new file mode 100644 index 0000000..04ae8f8 --- /dev/null +++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -0,0 +1,110 @@ +using Battleship.Drawnings; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +namespace Battleship.CollectionGenericObjects; +/// +/// Параметризованный набор объектов +/// +/// Параметр: ограничение - ссылочный тип +public class MassiveGenericObjects : ICollectionGenericObjects + where T : class +{ + /// + /// Массив объектов, которые храним + /// + private T?[] _collection; + public int Count => _collection.Length; + /// + /// Установка максимального кол-ва объектов + /// + public int SetMaxCount + { + set + { + if (value > 0) + { + if (_collection.Length > 0) + { + Array.Resize(ref _collection, value); + } + else + { + _collection = new T?[value]; + } + } + } + } + + /// + /// Конструктор + /// + public MassiveGenericObjects() + { + _collection = Array.Empty(); + } + /// + /// Получение объекта по позиции + /// + /// Позиция (индекс) + /// + public T? Get(int position) + { + if (position < 0 || position >= _collection.Length) + return null; + return _collection[position]; + } + public int Insert(T obj) + { + for (int i = 0; i < _collection.Length; i++) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + return -1; + } + + public bool Insert(T obj, int position) + { + if (position < 0 || position >= _collection.Length) // проверка позиции + return false; + if (_collection[position] == null) // Попытка вставить на указанную позицию + { + _collection[position] = obj; + return true; + } + for (int i = position; i < _collection.Length; i++) // попытка вставить объект на позицию после указанной + { + if (_collection[i] == null) + { + _collection[i] = obj; + return true; + } + } + for (int i = 0; i < position; i++) // попытка вставить объект на позицию до указанной + { + if (_collection[i] == null) + { + _collection[i] = obj; + return true; + } + } + return false; + } + + public T? Remove(int position) + { + if (position < 0 || position >= _collection.Length || _collection[position]==null) // проверка позиции и наличия объекта + return null; + T? temp = _collection[position]; + _collection[position] = null; + + return temp; + } +} diff --git a/Battleship/Battleship/CollectionGenericObjects/ShipDocks.cs b/Battleship/Battleship/CollectionGenericObjects/ShipDocks.cs new file mode 100644 index 0000000..ed35c78 --- /dev/null +++ b/Battleship/Battleship/CollectionGenericObjects/ShipDocks.cs @@ -0,0 +1,57 @@ +using Battleship.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.AccessControl; +using System.Text; +using System.Threading.Tasks; + +namespace Battleship.CollectionGenericObjects; + +/// +/// Реализация абстрактной компании - доки с кораблями +/// +public class ShipDocks : AbstractCompany +{ + /// + /// Конструктор + /// + /// + /// + /// + public ShipDocks(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) + { + } + + protected override void DrawBackground(Graphics g) + { + Pen pen = new Pen(Color.Brown, 4); + int x = 0, y = 0; + while (y + _placeSizeHeight < _pictureHeight) + { + while (x + _placeSizeWidth < _pictureWidth) + { + g.DrawLine(pen, x, y, x + _placeSizeWidth, y); + g.DrawLine(pen, x, y, x, y + _placeSizeHeight); + g.DrawLine(pen, x, y + _placeSizeHeight, x+_placeSizeWidth, y + _placeSizeHeight); + x += _placeSizeWidth + 50; + } + y += _placeSizeHeight; + x = 0; + } + } + + protected override void SetObjectsPosition() + { + int count = 0; + for (int iy = _placeSizeHeight * 11 + 5; iy >= 0; iy -= _placeSizeHeight) + { + for(int ix = 5; ix + _placeSizeWidth+50 < _pictureWidth; ix += _placeSizeWidth + 50) + { + _collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(count)?.SetPosition(ix, iy); + count++; + } + } + } +} \ No newline at end of file diff --git a/Battleship/Battleship/Drawnings/DrawningBattleship.cs b/Battleship/Battleship/Drawnings/DrawningBattleship.cs index 1ca0c69..2bc5fdb 100644 --- a/Battleship/Battleship/Drawnings/DrawningBattleship.cs +++ b/Battleship/Battleship/Drawnings/DrawningBattleship.cs @@ -10,12 +10,18 @@ namespace Battleship.Drawnings; public class DrawningBattleship : DrawningShip { /// - /// Конструктор + /// Конструктор /// - /// объект класса-сущности - public DrawningBattleship(EntityBattleship entityBattleship) : base(143, 75) + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия обвеса + /// Признак наличия антикрыла + /// Признак наличия гоночной полосы + public DrawningBattleship(int speed, double weight, Color bodycolor, Color additionalcolor, bool weapon, bool rockets) : base(143, 75) { - EntityShip = entityBattleship; + EntityShip = new EntityBattleship(speed, weight, bodycolor, additionalcolor, weapon, rockets); } public override void DrawTransport(Graphics g) { diff --git a/Battleship/Battleship/Drawnings/DrawningShip.cs b/Battleship/Battleship/Drawnings/DrawningShip.cs index c3db0a1..8ed7510 100644 --- a/Battleship/Battleship/Drawnings/DrawningShip.cs +++ b/Battleship/Battleship/Drawnings/DrawningShip.cs @@ -45,12 +45,14 @@ public class DrawningShip _startY = null; } /// - /// Конструктор прорисовки - /// - /// Объект класса-сущности - public DrawningShip(EntityShip entityShip) : this() + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + public DrawningShip(int speed, double weight, Color bodyColor) : this() { - EntityShip = entityShip; + EntityShip = new EntityShip(speed, weight, bodyColor); } /// /// Конструктор для наследников diff --git a/Battleship/Battleship/FormBattleship.Designer.cs b/Battleship/Battleship/FormBattleship.Designer.cs index 93d9d0c..1c22a4d 100644 --- a/Battleship/Battleship/FormBattleship.Designer.cs +++ b/Battleship/Battleship/FormBattleship.Designer.cs @@ -27,12 +27,10 @@ private void InitializeComponent() { pictureBoxBattleship = new PictureBox(); - buttonCreate = new Button(); buttonUp = new Button(); buttonDown = new Button(); buttonLeft = new Button(); buttonRight = new Button(); - buttonCreateSimple = new Button(); comboBoxStrategy = new ComboBox(); buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit(); @@ -47,17 +45,6 @@ pictureBoxBattleship.TabIndex = 0; pictureBoxBattleship.TabStop = false; // - // buttonCreate - // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(12, 844); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(316, 46); - buttonCreate.TabIndex = 1; - buttonCreate.Text = "Создать боевой корабль"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += buttonCreate_Click; - // // buttonUp // buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; @@ -106,17 +93,6 @@ buttonRight.UseVisualStyleBackColor = true; buttonRight.Click += ButtonMove_Click; // - // buttonCreateSimple - // - buttonCreateSimple.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreateSimple.Location = new Point(334, 844); - buttonCreateSimple.Name = "buttonCreateSimple"; - buttonCreateSimple.Size = new Size(316, 46); - buttonCreateSimple.TabIndex = 6; - buttonCreateSimple.Text = "Создать корабль"; - buttonCreateSimple.UseVisualStyleBackColor = true; - buttonCreateSimple.Click += buttonCreateSimple_Click; - // // comboBoxStrategy // comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; @@ -146,12 +122,10 @@ ClientSize = new Size(1496, 902); Controls.Add(buttonStrategyStep); Controls.Add(comboBoxStrategy); - Controls.Add(buttonCreateSimple); Controls.Add(buttonRight); Controls.Add(buttonLeft); Controls.Add(buttonDown); Controls.Add(buttonUp); - Controls.Add(buttonCreate); Controls.Add(pictureBoxBattleship); Name = "FormBattleship"; Text = "Линкор"; @@ -161,12 +135,10 @@ #endregion private PictureBox pictureBoxBattleship; - private Button buttonCreate; private Button buttonUp; private Button buttonDown; private Button buttonLeft; private Button buttonRight; - private Button buttonCreateSimple; private ComboBox comboBoxStrategy; private Button buttonStrategyStep; } diff --git a/Battleship/Battleship/FormBattleship.cs b/Battleship/Battleship/FormBattleship.cs index 25f1e5d..38f89ee 100644 --- a/Battleship/Battleship/FormBattleship.cs +++ b/Battleship/Battleship/FormBattleship.cs @@ -15,9 +15,22 @@ namespace Battleship public partial class FormBattleship : Form { private DrawningShip? _drawningShip; - private EntityShip? _entityShip; - private EntityBattleship? _entityBattleship; private AbstractStrategy? _strategy; + + /// + /// Получение объекта + /// + public DrawningShip SetShip + { + set + { + _drawningShip = value; //??? value в сеттерах - стандартная переменная? + _drawningShip.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height); + comboBoxStrategy.Enabled = true; + _strategy = null; + Draw(); + } + } public FormBattleship() { InitializeComponent(); @@ -32,41 +45,6 @@ namespace Battleship _drawningShip.DrawTransport(gr); pictureBoxBattleship.Image = bmp; } - private void CreateObject(string type) - { - Random random = new(); - switch (type) - { - case nameof(DrawningShip): - _entityShip = new EntityShip(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); - _drawningShip = new DrawningShip(_entityShip); - break; - case nameof(DrawningBattleship): - _entityBattleship = new EntityBattleship(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))); - _drawningShip = new DrawningBattleship(_entityBattleship); - break; - default: - return; - } - _drawningShip.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height); - _drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100)); - _strategy = null; - comboBoxStrategy.Enabled = true; - Draw(); - } - private void buttonCreate_Click(object sender, EventArgs e) // обработка кнопки "создать боевой корабль" - { - CreateObject(nameof(DrawningBattleship)); - } - private void buttonCreateSimple_Click(object sender, EventArgs e) // обработка кнопки "создать корабль" - { - CreateObject(nameof(DrawningShip)); - - } private void ButtonMove_Click(object sender, EventArgs e) // обработка кнопок движения { if (_drawningShip == null) diff --git a/Battleship/Battleship/FormShipCollection.Designer.cs b/Battleship/Battleship/FormShipCollection.Designer.cs new file mode 100644 index 0000000..e5bacaa --- /dev/null +++ b/Battleship/Battleship/FormShipCollection.Designer.cs @@ -0,0 +1,174 @@ +namespace Battleship +{ + partial class FormShipCollection + { + /// + /// 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() + { + Tools = new GroupBox(); + buttonRefresh = new Button(); + buttonGoToTest = new Button(); + buttonDelShip = new Button(); + maskedTextBox = new MaskedTextBox(); + buttonAddBettleship = new Button(); + buttonAddShip = new Button(); + comboBoxSelectorCompany = new ComboBox(); + pictureBox = new PictureBox(); + Tools.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + SuspendLayout(); + // + // Tools + // + Tools.Controls.Add(buttonRefresh); + Tools.Controls.Add(buttonGoToTest); + Tools.Controls.Add(buttonDelShip); + Tools.Controls.Add(maskedTextBox); + Tools.Controls.Add(buttonAddBettleship); + Tools.Controls.Add(buttonAddShip); + Tools.Controls.Add(comboBoxSelectorCompany); + Tools.Dock = DockStyle.Right; + Tools.Location = new Point(1605, 0); + Tools.Name = "Tools"; + Tools.Size = new Size(488, 1236); + Tools.TabIndex = 0; + Tools.TabStop = false; + Tools.Text = "Инструменты"; + // + // buttonRefresh + // + buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonRefresh.Location = new Point(14, 1134); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(468, 90); + buttonRefresh.TabIndex = 6; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // buttonGoToTest + // + buttonGoToTest.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonGoToTest.Location = new Point(6, 768); + buttonGoToTest.Name = "buttonGoToTest"; + buttonGoToTest.Size = new Size(476, 90); + buttonGoToTest.TabIndex = 5; + buttonGoToTest.Text = "Передать на тест"; + buttonGoToTest.UseVisualStyleBackColor = true; + buttonGoToTest.Click += ButtonGoToTest_Click; + // + // buttonDelShip + // + buttonDelShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonDelShip.Location = new Point(6, 573); + buttonDelShip.Name = "buttonDelShip"; + buttonDelShip.Size = new Size(476, 90); + buttonDelShip.TabIndex = 4; + buttonDelShip.Text = "Удалить корабль"; + buttonDelShip.UseVisualStyleBackColor = true; + buttonDelShip.Click += ButtonDelShip_Click; + // + // maskedTextBox + // + maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + maskedTextBox.Location = new Point(6, 520); + maskedTextBox.Mask = "00"; + maskedTextBox.Name = "maskedTextBox"; + maskedTextBox.Size = new Size(476, 39); + maskedTextBox.TabIndex = 3; + maskedTextBox.ValidatingType = typeof(int); + // + // buttonAddBettleship + // + buttonAddBettleship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddBettleship.Location = new Point(6, 283); + buttonAddBettleship.Name = "buttonAddBettleship"; + buttonAddBettleship.Size = new Size(476, 90); + buttonAddBettleship.TabIndex = 2; + buttonAddBettleship.Text = "Добавить боевой корабль"; + buttonAddBettleship.UseVisualStyleBackColor = true; + buttonAddBettleship.Click += ButtonAddBattleship_Click; + // + // buttonAddShip + // + buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddShip.Location = new Point(6, 172); + buttonAddShip.Name = "buttonAddShip"; + buttonAddShip.Size = new Size(476, 90); + buttonAddShip.TabIndex = 1; + buttonAddShip.Text = "Добавить корабль"; + buttonAddShip.UseVisualStyleBackColor = true; + buttonAddShip.Click += buttonAddShip_Click_1; + // + // comboBoxSelectorCompany + // + comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxSelectorCompany.FormattingEnabled = true; + comboBoxSelectorCompany.Items.AddRange(new object[] { "Доки" }); + comboBoxSelectorCompany.Location = new Point(6, 38); + comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; + comboBoxSelectorCompany.Size = new Size(476, 40); + comboBoxSelectorCompany.TabIndex = 0; + comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; + // + // pictureBox + // + pictureBox.Dock = DockStyle.Fill; + pictureBox.Location = new Point(0, 0); + pictureBox.Name = "pictureBox"; + pictureBox.Size = new Size(1605, 1236); + pictureBox.TabIndex = 1; + pictureBox.TabStop = false; + // + // FormShipCollection + // + AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(2093, 1236); + Controls.Add(pictureBox); + Controls.Add(Tools); + Name = "FormShipCollection"; + Text = "Коллекция кораблей"; + Tools.ResumeLayout(false); + Tools.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + ResumeLayout(false); + } + + #endregion + + private GroupBox Tools; + private Button buttonAddBettleship; + private Button buttonAddShip; + private ComboBox comboBoxSelectorCompany; + private Button buttonDelShip; + private MaskedTextBox maskedTextBox; + private PictureBox pictureBox; + private Button buttonRefresh; + private Button buttonGoToTest; + } +} \ No newline at end of file diff --git a/Battleship/Battleship/FormShipCollection.cs b/Battleship/Battleship/FormShipCollection.cs new file mode 100644 index 0000000..abcacce --- /dev/null +++ b/Battleship/Battleship/FormShipCollection.cs @@ -0,0 +1,166 @@ +using Battleship.CollectionGenericObjects; +using Battleship.Drawnings; +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 FormShipCollection : Form +{ + /// + /// Компания + /// + private AbstractCompany? _company = null; + + /// + /// Конструктор + /// + public FormShipCollection() + { + InitializeComponent(); + } + /// + /// Выбор компании + /// + /// + /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) + { + switch (comboBoxSelectorCompany.Text) + { + case "Доки": + _company = new ShipDocks(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + break; + } + + } + /// + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + private void CreateObject(string type) + { + if (_company == null) + { + return; + } + + Random random = new(); + DrawningShip drawningShip; + switch (type) + { + case nameof(DrawningShip): + drawningShip = new DrawningShip(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); + break; + case nameof(DrawningBattleship): + drawningShip = new DrawningBattleship(random.Next(100, 300), random.Next(1000, 3000), + GetColor(random), GetColor(random), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + + if (_company + drawningShip != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } + } + + /// + /// Получение цвета + /// + /// Генератор случайных чисел + /// + private static Color GetColor(Random random) + { + Color color = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)); + ColorDialog dialog = new(); + if (dialog.ShowDialog() == DialogResult.OK) + { + color = dialog.Color; + } + return color; + } + + private void ButtonDelShip_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) + { + return; + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + int pos = Convert.ToInt32(maskedTextBox.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } + } + + private void ButtonGoToTest_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + DrawningShip? ship = null; + int counter = 100; + while (ship == null) + { + ship = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + if (ship == null) + { + return; + } + + FormBattleship form = new() + { + SetShip = ship + }; + form.ShowDialog(); + + } + + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + pictureBox.Image = _company.Show(); + } + private void ButtonAddBattleship_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBattleship)); + + private void buttonAddShip_Click_1(object sender, EventArgs e) => CreateObject(nameof(DrawningShip)); +} diff --git a/Battleship/Battleship/FormShipCollection.resx b/Battleship/Battleship/FormShipCollection.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/Battleship/Battleship/FormShipCollection.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + \ No newline at end of file diff --git a/Battleship/Battleship/Program.cs b/Battleship/Battleship/Program.cs index 4d0e539..65edaed 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 FormBattleship()); + Application.Run(new FormShipCollection()); } } } \ No newline at end of file