This commit is contained in:
dyakonovr 2023-12-16 23:50:00 +04:00
parent 2468f39500
commit 2b49c57bd9
9 changed files with 245 additions and 28 deletions

View File

@ -39,6 +39,8 @@
listBoxStorages = new ListBox(); listBoxStorages = new ListBox();
deleteObjectButton = new Button(); deleteObjectButton = new Button();
groupBox1 = new GroupBox(); groupBox1 = new GroupBox();
sortByColorButton = new Button();
sortByTypeButton = new Button();
menuStrip = new MenuStrip(); menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem(); fileToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
@ -60,7 +62,7 @@
// //
// refreshObjectsButton // refreshObjectsButton
// //
refreshObjectsButton.Location = new Point(6, 410); refreshObjectsButton.Location = new Point(6, 440);
refreshObjectsButton.Name = "refreshObjectsButton"; refreshObjectsButton.Name = "refreshObjectsButton";
refreshObjectsButton.Size = new Size(139, 29); refreshObjectsButton.Size = new Size(139, 29);
refreshObjectsButton.TabIndex = 4; refreshObjectsButton.TabIndex = 4;
@ -70,7 +72,7 @@
// //
// deleteTankButton // deleteTankButton
// //
deleteTankButton.Location = new Point(6, 377); deleteTankButton.Location = new Point(6, 404);
deleteTankButton.Name = "deleteTankButton"; deleteTankButton.Name = "deleteTankButton";
deleteTankButton.Size = new Size(139, 29); deleteTankButton.Size = new Size(139, 29);
deleteTankButton.TabIndex = 5; deleteTankButton.TabIndex = 5;
@ -80,7 +82,7 @@
// //
// addTankButton // addTankButton
// //
addTankButton.Location = new Point(6, 307); addTankButton.Location = new Point(6, 338);
addTankButton.Name = "addTankButton"; addTankButton.Name = "addTankButton";
addTankButton.Size = new Size(139, 29); addTankButton.Size = new Size(139, 29);
addTankButton.TabIndex = 6; addTankButton.TabIndex = 6;
@ -90,7 +92,7 @@
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Location = new Point(6, 344); maskedTextBoxNumber.Location = new Point(6, 373);
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(139, 27); maskedTextBoxNumber.Size = new Size(139, 27);
maskedTextBoxNumber.TabIndex = 7; maskedTextBoxNumber.TabIndex = 7;
@ -106,14 +108,14 @@
// //
// textBoxStorageName // textBoxStorageName
// //
textBoxStorageName.Location = new Point(6, 67); textBoxStorageName.Location = new Point(6, 59);
textBoxStorageName.Name = "textBoxStorageName"; textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(139, 27); textBoxStorageName.Size = new Size(139, 27);
textBoxStorageName.TabIndex = 9; textBoxStorageName.TabIndex = 9;
// //
// addObjectButton // addObjectButton
// //
addObjectButton.Location = new Point(6, 100); addObjectButton.Location = new Point(6, 92);
addObjectButton.Name = "addObjectButton"; addObjectButton.Name = "addObjectButton";
addObjectButton.Size = new Size(139, 29); addObjectButton.Size = new Size(139, 29);
addObjectButton.TabIndex = 10; addObjectButton.TabIndex = 10;
@ -125,7 +127,7 @@
// //
listBoxStorages.FormattingEnabled = true; listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20; listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(6, 135); listBoxStorages.Location = new Point(6, 131);
listBoxStorages.Name = "listBoxStorages"; listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(139, 84); listBoxStorages.Size = new Size(139, 84);
listBoxStorages.TabIndex = 11; listBoxStorages.TabIndex = 11;
@ -133,7 +135,7 @@
// //
// deleteObjectButton // deleteObjectButton
// //
deleteObjectButton.Location = new Point(6, 234); deleteObjectButton.Location = new Point(6, 222);
deleteObjectButton.Name = "deleteObjectButton"; deleteObjectButton.Name = "deleteObjectButton";
deleteObjectButton.Size = new Size(139, 29); deleteObjectButton.Size = new Size(139, 29);
deleteObjectButton.TabIndex = 12; deleteObjectButton.TabIndex = 12;
@ -143,6 +145,8 @@
// //
// groupBox1 // groupBox1
// //
groupBox1.Controls.Add(sortByColorButton);
groupBox1.Controls.Add(sortByTypeButton);
groupBox1.Controls.Add(label2); groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(refreshObjectsButton); groupBox1.Controls.Add(refreshObjectsButton);
groupBox1.Controls.Add(deleteTankButton); groupBox1.Controls.Add(deleteTankButton);
@ -159,6 +163,26 @@
groupBox1.TabStop = false; groupBox1.TabStop = false;
groupBox1.Text = "Инструменты"; groupBox1.Text = "Инструменты";
// //
// sortByColorButton
//
sortByColorButton.Location = new Point(6, 297);
sortByColorButton.Name = "sortByColorButton";
sortByColorButton.Size = new Size(139, 29);
sortByColorButton.TabIndex = 14;
sortByColorButton.Text = "Сорт. по цвету";
sortByColorButton.UseVisualStyleBackColor = true;
sortByColorButton.Click += ButtonSortByColor_Click;
//
// sortByTypeButton
//
sortByTypeButton.Location = new Point(6, 262);
sortByTypeButton.Name = "sortByTypeButton";
sortByTypeButton.Size = new Size(139, 29);
sortByTypeButton.TabIndex = 13;
sortByTypeButton.Text = "Сорт. по типу";
sortByTypeButton.UseVisualStyleBackColor = true;
sortByTypeButton.Click += ButtonSortByType_Click;
//
// menuStrip // menuStrip
// //
menuStrip.ImageScalingSize = new Size(20, 20); menuStrip.ImageScalingSize = new Size(20, 20);
@ -238,5 +262,7 @@
private ToolStripMenuItem saveToolStripMenuItem; private ToolStripMenuItem saveToolStripMenuItem;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private Button sortByColorButton;
private Button sortByTypeButton;
} }
} }

View File

@ -29,7 +29,7 @@ namespace ProjectTank
for (int i = 0; i < _storage.Keys.Count; i++) for (int i = 0; i < _storage.Keys.Count; i++)
{ {
listBoxStorages.Items.Add(_storage.Keys[i]); listBoxStorages.Items.Add(_storage.Keys[i].Name);
} }
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count)) if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
@ -56,6 +56,35 @@ namespace ProjectTank
Log.Information($"Добавлен набор: {textBoxStorageName.Text}"); Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareTanks(new TankCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareTanks(new TankCompareByColor());
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareTanks(IComparer<DrawningTankBase?> comparer)
{
if (listBoxStorages.SelectedIndex == -1) return;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) return;
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowTanks();
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTanks(); pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTanks();
@ -107,6 +136,11 @@ namespace ProjectTank
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
} }
catch (ArgumentException ex)
{
Log.Warning($"Добавляемый объект уже существует в коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже существует в коллекции");
}
}); });
form.AddEvent(tankDelegate); form.AddEvent(tankDelegate);

View File

@ -0,0 +1,53 @@
using ProjectTank.DrawningObjects;
using ProjectTank.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectTank.Generics
{
internal class DrawningTankBaseEqutables : IEqualityComparer<DrawningTankBase?>
{
public bool Equals(DrawningTankBase? x, DrawningTankBase? y)
{
if (x == null || x.EntityTankBase == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTankBase == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTankBase.Speed != y.EntityTankBase.Speed)
{
return false;
}
if (x.EntityTankBase.Weight != y.EntityTankBase.Weight)
{
return false;
}
if (x.EntityTankBase.BodyColor != y.EntityTankBase.BodyColor)
{
return false;
}
if (x is DrawningTank && y is DrawningTank)
{
EntityTank EntityX = (EntityTank)x.EntityTankBase;
EntityTank EntityY = (EntityTank)y.EntityTankBase;
if (EntityX.AntiAirforceGun != EntityY.AntiAirforceGun)
return false;
if (EntityX.TankTower != EntityY.TankTower)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTankBase obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -27,17 +27,18 @@ namespace ProjectTank.Generics
_maxCount = count; _maxCount = count;
_places = new List<T?>(count); _places = new List<T?>(count);
} }
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
/// </summary> /// </summary>
/// <param name="tank">Добавляемый танк</param> /// <param name="tank">Добавляемый танк</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T tank) public bool Insert(T tank, IEqualityComparer<T>? equal = null)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
Insert(tank, 0); Insert(tank, 0, equal);
return true; return true;
} }
/// <summary> /// <summary>
@ -46,12 +47,17 @@ namespace ProjectTank.Generics
/// <param name="tank">Добавляемый танк</param> /// <param name="tank">Добавляемый танк</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T tank, int position) public bool Insert(T tank, int position, IEqualityComparer<T>? equal = null)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count)) if (!(position >= 0 && position <= Count))
return false; return false;
if (equal != null)
{
if (_places.Contains(tank, equal))
throw new ArgumentException(nameof(tank));
}
_places.Insert(position, tank); _places.Insert(position, tank);
return true; return true;
} }

View File

@ -0,0 +1,42 @@
using ProjectTank.DrawningObjects;
using ProjectTank.Entities;
namespace ProjectTank.Generics
{
internal class TankCompareByColor : IComparer<DrawningTankBase?>
{
public int Compare(DrawningTankBase? x, DrawningTankBase? y)
{
if (x == null || x.EntityTankBase == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityTankBase == null)
throw new ArgumentNullException(nameof(y));
if (x.EntityTankBase.BodyColor.Name != y.EntityTankBase.BodyColor.Name)
{
return x.EntityTankBase.BodyColor.Name.CompareTo(y.EntityTankBase.BodyColor.Name);
}
if (x.GetType().Name != y.GetType().Name)
{
if (x is DrawningTankBase) return -1;
else return 1;
}
if (x.GetType().Name == y.GetType().Name && x is DrawningTank)
{
EntityTank EntityX = (EntityTank)x.EntityTankBase;
EntityTank EntityY = (EntityTank)y.EntityTankBase;
if (EntityX.AdditionalColor.Name != EntityY.AdditionalColor.Name)
{
return EntityX.AdditionalColor.Name.CompareTo(EntityY.AdditionalColor.Name);
}
}
var speedCompare = x.EntityTankBase.Speed.CompareTo(y.EntityTankBase.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityTankBase.Weight.CompareTo(y.EntityTankBase.Weight);
}
}
}

View File

@ -0,0 +1,29 @@
using ProjectTank.DrawningObjects;
namespace ProjectTank.Generics
{
internal class TankCompareByType : IComparer<DrawningTankBase?>
{
public int Compare(DrawningTankBase? x, DrawningTankBase? y)
{
if (x == null || x.EntityTankBase == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTankBase == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTankBase.Speed.CompareTo(y.EntityTankBase.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTankBase.Weight.CompareTo(y.EntityTankBase.Weight);
}
}
}

View File

@ -0,0 +1,22 @@
namespace ProjectTank.Generics
{
internal class TanksCollectionInfo : IEquatable<TanksCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public TanksCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(TanksCollectionInfo? other)
{
if (other == null) return false;
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -48,6 +48,11 @@ namespace ProjectTank.Generics
_collection = new SetGeneric<T>(width * height); _collection = new SetGeneric<T>(width * height);
} }
/// <summary> /// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Перегрузка оператора сложения /// Перегрузка оператора сложения
/// </summary> /// </summary>
/// <param name="collect"></param> /// <param name="collect"></param>
@ -58,7 +63,7 @@ namespace ProjectTank.Generics
if (obj == null) if (obj == null)
return false; return false;
return collect?._collection.Insert(obj) ?? false; return collect?._collection.Insert(obj, new DrawningTankBaseEqutables()) ?? false;
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания

View File

@ -13,12 +13,12 @@ namespace ProjectTank.Generics
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, TanksGenericCollection<DrawningTankBase, readonly Dictionary<TanksCollectionInfo,
DrawningObjectTank>> _tankStorages; TanksGenericCollection<DrawningTankBase, DrawningObjectTank>> _tankStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _tankStorages.Keys.ToList(); public List<TanksCollectionInfo> Keys => _tankStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -46,7 +46,7 @@ namespace ProjectTank.Generics
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public TanksGenericStorage(int pictureWidth, int pictureHeight) public TanksGenericStorage(int pictureWidth, int pictureHeight)
{ {
_tankStorages = new Dictionary<string, _tankStorages = new Dictionary<TanksCollectionInfo,
TanksGenericCollection<DrawningTankBase, DrawningObjectTank>>(); TanksGenericCollection<DrawningTankBase, DrawningObjectTank>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
@ -55,10 +55,10 @@ namespace ProjectTank.Generics
/// Добавление набора /// Добавление набора
/// </summary> /// </summary>
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void AddSet(string name) public void AddSet(string name)
{ {
_tankStorages.Add(name, new TanksGenericCollection<DrawningTankBase, DrawningObjectTank> (_pictureWidth, _pictureHeight)); _tankStorages.Add(new TanksCollectionInfo(name, string.Empty),
new TanksGenericCollection<DrawningTankBase, DrawningObjectTank>(_pictureWidth, _pictureHeight));
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -66,11 +66,10 @@ namespace ProjectTank.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_tankStorages.ContainsKey(name)) if (!_tankStorages.ContainsKey(new TanksCollectionInfo(name, string.Empty)))
return; return;
_tankStorages.Remove(name); _tankStorages.Remove(new TanksCollectionInfo(name, string.Empty));
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
/// </summary> /// </summary>
@ -80,8 +79,9 @@ namespace ProjectTank.Generics
{ {
get get
{ {
if (_tankStorages.ContainsKey(ind)) TanksCollectionInfo indObj = new TanksCollectionInfo(ind, string.Empty);
return _tankStorages[ind]; if (_tankStorages.ContainsKey(indObj))
return _tankStorages[indObj];
return null; return null;
} }
} }
@ -98,19 +98,19 @@ namespace ProjectTank.Generics
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, TanksGenericCollection<DrawningTankBase, DrawningObjectTank>> record in _tankStorages) foreach (KeyValuePair<TanksCollectionInfo, TanksGenericCollection<DrawningTankBase, DrawningObjectTank>> record in _tankStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawningTankBase? elem in record.Value.GetTanks) foreach (DrawningTankBase? elem in record.Value.GetTanks)
{ {
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
} }
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
} }
if (data.Length == 0) if (data.Length == 0)
{ {
throw new Exception("Невалиданя операция, нет данных для сохранения"); throw new Exception("Невалидная операция, нет данных для сохранения");
} }
string toWrite = $"TanksStorage{Environment.NewLine}{data}"; string toWrite = $"TanksStorage{Environment.NewLine}{data}";
@ -178,7 +178,7 @@ namespace ProjectTank.Generics
} }
} }
} }
_tankStorages.Add(record[0], collection); _tankStorages.Add(new TanksCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine(); str = sr.ReadLine();
} while (str != null); } while (str != null);