Дабораторная работа №7
This commit is contained in:
parent
ce84c8d6be
commit
128a639927
@ -62,7 +62,7 @@ public abstract class AbstractCompany
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawingShip ship)
|
||||
{
|
||||
return company._collection.Insert(ship);
|
||||
return company._collection.Insert(ship, new DrawingShipEqutables());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -111,4 +111,5 @@ public abstract class AbstractCompany
|
||||
protected abstract void SetObjectsPosition();
|
||||
|
||||
protected abstract void DrawBackground(Graphics g);
|
||||
public void Sort(IComparer<DrawingShip?> comparer) => _collection?.CollectionSort(comparer);
|
||||
}
|
||||
|
75
Cruiser/Cruiser/CollectionGenericObjects/CollectionInfo.cs
Normal file
75
Cruiser/Cruiser/CollectionGenericObjects/CollectionInfo.cs
Normal file
@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Cruiser.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();
|
||||
}
|
||||
}
|
@ -8,7 +8,7 @@ namespace Cruiser.CollectionGenericObjects;
|
||||
|
||||
public enum CollectionType
|
||||
{
|
||||
None = 1,
|
||||
None = 0,
|
||||
Massive = 1,
|
||||
List = 2
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Cruiser.Drawings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -24,7 +25,7 @@ public interface ICollectionGenericObjects<T>
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <returns></returns>
|
||||
int Insert(T obj);
|
||||
int Insert(T obj, IEqualityComparer<T?>? comarer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Добавление в коллекцию по индексу
|
||||
@ -32,7 +33,7 @@ public interface ICollectionGenericObjects<T>
|
||||
/// <param name="obj"></param>
|
||||
/// <param name="position"></param>
|
||||
/// <returns></returns>
|
||||
int Insert(T obj, int position);
|
||||
int Insert(T obj, int position, IEqualityComparer<T?>? comarer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Удаление из коллекции по индесу
|
||||
@ -58,4 +59,6 @@ public interface ICollectionGenericObjects<T>
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
}
|
||||
|
@ -1,8 +1,10 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Cruiser.Drawings;
|
||||
using Cruiser.Exceptions;
|
||||
namespace Cruiser.CollectionGenericObjects;
|
||||
|
||||
@ -53,17 +55,31 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException();
|
||||
if (comparer != null)
|
||||
{
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(obj);
|
||||
}
|
||||
}
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException();
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||
if (comparer != null)
|
||||
{
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(obj);
|
||||
}
|
||||
}
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
@ -83,4 +99,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
_collection.Sort(comparer);
|
||||
}
|
||||
}
|
||||
|
@ -51,9 +51,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; i++)
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? i in _collection)
|
||||
{
|
||||
if (comparer.Equals(i, obj))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
@ -64,9 +74,21 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
throw new CollectionOverflowException();
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
|
||||
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? i in _collection)
|
||||
{
|
||||
if (comparer.Equals(i, obj))
|
||||
{
|
||||
throw new ObjectAlreadyExistsException(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
@ -111,6 +133,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
Array.Sort(_collection, comparer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -14,12 +14,12 @@ public class StorageCollection<T> where T : DrawingShip
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> Keys => _storages.Keys.ToList();
|
||||
public List<CollectionInfo> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
@ -29,7 +29,7 @@ public class StorageCollection<T> where T : DrawingShip
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
private readonly string _separatorKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
@ -41,7 +41,7 @@ public class StorageCollection<T> where T : DrawingShip
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
|
||||
|
||||
@ -54,43 +54,47 @@ public class StorageCollection<T> where T : DrawingShip
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
StringBuilder sb = new();
|
||||
sb.Append(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in
|
||||
_storages)
|
||||
|
||||
|
||||
using (StreamWriter writer = new(filename))
|
||||
{
|
||||
sb.Append(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.GetCollectionType);
|
||||
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))
|
||||
writer.Write(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
|
||||
writer.Write(value.Key);
|
||||
writer.Write(_separatorKeyValue);
|
||||
|
||||
writer.Write(value.Value.MaxCount);
|
||||
writer.Write(_separatorKeyValue);
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
writer.Write(data);
|
||||
writer.Write(_separatorItems);
|
||||
}
|
||||
}
|
||||
writer.Close();
|
||||
|
||||
}
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
|
||||
fs.Write(info, 0, info.Length);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -102,68 +106,66 @@ public class StorageCollection<T> where T : DrawingShip
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
string bufferTextFromFile = "";
|
||||
using (FileStream fs = new(filename, FileMode.Open))
|
||||
{
|
||||
byte[] b = new byte[fs.Length];
|
||||
UTF8Encoding temp = new(true);
|
||||
while (fs.Read(b, 0, b.Length) > 0)
|
||||
{
|
||||
bufferTextFromFile += temp.GetString(b);
|
||||
}
|
||||
}
|
||||
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
{
|
||||
throw new Exception("В файле нет данных");
|
||||
}
|
||||
if (!strs[0].Equals(_collectionKey))
|
||||
{
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
foreach (string data in strs)
|
||||
{
|
||||
string[] record = data.Split(_separatorForKeyValue,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
CollectionType collectionType =
|
||||
(CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection =
|
||||
StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawingShip() is T ship)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(ship) == -1)
|
||||
{
|
||||
throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new DataException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
throw new FileNotFoundException("Файл не существует!");
|
||||
}
|
||||
|
||||
using (StreamReader reader = new(filename))
|
||||
{
|
||||
string line = reader.ReadLine();
|
||||
if (line == null || line.Length == 0)
|
||||
{
|
||||
throw new ArgumentException("В файле нет данных");
|
||||
}
|
||||
if (!line.Equals(_collectionKey))
|
||||
{
|
||||
throw new InvalidDataException("В файле неверные данные");
|
||||
}
|
||||
|
||||
_storages.Clear();
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
string[] record = line.Split(_separatorKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
|
||||
throw new Exception("Не удалось определить информацию о коллекции:" + record[0]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new Exception("Не удалось создать коллекцию");
|
||||
if (collection == null)
|
||||
{
|
||||
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
|
||||
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||
|
||||
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawingShip() is T ship)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(ship) < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
_storages.Add(collectionInfo, collection);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -188,19 +190,23 @@ public class StorageCollection<T> where T : DrawingShip
|
||||
/// <param name="collectionType">Тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (_storages.ContainsKey(name))// || collectionType == CollectionType.None)
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
|
||||
|
||||
if (name == null || _storages.ContainsKey(collectionInfo))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch (collectionType)
|
||||
{
|
||||
case CollectionType.None:
|
||||
return;
|
||||
case CollectionType.Massive:
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
break;
|
||||
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||
return;
|
||||
case CollectionType.List:
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
break;
|
||||
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@ -210,9 +216,10 @@ public class StorageCollection<T> where T : DrawingShip
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
if (_storages.ContainsKey(name) && name != null)
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
{
|
||||
_storages.Remove(name);
|
||||
_storages.Remove(collectionInfo);
|
||||
}
|
||||
}
|
||||
|
||||
@ -225,11 +232,12 @@ public class StorageCollection<T> where T : DrawingShip
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_storages.ContainsKey(name))
|
||||
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
|
||||
if (!_storages.ContainsKey(collectionInfo))
|
||||
{
|
||||
return _storages[name];
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
return _storages[collectionInfo];
|
||||
}
|
||||
}
|
||||
}
|
34
Cruiser/Cruiser/Drawings/DrawingShipCompareByColor.cs
Normal file
34
Cruiser/Cruiser/Drawings/DrawingShipCompareByColor.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Cruiser.Drawings;
|
||||
|
||||
public class DrawingShipCompareByColor : IComparer<DrawingShip?>
|
||||
{
|
||||
public int Compare(DrawingShip? x, DrawingShip? y)
|
||||
{
|
||||
if (x == null || x.EntityShip == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityShip == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
|
||||
if (bodycolorCompare != 0)
|
||||
{
|
||||
return bodycolorCompare;
|
||||
}
|
||||
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
|
||||
}
|
||||
}
|
33
Cruiser/Cruiser/Drawings/DrawingShipCompareByType.cs
Normal file
33
Cruiser/Cruiser/Drawings/DrawingShipCompareByType.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Cruiser.Drawings;
|
||||
|
||||
namespace Cruiser.CollectionGenericObjects;
|
||||
|
||||
public class DrawingShipCompareByType : IComparer<DrawingShip?>
|
||||
{
|
||||
public int Compare(DrawingShip? x, DrawingShip? y)
|
||||
{
|
||||
if (x == null || x.EntityShip == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if (y == null || y.EntityShip == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
|
||||
}
|
||||
}
|
56
Cruiser/Cruiser/Drawings/DrawingShipEqutables.cs
Normal file
56
Cruiser/Cruiser/Drawings/DrawingShipEqutables.cs
Normal file
@ -0,0 +1,56 @@
|
||||
using Cruiser.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography.Xml;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Cruiser.Drawings;
|
||||
|
||||
public class DrawingShipEqutables : IEqualityComparer<DrawingShip?>
|
||||
{
|
||||
public bool Equals(DrawingShip? x, DrawingShip? y)
|
||||
{
|
||||
if (x == null || x.EntityShip == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (y == null || y.EntityShip == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityShip.Speed != y.EntityShip.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityShip.Weight != y.EntityShip.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x is DrawingCruiser && y is DrawingCruiser)
|
||||
{
|
||||
EntityCruiser crx = (EntityCruiser)x.EntityShip;
|
||||
EntityCruiser cry = (EntityCruiser)y.EntityShip;
|
||||
if (crx.Helicopter != cry.Helicopter) return false;
|
||||
if (crx.BodyKit != cry.BodyKit) return false;
|
||||
if (crx.Arms != cry.Arms) return false;
|
||||
if (crx.AdditionalColor != cry.AdditionalColor) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetHashCode([DisallowNull] DrawingShip obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
19
Cruiser/Cruiser/Exceptions/ObjectAlreadyExistsException.cs
Normal file
19
Cruiser/Cruiser/Exceptions/ObjectAlreadyExistsException.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Cruiser.Exceptions;
|
||||
|
||||
[Serializable]
|
||||
public class ObjectAlreadyExistsException : ApplicationException
|
||||
{
|
||||
public ObjectAlreadyExistsException(object i) : base("В коллекции уже есть такой элемент " + i) { }
|
||||
public ObjectAlreadyExistsException() : base() { }
|
||||
public ObjectAlreadyExistsException(string message) : base(message) { }
|
||||
public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception)
|
||||
{ }
|
||||
protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
39
Cruiser/Cruiser/FormShipCollection.Designer.cs
generated
39
Cruiser/Cruiser/FormShipCollection.Designer.cs
generated
@ -52,6 +52,8 @@
|
||||
LoadToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
buttonSortByColor = new Button();
|
||||
buttonSortByType = new Button();
|
||||
groupBoxTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelStorage.SuspendLayout();
|
||||
@ -68,7 +70,7 @@
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(852, 28);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(324, 742);
|
||||
groupBoxTools.Size = new Size(324, 841);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
@ -97,15 +99,17 @@
|
||||
//
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
||||
panelCompanyTools.Controls.Add(buttonAddShip);
|
||||
panelCompanyTools.Controls.Add(buttonRemoveShip);
|
||||
panelCompanyTools.Controls.Add(maskedTextBox);
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Location = new Point(12, 446);
|
||||
panelCompanyTools.Location = new Point(12, 415);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(300, 300);
|
||||
panelCompanyTools.Size = new Size(300, 414);
|
||||
panelCompanyTools.TabIndex = 2;
|
||||
//
|
||||
// buttonRefresh
|
||||
@ -248,7 +252,7 @@
|
||||
pictureBoxCollection.Dock = DockStyle.Fill;
|
||||
pictureBoxCollection.Location = new Point(0, 28);
|
||||
pictureBoxCollection.Name = "pictureBoxCollection";
|
||||
pictureBoxCollection.Size = new Size(852, 742);
|
||||
pictureBoxCollection.Size = new Size(852, 841);
|
||||
pictureBoxCollection.TabIndex = 1;
|
||||
pictureBoxCollection.TabStop = false;
|
||||
//
|
||||
@ -288,17 +292,38 @@
|
||||
// saveFileDialog
|
||||
//
|
||||
saveFileDialog.Filter = "txt file | *.txt";
|
||||
|
||||
//
|
||||
// openFileDialog
|
||||
//
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByColor.Location = new Point(19, 335);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(240, 52);
|
||||
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(19, 277);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(240, 52);
|
||||
buttonSortByType.TabIndex = 7;
|
||||
buttonSortByType.Text = "Сортировка по типу";
|
||||
buttonSortByType.UseVisualStyleBackColor = true;
|
||||
buttonSortByType.Click += ButtonSortByType_Click;
|
||||
//
|
||||
// FormShipCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1176, 770);
|
||||
ClientSize = new Size(1176, 869);
|
||||
Controls.Add(pictureBoxCollection);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
@ -343,5 +368,7 @@
|
||||
private ToolStripMenuItem LoadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
@ -39,6 +39,11 @@ public partial class FormShipCollection : Form
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogError("Ошибка: В коллекции превышено допустимое количество");
|
||||
}
|
||||
catch (ObjectAlreadyExistsException)
|
||||
{
|
||||
MessageBox.Show("Такой объект уже существует");
|
||||
_logger.LogError("Ошибка: такой объект уже существует {0}", ship);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -105,7 +110,7 @@ public partial class FormShipCollection : Form
|
||||
{
|
||||
DrawingShip? ship = null;
|
||||
int counter = 100;
|
||||
while(ship == null)
|
||||
while (ship == null)
|
||||
{
|
||||
ship = _company.GetRandomObject();
|
||||
counter--;
|
||||
@ -136,27 +141,27 @@ public partial class FormShipCollection : Form
|
||||
|
||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonMassive.Checked && !radioButtonList.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("Неверно введены данные для создания коллекции");
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
else if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RefreshListBoxItems();
|
||||
_logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType);
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation($"Добавлена коллекция - {textBoxCollectionName.Text}");
|
||||
RefreshListBoxItems();
|
||||
}
|
||||
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
@ -180,7 +185,7 @@ public partial class FormShipCollection : Form
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
string? colName = _storageCollection.Keys?[i].Name;
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
{
|
||||
listBoxCollection.Items.Add(colName);
|
||||
@ -225,9 +230,9 @@ public partial class FormShipCollection : Form
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName);
|
||||
_logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
catch(Exception ex)
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
@ -259,4 +264,18 @@ public partial class FormShipCollection : Form
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareShips(new DrawingShipCompareByType());
|
||||
|
||||
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareShips(new DrawingShipCompareByColor());
|
||||
|
||||
private void CompareShips(IComparer<DrawingShip?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_company.Sort(comparer);
|
||||
pictureBoxCollection.Image = _company.Show();
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user