Лабораторная работа№8

This commit is contained in:
nezui1 2024-05-20 21:23:21 +04:00
parent ed278533b7
commit fccfd0c91a
13 changed files with 520 additions and 150 deletions

View File

@ -37,7 +37,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, которые можно разместить в окне /// Вычисление максимального количества элементов, которые можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) + 1; private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight));
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -61,7 +61,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningWarPlane warPlane) public static int operator +(AbstractCompany company, DrawningWarPlane warPlane)
{ {
return company._collection.Insert(warPlane); return company._collection.Insert(warPlane, new DrawningWarPlaneEqtubles());
} }
/// <summary> /// <summary>
@ -75,6 +75,8 @@ public abstract class AbstractCompany
return company._collection.Remove(position); return company._collection.Remove(position);
} }
public void Sort(IComparer<DrawningWarPlane?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Получение случайного объекта из коллекции /// Получение случайного объекта из коллекции
/// </summary> /// </summary>

View File

@ -0,0 +1,91 @@
using ProjectAirFighter.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
///
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public bool IsEmpty()
{
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -1,5 +1,7 @@
using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawning;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -29,7 +31,7 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <param name="obj">Добавляемы объект</param> /// <param name="obj">Добавляемы объект</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась</returns> /// <returns>true - вставка прошла успешно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
@ -37,7 +39,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемы объект</param> /// <param name="obj">Добавляемы объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась</returns> /// <returns>true - вставка прошла успешно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -62,4 +64,7 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <returns>Поэлемениный вывод элементов коллекции</returns> /// <returns>Поэлемениный вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -1,6 +1,8 @@
using ProjectAirFighter.CollectionGenericObject; using Microsoft.VisualBasic.Devices;
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -63,20 +65,27 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj,IEqualityComparer<T?>? comparer = null)
{ {
//проверка, что не превышено максимальное количество элементов //проверка, что не превышено максимальное количество элементов
if(Count + 1 > _maxCount) if(Count + 1 > _maxCount)
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new EqualException(obj);
}
}
//вставка в конец набора //вставка в конец набора
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (Count + 1 > _maxCount) if (Count + 1 > _maxCount)
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
@ -84,6 +93,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new EqualException(obj);
}
}
//вставка по позиции //вставка по позиции
_collection.Insert(position,obj); _collection.Insert(position,obj);
return 1; return 1;
@ -106,4 +123,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -1,5 +1,6 @@
using ProjectAirFighter.CollectionGenericObject; using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawning;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -66,8 +67,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new EqualException(i);
}
}
}
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
@ -79,11 +90,23 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (position < 0 || position > Count) if (position < 0 || position > Count)
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new EqualException(i);
}
}
}
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@ -137,4 +160,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -1,4 +1,5 @@
using ProjectAirFighter.CollectionGenericObject; using Microsoft.AspNetCore.Http;
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Drawning; using ProjectAirFighter.Drawning;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
using System; using System;
@ -15,16 +16,18 @@ namespace ProjectAirFighter.CollectionGenericObjects;
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : DrawningWarPlane where T : DrawningWarPlane
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
private Dictionary<string, ICollectionGenericObjects<T>> _storages; private Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -43,7 +46,7 @@ public class StorageCollection<T>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@ -53,33 +56,28 @@ public class StorageCollection<T>
/// <param name="collectionType"></param> /// <param name="collectionType"></param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (name == null || _storages.ContainsKey(name)) CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if ( _storages.ContainsKey(collectionInfo))
{ {
return; return;
} }
switch(collectionType) if (collectionType == CollectionType.None) return;
{ else if (collectionType == CollectionType.Massive)
case CollectionType.None: _storages[collectionInfo] = new MassiveGenericObjects<T>();
return; else if (collectionType == CollectionType.List)
case CollectionType.Massive: _storages[collectionInfo] = new ListGenericObjects<T>();
_storages[name] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
return;
}
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name"></param> /// <param name="name"></param>
public void DelCollection(string name) public void DelCollection(CollectionInfo collectionInfo)
{ {
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(collectionInfo))
{ _storages.Remove(collectionInfo);
_storages.Remove(name);
}
} }
/// <summary> /// <summary>
@ -87,15 +85,15 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="name"></param> /// <param name="name"></param>
/// <returns></returns> /// <returns></returns>
public ICollectionGenericObjects<T> this[string name] public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
{ {
get get
{ {
//логика получения объекта //логика получения объекта
if(name == null || !_storages.ContainsKey(name)) if(_storages.ContainsKey(collectionInfo))
return null; return _storages[collectionInfo];
return _storages[name]; return null;
} }
} }
@ -104,42 +102,44 @@ public class StorageCollection<T>
public void SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
throw new Exception("В хранилище отсутсвуют коллекции для сохранения");
if (File.Exists(filename))
File.Delete(filename);
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
sw.Write(Environment.NewLine); throw new Exception("В хранилище отсутствуют коллекции для сохранения");
if (value.Value.Count == 0)
{
continue;
}
sw.Write(value.Key); }
sw.Write(_separatorForKeyValue); if (File.Exists(filename))
sw.Write(value.Value.GetCollectionType); {
sw.Write(_separatorForKeyValue); File.Delete(filename);
sw.Write(value.Value.MaxCount); }
sw.Write(_separatorForKeyValue); using (StreamWriter writer = new(filename))
{
foreach (T? item in value.Value.GetItems()) writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
string data = item?.GetDataForSave() ?? string.Empty; writer.Write(Environment.NewLine);
if (string.IsNullOrEmpty(data))
if (value.Value.Count == 0)
{ {
continue; continue;
} }
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
sw.Write(data); foreach (T? item in value.Value.GetItems())
sw.Write(_separatorItems); {
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
} }
} }
} }
/// <summary> /// <summary>
/// Загрузка информации по самолетам в хранилище из файла /// Загрузка информации по самолетам в хранилище из файла
@ -150,65 +150,60 @@ public class StorageCollection<T>
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не существует"); throw new FileNotFoundException($"{filename} не существует");
} }
using (StreamReader reader = File.OpenText(filename))
using (FileStream fs = new(filename, FileMode.Open))
{ {
using StreamReader sr = new StreamReader(fs); string line = reader.ReadLine();
if (line == null || line.Length == 0)
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{ {
throw new Exception("В файле нет данных"); throw new IOException("Файл не подходит");
} }
if (!line.Equals(_collectionKey))
if (!str.Equals(_collectionKey))
{ {
throw new Exception("В файле неверные данные");
throw new IOException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = "";
while (!sr.EndOfStream) while ((strs = reader.ReadLine()) != null)
{ {
string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? collectionInfo =
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); CollectionInfo.GetCollectionInfo(record[0]) ??
if (collection == null) throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]); ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningWarPlane() is T warPlane) if (elem?.CreateDrawningWarPlane() is T warPlane)
{ {
try try
{ {
if (collection.Insert(warPlane) == -1) collection.Insert(warPlane);
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
} }
catch(CollectionOverflowException ex) catch (Exception ex)
{ {
throw new Exception("Коллекция переполнена", ex); throw new FileFormatException(filename, ex);
} }
} }
} }
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
} }
} }
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public class DrawningCompareByColor : IComparer<DrawningWarPlane?>
{
public int Compare(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityWarPlane == null)
{
return 1;
}
if (y == null || y.EntityWarPlane == null)
{
return -1;
}
if (ToHex(x.EntityWarPlane.BodyColor) != ToHex(y.EntityWarPlane.BodyColor))
{
return String.Compare(ToHex(x.EntityWarPlane.BodyColor), ToHex(y.EntityWarPlane.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityWarPlane.Speed.CompareTo(y.EntityWarPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarPlane.Weight.CompareTo(y.EntityWarPlane.Weight);
}
static String ToHex(Color c)
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public class DrawningCompareByType : IComparer<DrawningWarPlane?>
{
public int Compare(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null || x.EntityWarPlane == null)
{
return -1;
}
if (y == null || y.EntityWarPlane == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityWarPlane.Speed.CompareTo(y.EntityWarPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarPlane.Weight.CompareTo(y.EntityWarPlane.Weight);
}
}

View File

@ -0,0 +1,65 @@
using ProjectAirFighter.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public class DrawningWarPlaneEqtubles : IEqualityComparer<DrawningWarPlane?>
{
public bool Equals(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarPlane != null && y.EntityWarPlane != null && x.EntityWarPlane.Speed != y.EntityWarPlane.Speed)
{
return false;
}
if (x.EntityWarPlane.Weight != y.EntityWarPlane.Weight)
{
return false;
}
if (x.EntityWarPlane.BodyColor != y.EntityWarPlane.BodyColor)
{
return false;
}
if (x is DrawningAirFighter && y is DrawningAirFighter)
{
if (((EntityAirFighter)x.EntityWarPlane).AdditionalColor !=
((EntityAirFighter)y.EntityWarPlane).AdditionalColor)
{
return false;
}
if (((EntityAirFighter)x.EntityWarPlane).Rocket !=
((EntityAirFighter)y.EntityWarPlane).Rocket)
{
return false;
}
if (((EntityAirFighter)x.EntityWarPlane).AdditionalWing !=
((EntityAirFighter)y.EntityWarPlane).AdditionalWing)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningWarPlane? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
internal class EqualException : ApplicationException
{
public EqualException(object i) : base("В коллекции уже есть такой элемент " + i) { }
public EqualException() : base() { }
public EqualException(string message) : base(message) { }
public EqualException(string message, Exception exception) : base(message, exception)
{ }
protected EqualException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBox1.SuspendLayout(); groupBox1.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -61,6 +63,8 @@
// //
// groupBox1 // groupBox1
// //
groupBox1.Controls.Add(buttonSortByType);
groupBox1.Controls.Add(buttonSortByColor);
groupBox1.Controls.Add(panelCompanyTools); groupBox1.Controls.Add(panelCompanyTools);
groupBox1.Controls.Add(buttonCreateCompany); groupBox1.Controls.Add(buttonCreateCompany);
groupBox1.Controls.Add(panelStorage); groupBox1.Controls.Add(panelStorage);
@ -68,7 +72,7 @@
groupBox1.Dock = DockStyle.Right; groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(659, 24); groupBox1.Location = new Point(659, 24);
groupBox1.Name = "groupBox1"; groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(174, 658); groupBox1.Size = new Size(174, 739);
groupBox1.TabIndex = 0; groupBox1.TabIndex = 0;
groupBox1.TabStop = false; groupBox1.TabStop = false;
groupBox1.Text = "Инструменты"; groupBox1.Text = "Инструменты";
@ -83,14 +87,14 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 373); panelCompanyTools.Location = new Point(0, 373);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(174, 278); panelCompanyTools.Size = new Size(174, 262);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonRemove // buttonRemove
// //
buttonRemove.Location = new Point(6, 145); buttonRemove.Location = new Point(6, 121);
buttonRemove.Name = "buttonRemove"; buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(162, 44); buttonRemove.Size = new Size(162, 48);
buttonRemove.TabIndex = 4; buttonRemove.TabIndex = 4;
buttonRemove.Text = "Удалить самолет"; buttonRemove.Text = "Удалить самолет";
buttonRemove.UseVisualStyleBackColor = true; buttonRemove.UseVisualStyleBackColor = true;
@ -98,9 +102,9 @@
// //
// buttonAddWarPlane // buttonAddWarPlane
// //
buttonAddWarPlane.Location = new Point(6, 27); buttonAddWarPlane.Location = new Point(6, 3);
buttonAddWarPlane.Name = "buttonAddWarPlane"; buttonAddWarPlane.Name = "buttonAddWarPlane";
buttonAddWarPlane.Size = new Size(162, 52); buttonAddWarPlane.Size = new Size(162, 56);
buttonAddWarPlane.TabIndex = 1; buttonAddWarPlane.TabIndex = 1;
buttonAddWarPlane.Text = "Добавление военного самолета"; buttonAddWarPlane.Text = "Добавление военного самолета";
buttonAddWarPlane.UseVisualStyleBackColor = true; buttonAddWarPlane.UseVisualStyleBackColor = true;
@ -108,9 +112,9 @@
// //
// button1 // button1
// //
button1.Location = new Point(6, 245); button1.Location = new Point(6, 221);
button1.Name = "button1"; button1.Name = "button1";
button1.Size = new Size(162, 30); button1.Size = new Size(162, 34);
button1.TabIndex = 6; button1.TabIndex = 6;
button1.Text = "Обновить"; button1.Text = "Обновить";
button1.UseVisualStyleBackColor = true; button1.UseVisualStyleBackColor = true;
@ -118,7 +122,7 @@
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(8, 111); maskedTextBoxPosition.Location = new Point(8, 87);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(162, 23); maskedTextBoxPosition.Size = new Size(162, 23);
@ -127,9 +131,9 @@
// //
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Location = new Point(6, 195); buttonGoToCheck.Location = new Point(6, 171);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(162, 44); buttonGoToCheck.Size = new Size(162, 48);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тест"; buttonGoToCheck.Text = "Передать на тест";
buttonGoToCheck.UseVisualStyleBackColor = true; buttonGoToCheck.UseVisualStyleBackColor = true;
@ -244,7 +248,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(659, 658); pictureBox.Size = new Size(659, 739);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -288,11 +292,31 @@
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByType
//
buttonSortByType.Location = new Point(8, 644);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(162, 35);
buttonSortByType.TabIndex = 10;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(8, 685);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(160, 42);
buttonSortByColor.TabIndex = 11;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormWarPlaneCollection // FormWarPlaneCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(833, 682); ClientSize = new Size(833, 763);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBox1); Controls.Add(groupBox1);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -337,5 +361,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
} }
} }

View File

@ -3,6 +3,7 @@ using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.CollectionGenericObjects; using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawning; using ProjectAirFighter.Drawning;
using ProjectAirFighter.Exceptions; using ProjectAirFighter.Exceptions;
using System.Runtime.Intrinsics.Arm;
namespace ProjectAirFighter; namespace ProjectAirFighter;
@ -61,13 +62,18 @@ public partial class FormWarPlaneCollection : Form
return; return;
} }
try { try
{
if (_company + warPlane != -1) if (_company + warPlane != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен: " + warPlane.GetDataForSave()); _logger.LogInformation("Объект добавлен: " + warPlane.GetDataForSave());
} }
else
{
MessageBox.Show("Не удалось добавить объект");
}
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
@ -99,7 +105,8 @@ public partial class FormWarPlaneCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try { try
{
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
@ -107,12 +114,13 @@ public partial class FormWarPlaneCollection : Form
_logger.LogInformation("Объект удален на позиции: " + pos); _logger.LogInformation("Объект удален на позиции: " + pos);
} }
} }
catch(ObjectNotFoundException ex) catch (ObjectNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
catch(PositionOutOfCollectionException ex) { catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
@ -131,7 +139,8 @@ public partial class FormWarPlaneCollection : Form
int counter = 100; int counter = 100;
while (warPlane == null) while (warPlane == null)
{ {
try { try
{
warPlane = _company.GetRandomObject(); warPlane = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
@ -186,25 +195,26 @@ public partial class FormWarPlaneCollection : Form
return; return;
} }
try { try
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{ {
collectionType = CollectionType.Massive; CollectionType collectionType = CollectionType.None;
} if (radioButtonMassive.Checked)
else if (radioButtonList.Checked) {
{ collectionType = CollectionType.Massive;
collectionType = CollectionType.List; }
} else if (radioButtonList.Checked)
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); {
RerfreshListBoxItems(); collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text); _logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("Ошибка: {Massege}", ex.Message); _logger.LogError("Ошибка: {Massege}", ex.Message);
} }
} }
/// <summary> /// <summary>
/// Обновление списка в listBoxCollection /// Обновление списка в listBoxCollection
/// </summary> /// </summary>
@ -213,8 +223,8 @@ public partial class FormWarPlaneCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; CollectionInfo? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName)) if (!colName!.IsEmpty())
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
} }
@ -233,16 +243,18 @@ public partial class FormWarPlaneCollection : Form
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try { try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
RerfreshListBoxItems(); _storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
} }
catch(Exception ex) { catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -259,24 +271,31 @@ public partial class FormWarPlaneCollection : Form
return; return;
} }
ICollectionGenericObjects<DrawningWarPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; ICollectionGenericObjects<DrawningWarPlane>? collection = _storageCollection[
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "")];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} }
try
switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": switch (comboBoxSelectorCompany.Text)
_company = new WarPlaneBase(pictureBox.Width, {
pictureBox.Height, collection); case "Хранилище":
break; _company = new WarPlaneBase(pictureBox.Width, pictureBox.Height, collection);
break;
}
}
catch (ObjectNotFoundException)
{
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
/// <summary> /// <summary>
@ -294,7 +313,8 @@ public partial class FormWarPlaneCollection : Form
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filname}", saveFileDialog.FileName); _logger.LogInformation("Сохранение в файл: {filname}", saveFileDialog.FileName);
} }
catch(Exception ex) { catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
@ -329,6 +349,27 @@ public partial class FormWarPlaneCollection : Form
} }
} }
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareWarPlanes(new DrawningCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareWarPlanes(new DrawningCompareByColor());
}
private void CompareWarPlanes(IComparer<DrawningWarPlane?> comparer)
{
if(_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }

View File

@ -126,4 +126,7 @@
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value> <value>261, 17</value>
</metadata> </metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>46</value>
</metadata>
</root> </root>