1 часть

This commit is contained in:
xom9kxom9k 2024-05-12 14:52:01 +04:00
parent c2e1ca2cc1
commit 2258c0b47c
11 changed files with 424 additions and 57 deletions

View File

@ -59,9 +59,10 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="airplan">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningArmoredCar airplan)
public static int operator +(AbstractCompany company, DrawningArmoredCar armoredCar)
{
return company._collection.Insert(airplan);
return company._collection?.Insert(armoredCar, new DrawningArmoredCarEqutables()) ?? throw new DrawingEquitablesException();
}
/// <summary>
@ -108,6 +109,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningArmoredCar?> comparer) =>
_collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона

View File

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

View File

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

View File

@ -52,17 +52,38 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Insert(position, obj);
return position;
}
@ -82,4 +103,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -58,9 +58,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -73,10 +83,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
if (_collection[position] == null)
{
_collection[position] = obj;
@ -123,4 +145,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
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

@ -17,12 +17,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();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
@ -43,7 +43,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -51,25 +51,26 @@ public class StorageCollection<T>
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
public void AddCollection(CollectionInfo collectionInfo)
{
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo);
if (collectionInfo.CollectionType == CollectionType.None)
throw new CollectionTypeException("Пустой тип коллекции");
if (collectionInfo.CollectionType == CollectionType.Massive)
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionInfo.CollectionType == CollectionType.List)
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
public void DelCollection(CollectionInfo collectionInfo)
{
if (_storages.ContainsKey(name))
_storages.Remove(name);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
@ -77,12 +78,12 @@ public class StorageCollection<T>
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
{
get
{
if (_storages.ContainsKey(name))
return _storages[name];
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -104,7 +105,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
@ -143,7 +144,7 @@ public class StorageCollection<T>
{
throw new FileNotFoundException($"{filename} не существует");
}
using (StreamReader reader = new(filename))
using (StreamReader reader = File.OpenText(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
@ -156,41 +157,41 @@ public class StorageCollection<T>
throw new IOException("В файле неверные данные");
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
string strs = "";
while ((strs = reader.ReadLine()) != null)
{
string[] record = line.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
string[] record = strs.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 Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
CollectionInfo? collectionInfo =
CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningArmoredCar() is T armoredCar)
if (elem?.CreateDrawningArmoredCar() is T ship)
{
try
{
if (collection.Insert(armoredCar) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
collection.Insert(ship);
}
catch (CollectionOverflowException ex)
catch (Exception ex)
{
throw new Exception("Коллекция переполнена", ex);
throw new FileFormatException(filename, ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningArmoredCarCompareByColor : IComparer<DrawningArmoredCar?>
{
public int Compare(DrawningArmoredCar? x, DrawningArmoredCar? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityAircraftGun == null)
{
return 1;
}
if (y == null || y.EntityAircraftGun == null)
{
return -1;
}
if (ToHex(x.EntityAircraftGun.BodyColor) != ToHex(y.EntityAircraftGun.BodyColor))
{
return String.Compare(ToHex(x.EntityAircraftGun.BodyColor), ToHex(y.EntityAircraftGun.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityAircraftGun.Speed.CompareTo(y.EntityAircraftGun.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAircraftGun.Weight.CompareTo(y.EntityAircraftGun.Weight);
static String ToHex(Color c)
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningArmoredCarCompareByType : IComparer<DrawningArmoredCar?>
{
public int Compare(DrawningArmoredCar? x, DrawningArmoredCar? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityAircraftGun == null)
{
return 1;
}
if (y == null || y.EntityAircraftGun == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityAircraftGun.Speed.CompareTo(y.EntityAircraftGun.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAircraftGun.Weight.CompareTo(y.EntityAircraftGun.Weight);
}
}

View File

@ -0,0 +1,66 @@
using AntiAircraftGun.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Drawnings;
public class DrawningArmoredCarEqutables : IEqualityComparer<DrawningArmoredCar?>
{
public bool Equals(DrawningArmoredCar? x, DrawningArmoredCar? y)
{
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityAircraftGun != null && y.EntityAircraftGun != null && x.EntityAircraftGun.Speed != y.EntityAircraftGun.Speed)
{
return false;
}
if (x.EntityAircraftGun.Weight != y.EntityAircraftGun.Weight)
{
return false;
}
if (x.EntityAircraftGun.BodyColor != y.EntityAircraftGun.BodyColor)
{
return false;
}
if (x is DrawningAntiAircraftGun && y is DrawningAntiAircraftGun)
{
if (((EntityAntiAircraftGun)x.EntityAircraftGun).AdditionalColor !=
((EntityAntiAircraftGun)y.EntityAircraftGun).AdditionalColor)
{
return false;
}
if (((EntityAntiAircraftGun)x.EntityAircraftGun).Tower !=
((EntityAntiAircraftGun)y.EntityAircraftGun).Tower)
{
return false;
}
if (((EntityAntiAircraftGun)x.EntityAircraftGun).Radar !=
((EntityAntiAircraftGun)y.EntityAircraftGun).Radar)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningArmoredCar obj)
{
return obj.GetHashCode();
}
}

View File

@ -30,6 +30,8 @@
{
groupBoxToools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddArmoredCar = new Button();
maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button();
@ -68,13 +70,15 @@
groupBoxToools.Dock = DockStyle.Right;
groupBoxToools.Location = new Point(1057, 24);
groupBoxToools.Name = "groupBoxToools";
groupBoxToools.Size = new Size(210, 612);
groupBoxToools.Size = new Size(210, 654);
groupBoxToools.TabIndex = 0;
groupBoxToools.TabStop = false;
groupBoxToools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddArmoredCar);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -83,9 +87,31 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 348);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(200, 261);
panelCompanyTools.Size = new Size(200, 306);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(7, 263);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(191, 39);
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(7, 218);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(191, 39);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddArmoredCar
//
buttonAddArmoredCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@ -99,7 +125,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(6, 94);
maskedTextBox.Location = new Point(6, 49);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(194, 23);
@ -109,7 +135,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 216);
buttonRefresh.Location = new Point(7, 173);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(191, 39);
buttonRefresh.TabIndex = 6;
@ -120,7 +146,7 @@
// buttonRemoveArmoredCar
//
buttonRemoveArmoredCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveArmoredCar.Location = new Point(6, 123);
buttonRemoveArmoredCar.Location = new Point(7, 78);
buttonRemoveArmoredCar.Name = "buttonRemoveArmoredCar";
buttonRemoveArmoredCar.Size = new Size(191, 44);
buttonRemoveArmoredCar.TabIndex = 4;
@ -131,7 +157,7 @@
// buttonGoToChek
//
buttonGoToChek.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToChek.Location = new Point(6, 171);
buttonGoToChek.Location = new Point(7, 128);
buttonGoToChek.Name = "buttonGoToChek";
buttonGoToChek.Size = new Size(191, 39);
buttonGoToChek.TabIndex = 5;
@ -248,7 +274,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1057, 612);
pictureBox.Size = new Size(1057, 654);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -296,7 +322,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1267, 636);
ClientSize = new Size(1267, 678);
Controls.Add(pictureBox);
Controls.Add(groupBoxToools);
Controls.Add(menuStrip);
@ -341,5 +367,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -77,7 +77,7 @@ public partial class FormArmoredCarCollection : Form
}
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
@ -343,5 +343,37 @@ public partial class FormArmoredCarCollection : Form
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareCars(new DrawningArmoredCarCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareCars(new DrawningArmoredCarCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareCars(IComparer<DrawningArmoredCar?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}