Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b6d4f83ae7 | |||
| ead2dcee19 | |||
| bcbc9f28b8 | |||
| 1fe1d75be5 | |||
| 44f2614f95 | |||
| 88fde22201 | |||
| 1641bff131 | |||
| d4b74a7d92 | |||
| ceb90e2be8 |
@@ -1,4 +1,5 @@
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using ProjectBattleship.Exceptions;
|
||||
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
@@ -30,8 +31,7 @@ public abstract class AbstractCompany
|
||||
/// Вычисление максимального количества элементов, который можно
|
||||
/// разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight /
|
||||
(_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@@ -44,7 +44,7 @@ public abstract class AbstractCompany
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_collection = collection;
|
||||
_collection.SetMaxCount = GetMaxCount;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
/// <summary>
|
||||
/// Перегрузка оператора сложения для класса
|
||||
@@ -55,7 +55,8 @@ public abstract class AbstractCompany
|
||||
public static int operator +(AbstractCompany company,
|
||||
DrawingWarship warship)
|
||||
{
|
||||
return company._collection?.Insert(warship) ?? 0;
|
||||
return company._collection?.Insert(warship, new DrawingWarshipEqutables()) ??
|
||||
throw new DrawningEquitablesException();
|
||||
}
|
||||
/// <summary>
|
||||
/// Перегрузка оператора удаления для класса
|
||||
@@ -78,6 +79,11 @@ public abstract class AbstractCompany
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
/// <summary>
|
||||
/// Сортировка
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
public void Sort(IComparer<DrawingWarship?> comparer) => _collection?.CollectionSort(comparer);
|
||||
/// <summary>
|
||||
/// Вывод всей коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
@@ -85,20 +91,30 @@ public abstract class AbstractCompany
|
||||
{
|
||||
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
|
||||
Graphics graphics = Graphics.FromImage(bitmap);
|
||||
DrawBackgound(graphics);
|
||||
DrawBackground(graphics);
|
||||
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawingWarship? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawingWarship? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException e)
|
||||
{ }
|
||||
catch (PositionOutOfCollectionException e)
|
||||
{ }
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackgound(Graphics g);
|
||||
protected abstract void DrawBackground(Graphics g);
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using ProjectBattleship.Exceptions;
|
||||
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
@@ -12,12 +13,12 @@ public class Docks : AbstractCompany
|
||||
/// <param name="picWidth"></param>
|
||||
/// <param name="picHeight"></param>
|
||||
/// <param name="collection"></param>
|
||||
public Docks(int picWidth, int picHeight,
|
||||
ICollectionGenericObjects<DrawingWarship> collection) :
|
||||
public Docks(int picWidth, int picHeight,
|
||||
ICollectionGenericObjects<DrawingWarship> collection) :
|
||||
base(picWidth, picHeight, collection)
|
||||
{
|
||||
}
|
||||
protected override void DrawBackgound(Graphics g)
|
||||
protected override void DrawBackground(Graphics g)
|
||||
{
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
@@ -26,48 +27,47 @@ public class Docks : AbstractCompany
|
||||
{
|
||||
for (int j = 0; j < height; ++j)
|
||||
{
|
||||
g.FillRectangle(brush, i * _placeSizeWidth,
|
||||
g.FillRectangle(brush, i * _placeSizeWidth,
|
||||
j * _placeSizeHeight, 200, 5);
|
||||
g.FillRectangle(brush, i * _placeSizeWidth,
|
||||
g.FillRectangle(brush, i * _placeSizeWidth,
|
||||
j * _placeSizeHeight, 5, 80);
|
||||
}
|
||||
}
|
||||
for (int j = 0; j < height - 4; ++j)
|
||||
{
|
||||
g.FillRectangle(brush, j * _placeSizeWidth,
|
||||
g.FillRectangle(brush, j * _placeSizeWidth,
|
||||
height * _placeSizeHeight, 200, 5);
|
||||
}
|
||||
}
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
if (_collection == null) return;
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int curWidth = width - 1;
|
||||
int curHeight = 0;
|
||||
|
||||
for (int i = 0; i < _collection.Count; i++)
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
DrawingWarship? _warship = _collection.Get(i);
|
||||
if (_warship != null)
|
||||
try
|
||||
{
|
||||
if (_warship.SetPictureSize(_pictureWidth, _pictureHeight))
|
||||
{
|
||||
_warship.SetPosition(_placeSizeWidth * curWidth + 20,
|
||||
curHeight * _placeSizeHeight + 15);
|
||||
}
|
||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
|
||||
}
|
||||
curWidth--;
|
||||
if (curWidth < 0)
|
||||
catch (ObjectNotFoundException) { }
|
||||
catch (PositionOutOfCollectionException e) { }
|
||||
if (curWidth > 0)
|
||||
curWidth--;
|
||||
else
|
||||
{
|
||||
curHeight++;
|
||||
curWidth = width - 1;
|
||||
curHeight++;
|
||||
}
|
||||
|
||||
if (curHeight >= height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +1,66 @@
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
using ProjectBattleship.DrawingObject;
|
||||
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Интерфейс описания действий для набора хранимых объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public interface ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Количество объектов в коллекции
|
||||
/// </summary>
|
||||
int Count { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Установка максимального количества элементов
|
||||
/// </summary>
|
||||
int SetMaxCount { set; }
|
||||
int MaxCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</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>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj, int position);
|
||||
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта из коллекции с конкретной позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
|
||||
T? Remove(int position);
|
||||
T Remove(int position);
|
||||
|
||||
/// <summary>
|
||||
/// Получение объекта по позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>Объект</returns>
|
||||
T? Get(int position);
|
||||
|
||||
/// <summary>
|
||||
/// Получение типа коллекции
|
||||
/// </summary>
|
||||
CollectionType GetCollectionType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Получение объектов коллекции по одному
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
}
|
||||
@@ -1,24 +1,44 @@
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
using ProjectBattleship.CollectionGenericObjects;
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using ProjectBattleship.Exceptions;
|
||||
|
||||
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
|
||||
public int MaxCount
|
||||
{
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
get
|
||||
{
|
||||
|
||||
return Count;
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@@ -27,33 +47,66 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
|
||||
public T? Get(int position)
|
||||
public T Get(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) return null;
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T? obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (Count == _maxCount) return -1;
|
||||
_collection.Add(obj);
|
||||
return Count - 1;
|
||||
}
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (comparer != null)
|
||||
{
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (comparer.Equals(_collection[i], obj))
|
||||
{
|
||||
throw new CollectionInsertException(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int Insert(T? obj, int position)
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (Count == _maxCount) return -1;
|
||||
if (position < 0 || position >= Count) return -1;
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (comparer != null)
|
||||
{
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (comparer.Equals(_collection[i], obj))
|
||||
{
|
||||
throw new CollectionInsertException(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) return null;
|
||||
T? obj = _collection[position];
|
||||
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < Count; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
_collection.Sort(comparer);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
using ProjectBattleship.Exceptions;
|
||||
using ProjectBattleship.CollectionGenericObjects;
|
||||
using ProjectBattleship.DrawingObject;
|
||||
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
@@ -11,8 +15,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
public int Count => _collection.Length;
|
||||
public int SetMaxCount
|
||||
/// <summary>
|
||||
/// Установка максимального кол-ва объектов
|
||||
/// </summary>
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
@@ -28,6 +39,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@@ -35,60 +49,120 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение объекта по позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция (индекс)</param>
|
||||
/// <returns></returns>
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position < 0 || position > Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
public int Insert(T obj)
|
||||
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
return Insert(obj, 0);
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position < 0 || position > Count)
|
||||
if (comparer != null)
|
||||
{
|
||||
return -1;
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (comparer.Equals(_collection[i], obj))
|
||||
{
|
||||
throw new CollectionInsertException(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
for (int i = position + 1; i < Count; i++)
|
||||
// вставка в свободное место набора
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return position;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = position - 1; i >= 0; i--)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return position;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (comparer != null)
|
||||
{
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (comparer.Equals(_collection[i], obj))
|
||||
{
|
||||
throw new CollectionInsertException(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_collection[position] != null)
|
||||
{
|
||||
bool pushed = false;
|
||||
for (int index = position + 1; index < Count; index++)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
position = index;
|
||||
pushed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pushed)
|
||||
{
|
||||
for (int index = position - 1; index >= 0; index--)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
position = index;
|
||||
pushed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!pushed)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
}
|
||||
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position < 0 || position > Count || _collection[position] == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
T? obj = _collection[position];
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
|
||||
T? temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
List<T?> value = new List<T?>(_collection);
|
||||
value.Sort(comparer);
|
||||
value.CopyTo(_collection, 0);
|
||||
}
|
||||
}
|
||||
@@ -1,75 +1,205 @@
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Класс-хранилище коллекций
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
using ProjectBattleship.Exceptions;
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using System.Text;
|
||||
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
|
||||
public class StorageCollection<T>
|
||||
where T : class
|
||||
where T : DrawingWarship
|
||||
{
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
private 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 = "CollectionsStorage";
|
||||
|
||||
/// <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>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
/// <param name="collectionInfo">тип коллекции</param>
|
||||
public void AddCollection(CollectionInfo collectionInfo)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name)) return;
|
||||
if (_storages.ContainsKey(name)) return;
|
||||
if (collectionType == CollectionType.None) return;
|
||||
if (collectionType == CollectionType.Massive)
|
||||
{
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
}
|
||||
else if (collectionType == CollectionType.List)
|
||||
{
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
}
|
||||
if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo);
|
||||
if (collectionInfo.CollectionType == CollectionType.None)
|
||||
throw new CollectionTypeException("Пустой тип коллекции");
|
||||
if (collectionInfo.CollectionType == CollectionType.Massive)
|
||||
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||
else if (collectionInfo.CollectionType == CollectionType.List)
|
||||
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
/// <param name="collectionInfo">тип коллекции</param>
|
||||
public void DelCollection(CollectionInfo collectionInfo)
|
||||
{
|
||||
if (_storages.ContainsKey(name))
|
||||
{
|
||||
_storages.Remove(name);
|
||||
}
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
_storages.Remove(collectionInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionInfo"></param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_storages.ContainsKey(name))
|
||||
{
|
||||
return _storages[name];
|
||||
}
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
return _storages[collectionInfo];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по самолетам в файл
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <exception cref="EmptyFileExeption"></exception>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new EmptyFileException();
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
sb.Append(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
}
|
||||
|
||||
writer.Write(sb);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new Exceptions.FileNotFoundException(filename);
|
||||
}
|
||||
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (string.IsNullOrEmpty(str))
|
||||
{
|
||||
throw new EmptyFileException(filename);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
CollectionInfo? collectionInfo =
|
||||
CollectionInfo.GetCollectionInfo(record[0]) ??
|
||||
throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]);
|
||||
|
||||
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)
|
||||
{
|
||||
if (elem?.CreateDrawingWarship() is T ship)
|
||||
{
|
||||
try
|
||||
{
|
||||
collection.Insert(ship);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exceptions.FileFormatException(filename, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_storages.Add(collectionInfo, collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static ICollectionGenericObjects<T>?
|
||||
CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,12 @@ namespace ProjectBattleship.DrawingObject;
|
||||
/// </summary>
|
||||
public class DrawingBattleship : DrawingWarship
|
||||
{
|
||||
public DrawingBattleship(EntityWarship warship) : base(150, 50)
|
||||
{
|
||||
EntityWarship = warship;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@@ -19,6 +25,7 @@ public class DrawingBattleship : DrawingWarship
|
||||
{
|
||||
EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketCompartment);
|
||||
}
|
||||
|
||||
public override void DrawTransport(Graphics g)
|
||||
{
|
||||
if (EntityWarship == null || EntityWarship is not EntityBattleship battleship ||
|
||||
|
||||
@@ -25,6 +25,8 @@ public class DrawingWarship
|
||||
/// Верхняя кооридната прорисовки военного корабля
|
||||
/// </summary>
|
||||
protected int? _startPosY;
|
||||
private EntityWarship warship;
|
||||
|
||||
/// <summary>
|
||||
/// Ширина прорисовки военного корабля
|
||||
/// </summary>
|
||||
@@ -63,6 +65,14 @@ public class DrawingWarship
|
||||
_drawingWarshipWidth = drawingWarshipWidth;
|
||||
_pictureHeight = drawingWarshipHeight;
|
||||
}
|
||||
|
||||
public DrawingWarship(EntityWarship warship)
|
||||
{
|
||||
EntityWarship = warship;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Установка границ поля
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using ProjectBattleship.DrawingObject;
|
||||
namespace ProjectBattleship;
|
||||
|
||||
public class DrawingWarshipCompareByColor : IComparer<DrawingWarship?>
|
||||
{
|
||||
public int Compare(DrawingWarship? x, DrawingWarship? y)
|
||||
{
|
||||
if (x == null && y == null) return 0;
|
||||
if (x == null || x.EntityWarship == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityWarship == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (ToHex(x.EntityWarship.BodyColor) != ToHex(y.EntityWarship.BodyColor))
|
||||
{
|
||||
return String.Compare(ToHex(x.EntityWarship.BodyColor), ToHex(y.EntityWarship.BodyColor),
|
||||
StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
|
||||
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
|
||||
}
|
||||
|
||||
private static String ToHex(Color c)
|
||||
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using ProjectBattleship.DrawingObject;
|
||||
namespace ProjectBattleship;
|
||||
|
||||
public class DrawingWarshipCompareByType : IComparer<DrawingWarship?>
|
||||
{
|
||||
public int Compare(DrawingWarship? x, DrawingWarship? y)
|
||||
{
|
||||
if (x == null && y == null) return 0;
|
||||
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,59 @@
|
||||
using ProjectBattleship.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
namespace ProjectBattleship.DrawingObject;
|
||||
/// <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)
|
||||
{
|
||||
if (((EntityBattleship)x.EntityWarship).AdditionalColor !=
|
||||
((EntityBattleship)y.EntityWarship).AdditionalColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (((EntityBattleship)x.EntityWarship).RocketCompartment !=
|
||||
((EntityBattleship)y.EntityWarship).RocketCompartment)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (((EntityBattleship)x.EntityWarship).Turret !=
|
||||
((EntityBattleship)y.EntityWarship).Turret)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public int GetHashCode([DisallowNull] DrawingWarship obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using ProjectBattleship.Entities;
|
||||
namespace ProjectBattleship.DrawingObject;
|
||||
/// <summary>
|
||||
/// Расширение для класса EntityWarship
|
||||
/// </summary>
|
||||
public static class ExtentionDrawingWarship
|
||||
{
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly string _separatorForObject = ":";
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="info">Строка с данными для создания объекта</param>
|
||||
/// <returns>Объект</returns>
|
||||
public static DrawingWarship? CreateDrawingWarship(this string info)
|
||||
{
|
||||
string[] strs = info.Split(_separatorForObject);
|
||||
EntityWarship? warship = EntityBattleship.CreateEntityBattleship(strs);
|
||||
if (warship != null)
|
||||
{
|
||||
return new DrawingBattleship(warship);
|
||||
}
|
||||
warship = EntityWarship.CreateEntityWarship(strs);
|
||||
if (warship != null)
|
||||
{
|
||||
return new DrawingWarship(warship);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение данных для сохранения в файл
|
||||
/// </summary>
|
||||
/// <param name="drawingWarship">Сохраняемый объект</param>
|
||||
/// <returns>Строка с данными по объекту</returns>
|
||||
public static string GetDataForSave(this DrawingWarship drawingWarship)
|
||||
{
|
||||
string[]? array = drawingWarship?.EntityWarship?.GetStringRepresentation();
|
||||
if (array == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Join(_separatorForObject, array);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace ProjectBattleship.Entities;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace ProjectBattleship.Entities;
|
||||
/// <summary>
|
||||
/// Класс-сущность "Линкор"
|
||||
/// </summary>
|
||||
@@ -19,4 +21,28 @@ public class EntityBattleship : EntityWarship
|
||||
Turret = turret;
|
||||
RocketCompartment = rocketCompartment;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение строк со значениями свойств объекта класса-сущности
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(),
|
||||
BodyColor.Name, AdditionalColor.Name, RocketCompartment.ToString(), Turret.ToString() };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityWarship? CreateEntityBattleship(string[] strs)
|
||||
{
|
||||
if (strs.Length != 7 || strs[0] != nameof(EntityBattleship))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new EntityBattleship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
|
||||
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace ProjectBattleship.Entities;
|
||||
/// <summary>
|
||||
/// Класс-сущность "Автомобиль"
|
||||
/// Класс-сущность "Военный корабль"
|
||||
/// </summary>
|
||||
public class EntityWarship
|
||||
{
|
||||
@@ -18,4 +18,27 @@ public class EntityWarship
|
||||
Weight = weight;
|
||||
BodyColor = bodyColor;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение строк со значениями свойств объекта класса-сущности
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityWarship), Speed.ToString(),
|
||||
Weight.ToString(), BodyColor.Name };
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityWarship? CreateEntityWarship(string[] strs)
|
||||
{
|
||||
if (strs.Length != 4 || strs[0] != nameof(EntityWarship))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new EntityWarship(Convert.ToInt32(strs[1]),
|
||||
Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
using ProjectBattleship.CollectionGenericObjects;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
public class CollectionAlreadyExistsException : Exception
|
||||
{
|
||||
public CollectionAlreadyExistsException() : base() { }
|
||||
public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { }
|
||||
public CollectionAlreadyExistsException(string name, Exception exception) :
|
||||
base($"Коллекция {name} уже существует!", exception)
|
||||
{ }
|
||||
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
|
||||
public class CollectionInfoException : Exception
|
||||
{
|
||||
public CollectionInfoException() : base() { }
|
||||
public CollectionInfoException(string message) : base(message) { }
|
||||
public CollectionInfoException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected CollectionInfoException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
|
||||
public class CollectionInsertException : Exception
|
||||
{
|
||||
public CollectionInsertException(object obj) : base($"Объект {obj} не удволетворяет уникальности") { }
|
||||
public CollectionInsertException() : base() { }
|
||||
public CollectionInsertException(string message) : base(message) { }
|
||||
public CollectionInsertException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected CollectionInsertException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.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 contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
|
||||
public class CollectionTypeException : Exception
|
||||
{
|
||||
public CollectionTypeException() : base() { }
|
||||
public CollectionTypeException(string message) : base(message) { }
|
||||
public CollectionTypeException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected CollectionTypeException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
|
||||
public class DrawningEquitablesException : Exception
|
||||
{
|
||||
public DrawningEquitablesException() : base("Объекты прорисовки одинаковые") { }
|
||||
public DrawningEquitablesException(string message) : base(message) { }
|
||||
public DrawningEquitablesException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected DrawningEquitablesException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -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) { }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
|
||||
public class FileFormatException : Exception
|
||||
{
|
||||
public FileFormatException() : base() { }
|
||||
public FileFormatException(string message) : base(message) { }
|
||||
public FileFormatException(string name, Exception exception) :
|
||||
base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception)
|
||||
{ }
|
||||
protected FileFormatException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
|
||||
public class FileNotFoundException : Exception
|
||||
{
|
||||
public FileNotFoundException(string name) : base($"Файл {name} не существует ") { }
|
||||
public FileNotFoundException() : base() { }
|
||||
public FileNotFoundException(string name, string message) : base(message) { }
|
||||
public FileNotFoundException(string name, string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected FileNotFoundException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.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 contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.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 contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -32,8 +32,9 @@ namespace ProjectBattleship
|
||||
{
|
||||
groupBoxCollectionTools = new GroupBox();
|
||||
panelCompanyTools = new Panel();
|
||||
buttonSortByColor = new Button();
|
||||
buttonSortByType = new Button();
|
||||
buttonRefresh = new Button();
|
||||
buttonAddBattleship = new Button();
|
||||
maskedTextBoxPosition = new MaskedTextBox();
|
||||
buttonAddWarship = new Button();
|
||||
buttonGoToCheck = new Button();
|
||||
@@ -49,10 +50,17 @@ namespace ProjectBattleship
|
||||
textBoxCollectionName = new TextBox();
|
||||
labelCollection = new Label();
|
||||
pictureBox = new PictureBox();
|
||||
menuStrip = new MenuStrip();
|
||||
файлToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveToolStripMenuItem = new ToolStripMenuItem();
|
||||
loadToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
groupBoxCollectionTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelCollection.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
||||
menuStrip.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
// groupBoxCollectionTools
|
||||
@@ -62,30 +70,51 @@ namespace ProjectBattleship
|
||||
groupBoxCollectionTools.Controls.Add(buttonCreateCompany);
|
||||
groupBoxCollectionTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxCollectionTools.Controls.Add(panelCollection);
|
||||
groupBoxCollectionTools.Location = new Point(694, 0);
|
||||
groupBoxCollectionTools.Location = new Point(699, 27);
|
||||
groupBoxCollectionTools.Name = "groupBoxCollectionTools";
|
||||
groupBoxCollectionTools.Size = new Size(279, 594);
|
||||
groupBoxCollectionTools.Size = new Size(279, 639);
|
||||
groupBoxCollectionTools.TabIndex = 1;
|
||||
groupBoxCollectionTools.TabStop = false;
|
||||
groupBoxCollectionTools.Text = "Инструменты";
|
||||
//
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
panelCompanyTools.Controls.Add(buttonAddBattleship);
|
||||
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
|
||||
panelCompanyTools.Controls.Add(buttonAddWarship);
|
||||
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
||||
panelCompanyTools.Controls.Add(buttonRemoveWarship);
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Location = new Point(6, 348);
|
||||
panelCompanyTools.Location = new Point(6, 354);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(267, 240);
|
||||
panelCompanyTools.Size = new Size(267, 279);
|
||||
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.Location = new Point(8, 203);
|
||||
buttonRefresh.Location = new Point(8, 163);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(251, 34);
|
||||
buttonRefresh.TabIndex = 7;
|
||||
@@ -93,19 +122,9 @@ namespace ProjectBattleship
|
||||
buttonRefresh.UseVisualStyleBackColor = true;
|
||||
buttonRefresh.Click += ButtonRefresh_Click;
|
||||
//
|
||||
// buttonAddBattleship
|
||||
//
|
||||
buttonAddBattleship.Location = new Point(8, 46);
|
||||
buttonAddBattleship.Name = "buttonAddBattleship";
|
||||
buttonAddBattleship.Size = new Size(251, 34);
|
||||
buttonAddBattleship.TabIndex = 3;
|
||||
buttonAddBattleship.Text = "Добавить линкор";
|
||||
buttonAddBattleship.UseVisualStyleBackColor = true;
|
||||
buttonAddBattleship.Click += ButtonAddBattleship_Click;
|
||||
//
|
||||
// maskedTextBoxPosition
|
||||
//
|
||||
maskedTextBoxPosition.Location = new Point(8, 86);
|
||||
maskedTextBoxPosition.Location = new Point(8, 46);
|
||||
maskedTextBoxPosition.Mask = "00";
|
||||
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
|
||||
maskedTextBoxPosition.Size = new Size(251, 31);
|
||||
@@ -124,7 +143,7 @@ namespace ProjectBattleship
|
||||
//
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Location = new Point(8, 163);
|
||||
buttonGoToCheck.Location = new Point(8, 123);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(251, 34);
|
||||
buttonGoToCheck.TabIndex = 6;
|
||||
@@ -134,7 +153,7 @@ namespace ProjectBattleship
|
||||
//
|
||||
// buttonRemoveWarship
|
||||
//
|
||||
buttonRemoveWarship.Location = new Point(8, 123);
|
||||
buttonRemoveWarship.Location = new Point(8, 83);
|
||||
buttonRemoveWarship.Name = "buttonRemoveWarship";
|
||||
buttonRemoveWarship.Size = new Size(251, 34);
|
||||
buttonRemoveWarship.TabIndex = 5;
|
||||
@@ -144,7 +163,7 @@ namespace ProjectBattleship
|
||||
//
|
||||
// buttonCreateCompany
|
||||
//
|
||||
buttonCreateCompany.Location = new Point(14, 314);
|
||||
buttonCreateCompany.Location = new Point(14, 320);
|
||||
buttonCreateCompany.Name = "buttonCreateCompany";
|
||||
buttonCreateCompany.Size = new Size(251, 34);
|
||||
buttonCreateCompany.TabIndex = 10;
|
||||
@@ -157,7 +176,7 @@ namespace ProjectBattleship
|
||||
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||
comboBoxSelectorCompany.FormattingEnabled = true;
|
||||
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
|
||||
comboBoxSelectorCompany.Location = new Point(14, 275);
|
||||
comboBoxSelectorCompany.Location = new Point(14, 281);
|
||||
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
|
||||
comboBoxSelectorCompany.Size = new Size(251, 33);
|
||||
comboBoxSelectorCompany.TabIndex = 0;
|
||||
@@ -172,7 +191,7 @@ namespace ProjectBattleship
|
||||
panelCollection.Controls.Add(radioButtonMassive);
|
||||
panelCollection.Controls.Add(textBoxCollectionName);
|
||||
panelCollection.Controls.Add(labelCollection);
|
||||
panelCollection.Location = new Point(6, 25);
|
||||
panelCollection.Location = new Point(6, 30);
|
||||
panelCollection.Name = "panelCollection";
|
||||
panelCollection.Size = new Size(267, 246);
|
||||
panelCollection.TabIndex = 9;
|
||||
@@ -247,19 +266,62 @@ namespace ProjectBattleship
|
||||
// pictureBox
|
||||
//
|
||||
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
|
||||
pictureBox.Location = new Point(0, 0);
|
||||
pictureBox.Location = new Point(0, 51);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(688, 594);
|
||||
pictureBox.Size = new Size(688, 615);
|
||||
pictureBox.TabIndex = 2;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
// menuStrip
|
||||
//
|
||||
menuStrip.ImageScalingSize = new Size(24, 24);
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(978, 33);
|
||||
menuStrip.TabIndex = 3;
|
||||
menuStrip.Text = "menuStrip";
|
||||
//
|
||||
// файлToolStripMenuItem
|
||||
//
|
||||
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
|
||||
файлToolStripMenuItem.Name = "файлToolStripMenuItem";
|
||||
файлToolStripMenuItem.Size = new Size(69, 29);
|
||||
файлToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// saveToolStripMenuItem
|
||||
//
|
||||
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
|
||||
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
|
||||
saveToolStripMenuItem.Size = new Size(278, 34);
|
||||
saveToolStripMenuItem.Text = "Сохранение ";
|
||||
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
|
||||
//
|
||||
// loadToolStripMenuItem
|
||||
//
|
||||
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
|
||||
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
|
||||
loadToolStripMenuItem.Size = new Size(278, 34);
|
||||
loadToolStripMenuItem.Text = "Загрузка";
|
||||
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
|
||||
//
|
||||
// saveFileDialog
|
||||
//
|
||||
saveFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// openFileDialog
|
||||
//
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// FormWarshipCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(10F, 25F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(978, 594);
|
||||
ClientSize = new Size(978, 666);
|
||||
Controls.Add(groupBoxCollectionTools);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(menuStrip);
|
||||
MainMenuStrip = menuStrip;
|
||||
Name = "FormWarshipCollection";
|
||||
Text = "Коллекция военных кораблей";
|
||||
groupBoxCollectionTools.ResumeLayout(false);
|
||||
@@ -268,12 +330,14 @@ namespace ProjectBattleship
|
||||
panelCollection.ResumeLayout(false);
|
||||
panelCollection.PerformLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
|
||||
menuStrip.ResumeLayout(false);
|
||||
menuStrip.PerformLayout();
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
private GroupBox groupBoxCollectionTools;
|
||||
private Button buttonAddBattleship;
|
||||
private Button buttonAddWarship;
|
||||
private ComboBox comboBoxSelectorCompany;
|
||||
private Button buttonRefresh;
|
||||
@@ -291,5 +355,13 @@ namespace ProjectBattleship
|
||||
private Button buttonCollectionDel;
|
||||
private ListBox listBoxCollection;
|
||||
private Panel panelCompanyTools;
|
||||
private MenuStrip menuStrip;
|
||||
private ToolStripMenuItem файлToolStripMenuItem;
|
||||
private ToolStripMenuItem saveToolStripMenuItem;
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private Button buttonSortByType;
|
||||
private Button buttonSortByColor;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using ProjectBattleship.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectBattleship;
|
||||
/// <summary>
|
||||
@@ -16,12 +18,17 @@ public partial class FormWarshipCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormWarshipCollection()
|
||||
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор компании
|
||||
@@ -31,7 +38,13 @@ public partial class FormWarshipCollection : Form
|
||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender,
|
||||
EventArgs e)
|
||||
{
|
||||
panelCompanyTools.Enabled = false;
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new Docks(pictureBox.Width, pictureBox.Height,
|
||||
new MassiveGenericObjects<DrawingWarship>());
|
||||
break;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление военного корабля
|
||||
@@ -47,21 +60,25 @@ public partial class FormWarshipCollection : Form
|
||||
/// <summary>
|
||||
/// Добавление военного корабля в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="car"></param>
|
||||
private void SetWarship(DrawingWarship? warship)
|
||||
/// <param name="Warship"></param>
|
||||
private void SetWarship(DrawingWarship warship)
|
||||
{
|
||||
if (_company == null || warship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (_company + warship != -1)
|
||||
try
|
||||
{
|
||||
var res = _company + warship;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Объект добавлен под индексом {res}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@@ -132,25 +149,29 @@ public partial class FormWarshipCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveWarship_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)
|
||||
|| _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
var res = _company - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@@ -206,12 +227,12 @@ public partial class FormWarshipCollection : Form
|
||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
|
||||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
@@ -221,9 +242,19 @@ public partial class FormWarshipCollection : Form
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text,
|
||||
collectionType);
|
||||
RerfreshListBoxItems();
|
||||
|
||||
try
|
||||
{
|
||||
_storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "2"));
|
||||
_logger.LogInformation("Добавление коллекции");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
@@ -237,16 +268,19 @@ public partial class FormWarshipCollection : Form
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Вы хотите удалить эту коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
|
||||
DialogResult.Yes)
|
||||
{
|
||||
string? name = listBoxCollection.SelectedItem.ToString();
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
{
|
||||
_storageCollection.DelCollection(name);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
|
||||
_storageCollection.DelCollection(collectionInfo!);
|
||||
_logger.LogInformation("Коллекция удалена");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
@@ -255,10 +289,10 @@ public partial class FormWarshipCollection : Form
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
CollectionInfo? col = _storageCollection.Keys?[i];
|
||||
if (!col!.IsEmpty())
|
||||
{
|
||||
listBoxCollection.Items.Add(colName);
|
||||
listBoxCollection.Items.Add(col);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -275,9 +309,9 @@ public partial class FormWarshipCollection : Form
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
ICollectionGenericObjects<DrawingWarship>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
ICollectionGenericObjects<DrawingWarship>? collection = _storageCollection[
|
||||
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
|
||||
new CollectionInfo("", CollectionType.None, "")]; if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
@@ -292,4 +326,84 @@ public partial class FormWarshipCollection : Form
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Сохранение"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
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 loadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
RerfreshListBoxItems();
|
||||
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
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)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
@@ -117,4 +117,13 @@
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>163, 17</value>
|
||||
</metadata>
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>351, 17</value>
|
||||
</metadata>
|
||||
</root>
|
||||
@@ -38,14 +38,7 @@ namespace ProjectBattleship
|
||||
/// <param name="WarshipDelegate"></param>
|
||||
public void AddEvent(Action<DrawingWarship> warshipDelegate)
|
||||
{
|
||||
if (WarshipDelegate != null)
|
||||
{
|
||||
WarshipDelegate = warshipDelegate;
|
||||
}
|
||||
else
|
||||
{
|
||||
WarshipDelegate += warshipDelegate;
|
||||
}
|
||||
WarshipDelegate += warshipDelegate;
|
||||
}
|
||||
/// <summary>
|
||||
/// Прорисовка объекта
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
using System.Drawing;
|
||||
using System;
|
||||
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
internal static class Program
|
||||
@@ -8,8 +14,27 @@ namespace ProjectBattleship
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormWarshipCollection());
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
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)
|
||||
{
|
||||
services.AddSingleton<FormWarshipCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddNLog("nlog.config");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,14 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
||||
20
ProjectBattleship/ProjectBattleship/serilogConfig.json
Normal file
20
ProjectBattleship/ProjectBattleship/serilogConfig.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs/log_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "Battleship"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user