8 лабораторная работа

This commit is contained in:
cleverman1337 2024-10-16 00:28:16 +03:00
parent 4851fb744c
commit f27e0bf714
13 changed files with 544 additions and 127 deletions

View File

@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
@ -56,7 +57,18 @@ public abstract class AbstractCompany
/// <returns></returns>
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>
@ -87,26 +99,38 @@ public abstract class AbstractCompany
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
DrawBackground(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningTank? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningTank? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTank?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
protected abstract void DrawBackground(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}
}

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.Linq;
using System.Text;
@ -28,7 +29,8 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@ -36,7 +38,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -62,4 +64,9 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Exceptions;
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -51,17 +52,47 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T? obj)
public int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
// 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);
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) throw new CollectionOverflowException(Count);
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (position < 0 || position > Count)
{
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);
return position;
}
@ -81,4 +112,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Exceptions;
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -49,9 +50,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null)
{
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)
{
@ -59,37 +68,51 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
throw new CollectionOverflowException(Count); ;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null)
{
if (position < 0 || position >= _collection.Length) throw new PositionOutOfCollectionException(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)
{
_collection[position] = obj;
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;
}
}
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
@ -113,4 +136,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -14,12 +14,12 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly 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();
private readonly string _collectionKey = "CollectionStorage";
@ -31,7 +31,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -39,18 +39,21 @@ public class StorageCollection<T>
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
public void AddCollection(CollectionInfo info)
{
if (string.IsNullOrEmpty(name)) return;
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
if (collectionType == CollectionType.Massive)
if (info == null || _storages.ContainsKey(info))
{
_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>());
}
}
@ -58,12 +61,14 @@ public class StorageCollection<T>
/// Удаление коллекции
/// </summary>
/// <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>
@ -71,23 +76,24 @@ public class StorageCollection<T>
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo info]
{
get
{
if (_storages.ContainsKey(name))
if (_storages.ContainsKey(info))
{
return _storages[name];
return _storages[info];
}
return null;
}
}
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@ -96,21 +102,20 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -123,61 +128,72 @@ public class StorageCollection<T>
}
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 reader = File.OpenText(filename))
using (StreamReader sr = new(filename))
{
string str = reader.ReadLine();
if (str == null || str.Length == 0)
string line = sr.ReadLine();
if (line == null || line.Length == 0)
{
throw new InvalidOperationException("В файле нет данных");
throw new FileFormatException("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
if (!line.Equals(_collectionKey))
{
throw new InvalidOperationException("В файле не верные данные");
throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = reader.ReadLine()) != null)
while ((line = sr.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
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 tank)
if (elem?.CreateDrawningTank() is T warship)
{
try
{
if (collection.Insert(tank)==-1)
if (collection.Insert(warship, new DrawningTankEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[3]);
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new InvalidOperationException("Коллекция переполнена", ex);
throw new OverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

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 height = _pictureHeight / _placeSizeHeight;

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

@ -30,8 +30,9 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddTank = new Button();
buttonAddArtillery = new Button();
buttonRefresh = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonGoToCheak = new Button();
@ -69,30 +70,53 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(715, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 484);
groupBoxTools.Size = new Size(200, 528);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTank);
panelCompanyTools.Controls.Add(buttonAddArtillery);
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, 276);
panelCompanyTools.Location = new Point(3, 297);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 205);
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, 9);
buttonAddTank.Location = new Point(12, 0);
buttonAddTank.Name = "buttonAddTank";
buttonAddTank.Size = new Size(170, 30);
buttonAddTank.TabIndex = 2;
@ -100,20 +124,10 @@
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;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(12, 174);
buttonRefresh.Location = new Point(12, 128);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(170, 23);
buttonRefresh.TabIndex = 6;
@ -123,7 +137,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(12, 82);
maskedTextBoxPosition.Location = new Point(12, 36);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(176, 23);
@ -133,7 +147,7 @@
// buttonGoToCheak
//
buttonGoToCheak.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheak.Location = new Point(12, 143);
buttonGoToCheak.Location = new Point(12, 97);
buttonGoToCheak.Name = "buttonGoToCheak";
buttonGoToCheak.Size = new Size(170, 25);
buttonGoToCheak.TabIndex = 5;
@ -144,7 +158,7 @@
// buttonRemoveTank
//
buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTank.Location = new Point(12, 110);
buttonRemoveTank.Location = new Point(12, 64);
buttonRemoveTank.Name = "buttonRemoveTank";
buttonRemoveTank.Size = new Size(170, 27);
buttonRemoveTank.TabIndex = 4;
@ -261,7 +275,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(715, 484);
pictureBox.Size = new Size(715, 528);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
pictureBox.Click += pictureBox_Click;
@ -311,7 +325,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(915, 508);
ClientSize = new Size(915, 552);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -335,7 +349,6 @@
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddTank;
private Button buttonAddArtillery;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonRemoveTank;
@ -357,5 +370,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -48,17 +48,22 @@ public partial class FormTankCollection : Form
/// <param name="tank"></param>
private void SetTank(DrawningTank? tank)
{
try {
if (_company == null || tank == null)
try
{
return;
}
if (_company == null || tank == null)
{
return;
}
if (_company + tank != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
if (_company + tank != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
}
else
{
MessageBox.Show("Такой объект уже есть в коллекции");
}
}
catch (CollectionOverflowException ex)
@ -66,7 +71,11 @@ public partial class FormTankCollection : Form
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
/// <summary>
@ -156,12 +165,10 @@ public partial class FormTankCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: заполнены не все данные для добавления коллекции");
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@ -171,8 +178,9 @@ public partial class FormTankCollection : Form
{
collectionType = CollectionType.List;
}
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_storageCollection.AddCollection(collectionInfo);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
@ -186,7 +194,7 @@ public partial class FormTankCollection : 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);
@ -207,7 +215,8 @@ public partial class FormTankCollection : Form
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
@ -225,7 +234,8 @@ public partial class FormTankCollection : Form
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)
{
MessageBox.Show("Коллекция не проинициализирована");
@ -249,15 +259,17 @@ public partial class FormTankCollection : Form
private void RefreshListBoxItems()
{
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))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
@ -294,4 +306,38 @@ public partial class FormTankCollection : Form
}
}
}
/// <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();
}
}