3 Commits

25 changed files with 1165 additions and 231 deletions

View File

@@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
@@ -32,7 +33,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@@ -45,7 +46,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
@@ -56,7 +57,18 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTank tank) public static int operator +(AbstractCompany company, DrawningTank tank)
{ {
return company._collection.Insert(tank); try
{
return company._collection.Insert(tank, 0, new DrawningTankEqutables());
}
catch (ObjectAlreadyInCollectionException)
{
return -1;
}
catch (CollectionOverflowException)
{
return -1;
}
} }
/// <summary> /// <summary>
@@ -65,11 +77,10 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param> /// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns> /// <returns></returns>
public static DrawningTank? operator -(AbstractCompany company, int position) public static DrawningTank operator -(AbstractCompany company, int position)
{ {
return company._collection?.Remove(position); return company._collection.Remove(position);
} }
/// <summary> /// <summary>
/// Получение случайного объекта из коллекции /// Получение случайного объекта из коллекции
/// </summary> /// </summary>
@@ -88,23 +99,35 @@ public abstract class AbstractCompany
{ {
Bitmap bitmap = new(_pictureWidth, _pictureHeight); Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics); DrawBackground(graphics);
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningTank? obj = _collection?.Get(i); try
obj?.DrawTransport(graphics); {
DrawningTank? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
} }
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTank?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g); protected abstract void DrawBackground(Graphics g);
/// <summary> /// <summary>
/// Расстановка объектов /// Расстановка объектов

View File

@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]),
strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@@ -1,4 +1,5 @@
using System; using SelfPropelledArtilleryUnit.Drawnings;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -14,21 +15,22 @@ public interface ICollectionGenericObjects<T>
where T : class where T : class
{ {
/// <summary> /// <summary>
/// Количество объектов в коллекции /// Количество объектов в коллекции
/// </summary> /// </summary>
int Count { get; } int Count { get; }
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
@@ -36,7 +38,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@@ -51,4 +53,20 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); 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,4 +1,6 @@
using System; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -19,10 +21,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary> /// </summary>
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; public int Count { get { return _collection.Count; } }
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
public int MaxCount
{
get
{
return _maxCount;
}
set
{
if (value > 0) _maxCount = value;
}
}
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -30,33 +46,75 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
_collection = new(); _collection = new();
} }
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) return null; if (position < 0 || position >= Count) return null;
return _collection[position]; return _collection[position];
} }
public int Insert(T? obj) public int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null)
{ {
if (Count == _maxCount) return -1; // TODO выброс ошибки, если переполнение
// TODO выброс ошибки, если такой объект есть в коллекции
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
_collection.Add(obj); _collection.Add(obj);
return Count - 1; return _collection.Count;
} }
public int Insert(T? obj, int position) public int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null)
{ {
if (Count == _maxCount) return -1; if (position < 0 || position > Count)
if (position < 0 || position >= Count) return -1; {
throw new PositionOutOfCollectionException(position);
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position < 0 || position >= Count) return null; if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
T? obj = _collection[position]; T? obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@@ -1,4 +1,6 @@
using System; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -9,15 +11,14 @@ namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
{ {
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length; public int Count => _collection.Length;
public int MaxCount
public int SetMaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@@ -34,9 +35,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
/// <summary> public CollectionType GetCollectionType => CollectionType.Massive;
/// Конструктор
/// </summary>
public MassiveGenericObjects() public MassiveGenericObjects()
{ {
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
@@ -45,13 +45,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= _collection.Length) if (position < 0 || position >= _collection.Length)
{
return null; return null;
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null)
public int Insert(T obj)
{ {
for (int i = 0; i < _collection.Length; i++) for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@@ -59,49 +68,76 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; return i;
} }
} }
return -1;
}
public int Insert(T obj, int position) throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null)
{ {
if (position < 0 || position >= _collection.Length) { return position; } // TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если такой объект есть в коллекции
// TODO выброс ошибки, если переполнение
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
else
{
for (int i = position + 1; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
for (int i = position - 1; i >= 0; i--) for (int i = position + 1; i < Count; i++)
{
if (_collection[i] == null)
{ {
if (_collection[i] == null) _collection[i] = obj;
{ return i;
_collection[i] = obj;
return i;
}
} }
} }
return -1; for (int i = position - 1; i >= 0; i--)
} {
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
public T? Remove(int position) throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{ {
if (position < 0 || position >= _collection.Length || _collection[position] == null) if (position < 0 || position >= _collection.Length)
return null; {
T? temp = _collection[position]; throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
} }
} }

View File

@@ -1,4 +1,6 @@
using System; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -7,24 +9,29 @@ using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningTank
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItem = ";";
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@@ -32,18 +39,21 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(CollectionInfo info)
{ {
if (string.IsNullOrEmpty(name)) return; if (info == null || _storages.ContainsKey(info))
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
if (collectionType == CollectionType.Massive)
{ {
_storages[name] = new MassiveGenericObjects<T>(); return;
} }
else if (collectionType == CollectionType.List)
if (info.CollectionType == CollectionType.Massive)
{ {
_storages[name] = new ListGenericObjects<T>(); _storages.Add(info, new MassiveGenericObjects<T>());
}
if (info.CollectionType == CollectionType.List)
{
_storages.Add(info, new ListGenericObjects<T>());
} }
} }
@@ -51,12 +61,14 @@ public class StorageCollection<T>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(CollectionInfo info)
{ {
if (_storages.ContainsKey(name)) if (info == null || !_storages.ContainsKey(info))
{ {
_storages.Remove(name); return;
} }
_storages.Remove(info);
} }
/// <summary> /// <summary>
@@ -64,15 +76,134 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <returns></returns> /// <returns></returns>
public ICollectionGenericObjects<T>? this[string name] public ICollectionGenericObjects<T>? this[CollectionInfo info]
{ {
get get
{ {
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(info))
{ {
return _storages[name]; return _storages[info];
} }
return null; return null;
} }
} }
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)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItem);
}
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new(filename))
{
string line = sr.ReadLine();
if (line == null || line.Length == 0)
{
throw new FileFormatException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
while ((line = sr.ReadLine()) != null)
{
string[] record = line.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("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTank() is T warship)
{
try
{
if (collection.Insert(warship, new DrawningTankEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new OverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }

View File

@@ -15,7 +15,7 @@ public class TankSharingService : AbstractCompany
{ {
} }
protected override void DrawBackgound(Graphics g) protected override void DrawBackground(Graphics g)
{ {
int width = _pictureWidth / _placeSizeWidth; int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight; int height = _pictureHeight / _placeSizeHeight;
@@ -36,25 +36,25 @@ public class TankSharingService : AbstractCompany
int width = _pictureWidth / _placeSizeWidth; int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight; int height = _pictureHeight / _placeSizeHeight;
int tankWidth = 0; int locomotiveWidth = 0;
int tankHeight = height - 1; int locomotiveHeight = height - 1;
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (_collection.Get(i) != null) if (_collection.Get(i) != null)
{ {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * tankWidth + 20, tankHeight * _placeSizeHeight + 20); _collection.Get(i).SetPosition(_placeSizeWidth * locomotiveWidth + 20, locomotiveHeight * _placeSizeHeight + 20);
} }
if (tankWidth < width - 1) if (locomotiveWidth < width - 1)
tankWidth++; locomotiveWidth++;
else else
{ {
tankWidth = 0; locomotiveWidth = 0;
tankHeight--; locomotiveHeight--;
} }
if (tankHeight < 0) if (locomotiveHeight < 0)
{ {
return; return;
} }

View File

@@ -20,7 +20,10 @@ public class DrawningArtillery : DrawningTank
{ {
EntityTank = new EntityArtillery(speed, weight, bodyColor, additionalColor, cannon, rocket); EntityTank = new EntityArtillery(speed, weight, bodyColor, additionalColor, cannon, rocket);
} }
public DrawningArtillery(EntityArtillery tank) : base(130, 20)
{
EntityTank = tank;
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {

View File

@@ -76,6 +76,10 @@ public class DrawningTank
_drawningTankWidth = drawningTankWidth; _drawningTankWidth = drawningTankWidth;
_pictureHeight = drawningTankHeight; _pictureHeight = drawningTankHeight;
} }
public DrawningTank(EntityTank tank)
{
EntityTank = tank;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>

View File

@@ -0,0 +1,44 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawningTankCompareByColor : IComparer<DrawningTank?>
{
public int Compare(DrawningTank? x, DrawningTank? y)
{
// TODO прописать логику сравения по цветам, скорости, весу
if (x == null || x.EntityTank == null)
{
return 1;
}
if (y == null || y.EntityTank == null)
{
return -1;
}
var bodyColorCompare = y.EntityTank.BodyColor.Name.CompareTo(x.EntityTank.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x is DrawningArtillery && y is DrawningArtillery)
{
var additionalColorCompare = (y.EntityTank as EntityArtillery).AdditionalColor.Name.CompareTo(
(x.EntityTank as EntityArtillery).AdditionalColor.Name);
if (additionalColorCompare != 0)
{
return additionalColorCompare;
}
}
var speedCompare = y.EntityTank.Speed.CompareTo(x.EntityTank.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTank.Weight.CompareTo(x.EntityTank.Weight);
}
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawningTankCompareByType : IComparer<DrawningTank?>
{
public int Compare(DrawningTank? x, DrawningTank? y)
{
if (x == null || x.EntityTank == null)
{
return 1;
}
if (y == null || y.EntityTank == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return y.GetType().Name.CompareTo(x.GetType().Name);
}
var speedCompare = y.EntityTank.Speed.CompareTo(x.EntityTank.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTank.Weight.CompareTo(x.EntityTank.Weight);
}
}

View File

@@ -0,0 +1,65 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawningTankEqutables : IEqualityComparer<DrawningTank?>
{
public bool Equals(DrawningTank? x, DrawningTank? y)
{
if (x == null || x.EntityTank == null)
{
return false;
}
if (y == null || y.EntityTank == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTank.Speed != y.EntityTank.Speed)
{
return false;
}
if (x.EntityTank.Weight != y.EntityTank.Weight)
{
return false;
}
if (x.EntityTank.BodyColor != y.EntityTank.BodyColor)
{
return false;
}
if (x is DrawningArtillery && y is DrawningArtillery)
{
// TODO доделать логику сравнения дополнительных параметров
if ((x.EntityTank as EntityArtillery)?.AdditionalColor !=
(y.EntityTank as EntityArtillery)?.AdditionalColor)
{
return false;
}
if ((x.EntityTank as EntityArtillery)?.Rocket !=
(y.EntityTank as EntityArtillery)?.Rocket)
{
return false;
}
if ((x.EntityTank as EntityArtillery)?.Cannon !=
(y.EntityTank as EntityArtillery)?.Cannon)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTank? obj)
{
return obj.GetHashCode();
}
}

View File

@@ -0,0 +1,51 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public static class ExtentionDrawningTank
{
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строк характеристик
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningTank? CreateDrawningTank(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTank? tank = EntityArtillery.CreateEntityArtillery(strs);
if (tank != null && tank is EntityArtillery tankA)
{
return new DrawningArtillery(tankA);
}
tank = EntityTank.CreateEntityTank(strs);
if (tank != null)
{
return new DrawningTank(tank);
}
return null;
}
/// <summary>
/// Подготовка данных для сохранения в файл
/// </summary>
/// <param name="drawningTank"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningTank drawningTank)
{
string[]? array = drawningTank?.EntityTank?.GetStringRepresentation();
if (array == null) { return string.Empty; }
return string.Join(_separatorForObject, array);
}
}

View File

@@ -38,6 +38,28 @@ public class EntityArtillery : EntityTank
Cannon = cannon; Cannon = cannon;
Rocket = rocket; Rocket = rocket;
} }
/// <summary>
/// Получение строк характеристик
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityArtillery), Speed.ToString(), Weight.ToString(), BodyColor.Name,
AdditionalColor.Name, Cannon.ToString(), Rocket.ToString() };
}
/// <summary>
/// Создание объекта по строкам характеристик
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityArtillery? CreateEntityArtillery(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityArtillery)) { return null; }
return new EntityArtillery(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]),
Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
} }

View File

@@ -35,5 +35,22 @@ public class EntityTank
BodyColor = bodyColor; BodyColor = bodyColor;
} }
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTank), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта по строкам характеристик
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTank? CreateEntityTank(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTank)) { return null; }
return new EntityTank(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace SelfPropelledArtilleryUnit.Exceptions;
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count : " + 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,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Exceptions;
[Serializable]
public 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,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Exceptions;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -29,6 +29,14 @@
private void InitializeComponent() private void InitializeComponent()
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddTank = new Button();
buttonRefresh = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonGoToCheak = new Button();
buttonRemoveTank = new Button();
buttonCreateCompany = new Button(); buttonCreateCompany = new Button();
panelStorage = new Panel(); panelStorage = new Panel();
buttonCollectionDel = new Button(); buttonCollectionDel = new Button();
@@ -38,19 +46,19 @@
radioButtonMassive = new RadioButton(); radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox(); textBoxCollectionName = new TextBox();
labelCollectionName = new Label(); labelCollectionName = new Label();
buttonRefresh = new Button();
buttonGoToCheak = new Button();
buttonRemoveTank = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddTank = new Button();
buttonAddArtillery = new Button();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
panelCompanyTools = new Panel(); menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
panelCompanyTools.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@@ -60,13 +68,104 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(715, 0); groupBoxTools.Location = new Point(715, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 508); groupBoxTools.Size = new Size(200, 528);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTank);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheak);
panelCompanyTools.Controls.Add(buttonRemoveTank);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 297);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 228);
panelCompanyTools.TabIndex = 9;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(12, 196);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(170, 23);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(12, 165);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(170, 25);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddTank
//
buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTank.Location = new Point(12, 0);
buttonAddTank.Name = "buttonAddTank";
buttonAddTank.Size = new Size(170, 30);
buttonAddTank.TabIndex = 2;
buttonAddTank.Text = "Добавление танка";
buttonAddTank.UseVisualStyleBackColor = true;
buttonAddTank.Click += ButtonAddTank_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(12, 128);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(170, 23);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(12, 36);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(176, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonGoToCheak
//
buttonGoToCheak.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheak.Location = new Point(12, 97);
buttonGoToCheak.Name = "buttonGoToCheak";
buttonGoToCheak.Size = new Size(170, 25);
buttonGoToCheak.TabIndex = 5;
buttonGoToCheak.Text = "Передать на тесты";
buttonGoToCheak.UseVisualStyleBackColor = true;
buttonGoToCheak.Click += ButtonGoToCheak_Click;
//
// buttonRemoveTank
//
buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTank.Location = new Point(12, 64);
buttonRemoveTank.Name = "buttonRemoveTank";
buttonRemoveTank.Size = new Size(170, 27);
buttonRemoveTank.TabIndex = 4;
buttonRemoveTank.Text = "Удалить танк";
buttonRemoveTank.UseVisualStyleBackColor = true;
buttonRemoveTank.Click += ButtonRemoveTank_Click;
//
// buttonCreateCompany // buttonCreateCompany
// //
buttonCreateCompany.Location = new Point(5, 267); buttonCreateCompany.Location = new Point(5, 267);
@@ -159,69 +258,6 @@
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:"; labelCollectionName.Text = "Название коллекции:";
// //
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(12, 174);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(170, 23);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheak
//
buttonGoToCheak.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheak.Location = new Point(12, 143);
buttonGoToCheak.Name = "buttonGoToCheak";
buttonGoToCheak.Size = new Size(170, 25);
buttonGoToCheak.TabIndex = 5;
buttonGoToCheak.Text = "Передать на тесты";
buttonGoToCheak.UseVisualStyleBackColor = true;
buttonGoToCheak.Click += ButtonGoToCheak_Click;
//
// buttonRemoveTank
//
buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTank.Location = new Point(12, 110);
buttonRemoveTank.Name = "buttonRemoveTank";
buttonRemoveTank.Size = new Size(170, 27);
buttonRemoveTank.TabIndex = 4;
buttonRemoveTank.Text = "Удалить танк";
buttonRemoveTank.UseVisualStyleBackColor = true;
buttonRemoveTank.Click += ButtonRemoveTank_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(12, 82);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(176, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonAddTank
//
buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTank.Location = new Point(12, 9);
buttonAddTank.Name = "buttonAddTank";
buttonAddTank.Size = new Size(170, 30);
buttonAddTank.TabIndex = 2;
buttonAddTank.Text = "Добавление танка";
buttonAddTank.UseVisualStyleBackColor = true;
buttonAddTank.Click += ButtonAddTank_Click;
//
// buttonAddArtillery
//
buttonAddArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddArtillery.Location = new Point(12, 45);
buttonAddArtillery.Name = "buttonAddArtillery";
buttonAddArtillery.Size = new Size(170, 31);
buttonAddArtillery.TabIndex = 1;
buttonAddArtillery.Text = "Добавление сау";
buttonAddArtillery.UseVisualStyleBackColor = true;
//
// comboBoxSelectorCompany // comboBoxSelectorCompany
// //
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@@ -237,43 +273,75 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(715, 508); pictureBox.Size = new Size(715, 528);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
pictureBox.Click += pictureBox_Click;
// //
// panelCompanyTools // menuStrip
// //
panelCompanyTools.Controls.Add(buttonAddTank); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
panelCompanyTools.Controls.Add(buttonAddArtillery); menuStrip.Location = new Point(0, 0);
panelCompanyTools.Controls.Add(buttonRefresh); menuStrip.Name = "menuStrip";
panelCompanyTools.Controls.Add(maskedTextBoxPosition); menuStrip.Size = new Size(915, 24);
panelCompanyTools.Controls.Add(buttonGoToCheak); menuStrip.TabIndex = 2;
panelCompanyTools.Controls.Add(buttonRemoveTank); menuStrip.Text = "menuStrip1";
panelCompanyTools.Dock = DockStyle.Bottom; //
panelCompanyTools.Enabled = false; // файлToolStripMenuItem
panelCompanyTools.Location = new Point(3, 300); //
panelCompanyTools.Name = "panelCompanyTools"; файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
panelCompanyTools.Size = new Size(194, 205); файлToolStripMenuItem.Name = айлToolStripMenuItem";
panelCompanyTools.TabIndex = 9; файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
// //
// FormTankCollection // FormTankCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(915, 508); ClientSize = new Size(915, 552);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTankCollection"; Name = "FormTankCollection";
Text = "Коллекция сау"; Text = "Коллекция сау";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
panelCompanyTools.ResumeLayout(false); menuStrip.ResumeLayout(false);
panelCompanyTools.PerformLayout(); menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -281,7 +349,6 @@
private GroupBox groupBoxTools; private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private Button buttonAddTank; private Button buttonAddTank;
private Button buttonAddArtillery;
private MaskedTextBox maskedTextBoxPosition; private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox; private PictureBox pictureBox;
private Button buttonRemoveTank; private Button buttonRemoveTank;
@@ -297,5 +364,13 @@
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Button buttonCollectionDel; private Button buttonCollectionDel;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@@ -1,7 +1,8 @@
 using Microsoft.Extensions.Logging;
using NLog;
using SelfPropelledArtilleryUnit.CollectionGenericObjects; using SelfPropelledArtilleryUnit.CollectionGenericObjects;
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit; namespace SelfPropelledArtilleryUnit;
@@ -12,14 +13,15 @@ public partial class FormTankCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
private readonly StorageCollection<DrawningTank> _storageCollection; private readonly StorageCollection<DrawningTank> _storageCollection;
private readonly Microsoft.Extensions.Logging.ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormTankCollection() public FormTankCollection(ILogger<FormTankCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
@@ -46,19 +48,33 @@ public partial class FormTankCollection : Form
/// <param name="tank"></param> /// <param name="tank"></param>
private void SetTank(DrawningTank? tank) private void SetTank(DrawningTank? tank)
{ {
if (_company == null || tank == null) try
{ {
return; if (_company == null || tank == null)
} {
return;
}
if (_company + tank != -1) if (_company + tank != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
}
else
{
MessageBox.Show("Такой объект уже есть в коллекции");
}
} }
else catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
} }
} }
@@ -80,16 +96,25 @@ public partial class FormTankCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); if (_company - pos != null)
pictureBox.Image = _company.Show(); {
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show();
}
} }
else catch (ObjectNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
} }
} }
@@ -142,26 +167,34 @@ public partial class FormTankCollection : Form
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{ {
collectionType = CollectionType.Massive; CollectionType collectionType = CollectionType.None;
} if (radioButtonMassive.Checked)
else if (radioButtonList.Checked) {
{ collectionType = CollectionType.Massive;
collectionType = CollectionType.List; }
} else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(collectionInfo);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
{ {
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@@ -176,12 +209,21 @@ public partial class FormTankCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) try
{ {
return; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
} }
private void ButtonCreateCompany_Click(object sender, EventArgs e) private void ButtonCreateCompany_Click(object sender, EventArgs e)
@@ -192,7 +234,8 @@ public partial class FormTankCollection : Form
return; return;
} }
ICollectionGenericObjects<DrawningTank>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningTank>? collection = _storageCollection[collectionInfo];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
@@ -208,5 +251,93 @@ public partial class FormTankCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
}
private void pictureBox_Click(object sender, EventArgs e)
{
}
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
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);
}
}
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTanks(new DrawningTankCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTanks(new DrawningTankCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareTanks(IComparer<DrawningTank?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@@ -117,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root> </root>

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using NLog.Extensions.Logging;
namespace SelfPropelledArtilleryUnit namespace SelfPropelledArtilleryUnit
{ {
internal static class Program internal static class Program
@@ -10,8 +15,21 @@ namespace SelfPropelledArtilleryUnit
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ServiceCollection services = new();
ConfigureServices(services);
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormTankCollection()); ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTankCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTankCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@@ -8,6 +8,13 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="NLog" Version="5.3.4" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.14" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@@ -23,4 +30,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

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="locomotivelog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>