Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7479a44cf3 | |||
| 26d83733e4 | |||
| b24c1358e2 | |||
| 45a9db6f9c | |||
| a925380371 | |||
| a810260e69 | |||
| 26fd2f83d9 | |||
| c21d2a3c02 | |||
| 5831712711 |
@@ -8,6 +8,19 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.9" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@@ -23,4 +36,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -32,7 +32,7 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight) + 2;
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@@ -56,7 +56,7 @@ public abstract class AbstractCompany
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawingWarship warship)
|
||||
{
|
||||
return company._collection.Insert(warship);
|
||||
return company._collection.Insert(warship, new DrawingWarshipEqutables());
|
||||
}
|
||||
/// <summary>
|
||||
/// Перезагрузка оператора удаления для класса
|
||||
@@ -98,6 +98,12 @@ public abstract class AbstractCompany
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка
|
||||
/// </summary>
|
||||
/// <param name="comparer"></param>
|
||||
public void Sort(IComparer<DrawingWarship?> comparer) => _collection?.CollectionSort(comparer);
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, хранящий информацию по коллекции
|
||||
/// </summary>
|
||||
public class CollectionInfo : IEquatable<CollectionInfo>
|
||||
{
|
||||
/// <summary>
|
||||
/// Название
|
||||
/// </summary>
|
||||
public string Name { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Тип
|
||||
/// </summary>
|
||||
public CollectionType CollectionType { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Описние
|
||||
/// </summary>
|
||||
public string Description { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly string _separator = "-";
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <param name="description"></param>
|
||||
public CollectionInfo(string name, CollectionType collectionType, string description)
|
||||
{
|
||||
Name = name;
|
||||
CollectionType = collectionType;
|
||||
Description = description;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
using Battleship.Drawings;
|
||||
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Интерфейс описания действий для набора хранимых объектов
|
||||
@@ -22,16 +24,18 @@ public interface ICollectionGenericObjects<T>
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="comparer">Сравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj);
|
||||
int Insert(T obj, IEqualityComparer<T?> comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию на конкретную позицию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <param name="comparer">Сравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj, int position);
|
||||
int Insert(T obj, int position, IEqualityComparer<T?> comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта из коллекции с конкретной позиции
|
||||
@@ -57,4 +61,10 @@ public interface ICollectionGenericObjects<T>
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IEnumerable<T> GetItems();
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer"></param>
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
using Battleship.Exceptions;
|
||||
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
@@ -11,7 +9,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
@@ -19,20 +16,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
private int _maxCount;
|
||||
|
||||
public int Count => _collection.Count;
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return Count;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int MaxCount { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } }
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@@ -44,55 +31,70 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0)
|
||||
return null;
|
||||
// проверка позиции
|
||||
// выброс ошибки, если выход за границы списка
|
||||
if (position < 0 || position > _maxCount) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
if (Count == _maxCount) return -1;
|
||||
// TODO выброс ошибки, если такой объект есть в коллекции
|
||||
if (comparer != null && _collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new CollectionAlreadyExistsException();
|
||||
}
|
||||
// проверка, что не превышено максимальное количество элементов
|
||||
if (_collection.Count >= _maxCount)
|
||||
{
|
||||
throw new CollectionOverflowException(_maxCount);
|
||||
}
|
||||
// вставка в конец набора
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
return _maxCount;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
if (position >= Count || position < 0)
|
||||
// TODO выброс ошибки, если такой объект есть в коллекции
|
||||
if (comparer != null && _collection.Contains(obj, comparer))
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
return -1;
|
||||
throw new CollectionAlreadyExistsException();
|
||||
}
|
||||
// проверка, что не превышено максимальное количество элементов
|
||||
if (Count >= _maxCount)
|
||||
throw new CollectionOverflowException(_maxCount);
|
||||
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= _maxCount)
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
|
||||
// вставка по позиции
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из списка
|
||||
if (position >= Count || position < 0)
|
||||
return null;
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
// проверка позиции
|
||||
if (position < 0 || position > _maxCount) throw new PositionOutOfCollectionException(position);
|
||||
// удаление объекта из списка
|
||||
T temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return temp;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < Count; ++i)
|
||||
for (int i = 0; i < _collection.Count; i++)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
_collection.Sort(comparer);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
|
||||
using Battleship.CollectionGenericObjects;
|
||||
using Battleship.Drawings;
|
||||
using Battleship.Exceptions;
|
||||
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
@@ -15,17 +18,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
public int MaxCount
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
if (Count > 0)
|
||||
if (_collection.Length > 0)
|
||||
{
|
||||
Array.Resize(ref _collection, value);
|
||||
}
|
||||
@@ -47,19 +51,24 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
|
||||
public T Get(int position)
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// проверка позиции
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{
|
||||
return null;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO вставка в свободное место набора
|
||||
// TODO выброс ошибки, если такой объект есть в коллекции
|
||||
if (comparer != null && _collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new CollectionAlreadyExistsException();
|
||||
}
|
||||
// вставка в свободное место набора
|
||||
int index = 0;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
@@ -68,64 +77,88 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
++index;
|
||||
index++;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
// если нет после, ищем до
|
||||
// TODO вставка
|
||||
|
||||
// TODO выброс ошибки, если такой объект есть в коллекции
|
||||
if (comparer != null && _collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new CollectionAlreadyExistsException();
|
||||
}
|
||||
|
||||
// проверка позиции
|
||||
if (position >= _collection.Length || position < 0)
|
||||
return -1;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
|
||||
// проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
if (_collection[position] != null)
|
||||
{
|
||||
// проверка, что после вставляемого элемента в массиве есть пустой элемент
|
||||
int nullIndex = -1;
|
||||
for (int i = position + 1; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
nullIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Если пустого элемента нет, то выходим
|
||||
if (nullIndex < 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
|
||||
int j = nullIndex - 1;
|
||||
while (j >= position)
|
||||
{
|
||||
_collection[j + 1] = _collection[j];
|
||||
j--;
|
||||
}
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
// вставка по позиции
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// проверка позиции
|
||||
// удаление объекта из массива, присвоив элементу массива значение null
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
int index = position + 1;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
++index;
|
||||
}
|
||||
index = position - 1;
|
||||
while (index >= 0)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
--index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||
if (position >= _collection.Length || position < 0)
|
||||
return null;
|
||||
T obj = _collection[position];
|
||||
T temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
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++)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
List<T?> lst = [.. _collection];
|
||||
lst.Sort(comparer.Compare);
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
_collection[i] = lst[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,47 @@
|
||||
using Battleship.Drawings;
|
||||
using System.Text;
|
||||
using Battleship.CollectionGenericObjects;
|
||||
using Battleship.Drawings;
|
||||
using Battleship.Exceptions;
|
||||
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Класс-хранилище коллекций
|
||||
/// Класс - хранилище коллекций
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class StorageCollection<T>
|
||||
where T : DrawingWarship
|
||||
{
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
private 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>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
@@ -41,61 +57,61 @@ public class StorageCollection<T>
|
||||
/// <param name="collectionType">Тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
|
||||
// проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(new CollectionInfo(name, collectionType, string.Empty)))
|
||||
{
|
||||
MessageBox.Show("Коллекция с таким именем уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
// TODO Прописать логику для добавления
|
||||
// прописать логику для добавления
|
||||
if (collectionType == CollectionType.List)
|
||||
{
|
||||
_storages.Add(name, new ListGenericObjects<T>());
|
||||
_storages.Add(new CollectionInfo(name, collectionType, string.Empty), new ListGenericObjects<T>());
|
||||
}
|
||||
if (collectionType == CollectionType.Massive)
|
||||
{
|
||||
_storages.Add(name, new MassiveGenericObjects<T>());
|
||||
_storages.Add(new CollectionInfo(name, collectionType, string.Empty), new MassiveGenericObjects<T>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
// TODO Прописать логику для удаления коллекции
|
||||
if (!_storages.ContainsKey(name))
|
||||
return;
|
||||
_storages.Remove(name);
|
||||
// прописать логику для удаления коллекции
|
||||
if (!_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) return;
|
||||
_storages.Remove(new CollectionInfo(name, CollectionType.None, string.Empty));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T> this[string name]
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
// TODO Продумать логику получения объекта
|
||||
if (_storages.ContainsKey((string)name))
|
||||
// продумать логику получения объекта
|
||||
if (_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty)))
|
||||
{
|
||||
return _storages[name];
|
||||
return _storages[new CollectionInfo(name, CollectionType.None, string.Empty)];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по кораблям в хранилище в файл
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filname"></param>
|
||||
/// <returns></returns>
|
||||
public bool SaveData(string filename)
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
@@ -106,7 +122,7 @@ public class StorageCollection<T>
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
writer.Write(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
@@ -117,8 +133,6 @@ public class StorageCollection<T>
|
||||
|
||||
writer.Write(value.Key);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.GetCollectionType);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.MaxCount);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
|
||||
@@ -135,19 +149,18 @@ public class StorageCollection<T>
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по кораблям в хранилище из файла
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <returns></returns>
|
||||
public bool LoadData(string filename)
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader reader = File.OpenText(filename))
|
||||
@@ -156,13 +169,12 @@ public class StorageCollection<T>
|
||||
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле нет данных");
|
||||
}
|
||||
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
|
||||
_storages.Clear();
|
||||
@@ -170,39 +182,46 @@ public class StorageCollection<T>
|
||||
while ((strs = reader.ReadLine()) != null)
|
||||
{
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
if (record.Length != 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
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)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawingWarship() is T bulldozer)
|
||||
{
|
||||
if (collection.Insert(bulldozer) == -1)
|
||||
try
|
||||
{
|
||||
return false;
|
||||
if (collection.Insert(bulldozer) == -1)
|
||||
{
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_storages.Add(record[0], collection);
|
||||
_storages.Add(collectionInfo, collection);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
@@ -217,4 +236,4 @@ public class StorageCollection<T>
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace Battleship.Drawings;
|
||||
|
||||
/// <summary>
|
||||
/// Сравнение по типу, скорости, весу
|
||||
/// </summary>
|
||||
internal class DrawingWarshipCompareByType : IComparer<DrawingWarship?>
|
||||
{
|
||||
public int Compare(DrawingWarship? x, DrawingWarship? y)
|
||||
{
|
||||
if (x == null || x.EntityWarship == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityWarship == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
|
||||
var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed);
|
||||
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
|
||||
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace Battleship.Drawings;
|
||||
|
||||
/// <summary>
|
||||
/// Сравнение по цвету, скорости, весу
|
||||
/// </summary>
|
||||
public class DrawingWarshipComparerByColor : IComparer<DrawingWarship?>
|
||||
{
|
||||
public int Compare(DrawingWarship? x, DrawingWarship? y)
|
||||
{
|
||||
// TODO прописать логику сравнения по цветам, скорости, весу
|
||||
if (x == null || x.EntityWarship == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityWarship == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (x.EntityWarship.BodyColor != y.EntityWarship.BodyColor)
|
||||
{
|
||||
return x.EntityWarship.BodyColor.Name.CompareTo(y.EntityWarship.BodyColor.Name);
|
||||
}
|
||||
|
||||
var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed);
|
||||
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
|
||||
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
|
||||
}
|
||||
}
|
||||
71
Battleship/Battleship/Drawings/DrawingWarshipEqutables.cs
Normal file
71
Battleship/Battleship/Drawings/DrawingWarshipEqutables.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
namespace Battleship.Drawings;
|
||||
|
||||
using Battleship.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
/// <summary>
|
||||
/// Реализация сравнения двух объектов класса-прорисовки
|
||||
/// </summary>
|
||||
public class DrawingWarshipEqutables : IEqualityComparer<DrawingWarship?>
|
||||
{
|
||||
public bool Equals(DrawingWarship? x, DrawingWarship? y)
|
||||
{
|
||||
if (x == null || x.EntityWarship == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityWarship == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.EntityWarship.Speed != y.EntityWarship.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.EntityWarship.Weight != y.EntityWarship.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityWarship.BodyColor != y.EntityWarship.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x is DrawingBattleship && y is DrawingBattleship)
|
||||
{
|
||||
// TODO доделать логику сравнения дополнительных параметров
|
||||
EntityBattleship xBattleship = (EntityBattleship)x.EntityWarship;
|
||||
EntityBattleship yBattleship = (EntityBattleship)y.EntityWarship;
|
||||
|
||||
if (xBattleship.AdditionalColor != yBattleship.AdditionalColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (xBattleship.Compartment != yBattleship.Compartment)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (xBattleship.Tower != yBattleship.Tower)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetHashCode([DisallowNull] DrawingWarship obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using Battleship.CollectionGenericObjects;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Battleship.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку повторяющегося элемента в коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class CollectionAlreadyExistsException : ApplicationException
|
||||
{
|
||||
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base("В коллекции уже есть такой элемент: " + collectionInfo) { }
|
||||
public CollectionAlreadyExistsException() : base("В коллекции уже есть такой элемент") { }
|
||||
public CollectionAlreadyExistsException(string message) : base(message) { }
|
||||
public CollectionAlreadyExistsException(string message, Exception exception) : base(message, exception) { }
|
||||
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Battleship.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class CollectionOverflowException : ApplicationException
|
||||
{
|
||||
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
|
||||
public CollectionOverflowException() : base() { }
|
||||
public CollectionOverflowException(string message) : base(message) { }
|
||||
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
|
||||
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
16
Battleship/Battleship/Exception/ObjectNotFoundException.cs
Normal file
16
Battleship/Battleship/Exception/ObjectNotFoundException.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Battleship.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class ObjectNotFoundException : ApplicationException
|
||||
{
|
||||
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
|
||||
public ObjectNotFoundException() : base() { }
|
||||
public ObjectNotFoundException(string message) : base(message) { }
|
||||
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Battleship.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что позиция вышла за границы коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class PositionOutOfCollectionException : ApplicationException
|
||||
{
|
||||
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
|
||||
public PositionOutOfCollectionException() : base() { }
|
||||
public PositionOutOfCollectionException(string message) : base(message) { }
|
||||
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
|
||||
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
@@ -30,6 +30,8 @@
|
||||
{
|
||||
groupBoxTools = new GroupBox();
|
||||
panelCompanyTools = new Panel();
|
||||
buttonSortByColor = new Button();
|
||||
buttonSortByType = new Button();
|
||||
buttonRefresh = new Button();
|
||||
maskedTextBox1 = new MaskedTextBox();
|
||||
buttonGoToCheck = new Button();
|
||||
@@ -66,7 +68,7 @@
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(876, 28);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(292, 628);
|
||||
groupBoxTools.Size = new Size(292, 744);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
@@ -74,20 +76,44 @@
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
panelCompanyTools.Controls.Add(maskedTextBox1);
|
||||
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
||||
panelCompanyTools.Controls.Add(buttonAddWarship);
|
||||
panelCompanyTools.Controls.Add(buttonRemoveWarship);
|
||||
panelCompanyTools.Location = new Point(6, 367);
|
||||
panelCompanyTools.Location = new Point(6, 395);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(283, 255);
|
||||
panelCompanyTools.Size = new Size(283, 337);
|
||||
panelCompanyTools.TabIndex = 10;
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByColor.Location = new Point(0, 283);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(280, 42);
|
||||
buttonSortByColor.TabIndex = 9;
|
||||
buttonSortByColor.Text = "Сортировка по цвету";
|
||||
buttonSortByColor.UseVisualStyleBackColor = true;
|
||||
buttonSortByColor.Click += ButtonSortByColor_Click;
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByType.Location = new Point(0, 235);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(283, 42);
|
||||
buttonSortByType.TabIndex = 8;
|
||||
buttonSortByType.Text = "Сортировка по типу";
|
||||
buttonSortByType.UseVisualStyleBackColor = true;
|
||||
buttonSortByType.Click += buttonSortByType_Click;
|
||||
//
|
||||
// buttonRefresh
|
||||
//
|
||||
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRefresh.Location = new Point(0, 214);
|
||||
buttonRefresh.Location = new Point(0, 187);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(280, 42);
|
||||
buttonRefresh.TabIndex = 6;
|
||||
@@ -98,7 +124,7 @@
|
||||
// maskedTextBox1
|
||||
//
|
||||
maskedTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
maskedTextBox1.Location = new Point(3, 85);
|
||||
maskedTextBox1.Location = new Point(3, 55);
|
||||
maskedTextBox1.Mask = "00";
|
||||
maskedTextBox1.Name = "maskedTextBox1";
|
||||
maskedTextBox1.Size = new Size(277, 27);
|
||||
@@ -107,7 +133,7 @@
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonGoToCheck.Location = new Point(0, 166);
|
||||
buttonGoToCheck.Location = new Point(0, 139);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(283, 42);
|
||||
buttonGoToCheck.TabIndex = 5;
|
||||
@@ -129,7 +155,7 @@
|
||||
// buttonRemoveWarship
|
||||
//
|
||||
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRemoveWarship.Location = new Point(0, 118);
|
||||
buttonRemoveWarship.Location = new Point(0, 91);
|
||||
buttonRemoveWarship.Name = "buttonRemoveWarship";
|
||||
buttonRemoveWarship.Size = new Size(283, 42);
|
||||
buttonRemoveWarship.TabIndex = 4;
|
||||
@@ -253,7 +279,7 @@
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 28);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(876, 628);
|
||||
pictureBox.Size = new Size(876, 744);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
@@ -303,7 +329,7 @@
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1168, 656);
|
||||
ClientSize = new Size(1168, 772);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip1);
|
||||
@@ -347,5 +373,7 @@
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog1;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using Battleship.CollectionGenericObjects;
|
||||
using Battleship.Drawings;
|
||||
using Battleship.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace Battleship;
|
||||
@@ -19,13 +21,16 @@ public partial class FormWarshipCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormWarshipCollection()
|
||||
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,8 +51,8 @@ public partial class FormWarshipCollection : Form
|
||||
private void ButtonAddWarship_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormWarshipConfig form = new();
|
||||
form.Show();
|
||||
form.AddEvent(SetWarship);
|
||||
form.Show();
|
||||
}
|
||||
|
||||
|
||||
@@ -61,17 +66,25 @@ public partial class FormWarshipCollection : Form
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + warship != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (_company + warship != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект: {object}", warship.GetDataForSave());
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (CollectionAlreadyExistsException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -85,21 +98,25 @@ public partial class FormWarshipCollection : Form
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBox1.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удален объект по позиции " + pos);
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,23 +133,34 @@ public partial class FormWarshipCollection : Form
|
||||
}
|
||||
|
||||
DrawingWarship? warship = null;
|
||||
int counter = 120;
|
||||
while (warship == null)
|
||||
int counter = 100;
|
||||
try
|
||||
{
|
||||
warship = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
while (warship == null)
|
||||
{
|
||||
break;
|
||||
warship = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (warship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
FormBattleship form = new()
|
||||
{
|
||||
SetWarship = warship
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
|
||||
FormBattleship form = new()
|
||||
catch (Exception ex)
|
||||
{
|
||||
SetWarship = warship
|
||||
};
|
||||
form.ShowDialog();
|
||||
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -157,7 +185,7 @@ public partial class FormWarshipCollection : 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);
|
||||
@@ -174,10 +202,10 @@ public partial class FormWarshipCollection : Form
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
@@ -187,8 +215,10 @@ public partial class FormWarshipCollection : Form
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Добавлена коллекция: {collectionName} типа: {collectionType}", textBoxCollectionName.Text, collectionType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -198,21 +228,28 @@ public partial class FormWarshipCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
// TODO прописать логику удаления элемента из коллекции
|
||||
//прописать логику удаления элемента из коллекции
|
||||
// нужно убедиться, что есть выбранная коллекция
|
||||
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
|
||||
// удалить и обновить ListBox
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
MessageBox.Show("Коллекция не выбрана"); return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
try
|
||||
{
|
||||
return;
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -228,9 +265,7 @@ public partial class FormWarshipCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
ICollectionGenericObjects<DrawingWarship>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
|
||||
if (collection == null)
|
||||
ICollectionGenericObjects<DrawingWarship>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
@@ -256,13 +291,16 @@ public partial class FormWarshipCollection : Form
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,15 +314,65 @@ public partial class FormWarshipCollection : Form
|
||||
{
|
||||
if (openFileDialog1.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog1.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog1.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", openFileDialog1.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по типу
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void buttonSortByType_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareWarship(new DrawingWarshipCompareByType());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по цвету
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonSortByColor_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareExcavators(new DrawingWarshipComparerByColor());
|
||||
}
|
||||
|
||||
private void CompareExcavators(IComparer<DrawingWarship?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_company.Sort(comparer);
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по сравнителю
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
private void CompareWarship(IComparer<DrawingWarship?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_company.Sort(comparer);
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
|
||||
namespace Battleship
|
||||
{
|
||||
internal static class Program
|
||||
@@ -11,7 +16,34 @@ namespace Battleship
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormWarshipCollection());
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormWarshipCollection>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
string[] path = Directory.GetCurrentDirectory().Split('\\');
|
||||
string pathNeed = "";
|
||||
for (int i = 0; i < path.Length - 3; i++)
|
||||
{
|
||||
pathNeed += path[i] + "\\";
|
||||
}
|
||||
services.AddSingleton<FormWarshipCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.AddJsonFile($"{pathNeed}serilog.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
14
Battleship/Battleship/nlog.config
Normal file
14
Battleship/Battleship/nlog.config
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true" internalLogLevel="Info">
|
||||
<targets>
|
||||
<target xsi:type="File" name= "tofile" filename="carlog-${shortdate}.log" />
|
||||
</targets>
|
||||
|
||||
<rules>
|
||||
<logger name ="*" minlevel="Debug" writeTo="tofile" />
|
||||
</rules>
|
||||
</nlog>
|
||||
</configuration>
|
||||
15
Battleship/Battleship/serilog.json
Normal file
15
Battleship/Battleship/serilog.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": { "path": "log.log" }
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user