diff --git a/solution/lab1/CollectionGenericObjects/AbstractCompany.cs b/solution/lab1/CollectionGenericObjects/AbstractCompany.cs index 04e7849..3720195 100644 --- a/solution/lab1/CollectionGenericObjects/AbstractCompany.cs +++ b/solution/lab1/CollectionGenericObjects/AbstractCompany.cs @@ -39,7 +39,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// /// Перегрузка оператора сложения для класса diff --git a/solution/lab1/CollectionGenericObjects/ICollectionGenericObjects.cs b/solution/lab1/CollectionGenericObjects/ICollectionGenericObjects.cs index 0fc8af2..ab6aacc 100644 --- a/solution/lab1/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/solution/lab1/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -16,7 +16,8 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } + /// /// Добавление объекта в коллекцию /// @@ -42,5 +43,17 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + int SetMaxCount { get; set; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); + } diff --git a/solution/lab1/CollectionGenericObjects/ListGenericObjects.cs b/solution/lab1/CollectionGenericObjects/ListGenericObjects.cs index ebaf977..f16d879 100644 --- a/solution/lab1/CollectionGenericObjects/ListGenericObjects.cs +++ b/solution/lab1/CollectionGenericObjects/ListGenericObjects.cs @@ -21,7 +21,27 @@ public class ListGenericObjects : ICollectionGenericObjects /// private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + + public int MaxCount + { + get + { + return Count; + } + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; + + public int SetMaxCount { set => throw new NotImplementedException(); } + int ICollectionGenericObjects.SetMaxCount { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + /// /// Конструктор /// @@ -30,6 +50,7 @@ public class ListGenericObjects : ICollectionGenericObjects _collection = new(); } + public T? Get(int position) { if (position >= 0 && position < _collection.Count) @@ -76,4 +97,11 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return temp; } + public IEnumerable GetItems() + { + for (int i = 0; i < Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/solution/lab1/CollectionGenericObjects/MassiveGenericObjects.cs b/solution/lab1/CollectionGenericObjects/MassiveGenericObjects.cs index 8353bdf..1980391 100644 --- a/solution/lab1/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/solution/lab1/CollectionGenericObjects/MassiveGenericObjects.cs @@ -15,7 +15,33 @@ public class MassiveGenericObjects : ICollectionGenericObjects private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } } + public int MaxCount + { + get + { + return _collection.Length; + } + set + { + if (value > 0) + { + if (_collection.Length > 0) + { + Array.Resize(ref _collection, value); + } + else + { + _collection = new T?[value]; + } + } + } + } + + public CollectionType GetCollectionType => CollectionType.Massive; + + public int SetMaxCount { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + /// /// Конструктор /// @@ -92,4 +118,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects return temp; } + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } diff --git a/solution/lab1/CollectionGenericObjects/StorageCollection.cs b/solution/lab1/CollectionGenericObjects/StorageCollection.cs index 3139ef4..cee9430 100644 --- a/solution/lab1/CollectionGenericObjects/StorageCollection.cs +++ b/solution/lab1/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using lab1.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -10,7 +11,7 @@ namespace lab1.CollectionGenericObjects; /// /// public class StorageCollection - where T : class + where T : DrawningTrackedVehicle { /// /// Словарь(хранилище) с коллекциями @@ -77,4 +78,131 @@ public class StorageCollection } } + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// + /// Сохранение информации по штурмовику в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + writer.Write(Environment.NewLine); + if (value.Value.Count == 0) + { + continue; + } + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.GetCollectionType); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + writer.Write(data); + writer.Write(_separatorItems); + } + } + return true; + } + } + /// + /// Загрузка информации по штурмовику в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + using (StreamReader fs = File.OpenText(filename)) + { + string str = fs.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + if (!str.StartsWith(_collectionKey)) + { + return false; + } + _storages.Clear(); + string strs = ""; + while ((strs = fs.ReadLine()) != null) + { + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; + } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + return false; + } + collection.MaxCount = Convert.ToInt32(record[2]); + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningEntityFighter() is T fighter) + { + if (collection.Insert(fighter) == -1) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + return true; + } + } + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? + CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } diff --git a/solution/lab1/Drawnings/DrawningTrackedVehicle.cs b/solution/lab1/Drawnings/DrawningTrackedVehicle.cs index 75d7c0d..9e9fb84 100644 --- a/solution/lab1/Drawnings/DrawningTrackedVehicle.cs +++ b/solution/lab1/Drawnings/DrawningTrackedVehicle.cs @@ -34,6 +34,7 @@ public class DrawningTrackedVehicle /// Верхняя координата прорисовки истребителя /// protected int? _startPosY; + private EntityTrackedVehicle fighter; /// /// Ширина прорисовки истребителя @@ -106,6 +107,11 @@ public class DrawningTrackedVehicle } + public DrawningTrackedVehicle(EntityTrackedVehicle fighter) + { + this.fighter = fighter; + } + /// /// Установка границ поля diff --git a/solution/lab1/Drawnings/ExtentionDrawningTrackedVehicle.cs b/solution/lab1/Drawnings/ExtentionDrawningTrackedVehicle.cs new file mode 100644 index 0000000..b429476 --- /dev/null +++ b/solution/lab1/Drawnings/ExtentionDrawningTrackedVehicle.cs @@ -0,0 +1,59 @@ +using lab1.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace lab1.Drawnings; + +public static class ExtentionDrawningTrackedVehicle +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningTrackedVehicle? CreateDrawningEntityFighter(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityTrackedVehicle? fighter = EntityFighter.CreateEntityFighter(strs); + if (fighter != null) + { + return new DrawingEntityFighter((EntityFighter)fighter); + } + + fighter = EntityTrackedVehicle.CreateEntityTrackedVehicle(strs); + + if (fighter != null) + { + return new DrawningTrackedVehicle(fighter); + } + return null; + } + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningTrackedVehicle drawningBaseStormtrooper) + { + string[]? array = drawningBaseStormtrooper?.EntityTrackedVehicle?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } +} + +internal class DrawingEntityFighter : DrawningTrackedVehicle +{ + public DrawingEntityFighter(EntityTrackedVehicle fighter) : base(fighter) + { + } +} \ No newline at end of file diff --git a/solution/lab1/Entities/EntityFighter.cs b/solution/lab1/Entities/EntityFighter.cs index f20d7c0..ef7fa49 100644 --- a/solution/lab1/Entities/EntityFighter.cs +++ b/solution/lab1/Entities/EntityFighter.cs @@ -1,4 +1,7 @@  +using static System.Reflection.Metadata.BlobBuilder; +using System.Net.Sockets; + namespace lab1.Entities; /// /// Класс-сущность "Истребитель" @@ -15,6 +18,10 @@ public class EntityFighter : EntityTrackedVehicle /// Признак (опция) наличия ковша /// public bool Kovsh { get; private set; } + public void setBodyTankColor(Color color) + { + AdditionalColor = color; + } /// /// Признак (опция) наличия опор для фиксации /// @@ -39,6 +46,36 @@ public class EntityFighter : EntityTrackedVehicle } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityFighter), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Kovsh.ToString(), Otval.ToString() }; + } + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityFighter? CreateEntityStormtrooper(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityFighter)) + { + return null; + } + return new EntityFighter(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } + + internal static EntityTrackedVehicle? CreateEntityFighter(string[] strs) + { + throw new NotImplementedException(); + } } + + + + diff --git a/solution/lab1/Entities/EntityTrackedVehicle.cs b/solution/lab1/Entities/EntityTrackedVehicle.cs index 79c5c87..278de67 100644 --- a/solution/lab1/Entities/EntityTrackedVehicle.cs +++ b/solution/lab1/Entities/EntityTrackedVehicle.cs @@ -27,6 +27,10 @@ public class EntityTrackedVehicle /// Шаг перемещения истребителя /// public double Step => Speed * 100 / Weight; + public void setBodyColor(Color color) + { + BodyColor = color; + } /// /// Конструктор сущности @@ -42,4 +46,32 @@ public class EntityTrackedVehicle } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityTrackedVehicle), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTrackedVehicle? CreateEntityBaseStormtrooper(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityTrackedVehicle)) + { + return null; + } + return new EntityTrackedVehicle(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } + + internal static EntityTrackedVehicle? CreateEntityTrackedVehicle(string[] strs) + { + throw new NotImplementedException(); + } } diff --git a/solution/lab1/FormTrackedVehicleCollection.Designer.cs b/solution/lab1/FormTrackedVehicleCollection.Designer.cs index 48a55e4..860f61b 100644 --- a/solution/lab1/FormTrackedVehicleCollection.Designer.cs +++ b/solution/lab1/FormTrackedVehicleCollection.Designer.cs @@ -30,7 +30,6 @@ { groupBoxTools = new GroupBox(); panelCompanyTools = new Panel(); - buttonAddFighter = new Button(); buttonAddTrackedVehicle = new Button(); buttonRefresh = new Button(); maskedTextBox = new MaskedTextBox(); @@ -47,10 +46,17 @@ labelCollectionName = new Label(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + SaveToolStripMenuItem = new ToolStripMenuItem(); + LoadToolStripMenuItem = new ToolStripMenuItem(); + openFileDialog = new OpenFileDialog(); + saveFileDialog = new SaveFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -60,16 +66,15 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(635, 0); + groupBoxTools.Location = new Point(635, 33); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(297, 615); + groupBoxTools.Size = new Size(297, 582); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // // panelCompanyTools // - panelCompanyTools.Controls.Add(buttonAddFighter); panelCompanyTools.Controls.Add(buttonAddTrackedVehicle); panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(maskedTextBox); @@ -81,17 +86,6 @@ panelCompanyTools.Size = new Size(282, 273); panelCompanyTools.TabIndex = 10; // - // buttonAddFighter - // - buttonAddFighter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonAddFighter.Location = new Point(6, 59); - buttonAddFighter.Name = "buttonAddFighter"; - buttonAddFighter.Size = new Size(273, 59); - buttonAddFighter.TabIndex = 2; - buttonAddFighter.Text = "Добавление гусеничной машины с оборудованием"; - buttonAddFighter.UseVisualStyleBackColor = true; - buttonAddFighter.Click += ButtonAddFighter_Click; - // // buttonAddTrackedVehicle // buttonAddTrackedVehicle.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; @@ -254,13 +248,55 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 33); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(635, 615); + pictureBox.Size = new Size(635, 582); pictureBox.TabIndex = 1; pictureBox.TabStop = false; pictureBox.Click += pictureBox1_Click; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(24, 24); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(932, 33); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(69, 29); + файлToolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + SaveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + SaveToolStripMenuItem.Size = new Size(273, 34); + SaveToolStripMenuItem.Text = "Сохранение"; + SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // LoadToolStripMenuItem + // + LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + LoadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + LoadToolStripMenuItem.Size = new Size(273, 34); + LoadToolStripMenuItem.Text = "Загрузка"; + LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *txt"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *txt"; + // // FormTrackedVehicleCollection // AutoScaleDimensions = new SizeF(10F, 25F); @@ -268,6 +304,8 @@ ClientSize = new Size(932, 615); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormTrackedVehicleCollection"; Text = "Коллекция гусеничных машин"; Load += FormTrackedVehicleCollection_Load; @@ -277,7 +315,10 @@ panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -285,7 +326,6 @@ private GroupBox groupBoxTools; private ComboBox comboBoxSelectorCompany; private Button buttonAddTrackedVehicle; - private Button buttonAddFighter; private PictureBox pictureBox; private Button buttonRemoveTrackedVehicle; private MaskedTextBox maskedTextBox; @@ -301,5 +341,11 @@ private Button button1CreateCompany; private Button buttonCollectionDel; private Panel panelCompanyTools; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/solution/lab1/FormTrackedVehicleCollection.cs b/solution/lab1/FormTrackedVehicleCollection.cs index 6f13647..ec9b14c 100644 --- a/solution/lab1/FormTrackedVehicleCollection.cs +++ b/solution/lab1/FormTrackedVehicleCollection.cs @@ -41,43 +41,28 @@ public partial class FormTrackedVehicleCollection : Form /// /// /// - private void ButtonAddTrackedVehicle_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTrackedVehicle)); - /// - /// Добавление истребителя - /// - /// - /// - private void ButtonAddFighter_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningEntityFighter)); + private void ButtonAddTrackedVehicle_Click(object sender, EventArgs e) + { + { + FormTrackedVehicleConfig form = new(); + form.Show(); + // передать метод ✔ + form.AddEvent(SetTrackedVehicle); + } + } /// - /// Создание объекта класса-перемещения + /// Добавление лодки в коллекцию /// - /// - private void CreateObject(string type) + /// + private void SetTrackedVehicle(DrawningTrackedVehicle trackedVehicle) { - if (_company == null) + if (_company == null || trackedVehicle == null) { return; } - Random random = new(); - DrawningTrackedVehicle drawningTrackedVehicle; - switch (type) - { - case nameof(DrawningTrackedVehicle): - drawningTrackedVehicle = new DrawningTrackedVehicle(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); - break; - case nameof(DrawningEntityFighter): - //TODO Выбор цветов - drawningTrackedVehicle = new DrawningEntityFighter(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 + drawningTrackedVehicle != -1) + if (_company + trackedVehicle >= 0) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); @@ -86,24 +71,6 @@ public partial class FormTrackedVehicleCollection : Form { 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; } /// @@ -243,18 +210,16 @@ public partial class FormTrackedVehicleCollection : Form // нужно убедиться, что есть выбранная коллекция // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись // удалить и обновить ListBox - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + if (_storageCollection.Keys.Contains(listBoxCollection.SelectedItem.ToString() ?? string.Empty)) + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString() ?? string.Empty); + RerfreshListBoxItems(); } + /// /// Обновление списка в listBoxCollection /// @@ -298,5 +263,49 @@ public partial class FormTrackedVehicleCollection : Form RerfreshListBoxItems(); } + /// + /// Обработка нажатия "Загрузка" + /// + /// + /// + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + // TODO продумать логику + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RerfreshListBoxItems(); + } + else + { + MessageBox.Show("Загрузка не удалась", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Сохранение прошло успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/solution/lab1/FormTrackedVehicleCollection.resx b/solution/lab1/FormTrackedVehicleCollection.resx index af32865..8033ac2 100644 --- a/solution/lab1/FormTrackedVehicleCollection.resx +++ b/solution/lab1/FormTrackedVehicleCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 165, 17 + + + 349, 20 + \ No newline at end of file diff --git a/solution/lab1/FormTrackedVehicleConfig.Designer.cs b/solution/lab1/FormTrackedVehicleConfig.Designer.cs index c003d41..4e87e25 100644 --- a/solution/lab1/FormTrackedVehicleConfig.Designer.cs +++ b/solution/lab1/FormTrackedVehicleConfig.Designer.cs @@ -74,7 +74,7 @@ groupBoxConfig.Dock = DockStyle.Left; groupBoxConfig.Location = new Point(0, 0); groupBoxConfig.Name = "groupBoxConfig"; - groupBoxConfig.Size = new Size(634, 212); + groupBoxConfig.Size = new Size(634, 420); groupBoxConfig.TabIndex = 0; groupBoxConfig.TabStop = false; groupBoxConfig.Text = "Параметры"; @@ -102,6 +102,7 @@ panelPurple.Name = "panelPurple"; panelPurple.Size = new Size(34, 37); panelPurple.TabIndex = 5; + panelPurple.MouseDown += Panel_MouseDown; // // panelBlack // @@ -110,6 +111,7 @@ panelBlack.Name = "panelBlack"; panelBlack.Size = new Size(34, 37); panelBlack.TabIndex = 4; + panelBlack.MouseDown += Panel_MouseDown; // // panelGray // @@ -118,6 +120,7 @@ panelGray.Name = "panelGray"; panelGray.Size = new Size(34, 37); panelGray.TabIndex = 3; + panelGray.MouseDown += Panel_MouseDown; // // panelWhite // @@ -126,6 +129,7 @@ panelWhite.Name = "panelWhite"; panelWhite.Size = new Size(34, 37); panelWhite.TabIndex = 2; + panelWhite.MouseDown += Panel_MouseDown; // // panelYellow // @@ -134,6 +138,7 @@ panelYellow.Name = "panelYellow"; panelYellow.Size = new Size(34, 37); panelYellow.TabIndex = 1; + panelYellow.MouseDown += Panel_MouseDown; // // panelBlue // @@ -150,6 +155,7 @@ panelGreen.Name = "panelGreen"; panelGreen.Size = new Size(34, 37); panelGreen.TabIndex = 1; + panelGreen.MouseDown += Panel_MouseDown; // // panelRed // @@ -158,6 +164,7 @@ panelRed.Name = "panelRed"; panelRed.Size = new Size(34, 37); panelRed.TabIndex = 0; + panelRed.MouseDown += Panel_MouseDown; // // checkBoxOtval // @@ -243,22 +250,23 @@ // pictureBoxObject.Location = new Point(659, 75); pictureBoxObject.Name = "pictureBoxObject"; - pictureBoxObject.Size = new Size(185, 78); + pictureBoxObject.Size = new Size(290, 227); pictureBoxObject.TabIndex = 1; pictureBoxObject.TabStop = false; // // buttonAdd // - buttonAdd.Location = new Point(640, 172); + buttonAdd.Location = new Point(640, 341); buttonAdd.Name = "buttonAdd"; buttonAdd.Size = new Size(106, 34); buttonAdd.TabIndex = 2; buttonAdd.Text = "Добавить"; buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; // // buttonCancel // - buttonCancel.Location = new Point(752, 172); + buttonCancel.Location = new Point(752, 341); buttonCancel.Name = "buttonCancel"; buttonCancel.Size = new Size(103, 34); buttonCancel.TabIndex = 3; @@ -272,13 +280,14 @@ panelObject1.Controls.Add(labelBodyColor); panelObject1.Location = new Point(644, 12); panelObject1.Name = "panelObject1"; - panelObject1.Size = new Size(211, 154); + panelObject1.Size = new Size(512, 323); panelObject1.TabIndex = 4; - panelObject1.DragDrop += panelObject1_DragDrop; + panelObject1.DragDrop += PanelObject1_DragDrop; panelObject1.DragEnter += PanelObject1_DragEnter; // // labelAdditionalColor // + labelAdditionalColor.AllowDrop = true; labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle; labelAdditionalColor.Location = new Point(102, 9); labelAdditionalColor.Name = "labelAdditionalColor"; @@ -286,9 +295,13 @@ labelAdditionalColor.TabIndex = 2; labelAdditionalColor.Text = "Доп. Цвет"; labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter; + labelAdditionalColor.Click += labelAdditionalColor_Click; + labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop; + labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter; // // labelBodyColor // + labelBodyColor.AllowDrop = true; labelBodyColor.BorderStyle = BorderStyle.FixedSingle; labelBodyColor.Location = new Point(3, 9); labelBodyColor.Name = "labelBodyColor"; @@ -296,17 +309,19 @@ labelBodyColor.TabIndex = 1; labelBodyColor.Text = "Цвет"; labelBodyColor.TextAlign = ContentAlignment.MiddleCenter; + labelBodyColor.DragDrop += labelBodyColor_DragDrop; + labelBodyColor.DragEnter += LabelBodyColor_DragEnter; // // FormTrackedVehicleConfig // AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(867, 212); - Controls.Add(panelObject1); + ClientSize = new Size(1168, 420); + Controls.Add(pictureBoxObject); Controls.Add(buttonCancel); Controls.Add(buttonAdd); - Controls.Add(pictureBoxObject); Controls.Add(groupBoxConfig); + Controls.Add(panelObject1); Name = "FormTrackedVehicleConfig"; Text = "Создание объекта"; Load += FormTrackedVehicleConfig_Load; diff --git a/solution/lab1/FormTrackedVehicleConfig.cs b/solution/lab1/FormTrackedVehicleConfig.cs index 4596a78..1e43b8d 100644 --- a/solution/lab1/FormTrackedVehicleConfig.cs +++ b/solution/lab1/FormTrackedVehicleConfig.cs @@ -1,4 +1,5 @@ using lab1.Drawnings; +using lab1.Entities; using System; using System.Collections.Generic; using System.ComponentModel; @@ -19,14 +20,18 @@ public partial class FormTrackedVehicleConfig : Form /// /// Объект - прорисовка гусеничной машины /// - private DrawningTrackedVehicle _trackedVehicle = null; + private DrawningTrackedVehicle? _trackedVehicle; + /// + /// Событие для предачи объекта + /// + private event TrackedVehicleDelegate? TrackedVehicleDelegate; /// /// Конструктор /// public FormTrackedVehicleConfig() { - + InitializeComponent(); panelRed.MouseDown += Panel_MouseDown; panelGreen.MouseDown += Panel_MouseDown; panelBlue.MouseDown += Panel_MouseDown; @@ -35,11 +40,15 @@ public partial class FormTrackedVehicleConfig : Form panelGray.MouseDown += Panel_MouseDown; panelBlack.MouseDown += Panel_MouseDown; panelPurple.MouseDown += Panel_MouseDown; - //TODO buttonCancel.Click with lambda с закрытием формы - buttonCancel.Click += (object sender, EventArgs e) => Close(); - InitializeComponent(); - + buttonCancel.Click += (sender, e) => Close(); } + /// + /// Привязка внешнего метода к событию + /// + /// + /// + + /// /// Прорисовка объекта @@ -78,12 +87,12 @@ public partial class FormTrackedVehicleConfig : Form /// /// /// - private void panelObject1_DragDrop(object sender, DragEventArgs e) + private void PanelObject1_DragDrop(object sender, DragEventArgs e) { switch (e.Data?.GetData(DataFormats.Text)?.ToString()) { - case "labelSimpleObject": + case "LabelSimpleObject": _trackedVehicle = new DrawningTrackedVehicle((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White); break; case "LabelModifiedObject": @@ -106,7 +115,7 @@ public partial class FormTrackedVehicleConfig : Form /// /// /// - private void Panel_MouseDown(object sender, MouseEventArgs e) + private void Panel_MouseDown(object? sender, MouseEventArgs e) { //TODO отправка цвета в Drag&Drop (sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy); @@ -123,4 +132,58 @@ public partial class FormTrackedVehicleConfig : Form e.Effect = DragDropEffects.None; } } + public void AddEvent(TrackedVehicleDelegate trainDelegate) + { + TrackedVehicleDelegate += trainDelegate; + } + + private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e) + { + if (_trackedVehicle.EntityTrackedVehicle is EntityFighter _rockets) + { + _rockets.setBodyTankColor((Color)e.Data.GetData(typeof(Color))); + } + DrawObject(); + + } + private void labelBodyColor_DragDrop(object sender, DragEventArgs e) + { + if (_trackedVehicle != null) + { + _trackedVehicle.EntityTrackedVehicle.setBodyColor((Color)e.Data.GetData(typeof(Color))); + DrawObject(); + } + } + private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e) + { + if (_trackedVehicle is DrawningEntityFighter) + { + if (e.Data.GetDataPresent(typeof(Color))) + { + e.Effect = DragDropEffects.Copy; + } + else + { + e.Effect = DragDropEffects.None; + } + } + } + /// + /// Передача объекта + /// + /// + /// + private void buttonAdd_Click(object sender, EventArgs e) + { + if (_trackedVehicle != null) + { + TrackedVehicleDelegate?.Invoke(_trackedVehicle); + Close(); + } + } + + private void labelAdditionalColor_Click(object sender, EventArgs e) + { + + } } diff --git a/solution/lab1/TrackedVehicleDelegate.cs b/solution/lab1/TrackedVehicleDelegate.cs new file mode 100644 index 0000000..3d7b0c4 --- /dev/null +++ b/solution/lab1/TrackedVehicleDelegate.cs @@ -0,0 +1,15 @@ +using lab1.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace lab1; +/// +/// Делегат передачи объекта класса-прорисовки +/// +/// + +public delegate void TrackedVehicleDelegate(DrawningTrackedVehicle trackedVehicle); +