12 Commits

27 changed files with 1144 additions and 206 deletions

View File

@@ -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>

View File

@@ -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>
/// Конструктор
@@ -45,7 +45,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <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>

View File

@@ -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();
}
}

View File

@@ -1,4 +1,6 @@
namespace Battleship.CollectionGenericObjects;
using Battleship.Drawings;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@@ -15,22 +17,25 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <returns></returns>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </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>
/// Удаление объекта из коллекции с конкретной позиции
@@ -45,4 +50,21 @@ public interface ICollectionGenericObjects<T>
/// <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);
}

View File

@@ -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,14 +9,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// Список объектов, которые храним
/// </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 { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@@ -30,47 +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 < _collection.Count; i++)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -1,4 +1,8 @@
namespace Battleship.CollectionGenericObjects;
using Battleship.CollectionGenericObjects;
using Battleship.Drawings;
using Battleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -14,13 +18,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (Count > 0)
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
@@ -32,6 +41,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -40,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)
{
@@ -61,56 +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;
T temp = _collection[position];
_collection[position] = null;
return temp;
}
public T Remove(int position)
public IEnumerable<T?> GetItems()
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
return null;
T obj = _collection[position];
_collection[position] = null;
return obj;
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];
}
}
}

View File

@@ -1,30 +1,55 @@
namespace Battleship.CollectionGenericObjects;
using Battleship.CollectionGenericObjects;
using Battleship.Drawings;
using Battleship.Exceptions;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// Класс - хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
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";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
@@ -32,48 +57,183 @@ public class StorageCollection<T>
/// <param name="collectionType">Тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
if (_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="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader reader = File.OpenText(filename))
{
string str = reader.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = reader.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingWarship() is T bulldozer)
{
try
{
if (collection.Insert(bulldozer) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -16,11 +16,17 @@ public class DrawingBattleship : DrawingWarship
/// <param name="bodyDeck">Признак наличия палубы</param>
/// <param name="compartment">Признак наличия отсека для ракет</param>
/// <param name="tower">Признак наличия башни</param>
public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 80)
public DrawingBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(129, 80)
{
EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor);
}
public DrawingBattleship(EntityBattleship warship) : base(129, 80)
{
EntityWarship = new EntityBattleship(warship.Speed, warship.Weight, warship.BodyColor, warship.Compartment, warship.Tower, warship.BodyDeck, warship.AdditionalColor);
}
public override void DrawTransport(Graphics g)
{
if (EntityWarship == null || EntityWarship is not EntityBattleship battleship || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@@ -88,8 +88,13 @@ public class DrawingWarship
/// <param name="drawingWarshipHeight">Высота прорисовки военного корабля</param>
protected DrawingWarship(int drawingWarshipWidth, int drawingWarshipHeight) : this()
{
_drawingWarshipWidth = drawingWarshipWidth;
_drawingWarshipHeight = drawingWarshipHeight;
this._drawingWarshipWidth = drawingWarshipWidth;
this._drawingWarshipHeight = drawingWarshipHeight;
}
public DrawingWarship(EntityWarship ship) : this()
{
EntityWarship = new EntityWarship(ship.Speed, ship.Weight, ship.BodyColor);
}
/// <summary>

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View 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();
}
}

View File

@@ -0,0 +1,53 @@
using Battleship.Entities;
namespace Battleship.Drawings;
/// <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((EntityBattleship)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);
}
}

View File

@@ -5,18 +5,6 @@
/// </summary>
public class EntityBattleship : EntityWarship
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// /// <summary>
/// Признак (опция) отсека для ракет
/// </summary>
@@ -37,6 +25,7 @@ public class EntityBattleship : EntityWarship
{
AdditionalColor = color;
}
/// <summary>
/// Перемещение линкора
/// </summary>
@@ -50,12 +39,32 @@ public class EntityBattleship : EntityWarship
/// <param name="bodyColor"></param>
public EntityBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
Compartment = compartment;
Tower = tower;
BodyDeck = bodyDeck;
AdditionalColor = additionalColor;
}
/// <summary>
/// Получение строки с значением свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(), BodyColor.Name, Compartment.ToString(), Tower.ToString(), BodyDeck.ToString(), AdditionalColor.Name};
}
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBattleship? CreateEntityBattleship(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityBattleship))
{
return null;
}
return new EntityBattleship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Color.FromName(strs[7]));
}
}

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Entities;
namespace Battleship.Entities;
/// <summary>
/// Класс-сущность Военный корабль
/// </summary>
@@ -22,6 +16,11 @@ public class EntityWarship
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
/// <param name="color"></param>
public void SetBodyColor(Color color)
{
BodyColor = color;
@@ -44,4 +43,28 @@ 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]));
}
}

View File

@@ -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) { }
}

View File

@@ -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) { }
}

View 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) { }
}

View File

@@ -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) { }
}

View File

@@ -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();
@@ -46,10 +48,17 @@
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
pictureBox = new PictureBox();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog1 = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@@ -57,9 +66,9 @@
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(876, 0);
groupBoxTools.Location = new Point(876, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(292, 656);
groupBoxTools.Size = new Size(292, 744);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@@ -67,22 +76,46 @@
// 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, 374);
panelCompanyTools.Location = new Point(6, 395);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(283, 276);
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(3, 228);
buttonRefresh.Location = new Point(0, 187);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(277, 42);
buttonRefresh.Size = new Size(280, 42);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -91,7 +124,7 @@
// maskedTextBox1
//
maskedTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox1.Location = new Point(3, 99);
maskedTextBox1.Location = new Point(3, 55);
maskedTextBox1.Mask = "00";
maskedTextBox1.Name = "maskedTextBox1";
maskedTextBox1.Size = new Size(277, 27);
@@ -100,9 +133,9 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 180);
buttonGoToCheck.Location = new Point(0, 139);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(277, 42);
buttonGoToCheck.Size = new Size(283, 42);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@@ -111,9 +144,9 @@
// buttonAddWarship
//
buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddWarship.Location = new Point(3, 3);
buttonAddWarship.Location = new Point(0, 7);
buttonAddWarship.Name = "buttonAddWarship";
buttonAddWarship.Size = new Size(277, 42);
buttonAddWarship.Size = new Size(280, 42);
buttonAddWarship.TabIndex = 1;
buttonAddWarship.Text = "Добавление корабля";
buttonAddWarship.UseVisualStyleBackColor = true;
@@ -122,9 +155,9 @@
// buttonRemoveWarship
//
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveWarship.Location = new Point(0, 132);
buttonRemoveWarship.Location = new Point(0, 91);
buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(280, 42);
buttonRemoveWarship.Size = new Size(283, 42);
buttonRemoveWarship.TabIndex = 4;
buttonRemoveWarship.Text = "Удалить корабль";
buttonRemoveWarship.UseVisualStyleBackColor = true;
@@ -244,19 +277,63 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(876, 656);
pictureBox.Size = new Size(876, 744);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1168, 28);
menuStrip1.TabIndex = 2;
menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "text file | *.txt";
//
// openFileDialog1
//
openFileDialog1.FileName = "openFileDialog";
openFileDialog1.Filter = "text file | *.txt";
//
// FormWarshipCollection
//
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);
MainMenuStrip = menuStrip1;
Name = "FormWarshipCollection";
Text = "Коллекция кораблей";
groupBoxTools.ResumeLayout(false);
@@ -265,7 +342,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -287,5 +367,13 @@
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private Panel panelCompanyTools;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog1;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -1,5 +1,8 @@
using Battleship.CollectionGenericObjects;
using Battleship.Drawings;
using Battleship.Exceptions;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace Battleship;
@@ -18,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>
@@ -34,7 +40,7 @@ public partial class FormWarshipCollection : Form
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
panelCompanyTools.Enabled = false;
}
/// <summary>
@@ -45,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();
}
@@ -60,18 +66,26 @@ 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>
/// Удаление объекта
@@ -84,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);
}
}
@@ -115,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>
@@ -156,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);
@@ -173,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)
{
@@ -186,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>
@@ -197,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>
@@ -227,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;
@@ -241,8 +277,102 @@ public partial class FormWarshipCollection : Form
_company = new WarshipSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
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(ex.Message, "Результат", 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 (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog1.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Сохранение в файл: {filename}", openFileDialog1.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)
{
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();
}
}

View File

@@ -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="menuStrip1.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>153, 17</value>
</metadata>
<metadata name="openFileDialog1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>318, 17</value>
</metadata>
</root>

View File

@@ -107,8 +107,7 @@ public partial class FormWarshipConfig : Form
_warship = new DrawingWarship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_warship = new DrawingBattleship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxBodyDeck.Checked, checkBoxCompartment.Checked, checkBoxTower.Checked);
_warship = new DrawingBattleship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White, checkBoxCompartment.Checked, checkBoxTower.Checked, checkBoxBodyDeck.Checked, Color.Black);
break;
}

View File

@@ -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());
});
}
}
}

View 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>

View File

@@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}

0
log.txt Normal file
View File