LabWork08
This commit is contained in:
parent
ead2dcee19
commit
b6d4f83ae7
@ -55,7 +55,8 @@ public abstract class AbstractCompany
|
|||||||
public static int operator +(AbstractCompany company,
|
public static int operator +(AbstractCompany company,
|
||||||
DrawingWarship warship)
|
DrawingWarship warship)
|
||||||
{
|
{
|
||||||
return company._collection?.Insert(warship, new DrawiningWarshipEqutables()) ?? 0;
|
return company._collection?.Insert(warship, new DrawingWarshipEqutables()) ??
|
||||||
|
throw new DrawningEquitablesException();
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Перегрузка оператора удаления для класса
|
/// Перегрузка оператора удаления для класса
|
||||||
@ -81,7 +82,7 @@ public abstract class AbstractCompany
|
|||||||
/// Сортировка
|
/// Сортировка
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="comparer">Сравнитель объектов</param>
|
/// <param name="comparer">Сравнитель объектов</param>
|
||||||
public void Sort(IComparer<DrawningAircraft?> comparer) => _collection?.CollectionSort(comparer);
|
public void Sort(IComparer<DrawingWarship?> comparer) => _collection?.CollectionSort(comparer);
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Вывод всей коллекции
|
/// Вывод всей коллекции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
@ -0,0 +1,82 @@
|
|||||||
|
namespace ProjectBattleship.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 bool IsEmpty()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int GetHashCode()
|
||||||
|
{
|
||||||
|
return Name.GetHashCode();
|
||||||
|
}
|
||||||
|
}
|
@ -22,25 +22,23 @@ where T : class
|
|||||||
/// Добавление объекта в коллекцию
|
/// Добавление объекта в коллекцию
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj">Добавляемый объект</param>
|
/// <param name="obj">Добавляемый объект</param>
|
||||||
/// <param name="comparer">Сравнение двух объектов</param>
|
|
||||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||||
int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null);
|
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление объекта в коллекцию на конкретную позицию
|
/// Добавление объекта в коллекцию на конкретную позицию
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj">Добавляемый объект</param>
|
/// <param name="obj">Добавляемый объект</param>
|
||||||
/// <param name="position">Позиция</param>
|
/// <param name="position">Позиция</param>
|
||||||
/// <param name="comparer">Сравнение двух объектов</param>
|
|
||||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||||
int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null);
|
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Удаление объекта из коллекции с конкретной позиции
|
/// Удаление объекта из коллекции с конкретной позиции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="position">Позиция</param>
|
/// <param name="position">Позиция</param>
|
||||||
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
|
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
|
||||||
T? Remove(int position);
|
T Remove(int position);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получение объекта по позиции
|
/// Получение объекта по позиции
|
||||||
|
@ -3,7 +3,7 @@ using ProjectBattleship.DrawingObject;
|
|||||||
using ProjectBattleship.Exceptions;
|
using ProjectBattleship.Exceptions;
|
||||||
|
|
||||||
|
|
||||||
namespace Battleship.CollectionGenericObjects;
|
namespace ProjectBattleship.CollectionGenericObjects;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Параметризованный набор объектов
|
/// Параметризованный набор объектов
|
||||||
@ -53,10 +53,9 @@ where T : class
|
|||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null)
|
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||||
{
|
{
|
||||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
|
|
||||||
if (comparer != null)
|
if (comparer != null)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < Count; i++)
|
for (int i = 0; i < Count; i++)
|
||||||
@ -71,8 +70,7 @@ where T : class
|
|||||||
_collection.Add(obj);
|
_collection.Add(obj);
|
||||||
return Count;
|
return Count;
|
||||||
}
|
}
|
||||||
|
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||||
public int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null)
|
|
||||||
{
|
{
|
||||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||||
@ -88,7 +86,6 @@ where T : class
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
_collection.Insert(position, obj);
|
_collection.Insert(position, obj);
|
||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
@ -108,7 +105,6 @@ where T : class
|
|||||||
yield return _collection[i];
|
yield return _collection[i];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void CollectionSort(IComparer<T?> comparer)
|
public void CollectionSort(IComparer<T?> comparer)
|
||||||
{
|
{
|
||||||
_collection.Sort(comparer);
|
_collection.Sort(comparer);
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
using ProjectBattleship.CollectionGenericObjects;
|
using ProjectBattleship.CollectionGenericObjects;
|
||||||
using ProjectBattleship.DrawingObject;
|
using ProjectBattleship.DrawingObject;
|
||||||
|
|
||||||
namespace Battleship.CollectionGenericObjects;
|
namespace ProjectBattleship.CollectionGenericObjects;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Параметризованный набор объектов
|
/// Параметризованный набор объектов
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -61,7 +61,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
return _collection[position];
|
return _collection[position];
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null)
|
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||||
{
|
{
|
||||||
if (comparer != null)
|
if (comparer != null)
|
||||||
{
|
{
|
||||||
@ -74,6 +74,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// вставка в свободное место набора
|
// вставка в свободное место набора
|
||||||
for (int i = 0; i < Count; i++)
|
for (int i = 0; i < Count; i++)
|
||||||
{
|
{
|
||||||
@ -87,7 +88,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
throw new CollectionOverflowException(Count);
|
throw new CollectionOverflowException(Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null)
|
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||||
{
|
{
|
||||||
// проверка позиции
|
// проверка позиции
|
||||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||||
@ -135,14 +136,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// вставка
|
|
||||||
_collection[position] = obj;
|
_collection[position] = obj;
|
||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public T? Remove(int position)
|
public T? Remove(int position)
|
||||||
{
|
{
|
||||||
// проверка позиции
|
|
||||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||||
|
|
||||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||||
@ -151,6 +151,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
_collection[position] = null;
|
_collection[position] = null;
|
||||||
return temp;
|
return temp;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<T?> GetItems()
|
public IEnumerable<T?> GetItems()
|
||||||
{
|
{
|
||||||
for (int i = 0; i < _collection.Length; ++i)
|
for (int i = 0; i < _collection.Length; ++i)
|
||||||
@ -158,7 +159,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
|||||||
yield return _collection[i];
|
yield return _collection[i];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void CollectionSort(IComparer<T?> comparer)
|
public void CollectionSort(IComparer<T?> comparer)
|
||||||
{
|
{
|
||||||
List<T?> value = new List<T?>(_collection);
|
List<T?> value = new List<T?>(_collection);
|
||||||
|
@ -1,23 +1,20 @@
|
|||||||
using ProjectBattleship.CollectionGenericObjects;
|
using ProjectBattleship.Exceptions;
|
||||||
using ProjectBattleship.DrawingObject;
|
using ProjectBattleship.DrawingObject;
|
||||||
using ProjectBattleship.Exceptions;
|
using System.Text;
|
||||||
|
|
||||||
namespace Battleship.CollectionGenericObjects;
|
namespace ProjectBattleship.CollectionGenericObjects;
|
||||||
|
|
||||||
/// <summary>
|
public class StorageCollection<T>
|
||||||
/// Класс-хранилище коллекций
|
where T : DrawingWarship
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="T"></typeparam>
|
|
||||||
public class StorageCollection<T> where T : DrawingWarship
|
|
||||||
{
|
{
|
||||||
/// <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>
|
||||||
/// Ключевое слово, с которого должен начинаться файл
|
/// Ключевое слово, с которого должен начинаться файл
|
||||||
@ -39,166 +36,170 @@ public class StorageCollection<T> where T : DrawingWarship
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public StorageCollection()
|
public StorageCollection()
|
||||||
{
|
{
|
||||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление коллекции в хранилище
|
/// Добавление коллекции в хранилище
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="name">Название коллекции</param>
|
/// <param name="collectionInfo">тип коллекции</param>
|
||||||
/// <param name="collectionType">тип коллекции</param>
|
public void AddCollection(CollectionInfo collectionInfo)
|
||||||
public void AddCollection(string name, CollectionType collectionType)
|
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
|
if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo);
|
||||||
return;
|
if (collectionInfo.CollectionType == CollectionType.None)
|
||||||
switch (collectionType)
|
throw new CollectionTypeException("Пустой тип коллекции");
|
||||||
{
|
if (collectionInfo.CollectionType == CollectionType.Massive)
|
||||||
case CollectionType.List:
|
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||||
_storages.Add(name, new ListGenericObjects<T>());
|
else if (collectionInfo.CollectionType == CollectionType.List)
|
||||||
break;
|
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||||
case CollectionType.Massive:
|
|
||||||
_storages.Add(name, new MassiveGenericObjects<T>());
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Удаление коллекции
|
/// Удаление коллекции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="name">Название коллекции</param>
|
/// <param name="collectionInfo">тип коллекции</param>
|
||||||
public void DelCollection(string name)
|
public void DelCollection(CollectionInfo collectionInfo)
|
||||||
{
|
{
|
||||||
if (_storages.ContainsKey(name)) { _storages.Remove(name); }
|
if (_storages.ContainsKey(collectionInfo))
|
||||||
|
_storages.Remove(collectionInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Доступ к коллекции
|
/// Доступ к коллекции
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="name">Название коллекции</param>
|
/// <param name="collectionInfo"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public ICollectionGenericObjects<T>? this[string name]
|
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
|
||||||
{
|
{
|
||||||
get
|
get
|
||||||
{
|
{
|
||||||
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
|
if (_storages.ContainsKey(collectionInfo))
|
||||||
return value;
|
return _storages[collectionInfo];
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Сохранение информации по самолетам в хранилище в файл
|
/// Сохранение информации по самолетам в файл
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="filename">Путь и имя файла</param>
|
/// <param name="filename"></param>
|
||||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
/// <exception cref="EmptyFileExeption"></exception>
|
||||||
public void SaveData(string filename)
|
public void SaveData(string filename)
|
||||||
{
|
{
|
||||||
if (_storages.Count == 0)
|
if (_storages.Count == 0)
|
||||||
{
|
{
|
||||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
throw new EmptyFileException();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (File.Exists(filename))
|
if (File.Exists(filename))
|
||||||
{
|
{
|
||||||
File.Delete(filename);
|
File.Delete(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
using FileStream fs = new(filename, FileMode.Create);
|
using (StreamWriter writer = new StreamWriter(filename))
|
||||||
using StreamWriter streamWriter = new StreamWriter(fs);
|
|
||||||
streamWriter.Write(_collectionKey);
|
|
||||||
|
|
||||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
|
||||||
{
|
{
|
||||||
streamWriter.Write(Environment.NewLine);
|
writer.Write(_collectionKey);
|
||||||
|
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||||
if (value.Value.Count == 0)
|
|
||||||
{
|
{
|
||||||
continue;
|
StringBuilder sb = new();
|
||||||
}
|
sb.Append(Environment.NewLine);
|
||||||
|
if (value.Value.Count == 0)
|
||||||
streamWriter.Write(value.Key);
|
|
||||||
streamWriter.Write(_separatorForKeyValue);
|
|
||||||
streamWriter.Write(value.Value.GetCollectionType);
|
|
||||||
streamWriter.Write(_separatorForKeyValue);
|
|
||||||
streamWriter.Write(value.Value.MaxCount);
|
|
||||||
streamWriter.Write(_separatorForKeyValue);
|
|
||||||
|
|
||||||
|
|
||||||
foreach (T? item in value.Value.GetItems())
|
|
||||||
{
|
|
||||||
string data = item?.GetDataForSave() ?? string.Empty;
|
|
||||||
if (string.IsNullOrEmpty(data))
|
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sb.Append(value.Key);
|
||||||
|
sb.Append(_separatorForKeyValue);
|
||||||
|
sb.Append(value.Value.MaxCount);
|
||||||
|
sb.Append(_separatorForKeyValue);
|
||||||
|
foreach (T? item in value.Value.GetItems())
|
||||||
|
{
|
||||||
|
string data = item?.GetDataForSave() ?? string.Empty;
|
||||||
|
if (string.IsNullOrEmpty(data))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
streamWriter.Write(data);
|
sb.Append(data);
|
||||||
streamWriter.Write(_separatorItems);
|
sb.Append(_separatorItems);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.Write(sb);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Загрузка информации по кораблям в хранилище из файла
|
/// Загрузка информации по автомобилям в хранилище из файла
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="filename"></param>
|
/// <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 System.IO.FileNotFoundException("Файл не существует");
|
throw new Exceptions.FileNotFoundException(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
using (StreamReader sr = new StreamReader(filename))
|
using (StreamReader fs = File.OpenText(filename))
|
||||||
{
|
{
|
||||||
string? str;
|
string str = fs.ReadLine();
|
||||||
str = sr.ReadLine();
|
if (string.IsNullOrEmpty(str))
|
||||||
if (str != _collectionKey.ToString())
|
|
||||||
throw new FormatException("В файле неверные данные");
|
|
||||||
_storages.Clear();
|
|
||||||
while ((str = sr.ReadLine()) != null)
|
|
||||||
{
|
{
|
||||||
string[] record = str.Split(_separatorForKeyValue);
|
throw new EmptyFileException(filename);
|
||||||
if (record.Length != 4)
|
}
|
||||||
|
|
||||||
|
if (!str.StartsWith(_collectionKey))
|
||||||
|
{
|
||||||
|
throw new Exceptions.FileFormatException(filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
_storages.Clear();
|
||||||
|
string strs = "";
|
||||||
|
while ((strs = fs.ReadLine()) != null)
|
||||||
|
{
|
||||||
|
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
if (record.Length != 3)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
|
||||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
|
||||||
if (collection == null)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
CollectionInfo? collectionInfo =
|
||||||
|
CollectionInfo.GetCollectionInfo(record[0]) ??
|
||||||
|
throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]);
|
||||||
|
|
||||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
ICollectionGenericObjects<T>? collection =
|
||||||
|
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
|
||||||
|
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
|
||||||
|
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||||
|
|
||||||
|
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||||
foreach (string elem in set)
|
foreach (string elem in set)
|
||||||
{
|
{
|
||||||
if (elem?.CreateDrawingWarship() is T Warship)
|
if (elem?.CreateDrawingWarship() is T ship)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (collection.Insert(Warship) == -1)
|
collection.Insert(ship);
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (CollectionOverflowException ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
throw new Exceptions.FileFormatException(filename, ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_storages.Add(record[0], collection);
|
|
||||||
|
_storages.Add(collectionInfo, collection);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) => collectionType switch
|
private static ICollectionGenericObjects<T>?
|
||||||
|
CreateCollection(CollectionType collectionType)
|
||||||
{
|
{
|
||||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
return collectionType switch
|
||||||
CollectionType.List => new ListGenericObjects<T>(),
|
{
|
||||||
_ => null,
|
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||||
};
|
CollectionType.List => new ListGenericObjects<T>(),
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
@ -1,5 +1,5 @@
|
|||||||
using ProjectBattleship.DrawingObject;
|
using ProjectBattleship.DrawingObject;
|
||||||
namespace Battleship;
|
namespace ProjectBattleship;
|
||||||
|
|
||||||
public class DrawingWarshipCompareByColor : IComparer<DrawingWarship?>
|
public class DrawingWarshipCompareByColor : IComparer<DrawingWarship?>
|
||||||
{
|
{
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
using ProjectBattleship.DrawingObject;
|
using ProjectBattleship.DrawingObject;
|
||||||
namespace Battleship;
|
namespace ProjectBattleship;
|
||||||
|
|
||||||
public class DrawingWarshipCompareByType : IComparer<DrawingWarship?>
|
public class DrawingWarshipCompareByType : IComparer<DrawingWarship?>
|
||||||
{
|
{
|
||||||
|
@ -4,7 +4,7 @@ namespace ProjectBattleship.DrawingObject;
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Реализация сравнения двух объектов класса-прорисовки
|
/// Реализация сравнения двух объектов класса-прорисовки
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class DrawiningWarshipEqutables : IEqualityComparer<DrawingWarship?>
|
public class DrawingWarshipEqutables : IEqualityComparer<DrawingWarship?>
|
||||||
{
|
{
|
||||||
public bool Equals(DrawingWarship? x, DrawingWarship? y)
|
public bool Equals(DrawingWarship? x, DrawingWarship? y)
|
||||||
{
|
{
|
||||||
|
@ -1,9 +1,10 @@
|
|||||||
using System.Runtime.Serialization;
|
using System.Runtime.Serialization;
|
||||||
|
using ProjectBattleship.CollectionGenericObjects;
|
||||||
namespace ProjectBattleship.Exceptions;
|
namespace ProjectBattleship.Exceptions;
|
||||||
public class CollectionAlreadyExistsException : Exception
|
public class CollectionAlreadyExistsException : Exception
|
||||||
{
|
{
|
||||||
public CollectionAlreadyExistsException() : base() { }
|
public CollectionAlreadyExistsException() : base() { }
|
||||||
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { }
|
public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { }
|
||||||
public CollectionAlreadyExistsException(string name, Exception exception) :
|
public CollectionAlreadyExistsException(string name, Exception exception) :
|
||||||
base($"Коллекция {name} уже существует!", exception)
|
base($"Коллекция {name} уже существует!", exception)
|
||||||
{ }
|
{ }
|
||||||
|
@ -0,0 +1,14 @@
|
|||||||
|
using System.Runtime.Serialization;
|
||||||
|
namespace ProjectBattleship.Exceptions;
|
||||||
|
|
||||||
|
public class EmptyFileException : Exception
|
||||||
|
{
|
||||||
|
public EmptyFileException(string name) : base($"Файл {name} пустой ") { }
|
||||||
|
public EmptyFileException() : base("В хранилище отсутствуют коллекции для сохранения") { }
|
||||||
|
public EmptyFileException(string name, string message) : base(message) { }
|
||||||
|
public EmptyFileException(string name, string message, Exception exception) :
|
||||||
|
base(message, exception)
|
||||||
|
{ }
|
||||||
|
protected EmptyFileException(SerializationInfo info, StreamingContext
|
||||||
|
contex) : base(info, contex) { }
|
||||||
|
}
|
@ -1,14 +0,0 @@
|
|||||||
using System.Runtime.Serialization;
|
|
||||||
namespace ProjectBattleship.Exceptions;
|
|
||||||
|
|
||||||
public class EmptyFileExeption : Exception
|
|
||||||
{
|
|
||||||
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
|
|
||||||
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
|
|
||||||
public EmptyFileExeption(string name, string message) : base(message) { }
|
|
||||||
public EmptyFileExeption(string name, string message, Exception exception) :
|
|
||||||
base(message, exception)
|
|
||||||
{ }
|
|
||||||
protected EmptyFileExeption(SerializationInfo info, StreamingContext
|
|
||||||
contex) : base(info, contex) { }
|
|
||||||
}
|
|
@ -9,8 +9,8 @@ internal class PositionOutOfCollectionException : ApplicationException
|
|||||||
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
|
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
|
||||||
public PositionOutOfCollectionException() : base() { }
|
public PositionOutOfCollectionException() : base() { }
|
||||||
public PositionOutOfCollectionException(string message) : base(message) { }
|
public PositionOutOfCollectionException(string message) : base(message) { }
|
||||||
public PositionOutOfCollectionException(string message, Exception
|
public PositionOutOfCollectionException(string message, Exception
|
||||||
exception) : base(message, exception) { }
|
exception) : base(message, exception) { }
|
||||||
protected PositionOutOfCollectionException(SerializationInfo info,
|
protected PositionOutOfCollectionException(SerializationInfo info,
|
||||||
StreamingContext contex) : base(info, contex) { }
|
StreamingContext contex) : base(info, contex) { }
|
||||||
}
|
}
|
@ -32,6 +32,8 @@ namespace ProjectBattleship
|
|||||||
{
|
{
|
||||||
groupBoxCollectionTools = new GroupBox();
|
groupBoxCollectionTools = new GroupBox();
|
||||||
panelCompanyTools = new Panel();
|
panelCompanyTools = new Panel();
|
||||||
|
buttonSortByColor = new Button();
|
||||||
|
buttonSortByType = new Button();
|
||||||
buttonRefresh = new Button();
|
buttonRefresh = new Button();
|
||||||
maskedTextBoxPosition = new MaskedTextBox();
|
maskedTextBoxPosition = new MaskedTextBox();
|
||||||
buttonAddWarship = new Button();
|
buttonAddWarship = new Button();
|
||||||
@ -70,13 +72,15 @@ namespace ProjectBattleship
|
|||||||
groupBoxCollectionTools.Controls.Add(panelCollection);
|
groupBoxCollectionTools.Controls.Add(panelCollection);
|
||||||
groupBoxCollectionTools.Location = new Point(699, 27);
|
groupBoxCollectionTools.Location = new Point(699, 27);
|
||||||
groupBoxCollectionTools.Name = "groupBoxCollectionTools";
|
groupBoxCollectionTools.Name = "groupBoxCollectionTools";
|
||||||
groupBoxCollectionTools.Size = new Size(279, 653);
|
groupBoxCollectionTools.Size = new Size(279, 639);
|
||||||
groupBoxCollectionTools.TabIndex = 1;
|
groupBoxCollectionTools.TabIndex = 1;
|
||||||
groupBoxCollectionTools.TabStop = false;
|
groupBoxCollectionTools.TabStop = false;
|
||||||
groupBoxCollectionTools.Text = "Инструменты";
|
groupBoxCollectionTools.Text = "Инструменты";
|
||||||
//
|
//
|
||||||
// panelCompanyTools
|
// panelCompanyTools
|
||||||
//
|
//
|
||||||
|
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||||
|
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||||
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
|
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
|
||||||
panelCompanyTools.Controls.Add(buttonAddWarship);
|
panelCompanyTools.Controls.Add(buttonAddWarship);
|
||||||
@ -85,9 +89,29 @@ namespace ProjectBattleship
|
|||||||
panelCompanyTools.Enabled = false;
|
panelCompanyTools.Enabled = false;
|
||||||
panelCompanyTools.Location = new Point(6, 354);
|
panelCompanyTools.Location = new Point(6, 354);
|
||||||
panelCompanyTools.Name = "panelCompanyTools";
|
panelCompanyTools.Name = "panelCompanyTools";
|
||||||
panelCompanyTools.Size = new Size(267, 208);
|
panelCompanyTools.Size = new Size(267, 279);
|
||||||
panelCompanyTools.TabIndex = 11;
|
panelCompanyTools.TabIndex = 11;
|
||||||
//
|
//
|
||||||
|
// buttonSortByColor
|
||||||
|
//
|
||||||
|
buttonSortByColor.Location = new Point(8, 243);
|
||||||
|
buttonSortByColor.Name = "buttonSortByColor";
|
||||||
|
buttonSortByColor.Size = new Size(251, 34);
|
||||||
|
buttonSortByColor.TabIndex = 13;
|
||||||
|
buttonSortByColor.Text = "Сортировка по цвету";
|
||||||
|
buttonSortByColor.UseVisualStyleBackColor = true;
|
||||||
|
buttonSortByColor.Click += ButtonSortByColor_Click;
|
||||||
|
//
|
||||||
|
// buttonSortByType
|
||||||
|
//
|
||||||
|
buttonSortByType.Location = new Point(8, 203);
|
||||||
|
buttonSortByType.Name = "buttonSortByType";
|
||||||
|
buttonSortByType.Size = new Size(251, 34);
|
||||||
|
buttonSortByType.TabIndex = 12;
|
||||||
|
buttonSortByType.Text = "Сортировка по типу";
|
||||||
|
buttonSortByType.UseVisualStyleBackColor = true;
|
||||||
|
buttonSortByType.Click += ButtonSortByType_Click;
|
||||||
|
//
|
||||||
// buttonRefresh
|
// buttonRefresh
|
||||||
//
|
//
|
||||||
buttonRefresh.Location = new Point(8, 163);
|
buttonRefresh.Location = new Point(8, 163);
|
||||||
@ -244,7 +268,7 @@ namespace ProjectBattleship
|
|||||||
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
|
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
|
||||||
pictureBox.Location = new Point(0, 51);
|
pictureBox.Location = new Point(0, 51);
|
||||||
pictureBox.Name = "pictureBox";
|
pictureBox.Name = "pictureBox";
|
||||||
pictureBox.Size = new Size(688, 602);
|
pictureBox.Size = new Size(688, 615);
|
||||||
pictureBox.TabIndex = 2;
|
pictureBox.TabIndex = 2;
|
||||||
pictureBox.TabStop = false;
|
pictureBox.TabStop = false;
|
||||||
//
|
//
|
||||||
@ -293,7 +317,7 @@ namespace ProjectBattleship
|
|||||||
//
|
//
|
||||||
AutoScaleDimensions = new SizeF(10F, 25F);
|
AutoScaleDimensions = new SizeF(10F, 25F);
|
||||||
AutoScaleMode = AutoScaleMode.Font;
|
AutoScaleMode = AutoScaleMode.Font;
|
||||||
ClientSize = new Size(978, 653);
|
ClientSize = new Size(978, 666);
|
||||||
Controls.Add(groupBoxCollectionTools);
|
Controls.Add(groupBoxCollectionTools);
|
||||||
Controls.Add(pictureBox);
|
Controls.Add(pictureBox);
|
||||||
Controls.Add(menuStrip);
|
Controls.Add(menuStrip);
|
||||||
@ -337,5 +361,7 @@ namespace ProjectBattleship
|
|||||||
private ToolStripMenuItem loadToolStripMenuItem;
|
private ToolStripMenuItem loadToolStripMenuItem;
|
||||||
private SaveFileDialog saveFileDialog;
|
private SaveFileDialog saveFileDialog;
|
||||||
private OpenFileDialog openFileDialog;
|
private OpenFileDialog openFileDialog;
|
||||||
|
private Button buttonSortByType;
|
||||||
|
private Button buttonSortByColor;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,5 @@
|
|||||||
using Battleship.CollectionGenericObjects;
|
using ProjectBattleship.CollectionGenericObjects;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using ProjectBattleship.CollectionGenericObjects;
|
|
||||||
using ProjectBattleship.DrawingObject;
|
using ProjectBattleship.DrawingObject;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
|
||||||
@ -39,7 +38,13 @@ public partial class FormWarshipCollection : Form
|
|||||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender,
|
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender,
|
||||||
EventArgs e)
|
EventArgs e)
|
||||||
{
|
{
|
||||||
panelCompanyTools.Enabled = false;
|
switch (comboBoxSelectorCompany.Text)
|
||||||
|
{
|
||||||
|
case "Хранилище":
|
||||||
|
_company = new Docks(pictureBox.Width, pictureBox.Height,
|
||||||
|
new MassiveGenericObjects<DrawingWarship>());
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавление военного корабля
|
/// Добавление военного корабля
|
||||||
@ -240,7 +245,7 @@ public partial class FormWarshipCollection : Form
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
_storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "2"));
|
||||||
_logger.LogInformation("Добавление коллекции");
|
_logger.LogInformation("Добавление коллекции");
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
@ -270,7 +275,8 @@ public partial class FormWarshipCollection : Form
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
|
||||||
|
_storageCollection.DelCollection(collectionInfo!);
|
||||||
_logger.LogInformation("Коллекция удалена");
|
_logger.LogInformation("Коллекция удалена");
|
||||||
RerfreshListBoxItems();
|
RerfreshListBoxItems();
|
||||||
}
|
}
|
||||||
@ -283,10 +289,10 @@ public partial class FormWarshipCollection : 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? col = _storageCollection.Keys?[i];
|
||||||
if (!string.IsNullOrEmpty(colName))
|
if (!col!.IsEmpty())
|
||||||
{
|
{
|
||||||
listBoxCollection.Items.Add(colName);
|
listBoxCollection.Items.Add(col);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -303,9 +309,9 @@ public partial class FormWarshipCollection : Form
|
|||||||
MessageBox.Show("Коллекция не выбрана");
|
MessageBox.Show("Коллекция не выбрана");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ICollectionGenericObjects<DrawingWarship>? collection =
|
ICollectionGenericObjects<DrawingWarship>? collection = _storageCollection[
|
||||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
|
||||||
if (collection == null)
|
new CollectionInfo("", CollectionType.None, "")]; if (collection == null)
|
||||||
{
|
{
|
||||||
MessageBox.Show("Коллекция не проинициализирована");
|
MessageBox.Show("Коллекция не проинициализирована");
|
||||||
return;
|
return;
|
||||||
@ -366,4 +372,38 @@ public partial class FormWarshipCollection : Form
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Сортировка по типу
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="sender"></param>
|
||||||
|
/// <param name="e"></param>
|
||||||
|
private void ButtonSortByType_Click(object sender, EventArgs e)
|
||||||
|
{
|
||||||
|
CompareWarships(new DrawingWarshipCompareByType());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сортировка по цвету
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="sender"></param>
|
||||||
|
/// <param name="e"></param>
|
||||||
|
private void ButtonSortByColor_Click(object sender, EventArgs e)
|
||||||
|
{
|
||||||
|
CompareWarships(new DrawingWarshipCompareByColor());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сортировка по сравнителю
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="comparer">Сравнитель объектов</param>
|
||||||
|
private void CompareWarships(IComparer<DrawingWarship?> comparer)
|
||||||
|
{
|
||||||
|
if (_company == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_company.Sort(comparer);
|
||||||
|
pictureBox.Image = _company.Show();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -38,14 +38,7 @@ namespace ProjectBattleship
|
|||||||
/// <param name="WarshipDelegate"></param>
|
/// <param name="WarshipDelegate"></param>
|
||||||
public void AddEvent(Action<DrawingWarship> warshipDelegate)
|
public void AddEvent(Action<DrawingWarship> warshipDelegate)
|
||||||
{
|
{
|
||||||
if (WarshipDelegate != null)
|
WarshipDelegate += warshipDelegate;
|
||||||
{
|
|
||||||
WarshipDelegate = warshipDelegate;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
WarshipDelegate += warshipDelegate;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Прорисовка объекта
|
/// Прорисовка объекта
|
||||||
|
Loading…
x
Reference in New Issue
Block a user