8 лабораторная работа

This commit is contained in:
cleverman1337 2024-10-16 00:28:16 +03:00
parent 4851fb744c
commit f27e0bf714
13 changed files with 544 additions and 127 deletions

View File

@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
@ -56,7 +57,18 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTank tank) public static int operator +(AbstractCompany company, DrawningTank tank)
{ {
return company._collection.Insert(tank); try
{
return company._collection.Insert(tank, 0, new DrawningTankEqutables());
}
catch (ObjectAlreadyInCollectionException)
{
return -1;
}
catch (CollectionOverflowException)
{
return -1;
}
} }
/// <summary> /// <summary>
@ -87,26 +99,38 @@ public abstract class AbstractCompany
{ {
Bitmap bitmap = new(_pictureWidth, _pictureHeight); Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics); DrawBackground(graphics);
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningTank? obj = _collection?.Get(i); try
obj?.DrawTransport(graphics); {
DrawningTank? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
} }
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTank?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g); protected abstract void DrawBackground(Graphics g);
/// <summary> /// <summary>
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
} }

View File

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
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 override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -1,4 +1,5 @@
using System; using SelfPropelledArtilleryUnit.Drawnings;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -28,7 +29,8 @@ 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<DrawningTank?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
@ -36,7 +38,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<DrawningTank?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -62,4 +64,9 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Exceptions; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -51,17 +52,47 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T? obj) public int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); // TODO выброс ошибки, если переполнение
// TODO выброс ошибки, если такой объект есть в коллекции
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
_collection.Add(obj); _collection.Add(obj);
return Count - 1; return _collection.Count;
} }
public int Insert(T? obj, int position) public int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position < 0 || position > Count)
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); {
throw new PositionOutOfCollectionException(position);
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
@ -81,4 +112,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,4 +1,5 @@
using SelfPropelledArtilleryUnit.Exceptions; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -49,9 +50,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null)
{ {
for (int i = 0; i < _collection.Length; i++) for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@ -59,37 +68,51 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; return i;
} }
} }
throw new CollectionOverflowException(Count); ;
throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null)
{ {
if (position < 0 || position >= _collection.Length) throw new PositionOutOfCollectionException(position); // TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если такой объект есть в коллекции
// TODO выброс ошибки, если переполнение
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
else
{
for (int i = position + 1; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
for (int i = position - 1; i >= 0; i--) for (int i = position + 1; i < Count; i++)
{
if (_collection[i] == null)
{ {
if (_collection[i] == null) _collection[i] = obj;
{ return i;
_collection[i] = obj;
return i;
}
} }
} }
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
@ -113,4 +136,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -14,12 +14,12 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage"; private readonly string _collectionKey = "CollectionStorage";
@ -31,7 +31,7 @@ public class StorageCollection<T>
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@ -39,18 +39,21 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(CollectionInfo info)
{ {
if (string.IsNullOrEmpty(name)) return; if (info == null || _storages.ContainsKey(info))
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
if (collectionType == CollectionType.Massive)
{ {
_storages[name] = new MassiveGenericObjects<T>(); return;
} }
else if (collectionType == CollectionType.List)
if (info.CollectionType == CollectionType.Massive)
{ {
_storages[name] = new ListGenericObjects<T>(); _storages.Add(info, new MassiveGenericObjects<T>());
}
if (info.CollectionType == CollectionType.List)
{
_storages.Add(info, new ListGenericObjects<T>());
} }
} }
@ -58,12 +61,14 @@ public class StorageCollection<T>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(CollectionInfo info)
{ {
if (_storages.ContainsKey(name)) if (info == null || !_storages.ContainsKey(info))
{ {
_storages.Remove(name); return;
} }
_storages.Remove(info);
} }
/// <summary> /// <summary>
@ -71,23 +76,24 @@ 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 info]
{ {
get get
{ {
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(info))
{ {
return _storages[name]; return _storages[info];
} }
return null; return null;
} }
} }
public void SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения"); throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -96,21 +102,20 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); StringBuilder sb = new();
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); sb.Append(value.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -123,61 +128,72 @@ public class StorageCollection<T>
} }
writer.Write(sb); writer.Write(sb);
} }
} }
} }
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException("Файл не существует"); throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader reader = File.OpenText(filename))
using (StreamReader sr = new(filename))
{ {
string str = reader.ReadLine(); string line = sr.ReadLine();
if (str == null || str.Length == 0)
if (line == null || line.Length == 0)
{ {
throw new InvalidOperationException("В файле нет данных"); throw new FileFormatException("В файле нет данных");
} }
if (!str.StartsWith(_collectionKey)) if (!line.Equals(_collectionKey))
{ {
throw new InvalidOperationException("В файле не верные данные"); throw new FileFormatException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = "";
while ((strs = reader.ReadLine()) != null) while ((line = sr.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
if (collection == null) throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
{ ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new InvalidOperationException("Не удалось создать коллекцию"); throw new Exception("Не удалось создать коллекцию");
} collection.MaxCount = Convert.ToInt32(record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTank() is T tank) if (elem?.CreateDrawningTank() is T warship)
{ {
try try
{ {
if (collection.Insert(tank)==-1) if (collection.Insert(warship, new DrawningTankEqutables()) == -1)
{ {
throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[3]); throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
} }
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
throw new InvalidOperationException("Коллекция переполнена", ex); throw new OverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }

View File

@ -15,7 +15,7 @@ public class TankSharingService : AbstractCompany
{ {
} }
protected override void DrawBackgound(Graphics g) protected override void DrawBackground(Graphics g)
{ {
int width = _pictureWidth / _placeSizeWidth; int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight; int height = _pictureHeight / _placeSizeHeight;

View File

@ -0,0 +1,44 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawningTankCompareByColor : IComparer<DrawningTank?>
{
public int Compare(DrawningTank? x, DrawningTank? y)
{
// TODO прописать логику сравения по цветам, скорости, весу
if (x == null || x.EntityTank == null)
{
return 1;
}
if (y == null || y.EntityTank == null)
{
return -1;
}
var bodyColorCompare = y.EntityTank.BodyColor.Name.CompareTo(x.EntityTank.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x is DrawningArtillery && y is DrawningArtillery)
{
var additionalColorCompare = (y.EntityTank as EntityArtillery).AdditionalColor.Name.CompareTo(
(x.EntityTank as EntityArtillery).AdditionalColor.Name);
if (additionalColorCompare != 0)
{
return additionalColorCompare;
}
}
var speedCompare = y.EntityTank.Speed.CompareTo(x.EntityTank.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTank.Weight.CompareTo(x.EntityTank.Weight);
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawningTankCompareByType : IComparer<DrawningTank?>
{
public int Compare(DrawningTank? x, DrawningTank? y)
{
if (x == null || x.EntityTank == null)
{
return 1;
}
if (y == null || y.EntityTank == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return y.GetType().Name.CompareTo(x.GetType().Name);
}
var speedCompare = y.EntityTank.Speed.CompareTo(x.EntityTank.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTank.Weight.CompareTo(x.EntityTank.Weight);
}
}

View File

@ -0,0 +1,65 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawningTankEqutables : IEqualityComparer<DrawningTank?>
{
public bool Equals(DrawningTank? x, DrawningTank? y)
{
if (x == null || x.EntityTank == null)
{
return false;
}
if (y == null || y.EntityTank == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTank.Speed != y.EntityTank.Speed)
{
return false;
}
if (x.EntityTank.Weight != y.EntityTank.Weight)
{
return false;
}
if (x.EntityTank.BodyColor != y.EntityTank.BodyColor)
{
return false;
}
if (x is DrawningArtillery && y is DrawningArtillery)
{
// TODO доделать логику сравнения дополнительных параметров
if ((x.EntityTank as EntityArtillery)?.AdditionalColor !=
(y.EntityTank as EntityArtillery)?.AdditionalColor)
{
return false;
}
if ((x.EntityTank as EntityArtillery)?.Rocket !=
(y.EntityTank as EntityArtillery)?.Rocket)
{
return false;
}
if ((x.EntityTank as EntityArtillery)?.Cannon !=
(y.EntityTank as EntityArtillery)?.Cannon)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTank? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -30,8 +30,9 @@
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddTank = new Button(); buttonAddTank = new Button();
buttonAddArtillery = new Button();
buttonRefresh = new Button(); buttonRefresh = new Button();
maskedTextBoxPosition = new MaskedTextBox(); maskedTextBoxPosition = new MaskedTextBox();
buttonGoToCheak = new Button(); buttonGoToCheak = new Button();
@ -69,30 +70,53 @@
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(715, 24); groupBoxTools.Location = new Point(715, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 484); groupBoxTools.Size = new Size(200, 528);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTank); panelCompanyTools.Controls.Add(buttonAddTank);
panelCompanyTools.Controls.Add(buttonAddArtillery);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheak); panelCompanyTools.Controls.Add(buttonGoToCheak);
panelCompanyTools.Controls.Add(buttonRemoveTank); panelCompanyTools.Controls.Add(buttonRemoveTank);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 276); panelCompanyTools.Location = new Point(3, 297);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 205); panelCompanyTools.Size = new Size(194, 228);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(12, 196);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(170, 23);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(12, 165);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(170, 25);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddTank // buttonAddTank
// //
buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTank.Location = new Point(12, 9); buttonAddTank.Location = new Point(12, 0);
buttonAddTank.Name = "buttonAddTank"; buttonAddTank.Name = "buttonAddTank";
buttonAddTank.Size = new Size(170, 30); buttonAddTank.Size = new Size(170, 30);
buttonAddTank.TabIndex = 2; buttonAddTank.TabIndex = 2;
@ -100,20 +124,10 @@
buttonAddTank.UseVisualStyleBackColor = true; buttonAddTank.UseVisualStyleBackColor = true;
buttonAddTank.Click += ButtonAddTank_Click; buttonAddTank.Click += ButtonAddTank_Click;
// //
// buttonAddArtillery
//
buttonAddArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddArtillery.Location = new Point(12, 45);
buttonAddArtillery.Name = "buttonAddArtillery";
buttonAddArtillery.Size = new Size(170, 31);
buttonAddArtillery.TabIndex = 1;
buttonAddArtillery.Text = "Добавление сау";
buttonAddArtillery.UseVisualStyleBackColor = true;
//
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(12, 174); buttonRefresh.Location = new Point(12, 128);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(170, 23); buttonRefresh.Size = new Size(170, 23);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@ -123,7 +137,7 @@
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(12, 82); maskedTextBoxPosition.Location = new Point(12, 36);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(176, 23); maskedTextBoxPosition.Size = new Size(176, 23);
@ -133,7 +147,7 @@
// buttonGoToCheak // buttonGoToCheak
// //
buttonGoToCheak.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheak.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheak.Location = new Point(12, 143); buttonGoToCheak.Location = new Point(12, 97);
buttonGoToCheak.Name = "buttonGoToCheak"; buttonGoToCheak.Name = "buttonGoToCheak";
buttonGoToCheak.Size = new Size(170, 25); buttonGoToCheak.Size = new Size(170, 25);
buttonGoToCheak.TabIndex = 5; buttonGoToCheak.TabIndex = 5;
@ -144,7 +158,7 @@
// buttonRemoveTank // buttonRemoveTank
// //
buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTank.Location = new Point(12, 110); buttonRemoveTank.Location = new Point(12, 64);
buttonRemoveTank.Name = "buttonRemoveTank"; buttonRemoveTank.Name = "buttonRemoveTank";
buttonRemoveTank.Size = new Size(170, 27); buttonRemoveTank.Size = new Size(170, 27);
buttonRemoveTank.TabIndex = 4; buttonRemoveTank.TabIndex = 4;
@ -261,7 +275,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(715, 484); pictureBox.Size = new Size(715, 528);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
pictureBox.Click += pictureBox_Click; pictureBox.Click += pictureBox_Click;
@ -311,7 +325,7 @@
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(915, 508); ClientSize = new Size(915, 552);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -335,7 +349,6 @@
private GroupBox groupBoxTools; private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private Button buttonAddTank; private Button buttonAddTank;
private Button buttonAddArtillery;
private MaskedTextBox maskedTextBoxPosition; private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox; private PictureBox pictureBox;
private Button buttonRemoveTank; private Button buttonRemoveTank;
@ -357,5 +370,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -48,17 +48,22 @@ public partial class FormTankCollection : Form
/// <param name="tank"></param> /// <param name="tank"></param>
private void SetTank(DrawningTank? tank) private void SetTank(DrawningTank? tank)
{ {
try { try
if (_company == null || tank == null)
{ {
return; if (_company == null || tank == null)
} {
return;
}
if (_company + tank != -1) if (_company + tank != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + tank.GetDataForSave()); _logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
}
else
{
MessageBox.Show("Такой объект уже есть в коллекции");
} }
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
@ -66,7 +71,11 @@ public partial class FormTankCollection : Form
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);
} }
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
} }
/// <summary> /// <summary>
@ -156,12 +165,10 @@ public partial class FormTankCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: заполнены не все данные для добавления коллекции");
return; return;
} }
try try
{ {
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@ -171,8 +178,9 @@ public partial class FormTankCollection : Form
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(collectionInfo);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
} }
@ -186,7 +194,7 @@ public partial class FormTankCollection : 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]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -207,7 +215,8 @@ public partial class FormTankCollection : Form
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
} }
@ -225,7 +234,8 @@ public partial class FormTankCollection : Form
return; return;
} }
ICollectionGenericObjects<DrawningTank>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningTank>? collection = _storageCollection[collectionInfo];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
@ -249,15 +259,17 @@ public partial class FormTankCollection : Form
private void RefreshListBoxItems() private void RefreshListBoxItems()
{ {
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]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
} }
} }
} }
private void saveToolStripMenuItem_Click(object sender, EventArgs e) private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
@ -294,4 +306,38 @@ public partial class FormTankCollection : Form
} }
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTanks(new DrawningTankCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTanks(new DrawningTankCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareTanks(IComparer<DrawningTank?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }