13 Commits

30 changed files with 1846 additions and 265 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,21 +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>
/// /// <summary>
/// Признак (опция) отсека для ракет
/// </summary>
@@ -36,6 +21,11 @@ public class EntityBattleship : EntityWarship
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color)
{
AdditionalColor = color;
}
/// <summary>
/// Перемещение линкора
/// </summary>
@@ -49,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,16 @@ public class EntityWarship
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
/// <param name="color"></param>
public void SetBodyColor(Color color)
{
BodyColor = color;
}
/// <summary>
/// Перемещение военного корабля
/// </summary>
@@ -39,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,12 +30,13 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonRefresh = new Button();
maskedTextBox1 = new MaskedTextBox();
buttonGoToCheck = new Button();
buttonAddWarship = new Button();
buttonRemoveWarship = new Button();
buttonAddBattleship = new Button();
panelStorage = new Panel();
comboBoxSelectorCompany = new ComboBox();
buttonCollectionDel = new Button();
@@ -47,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
@@ -58,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 = "Инструменты";
@@ -68,23 +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.Controls.Add(buttonAddBattleship);
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;
@@ -93,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);
@@ -102,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;
@@ -113,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;
@@ -124,25 +155,14 @@
// 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;
buttonRemoveWarship.Click += ButtonRemoveWarship_Click_1;
//
// buttonAddBattleship
//
buttonAddBattleship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBattleship.Location = new Point(3, 51);
buttonAddBattleship.Name = "buttonAddBattleship";
buttonAddBattleship.Size = new Size(277, 42);
buttonAddBattleship.TabIndex = 2;
buttonAddBattleship.Text = "Добавление линкора";
buttonAddBattleship.UseVisualStyleBackColor = true;
buttonAddBattleship.Click += ButtonAddBattleship_Click;
//
// panelStorage
//
panelStorage.Controls.Add(comboBoxSelectorCompany);
@@ -257,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);
@@ -278,13 +342,15 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddBattleship;
private Button buttonAddWarship;
private Button buttonRemoveWarship;
private PictureBox pictureBox;
@@ -301,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,84 +40,53 @@ public partial class FormWarshipCollection : Form
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление линкора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddBattleship_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawingBattleship));
}
/// <summary>
/// Добавление военного корабля
/// Добавление корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddWarship_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawingWarship));
FormWarshipConfig form = new();
form.AddEvent(SetWarship);
form.Show();
}
/// <summary>
/// Создание объекта
/// Добавление корабля в коллекцию
/// </summary>
/// <param name="type"></param>
private void CreateObject(string type)
/// <param name="warship"></param>
private void SetWarship(DrawingWarship warship)
{
if (_company == null)
if (_company == null || warship == null)
{
return;
}
Random random = new();
DrawingWarship drawingWarship;
switch (type)
try
{
case nameof(DrawingWarship):
drawingWarship = new DrawingWarship(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawingBattleship):
drawingWarship = new DrawingBattleship(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random),
GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(1, 2)), Convert.ToBoolean(random.Next(1, 2)));
break;
default:
return;
if (_company + warship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {object}", warship.GetDataForSave());
}
}
if (_company + drawingWarship != -1)
catch (CollectionOverflowException ex)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
else
catch (CollectionAlreadyExistsException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Удаление объекта
/// </summary>
@@ -123,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);
}
}
@@ -154,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>
@@ -195,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);
@@ -212,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)
{
@@ -225,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>
@@ -236,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>
@@ -266,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;
@@ -280,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

@@ -0,0 +1,370 @@
namespace Battleship
{
partial class FormWarshipConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxTower = new CheckBox();
checkBoxCompartment = new CheckBox();
checkBoxBodyDeck = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxTower);
groupBoxConfig.Controls.Add(checkBoxCompartment);
groupBoxConfig.Controls.Add(checkBoxBodyDeck);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(581, 274);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(259, 35);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(300, 155);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(230, 89);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(50, 46);
panelPurple.TabIndex = 7;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(163, 89);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(50, 46);
panelBlack.TabIndex = 6;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(97, 89);
panelGray.Name = "panelGray";
panelGray.Size = new Size(50, 46);
panelGray.TabIndex = 5;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(31, 89);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(50, 46);
panelWhite.TabIndex = 4;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(230, 26);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(50, 46);
panelYellow.TabIndex = 3;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(163, 26);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(50, 46);
panelBlue.TabIndex = 2;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(97, 26);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(50, 46);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(31, 26);
panelRed.Name = "panelRed";
panelRed.Size = new Size(50, 46);
panelRed.TabIndex = 0;
//
// checkBoxTower
//
checkBoxTower.AutoSize = true;
checkBoxTower.Location = new Point(12, 231);
checkBoxTower.Name = "checkBoxTower";
checkBoxTower.Size = new Size(205, 24);
checkBoxTower.TabIndex = 8;
checkBoxTower.Text = "Признак наличия башни";
checkBoxTower.UseVisualStyleBackColor = true;
//
// checkBoxCompartment
//
checkBoxCompartment.AutoSize = true;
checkBoxCompartment.Location = new Point(12, 179);
checkBoxCompartment.Name = "checkBoxCompartment";
checkBoxCompartment.Size = new Size(210, 24);
checkBoxCompartment.TabIndex = 7;
checkBoxCompartment.Text = "Признак отсека для ракет";
checkBoxCompartment.UseVisualStyleBackColor = true;
//
// checkBoxBodyDeck
//
checkBoxBodyDeck.AutoSize = true;
checkBoxBodyDeck.Location = new Point(12, 124);
checkBoxBodyDeck.Name = "checkBoxBodyDeck";
checkBoxBodyDeck.Size = new Size(210, 24);
checkBoxBodyDeck.TabIndex = 6;
checkBoxBodyDeck.Text = "Признак наличия палубы";
checkBoxBodyDeck.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(94, 76);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(90, 27);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 78);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(94, 35);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(128, 27);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 37);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(422, 206);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(137, 49);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += labelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(259, 206);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(137, 49);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой ";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += labelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(14, 66);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(187, 125);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(601, 216);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(87, 29);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(706, 216);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 29);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(587, 12);
panelObject.Name = "panelObject";
panelObject.Size = new Size(209, 198);
panelObject.TabIndex = 4;
panelObject.DragDrop += panelObject_DragDrop;
panelObject.DragEnter += panelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(119, 16);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(82, 38);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(14, 16);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(73, 38);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет ";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
//
// FormWarshipConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 274);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormWarshipConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private CheckBox checkBoxBodyDeck;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxCompartment;
private CheckBox checkBoxTower;
private GroupBox groupBoxColors;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,191 @@
using Battleship.Drawings;
using Battleship.Entities;
namespace Battleship;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormWarshipConfig : Form
{
/// <summary>
/// Объект - прорисовка корабля
/// </summary>
private DrawingWarship? _warship;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawingWarship>? WarshipDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormWarshipConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
//к buttonCancel.Click привязать анонимный метод через lambda с закрытием формы
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="warshipDelegate"></param>
public void AddEvent(Action<DrawingWarship> warshipDelegate)
{
if (WarshipDelegate == null)
{
WarshipDelegate = warshipDelegate;
}
else
{
WarshipDelegate += warshipDelegate;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_warship?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_warship?.SetPosition(5, 5);
_warship?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Прорисовка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действие при приеме перетаскивающей информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_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, checkBoxCompartment.Checked, checkBoxTower.Checked, checkBoxBodyDeck.Checked, Color.Black);
break;
}
DrawObject();
}
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
// TODO отправка цвета в Drag&Drop
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
// Логика смены цветов: основного и дополнительного (для продвинутого объекта)
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_warship != null)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
_warship.EntityWarship.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
}
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_warship != null && _warship is DrawingBattleship)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_warship != null && _warship.EntityWarship is EntityBattleship _battleship)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
_battleship.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_warship != null)
{
WarshipDelegate?.Invoke(_warship);
Close();
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<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="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

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,8 @@
using Battleship.Drawings;
namespace Battleship;
/// <summary>
/// Делегат передачи объекта прорисовки
/// </summary>
/// <param name="warship"></param>
public delegate void WarshipDelegate(DrawingWarship warship);

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