From 9b285d16f4b4aef1b10190d25f0abc659c7f56ac Mon Sep 17 00:00:00 2001 From: victinass Date: Fri, 1 Mar 2024 21:04:02 +0400 Subject: [PATCH 1/4] =?UTF-8?q?=D0=9A=D0=BE=D0=BB=D0=BB=D0=B5=D0=BA=D1=86?= =?UTF-8?q?=D0=B8=D0=B8=20=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ICollectionGenericObjects.cs | 50 +++++++++++++++ .../MassiveGenericObjects.cs | 61 +++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs create mode 100644 Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs diff --git a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs new file mode 100644 index 0000000..8930d59 --- /dev/null +++ b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -0,0 +1,50 @@ +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 - вставка не удалась + bool Insert(T obj); + + /// + /// Добавление объекта в коллекцию на конкретную позицию + /// + /// Добавляемый объект + /// Позиция + /// true - вставка прошла удачно, false - вставка не удалась + bool Insert(T obj, int position); + + /// + /// Удаление объекта из коллекции с конкретной позиции + /// + /// + /// true - удаление прошло удачно, false - удаление не удалось + bool 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..daaf775 --- /dev/null +++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +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) { _collection = new T?[value]; } } } + + /// + /// Конструктор + /// + public MassiveGenericObjects() + { + _collection = Array.Empty(); + } + + public T? Get(int position) + { + //TODO проверка позиции + return _collection[position]; + } + + public bool Insert(T obj) + { + //TODO вставка в свободное место набора + return false; + } + + public bool Insert(T obj, int position) + { + // TODO проверка позиции + // TODO проверка, что элемент массива по этой позиции пустой, если нет, то + // ищется свободное место после этой позиции и идет вставка туда + // TODO вставка + return false; + + } + + public bool Remove(int position) + { + // TODO проверка позиции + // TODO удаление объекта из массива, присвоив элементу массива значение null + return true; + } +} -- 2.25.1 From 3b0784dd0b27fa1e35fa4aad6aa43725bf022d54 Mon Sep 17 00:00:00 2001 From: victinass Date: Mon, 4 Mar 2024 10:02:32 +0400 Subject: [PATCH 2/4] =?UTF-8?q?=D0=BF=D0=BE=D1=82=D0=BE=D0=BC=20=D0=B4?= =?UTF-8?q?=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 111 +++++++++++ .../ICollectionGenericObjects.cs | 13 +- .../MassiveGenericObjects.cs | 51 ++++- .../WarshipSharingService.cs | 54 +++++ .../Battleship/FormBattleship.Designer.cs | 28 --- Battleship/Battleship/FormBattleship.cs | 73 ++----- .../FormWarshipCollection.Designer.cs | 173 ++++++++++++++++ .../Battleship/FormWarshipCollection.cs | 185 ++++++++++++++++++ .../Battleship/FormWarshipCollection.resx | 120 ++++++++++++ Battleship/Battleship/Program.cs | 2 +- 10 files changed, 713 insertions(+), 97 deletions(-) create mode 100644 Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs create mode 100644 Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs create mode 100644 Battleship/Battleship/FormWarshipCollection.Designer.cs create mode 100644 Battleship/Battleship/FormWarshipCollection.cs create mode 100644 Battleship/Battleship/FormWarshipCollection.resx diff --git a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs new file mode 100644 index 0000000..276bc64 --- /dev/null +++ b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs @@ -0,0 +1,111 @@ +using Battleship.Drawings; + +namespace Battleship.CollectionGenericObjects; + +public abstract class AbstractCompany +{ + /// + /// Размер места (ширина) + /// + protected readonly int _placeSizeWidth = 210; + + /// + /// Размер места (высота) + /// + protected readonly int _placeSizeHeight = 80; + + /// + /// Ширина окна + /// + protected int _pictureWidth; + + /// + /// Высота окна + /// + protected int _pictureHeight; + + protected ICollectionGenericObjects? _collection = null; + + /// + /// Вычисление максимального количества элементов, который можно разместить в окне + /// + private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _pictureHeight); + + + /// + /// Конструктор + /// + /// Ширина окна + /// Высота окна + /// Коллеккция кораблей + public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) + { + _pictureWidth = picWidth; + _pictureHeight = picHeight; + _collection = collection; + _collection.SetMaxCount = GetMaxCount; + } + + /// + /// Перезагрузка оператора сложения для класса + /// + /// Компания + /// Добавляемый объект + /// + public static bool operator +(AbstractCompany company, DrawingWarship car) + { + return company._collection?.Insert(car) ?? false; + } + + /// + /// Перезагрузка оператора удаления для класса + /// + /// Компания + /// Номер удаляемого объекта + /// + public static bool operator -(AbstractCompany company, int position) + { + return company._collection?.Remove(position) ?? false; + } + + /// + /// Получение случайного объекта из коллекции + /// + /// + public DrawingWarship? 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++) + { + DrawingWarship? 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 index 8930d59..cca3024 100644 --- a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,13 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Battleship.CollectionGenericObjects; +namespace Battleship.CollectionGenericObjects; +/// +/// Интерфейс описания действий для набора хранимых объектов +/// +/// Параметр: ограничение - ссылочный тип public interface ICollectionGenericObjects where T : class + { /// /// Количество объектов в коллекции diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs index daaf775..8873549 100644 --- a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Battleship.CollectionGenericObjects; +namespace Battleship.CollectionGenericObjects; /// /// Параметрированный набор объектов @@ -33,12 +27,26 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { //TODO проверка позиции + if(position >= _collection.Length || position < 0) + { + return null; + } return _collection[position]; } public bool Insert(T obj) { //TODO вставка в свободное место набора + int index = 0; + while (index < _collection.Length) + { + if (_collection[index] == null) + { + _collection[index] = obj; + return true; + } + index++; + } return false; } @@ -48,6 +56,28 @@ public class MassiveGenericObjects : ICollectionGenericObjects // TODO проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда // TODO вставка + if (position >= _collection.Length || position < 0) + return false; + + while (position + 1 < _collection.Length) + { + if (_collection[position] == null) + { + _collection[position] = obj; + return true; + } + position++; + } + + while (position - 1 >= 0) + { + if (_collection[position] == null) + { + _collection[position] = obj; + return true; + } + position--; + } return false; } @@ -56,6 +86,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects { // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null + if (position >= _collection.Length || position < 0) + { + return false; + } + _collection[position] = null; return true; } -} +} \ No newline at end of file diff --git a/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs b/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs new file mode 100644 index 0000000..4fc363b --- /dev/null +++ b/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs @@ -0,0 +1,54 @@ +using Battleship.Drawings; + +namespace Battleship.CollectionGenericObjects; + +public class WarshipSharingService : AbstractCompany +{ + + public WarshipSharingService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) + { + } + + protected override void DrawBackground(Graphics g) + { + Pen pen = new(Color.Black, 3); + for (int i = 0; i <= _pictureWidth / _placeSizeWidth; i++) + { + for (int j = 0; j <= _pictureHeight / _placeSizeHeight; j++) + { + g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight); + } + g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight); + } + } + + protected override void SetObjectsPosition() + { + int width = _pictureWidth / _placeSizeWidth; + int height = _pictureHeight / _placeSizeHeight; + + int posWidth = 0; + int posHeight = height; + + for (int i = 0; i < (_collection?.Count ?? 0); i++) + { + if (_collection?.Get(i) != null) + { + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(_placeSizeWidth * posWidth + 4, posHeight * _placeSizeHeight + 4, width, height); + } + + if (posWidth < width) + posWidth++; + else + { + posWidth = 0; + posHeight--; + } + if (posHeight < 0) + { + return; + } + } + } +} \ No newline at end of file diff --git a/Battleship/Battleship/FormBattleship.Designer.cs b/Battleship/Battleship/FormBattleship.Designer.cs index 7b7abf3..33f68f9 100644 --- a/Battleship/Battleship/FormBattleship.Designer.cs +++ b/Battleship/Battleship/FormBattleship.Designer.cs @@ -29,12 +29,10 @@ partial class FormBattleship private void InitializeComponent() { pictureBoxBattleship = new PictureBox(); - buttonCreate = new Button(); buttonLeft = new Button(); buttonDown = new Button(); buttonRight = new Button(); buttonUp = new Button(); - buttonCreateWarshit = new Button(); comboBoxStrategy = new ComboBox(); buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit(); @@ -48,17 +46,6 @@ partial class FormBattleship pictureBoxBattleship.TabIndex = 0; pictureBoxBattleship.TabStop = false; // - // buttonCreate - // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(12, 518); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(267, 29); - buttonCreate.TabIndex = 0; - buttonCreate.Text = "Создать линкор"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += buttonCreate_Click; - // // buttonLeft // buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; @@ -107,17 +94,6 @@ partial class FormBattleship buttonUp.UseVisualStyleBackColor = true; buttonUp.Click += buttonMove_Click; // - // buttonCreateWarshit - // - buttonCreateWarshit.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreateWarshit.Location = new Point(316, 518); - buttonCreateWarshit.Name = "buttonCreateWarshit"; - buttonCreateWarshit.Size = new Size(267, 29); - buttonCreateWarshit.TabIndex = 5; - buttonCreateWarshit.Text = "Создать военный корабль"; - buttonCreateWarshit.UseVisualStyleBackColor = true; - buttonCreateWarshit.Click += buttonCreateWarshit_Click; - // // comboBoxStrategy // comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; @@ -147,12 +123,10 @@ partial class FormBattleship ClientSize = new Size(957, 559); Controls.Add(buttonStrategyStep); Controls.Add(comboBoxStrategy); - Controls.Add(buttonCreateWarshit); Controls.Add(buttonUp); Controls.Add(buttonRight); Controls.Add(buttonDown); Controls.Add(buttonLeft); - Controls.Add(buttonCreate); Controls.Add(pictureBoxBattleship); Name = "FormBattleship"; Text = "Линкор"; @@ -163,12 +137,10 @@ partial class FormBattleship #endregion private PictureBox pictureBoxBattleship; - private Button buttonCreate; private Button buttonDown; private Button buttonRight; private Button buttonUp; private Button buttonLeft; - private Button buttonCreateWarshit; private ComboBox comboBoxStrategy; private Button buttonStrategyStep; } \ No newline at end of file diff --git a/Battleship/Battleship/FormBattleship.cs b/Battleship/Battleship/FormBattleship.cs index 27ff7be..455f7f5 100644 --- a/Battleship/Battleship/FormBattleship.cs +++ b/Battleship/Battleship/FormBattleship.cs @@ -17,6 +17,21 @@ public partial class FormBattleship : Form /// private AbstractStrategy? _strategy; + + /// + /// Получение объекта + /// + public DrawingWarship SetWarship + { + set + { + _drawingWarship = value; + _drawingWarship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height); + _strategy = null; + Draw(); + } + } + /// /// Конструктор формы /// @@ -43,54 +58,6 @@ public partial class FormBattleship : Form } - private void CreateObject(string type) - { - Random random = new(); - switch (type) - { - case nameof(DrawingWarship): - _drawingWarship = new DrawingWarship(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(DrawingBattleship): - _drawingWarship = new DrawingBattleship(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - break; - default: - return; - } - - _drawingWarship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height); - _drawingWarship.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxBattleship.Width, pictureBoxBattleship.Height); - _strategy = null; - comboBoxStrategy.Enabled = true; - Draw(); - } - - /// - /// обработка нажатия кнопки "создать линкор" - /// - /// - /// - private void buttonCreate_Click(object sender, EventArgs e) - { - CreateObject(nameof(DrawingBattleship)); - - } - - /// - /// обработка нажатия кнопки "создать военный корабль" - /// - /// - /// - private void buttonCreateWarshit_Click(object sender, EventArgs e) - { - CreateObject(nameof(DrawingWarship)); - - } - /// /// кнопки вверх/вниз/влево/вправо /// @@ -157,13 +124,13 @@ public partial class FormBattleship : Form return; } comboBoxStrategy.Enabled = false; - _strategy.MakeStep(); - Draw(); + _strategy.MakeStep(); + Draw(); - if (_strategy.GetStatus() == StrategyStatus.Finish) - { + if (_strategy.GetStatus() == StrategyStatus.Finish) + { comboBoxStrategy.Enabled = true; _strategy = null; - } + } } } \ No newline at end of file diff --git a/Battleship/Battleship/FormWarshipCollection.Designer.cs b/Battleship/Battleship/FormWarshipCollection.Designer.cs new file mode 100644 index 0000000..873ec32 --- /dev/null +++ b/Battleship/Battleship/FormWarshipCollection.Designer.cs @@ -0,0 +1,173 @@ +namespace Battleship +{ + partial class FormWarshipCollection + { + /// + /// 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() + { + groupBoxTools = new GroupBox(); + buttonRefresh = new Button(); + buttonGoToCheck = new Button(); + buttonRemoveWarship = new Button(); + maskedTextBox = new MaskedTextBox(); + buttonAddBattleship = new Button(); + buttonAddWarship = new Button(); + comboBoxSelectionCompany = new ComboBox(); + pictureBox = new PictureBox(); + groupBoxTools.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + SuspendLayout(); + // + // groupBoxTools + // + groupBoxTools.Controls.Add(buttonRefresh); + groupBoxTools.Controls.Add(buttonGoToCheck); + groupBoxTools.Controls.Add(buttonRemoveWarship); + groupBoxTools.Controls.Add(maskedTextBox); + groupBoxTools.Controls.Add(buttonAddBattleship); + groupBoxTools.Controls.Add(buttonAddWarship); + groupBoxTools.Controls.Add(comboBoxSelectionCompany); + groupBoxTools.Dock = DockStyle.Right; + groupBoxTools.Location = new Point(706, 0); + groupBoxTools.Name = "groupBoxTools"; + groupBoxTools.Size = new Size(273, 594); + groupBoxTools.TabIndex = 0; + groupBoxTools.TabStop = false; + groupBoxTools.Text = "Инструменты"; + // + // buttonRefresh + // + buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonRefresh.Location = new Point(12, 477); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(255, 42); + buttonRefresh.TabIndex = 6; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // buttonGoToCheck + // + buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonGoToCheck.Location = new Point(12, 381); + buttonGoToCheck.Name = "buttonGoToCheck"; + buttonGoToCheck.Size = new Size(255, 42); + buttonGoToCheck.TabIndex = 5; + buttonGoToCheck.Text = "Передать на тесты"; + buttonGoToCheck.UseVisualStyleBackColor = true; + buttonGoToCheck.Click += buttonGoToCheck_Click; + // + // buttonRemoveWarship + // + buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonRemoveWarship.Location = new Point(12, 283); + buttonRemoveWarship.Name = "buttonRemoveWarship"; + buttonRemoveWarship.Size = new Size(255, 42); + buttonRemoveWarship.TabIndex = 4; + buttonRemoveWarship.Text = "Удалить корабль"; + buttonRemoveWarship.UseVisualStyleBackColor = true; + // + // maskedTextBox + // + maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + maskedTextBox.Location = new Point(12, 238); + maskedTextBox.Mask = "00"; + maskedTextBox.Name = "maskedTextBox"; + maskedTextBox.Size = new Size(255, 27); + maskedTextBox.TabIndex = 3; + // + // buttonAddBattleship + // + buttonAddBattleship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddBattleship.Location = new Point(12, 143); + buttonAddBattleship.Name = "buttonAddBattleship"; + buttonAddBattleship.Size = new Size(255, 42); + buttonAddBattleship.TabIndex = 2; + buttonAddBattleship.Text = "Добавление линкора"; + buttonAddBattleship.UseVisualStyleBackColor = true; + buttonAddBattleship.Click += buttonAddBattleship_Click; + // + // buttonAddWarship + // + buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonAddWarship.Location = new Point(12, 95); + buttonAddWarship.Name = "buttonAddWarship"; + buttonAddWarship.Size = new Size(255, 42); + buttonAddWarship.TabIndex = 1; + buttonAddWarship.Text = "Добавление корабля"; + buttonAddWarship.UseVisualStyleBackColor = true; + buttonAddWarship.Click += buttonAddWarship_Click; + // + // comboBoxSelectionCompany + // + comboBoxSelectionCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + comboBoxSelectionCompany.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxSelectionCompany.FormattingEnabled = true; + comboBoxSelectionCompany.Items.AddRange(new object[] { "Хранилище" }); + comboBoxSelectionCompany.Location = new Point(12, 26); + comboBoxSelectionCompany.Name = "comboBoxSelectionCompany"; + comboBoxSelectionCompany.Size = new Size(255, 28); + comboBoxSelectionCompany.TabIndex = 0; + comboBoxSelectionCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; + // + // pictureBox + // + pictureBox.Dock = DockStyle.Fill; + pictureBox.Location = new Point(0, 0); + pictureBox.Name = "pictureBox"; + pictureBox.Size = new Size(706, 594); + pictureBox.TabIndex = 1; + pictureBox.TabStop = false; + // + // FormWarshipCollection + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(979, 594); + Controls.Add(pictureBox); + Controls.Add(groupBoxTools); + Name = "FormWarshipCollection"; + Text = "Коллекция кораблей"; + //Load += this.FormWarshipCollection_Load; + groupBoxTools.ResumeLayout(false); + groupBoxTools.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + ResumeLayout(false); + } + #endregion + + private GroupBox groupBoxTools; + private ComboBox comboBoxSelectionCompany; + private MaskedTextBox maskedTextBoxPosition; + private Button buttonAddBattleship; + private Button buttonAddWarship; + private Button buttonRemoveWarship; + private MaskedTextBox maskedTextBox; + private PictureBox pictureBox; + private Button buttonRefresh; + private Button buttonGoToCheck; + } +} \ No newline at end of file diff --git a/Battleship/Battleship/FormWarshipCollection.cs b/Battleship/Battleship/FormWarshipCollection.cs new file mode 100644 index 0000000..8fedfb7 --- /dev/null +++ b/Battleship/Battleship/FormWarshipCollection.cs @@ -0,0 +1,185 @@ +using Battleship.CollectionGenericObjects; +using Battleship.Drawings; + +namespace Battleship; + +/// +/// Форма работы с компанией и ее коллекцией +/// +public partial class FormWarshipCollection : Form +{ + /// + /// Компания + /// + private AbstractCompany? _company = null; + + /// + /// Конструктор + /// + public FormWarshipCollection() + { + InitializeComponent(); + } + + /// + /// Выбор компании + /// + /// + /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) + { + switch (comboBoxSelectionCompany.Text) + { + case "Хранилище": + _company = new WarshipSharingService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + break; + } + } + + /// + /// Создание объекта + /// + /// + private void CreateObject(string type) + { + if (_company == null) + { + return; + } + Random random = new(); + DrawingWarship drawingWarship; + switch (type) + { + case nameof(DrawingWarship): + drawingWarship = new DrawingWarship(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); + break; + case nameof(DrawingBattleship): + drawingWarship = new DrawingBattleship(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + + if (_company + drawingWarship) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } + } + + /// + /// Получение цвета + /// + /// Генератор случайных чисел + /// + private static Color GetColor(Random random) + { + Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + ColorDialog dialog = new(); + if (dialog.ShowDialog() == DialogResult.OK) + { + color = dialog.Color; + } + return color; + } + + /// + /// Добавление линкора + /// + /// + /// + private void buttonAddBattleship_Click(object sender, EventArgs e) + { + CreateObject(nameof(DrawingBattleship)); + } + + /// + /// Добавление военного корабля + /// + /// + /// + private void buttonAddWarship_Click(object sender, EventArgs e) + { + CreateObject(nameof(DrawingWarship)); + } + + /// + /// Удаление объекта + /// + /// + /// + private void ButtonRemoveCar_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) + { + return; + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + if (_company - pos) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } + } + + /// + /// Передача на тесты + /// + /// + /// + private void buttonGoToCheck_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + DrawingWarship? warship = null; + int counter = 100; + while (warship == null) + { + warship = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + FormBattleship form = new FormBattleship(); + form.SetWarship = warship; + form.ShowDialog(); + + } + + /// + /// Обновление + /// + /// + /// + private void buttonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + pictureBox.Image = _company.Show(); + } +} \ No newline at end of file diff --git a/Battleship/Battleship/FormWarshipCollection.resx b/Battleship/Battleship/FormWarshipCollection.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/Battleship/Battleship/FormWarshipCollection.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..440f8c8 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 FormWarshipCollection()); } } } \ No newline at end of file -- 2.25.1 From 3fa56e548d5549e0933cb144a4063101a3ba238d Mon Sep 17 00:00:00 2001 From: victinass Date: Sun, 24 Mar 2024 16:13:12 +0400 Subject: [PATCH 3/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=963?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 14 ++-- .../ICollectionGenericObjects.cs | 8 +- .../MassiveGenericObjects.cs | 76 +++++++++++-------- .../WarshipSharingService.cs | 17 ++++- .../Battleship/Drawings/DrawingBattleship.cs | 4 +- .../Battleship/Drawings/DrawingWarship.cs | 4 +- .../FormWarshipCollection.Designer.cs | 28 +++---- .../Battleship/FormWarshipCollection.cs | 44 +++++++++-- 8 files changed, 124 insertions(+), 71 deletions(-) diff --git a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs index 276bc64..ff298ab 100644 --- a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs +++ b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs @@ -7,7 +7,7 @@ public abstract class AbstractCompany /// /// Размер места (ширина) /// - protected readonly int _placeSizeWidth = 210; + protected readonly int _placeSizeWidth = 238; /// /// Размер места (высота) @@ -29,7 +29,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _pictureHeight); + private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight) + 2; /// @@ -52,9 +52,9 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static bool operator +(AbstractCompany company, DrawingWarship car) + public static int operator +(AbstractCompany company, DrawingWarship warship) { - return company._collection?.Insert(car) ?? false; + return company._collection.Insert(warship); } /// @@ -63,9 +63,9 @@ public abstract class AbstractCompany /// Компания /// Номер удаляемого объекта /// - public static bool operator -(AbstractCompany company, int position) + public static DrawingWarship operator -(AbstractCompany company, int position) { - return company._collection?.Remove(position) ?? false; + return company._collection.Remove(position); } /// @@ -89,7 +89,7 @@ public abstract class AbstractCompany DrawBackground(graphics); SetObjectsPosition(); - for (int i = 0; i < (_collection?.Count ?? 0); i++) + for (int i = 0; i < (_collection?.Count ?? 0); ++i) { DrawingWarship? obj = _collection?.Get(i); obj?.DrawTransport(graphics); diff --git a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs index cca3024..fb30a96 100644 --- a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -14,7 +14,7 @@ public interface ICollectionGenericObjects int Count { get; } /// - /// Установка минимального количества элементов + /// Установка максимального количества элементов /// int SetMaxCount { set; } @@ -23,7 +23,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - bool Insert(T obj); + int Insert(T obj); /// /// Добавление объекта в коллекцию на конкретную позицию @@ -31,14 +31,14 @@ public interface ICollectionGenericObjects /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - bool Insert(T obj, int position); + int Insert(T obj, int position); /// /// Удаление объекта из коллекции с конкретной позиции /// /// /// true - удаление прошло удачно, false - удаление не удалось - bool Remove(int position); + T? Remove(int position); /// /// Получение объекта по позиции diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs index 8873549..f86cc95 100644 --- a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,14 +1,16 @@ -namespace Battleship.CollectionGenericObjects; +using Battleship.CollectionGenericObjects; + +//namespace Battleship.CollectionGenericObjects; /// -/// Параметрированный набор объектов +/// Параметризованный набор объектов /// /// Параметр: ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects where T : class { /// - /// Массив объектов, которые хранили + /// Массив объектов, которые храним /// private T?[] _collection; @@ -21,76 +23,88 @@ public class MassiveGenericObjects : ICollectionGenericObjects /// public MassiveGenericObjects() { - _collection = Array.Empty(); + _collection = Array.Empty(); } public T? Get(int position) { - //TODO проверка позиции - if(position >= _collection.Length || position < 0) + // TODO проверка позиции + if (position >= _collection.Length || position < 0) { return null; } return _collection[position]; } - public bool Insert(T obj) + public int Insert(T obj) { - //TODO вставка в свободное место набора + // TODO вставка в свободное место набора int index = 0; while (index < _collection.Length) { if (_collection[index] == null) { _collection[index] = obj; - return true; + return index; } index++; } - return false; + return -1; } - public bool Insert(T obj, int position) + public int Insert(T obj, int position) { // TODO проверка позиции // TODO проверка, что элемент массива по этой позиции пустой, если нет, то - // ищется свободное место после этой позиции и идет вставка туда + // ищется свободное место после этой позиции и идет вставка туда + // если нет после, ищем до // TODO вставка if (position >= _collection.Length || position < 0) - return false; + return -1; - while (position + 1 < _collection.Length) - { - if (_collection[position] == null) + // TODO проверка, что элемент массива по этой позиции пустой, если нет, то + if (_collection[position] != null) { - _collection[position] = obj; - return true; - } - position++; + // проверка, что после вставляемого элемента в массиве есть пустой элемент + int nullIndex = -1; + for (int i = position + 1; i < Count; i++) + { + if (_collection[i] == null) + { + nullIndex = i; + break; } - - while (position - 1 >= 0) - { - if (_collection[position] == null) + ++index; + } + // Если пустого элемента нет, то выходим + if (nullIndex < 0) { - _collection[position] = obj; - return true; + return -1; + } + // сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента + int j = nullIndex - 1; + while (j >= position) + { + _collection[j + 1] = _collection[j]; + j--; } position--; } - return false; - + // TODO вставка по позиции + _collection[position] = obj; + return position; } - public bool Remove(int position) + public T? Remove(int position) { // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null if (position >= _collection.Length || position < 0) { - return false; + return null; } + T temp = _collection[position]; _collection[position] = null; - return true; + return temp; } } \ No newline at end of file diff --git a/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs b/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs index 4fc363b..b0943f2 100644 --- a/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs +++ b/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs @@ -2,16 +2,24 @@ namespace Battleship.CollectionGenericObjects; +/// +/// Реализация абстрактной компании - доки +/// public class WarshipSharingService : AbstractCompany { - + /// + /// Конструктор + /// + /// + /// + /// public WarshipSharingService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) { } protected override void DrawBackground(Graphics g) { - Pen pen = new(Color.Black, 3); + Pen pen = new(Color.DarkSlateBlue, 4); for (int i = 0; i <= _pictureWidth / _placeSizeWidth; i++) { for (int j = 0; j <= _pictureHeight / _placeSizeHeight; j++) @@ -22,20 +30,21 @@ public class WarshipSharingService : AbstractCompany } } + //установка объектов protected override void SetObjectsPosition() { int width = _pictureWidth / _placeSizeWidth; int height = _pictureHeight / _placeSizeHeight; int posWidth = 0; - int posHeight = height; + int posHeight = height - 1; for (int i = 0; i < (_collection?.Count ?? 0); i++) { if (_collection?.Get(i) != null) { _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(i)?.SetPosition(_placeSizeWidth * posWidth + 4, posHeight * _placeSizeHeight + 4, width, height); + _collection?.Get(i)?.SetPosition(_placeSizeWidth * posWidth + 4, posHeight * _placeSizeHeight + 4); } if (posWidth < width) diff --git a/Battleship/Battleship/Drawings/DrawingBattleship.cs b/Battleship/Battleship/Drawings/DrawingBattleship.cs index fdb8d10..bb835c3 100644 --- a/Battleship/Battleship/Drawings/DrawingBattleship.cs +++ b/Battleship/Battleship/Drawings/DrawingBattleship.cs @@ -17,9 +17,7 @@ public class DrawingBattleship : DrawingWarship /// Признак наличия палубы /// Признак наличия отсека для ракет /// Признак наличия башни - /// - - public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 60) + public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 80) { EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor); } diff --git a/Battleship/Battleship/Drawings/DrawingWarship.cs b/Battleship/Battleship/Drawings/DrawingWarship.cs index 2480935..a5afa8f 100644 --- a/Battleship/Battleship/Drawings/DrawingWarship.cs +++ b/Battleship/Battleship/Drawings/DrawingWarship.cs @@ -37,7 +37,7 @@ public class DrawingWarship /// /// Высота прорисовки военного корабля /// - private readonly int _drawingWarshipHeight = 40; + private readonly int _drawingWarshipHeight = 80; /// /// Координата Х объекта @@ -135,7 +135,7 @@ public class DrawingWarship /// Координата X /// Координата Y - public void SetPosition(int x, int y, int width, int height) + public void SetPosition(int x, int y) { if (!_pictureWidth.HasValue || !_pictureHeight.HasValue) { diff --git a/Battleship/Battleship/FormWarshipCollection.Designer.cs b/Battleship/Battleship/FormWarshipCollection.Designer.cs index 873ec32..235a23d 100644 --- a/Battleship/Battleship/FormWarshipCollection.Designer.cs +++ b/Battleship/Battleship/FormWarshipCollection.Designer.cs @@ -51,9 +51,9 @@ groupBoxTools.Controls.Add(buttonAddWarship); groupBoxTools.Controls.Add(comboBoxSelectionCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(706, 0); + groupBoxTools.Location = new Point(861, 0); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(273, 594); + groupBoxTools.Size = new Size(292, 583); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -63,18 +63,18 @@ buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Location = new Point(12, 477); buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(255, 42); + buttonRefresh.Size = new Size(274, 42); buttonRefresh.TabIndex = 6; buttonRefresh.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true; - buttonRefresh.Click += buttonRefresh_Click; + buttonRefresh.Click += ButtonRefresh_Click; // // buttonGoToCheck // buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Location = new Point(12, 381); buttonGoToCheck.Name = "buttonGoToCheck"; - buttonGoToCheck.Size = new Size(255, 42); + buttonGoToCheck.Size = new Size(274, 42); buttonGoToCheck.TabIndex = 5; buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.UseVisualStyleBackColor = true; @@ -85,7 +85,7 @@ buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveWarship.Location = new Point(12, 283); buttonRemoveWarship.Name = "buttonRemoveWarship"; - buttonRemoveWarship.Size = new Size(255, 42); + buttonRemoveWarship.Size = new Size(274, 42); buttonRemoveWarship.TabIndex = 4; buttonRemoveWarship.Text = "Удалить корабль"; buttonRemoveWarship.UseVisualStyleBackColor = true; @@ -96,7 +96,7 @@ maskedTextBox.Location = new Point(12, 238); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; - maskedTextBox.Size = new Size(255, 27); + maskedTextBox.Size = new Size(274, 27); maskedTextBox.TabIndex = 3; // // buttonAddBattleship @@ -104,22 +104,22 @@ buttonAddBattleship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddBattleship.Location = new Point(12, 143); buttonAddBattleship.Name = "buttonAddBattleship"; - buttonAddBattleship.Size = new Size(255, 42); + buttonAddBattleship.Size = new Size(274, 42); buttonAddBattleship.TabIndex = 2; buttonAddBattleship.Text = "Добавление линкора"; buttonAddBattleship.UseVisualStyleBackColor = true; - buttonAddBattleship.Click += buttonAddBattleship_Click; + buttonAddBattleship.Click += ButtonAddBattleship_Click; // // buttonAddWarship // buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddWarship.Location = new Point(12, 95); buttonAddWarship.Name = "buttonAddWarship"; - buttonAddWarship.Size = new Size(255, 42); + buttonAddWarship.Size = new Size(274, 42); buttonAddWarship.TabIndex = 1; buttonAddWarship.Text = "Добавление корабля"; buttonAddWarship.UseVisualStyleBackColor = true; - buttonAddWarship.Click += buttonAddWarship_Click; + buttonAddWarship.Click += ButtonAddWarship_Click; // // comboBoxSelectionCompany // @@ -129,7 +129,7 @@ comboBoxSelectionCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectionCompany.Location = new Point(12, 26); comboBoxSelectionCompany.Name = "comboBoxSelectionCompany"; - comboBoxSelectionCompany.Size = new Size(255, 28); + comboBoxSelectionCompany.Size = new Size(274, 28); comboBoxSelectionCompany.TabIndex = 0; comboBoxSelectionCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged; // @@ -138,7 +138,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 0); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(706, 594); + pictureBox.Size = new Size(861, 583); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -146,7 +146,7 @@ // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(979, 594); + ClientSize = new Size(1153, 583); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Name = "FormWarshipCollection"; diff --git a/Battleship/Battleship/FormWarshipCollection.cs b/Battleship/Battleship/FormWarshipCollection.cs index 8fedfb7..6a425c9 100644 --- a/Battleship/Battleship/FormWarshipCollection.cs +++ b/Battleship/Battleship/FormWarshipCollection.cs @@ -63,7 +63,7 @@ public partial class FormWarshipCollection : Form return; } - if (_company + drawingWarship) + if (_company + drawingWarship != -1) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); @@ -90,12 +90,44 @@ public partial class FormWarshipCollection : Form return color; } + /// + /// Передача на тесты + /// + /// + /// + private void buttonGoToCheck_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + DrawingWarship? warship = null; + int counter = 120; + while (warship == null) + { + warship = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + FormBattleship form = new() + { + SetWarship = warship + }; + form.ShowDialog(); + + } + /// /// Добавление линкора /// /// /// - private void buttonAddBattleship_Click(object sender, EventArgs e) + private void ButtonAddBattleship_Click(object sender, EventArgs e) { CreateObject(nameof(DrawingBattleship)); } @@ -105,7 +137,7 @@ public partial class FormWarshipCollection : Form /// /// /// - private void buttonAddWarship_Click(object sender, EventArgs e) + private void ButtonAddWarship_Click(object sender, EventArgs e) { CreateObject(nameof(DrawingWarship)); } @@ -115,7 +147,7 @@ public partial class FormWarshipCollection : Form /// /// /// - private void ButtonRemoveCar_Click(object sender, EventArgs e) + private void buttonRemoveWarship_Click_1(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { @@ -128,7 +160,7 @@ public partial class FormWarshipCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos) + if (_company - pos != null) { MessageBox.Show("Объект удален"); pictureBox.Image = _company.Show(); @@ -174,7 +206,7 @@ public partial class FormWarshipCollection : Form /// /// /// - private void buttonRefresh_Click(object sender, EventArgs e) + private void ButtonRefresh_Click(object sender, EventArgs e) { if (_company == null) { -- 2.25.1 From 3ac1dab1c97c86e9826854eccf30d044681809c2 Mon Sep 17 00:00:00 2001 From: victinass Date: Sun, 24 Mar 2024 16:13:26 +0400 Subject: [PATCH 4/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=963?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 4 +- .../ICollectionGenericObjects.cs | 2 +- .../MassiveGenericObjects.cs | 14 +++---- .../WarshipSharingService.cs | 2 +- .../Battleship/Drawings/DrawingBattleship.cs | 1 - .../Battleship/Drawings/DrawingWarship.cs | 2 +- .../FormWarshipCollection.Designer.cs | 27 +++++++------ .../Battleship/FormWarshipCollection.cs | 38 ++----------------- .../MovementStrategy/IMoveableObjectcs.cs | 8 +--- 9 files changed, 28 insertions(+), 70 deletions(-) diff --git a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs index ff298ab..2f8e832 100644 --- a/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs +++ b/Battleship/Battleship/CollectionGenericObjects/AbstractCompany.cs @@ -56,7 +56,6 @@ public abstract class AbstractCompany { return company._collection.Insert(warship); } - /// /// Перезагрузка оператора удаления для класса /// @@ -107,5 +106,4 @@ public abstract class AbstractCompany /// Расстановка объектов /// protected abstract void SetObjectsPosition(); -} - +} \ No newline at end of file diff --git a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs index fb30a96..4cb31a9 100644 --- a/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -46,4 +46,4 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); -} +} \ No newline at end of file diff --git a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs index f86cc95..fce9967 100644 --- a/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Battleship/Battleship/CollectionGenericObjects/MassiveGenericObjects.cs @@ -64,23 +64,22 @@ public class MassiveGenericObjects : ICollectionGenericObjects // TODO проверка, что элемент массива по этой позиции пустой, если нет, то if (_collection[position] != null) - { + { // проверка, что после вставляемого элемента в массиве есть пустой элемент int nullIndex = -1; for (int i = position + 1; i < Count; i++) - { - if (_collection[i] == null) { + if (_collection[i] == null) + { nullIndex = i; break; - } - ++index; - } + } + } // Если пустого элемента нет, то выходим if (nullIndex < 0) { return -1; - } + } // сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента int j = nullIndex - 1; while (j >= position) @@ -88,7 +87,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection[j + 1] = _collection[j]; j--; } - position--; } // TODO вставка по позиции _collection[position] = obj; diff --git a/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs b/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs index b0943f2..3aca316 100644 --- a/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs +++ b/Battleship/Battleship/CollectionGenericObjects/WarshipSharingService.cs @@ -54,7 +54,7 @@ public class WarshipSharingService : AbstractCompany posWidth = 0; posHeight--; } - if (posHeight < 0) + if (posHeight > height) { return; } diff --git a/Battleship/Battleship/Drawings/DrawingBattleship.cs b/Battleship/Battleship/Drawings/DrawingBattleship.cs index bb835c3..490fc08 100644 --- a/Battleship/Battleship/Drawings/DrawingBattleship.cs +++ b/Battleship/Battleship/Drawings/DrawingBattleship.cs @@ -1,5 +1,4 @@ using Battleship.Entities; -//using System.Drawings; namespace Battleship.Drawings; /// diff --git a/Battleship/Battleship/Drawings/DrawingWarship.cs b/Battleship/Battleship/Drawings/DrawingWarship.cs index a5afa8f..5d6e271 100644 --- a/Battleship/Battleship/Drawings/DrawingWarship.cs +++ b/Battleship/Battleship/Drawings/DrawingWarship.cs @@ -238,7 +238,7 @@ public class DrawingWarship Brush brBlack = new SolidBrush(Color.Black); g.FillRectangle(brBlack, _startPosX.Value + 5, _startPosY.Value + 7, 5, 10); //верхний g.FillRectangle(brBlack, _startPosX.Value + 5, _startPosY.Value + 22, 5, 10); //нижний - //границы двигателей + //границы двигателей g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 7, 5, 10); //двигатель верхний g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 22, 5, 10); //двигатель нижний diff --git a/Battleship/Battleship/FormWarshipCollection.Designer.cs b/Battleship/Battleship/FormWarshipCollection.Designer.cs index 235a23d..47b969c 100644 --- a/Battleship/Battleship/FormWarshipCollection.Designer.cs +++ b/Battleship/Battleship/FormWarshipCollection.Designer.cs @@ -32,21 +32,21 @@ buttonRefresh = new Button(); buttonGoToCheck = new Button(); buttonRemoveWarship = new Button(); - maskedTextBox = new MaskedTextBox(); buttonAddBattleship = new Button(); buttonAddWarship = new Button(); comboBoxSelectionCompany = new ComboBox(); pictureBox = new PictureBox(); + maskedTextBox1 = new MaskedTextBox(); groupBoxTools.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); SuspendLayout(); // // groupBoxTools // + groupBoxTools.Controls.Add(maskedTextBox1); groupBoxTools.Controls.Add(buttonRefresh); groupBoxTools.Controls.Add(buttonGoToCheck); groupBoxTools.Controls.Add(buttonRemoveWarship); - groupBoxTools.Controls.Add(maskedTextBox); groupBoxTools.Controls.Add(buttonAddBattleship); groupBoxTools.Controls.Add(buttonAddWarship); groupBoxTools.Controls.Add(comboBoxSelectionCompany); @@ -89,15 +89,7 @@ buttonRemoveWarship.TabIndex = 4; buttonRemoveWarship.Text = "Удалить корабль"; buttonRemoveWarship.UseVisualStyleBackColor = true; - // - // maskedTextBox - // - maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(12, 238); - maskedTextBox.Mask = "00"; - maskedTextBox.Name = "maskedTextBox"; - maskedTextBox.Size = new Size(274, 27); - maskedTextBox.TabIndex = 3; + buttonRemoveWarship.Click += buttonRemoveWarship_Click_1; // // buttonAddBattleship // @@ -142,6 +134,15 @@ pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // maskedTextBox1 + // + maskedTextBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right; + maskedTextBox1.Location = new Point(12, 250); + maskedTextBox1.Mask = "00"; + maskedTextBox1.Name = "maskedTextBox1"; + maskedTextBox1.Size = new Size(274, 27); + maskedTextBox1.TabIndex = 7; + // // FormWarshipCollection // AutoScaleDimensions = new SizeF(8F, 20F); @@ -151,7 +152,6 @@ Controls.Add(groupBoxTools); Name = "FormWarshipCollection"; Text = "Коллекция кораблей"; - //Load += this.FormWarshipCollection_Load; groupBoxTools.ResumeLayout(false); groupBoxTools.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); @@ -161,13 +161,12 @@ private GroupBox groupBoxTools; private ComboBox comboBoxSelectionCompany; - private MaskedTextBox maskedTextBoxPosition; private Button buttonAddBattleship; private Button buttonAddWarship; private Button buttonRemoveWarship; - private MaskedTextBox maskedTextBox; private PictureBox pictureBox; private Button buttonRefresh; private Button buttonGoToCheck; + private MaskedTextBox maskedTextBox1; } } \ No newline at end of file diff --git a/Battleship/Battleship/FormWarshipCollection.cs b/Battleship/Battleship/FormWarshipCollection.cs index 6a425c9..21a1d8b 100644 --- a/Battleship/Battleship/FormWarshipCollection.cs +++ b/Battleship/Battleship/FormWarshipCollection.cs @@ -55,8 +55,8 @@ public partial class FormWarshipCollection : Form break; case nameof(DrawingBattleship): drawingWarship = new DrawingBattleship(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)), + GetColor(random), + GetColor(random), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); break; default: @@ -149,7 +149,7 @@ public partial class FormWarshipCollection : Form /// private void buttonRemoveWarship_Click_1(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) + if (string.IsNullOrEmpty(maskedTextBox1.Text) || _company == null) { return; } @@ -159,7 +159,7 @@ public partial class FormWarshipCollection : Form return; } - int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + int pos = Convert.ToInt32(maskedTextBox1.Text); if (_company - pos != null) { MessageBox.Show("Объект удален"); @@ -171,36 +171,6 @@ public partial class FormWarshipCollection : Form } } - /// - /// Передача на тесты - /// - /// - /// - private void buttonGoToCheck_Click(object sender, EventArgs e) - { - if (_company == null) - { - return; - } - - DrawingWarship? warship = null; - int counter = 100; - while (warship == null) - { - warship = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } - } - - FormBattleship form = new FormBattleship(); - form.SetWarship = warship; - form.ShowDialog(); - - } - /// /// Обновление /// diff --git a/Battleship/Battleship/MovementStrategy/IMoveableObjectcs.cs b/Battleship/Battleship/MovementStrategy/IMoveableObjectcs.cs index 913cef6..16dbad9 100644 --- a/Battleship/Battleship/MovementStrategy/IMoveableObjectcs.cs +++ b/Battleship/Battleship/MovementStrategy/IMoveableObjectcs.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Battleship.MovementStrategy; +namespace Battleship.MovementStrategy; public interface IMoveableObjectcs { -- 2.25.1