New thread

This commit is contained in:
Игорь Гордеев 2023-12-29 16:47:18 +04:00
parent 41e57526ba
commit 24b957d2f1
13 changed files with 284 additions and 48 deletions

View File

@ -0,0 +1,57 @@
using ElectricLocomotive.DrawningObject;
using ElectricLocomotive.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ElectricLocomotive
{
internal class DrawningLocomotiveEqutables : IEqualityComparer<DrawningLocomotive?>
{
public bool Equals(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityLocomotive == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityLocomotive.Speed != y.EntityLocomotive.Speed)
{
return false;
}
if (x.EntityLocomotive.Weight != y.EntityLocomotive.Weight)
{
return false;
}
if (x.EntityLocomotive.BodyColor != y.EntityLocomotive.BodyColor)
{
return false;
}
if (x is DrawningElectricLocomotive && y is DrawningElectricLocomotive)
{
if ((x.EntityLocomotive as EntityElectroLocomotive).AdditionalColor != (y.EntityLocomotive as EntityElectroLocomotive).AdditionalColor)
{
return false;
}
if ((x.EntityLocomotive as EntityElectroLocomotive).Horns_1 != (y.EntityLocomotive as EntityElectroLocomotive).Horns_1)
{
return false;
}
if ((x.EntityLocomotive as EntityElectroLocomotive).Horns_2 != (y.EntityLocomotive as EntityElectroLocomotive).Horns_2)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningLocomotive obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -1,10 +1,6 @@
using ElectricLocomotive.DrawningObject;
using ElectricLocomotive.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectricLocomotive
{

View File

@ -31,6 +31,8 @@
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormLocomotiveCollection));
CollectionPictureBox = new PictureBox();
ToolsBox = new GroupBox();
button2 = new Button();
button1 = new Button();
NaborGroupBox = new GroupBox();
ButtomRemoveNabor = new Button();
listBoxStorage = new ListBox();
@ -62,6 +64,8 @@
//
// ToolsBox
//
ToolsBox.Controls.Add(button2);
ToolsBox.Controls.Add(button1);
ToolsBox.Controls.Add(NaborGroupBox);
ToolsBox.Controls.Add(Input);
ToolsBox.Controls.Add(RefreshCollection);
@ -74,6 +78,26 @@
ToolsBox.TabStop = false;
ToolsBox.Text = "Инструменты";
//
// button2
//
button2.Location = new Point(13, 273);
button2.Name = "button2";
button2.Size = new Size(173, 29);
button2.TabIndex = 5;
button2.Text = "Сортировать по цвету";
button2.UseVisualStyleBackColor = true;
button2.Click += ButtonSortByColor_Click;
//
// button1
//
button1.Location = new Point(13, 241);
button1.Name = "button1";
button1.Size = new Size(173, 29);
button1.TabIndex = 4;
button1.Text = "Сортировать по типу";
button1.UseVisualStyleBackColor = true;
button1.Click += ButtonSortByType_Click;
//
// NaborGroupBox
//
NaborGroupBox.Controls.Add(ButtomRemoveNabor);
@ -82,14 +106,14 @@
NaborGroupBox.Controls.Add(textBoxStorageName);
NaborGroupBox.Location = new Point(7, 22);
NaborGroupBox.Name = "NaborGroupBox";
NaborGroupBox.Size = new Size(185, 280);
NaborGroupBox.Size = new Size(185, 213);
NaborGroupBox.TabIndex = 4;
NaborGroupBox.TabStop = false;
NaborGroupBox.Text = "Наборы";
//
// ButtomRemoveNabor
//
ButtomRemoveNabor.Location = new Point(6, 221);
ButtomRemoveNabor.Location = new Point(6, 159);
ButtomRemoveNabor.Name = "ButtomRemoveNabor";
ButtomRemoveNabor.Size = new Size(173, 48);
ButtomRemoveNabor.TabIndex = 3;
@ -101,17 +125,17 @@
//
listBoxStorage.FormattingEnabled = true;
listBoxStorage.ItemHeight = 15;
listBoxStorage.Location = new Point(6, 112);
listBoxStorage.Location = new Point(6, 89);
listBoxStorage.Name = "listBoxStorage";
listBoxStorage.Size = new Size(173, 94);
listBoxStorage.Size = new Size(173, 64);
listBoxStorage.TabIndex = 2;
listBoxStorage.SelectedIndexChanged += listBoxStorage_SelectedIndexChanged;
//
// AddNabor
//
AddNabor.Location = new Point(6, 63);
AddNabor.Location = new Point(6, 51);
AddNabor.Name = "AddNabor";
AddNabor.Size = new Size(173, 43);
AddNabor.Size = new Size(173, 32);
AddNabor.TabIndex = 1;
AddNabor.Text = "Добавить набор";
AddNabor.UseVisualStyleBackColor = true;
@ -119,7 +143,7 @@
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(6, 34);
textBoxStorageName.Location = new Point(6, 22);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(173, 23);
textBoxStorageName.TabIndex = 0;
@ -212,9 +236,9 @@
Controls.Add(menuStrip);
Controls.Add(ToolsBox);
Controls.Add(CollectionPictureBox);
MainMenuStrip = menuStrip;
Name = "FormLocomotiveCollection";
Text = "Коллекция";
MainMenuStrip = menuStrip;
((System.ComponentModel.ISupportInitialize)CollectionPictureBox).EndInit();
ToolsBox.ResumeLayout(false);
ToolsBox.PerformLayout();
@ -246,5 +270,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private GroupBox groupBoxMenu;
private Button button2;
private Button button1;
}
}

View File

@ -3,12 +3,12 @@ using ElectricLocomotive.Generics;
using Microsoft.Extensions.Logging;
using ProjectElectricLocomotive;
using ProjectElectricLocomotive.Exceptions;
using ProjectElectricLocomotive.Generics;
namespace ElectricLocomotive
{
public partial class FormLocomotiveCollection : Form
{
private readonly LocomotiveGenericStorage _storage;
/// <summary>
/// Логер
@ -116,8 +116,13 @@ namespace ElectricLocomotive
MessageBox.Show(ex.Message);
_logger.LogInformation("Не удалось добавить объект");
}
//проверяем, удалось ли нам загрузить объект
catch (ArgumentException)
{
_logger.LogWarning("Добавляемый объект уже существует в коллекции");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
//проверяем, удалось ли нам загрузить объект
}
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
@ -137,7 +142,7 @@ namespace ElectricLocomotive
int pos = Convert.ToInt32(Input.Text);
try
{
if ( obj - pos != null )
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции{pos}");
@ -166,6 +171,25 @@ namespace ElectricLocomotive
}
CollectionPictureBox.Image = obj.ShowLocomotives();
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareLocomotives(new LocomotiveCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareLocomotives(new LocomotiveCompareByColor());
private void CompareLocomotives(IComparer<DrawningLocomotive?> comparer)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
CollectionPictureBox.Image = obj.ShowLocomotives();
}
/// <summary>
/// Обработка нажатия "Сохранение"

View File

@ -118,7 +118,7 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>19, 13</value>
<value>279, 17</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="LoadToolStripMenuItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
@ -141,4 +141,10 @@
hqArRNaMLA7CYANAAGYISIA0/O0/AID67ECmnhNDAAAAAElFTkSuQmCC
</value>
</data>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>146, 17</value>
</metadata>
</root>

View File

@ -30,6 +30,7 @@ namespace ElectricLocomotive
panelColorBlue.MouseDown += PanelColor_MouseDown;
buttonCancelObject.Click += (s, e) => Close();
}
public void AddEvent(Action<DrawningLocomotive> ev)
{

View File

@ -0,0 +1,49 @@

using ElectricLocomotive.DrawningObject;
using ElectricLocomotive.Entities;
namespace ElectricLocomotive
{
internal class LocomotiveCompareByColor : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityLocomotive == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityLocomotive.BodyColor.Name != y.EntityLocomotive.BodyColor.Name)
{
return x.EntityLocomotive.BodyColor.Name.CompareTo(y.EntityLocomotive.BodyColor.Name);
}
if (x.GetType().Name != y.GetType().Name)
{
if (x is DrawningLocomotive)
return -1;
else
return 1;
}
if (x.GetType().Name == y.GetType().Name && x is DrawningLocomotive)
{
EntityElectroLocomotive entityX = (EntityElectroLocomotive)x.EntityLocomotive;
EntityElectroLocomotive entityY = (EntityElectroLocomotive)y.EntityLocomotive;
if (entityX.AdditionalColor.Name != entityY.AdditionalColor.Name)
{
return entityX.AdditionalColor.Name.CompareTo(entityY.AdditionalColor.Name);
}
}
var speedCompare =
x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ElectricLocomotive.DrawningObject;
using ProjectElectricLocomotive.DrawingObjects;
namespace ProjectElectricLocomotive.Generics
{
internal class LocomotiveCompareByType : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityLocomotive == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
}
}
}

View File

@ -13,12 +13,12 @@ namespace ElectricLocomotive.Generics
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive>> _locomotivesStorage;
readonly Dictionary<LocomotivesCollectionInfo, LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive>> _locomotivesStorage;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _locomotivesStorage.Keys.ToList();
public List<LocomotivesCollectionInfo> Keys => _locomotivesStorage.Keys.ToList();
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
@ -32,7 +32,6 @@ namespace ElectricLocomotive.Generics
/// </summary>
private static readonly char _separatorForObject = ':';
private readonly int _pictureWidth;
private readonly int _pictureHeight;
@ -44,7 +43,7 @@ namespace ElectricLocomotive.Generics
/// <param name="pictureHeight"></param>
public LocomotiveGenericStorage(int pictureWidth, int pictureHeight)
{
_locomotivesStorage = new Dictionary<string, LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive>>();
_locomotivesStorage = new Dictionary<LocomotivesCollectionInfo, LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -54,9 +53,10 @@ namespace ElectricLocomotive.Generics
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (!_locomotivesStorage.ContainsKey(name))
if (!_locomotivesStorage.ContainsKey(new LocomotivesCollectionInfo(name, "")))
{
_locomotivesStorage.Add(name, new LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive>(_pictureWidth, _pictureHeight));
_locomotivesStorage.Add(new LocomotivesCollectionInfo(name, ""),
new LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive>(_pictureWidth, _pictureHeight));
}
}
@ -66,9 +66,9 @@ namespace ElectricLocomotive.Generics
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_locomotivesStorage.ContainsKey(name))
if (_locomotivesStorage.ContainsKey(new LocomotivesCollectionInfo(name, "")))
{
_locomotivesStorage.Remove(name);
_locomotivesStorage.Remove(new LocomotivesCollectionInfo(name, ""));
}
}
@ -83,10 +83,9 @@ namespace ElectricLocomotive.Generics
{
get
{
// TODO Продумать логику получения набора
if (_locomotivesStorage.ContainsKey(ind))
if (_locomotivesStorage.ContainsKey(new LocomotivesCollectionInfo(ind, "")))
{
return _locomotivesStorage[ind];
return _locomotivesStorage[new LocomotivesCollectionInfo(ind, "")];
}
return null;
}
@ -104,7 +103,7 @@ namespace ElectricLocomotive.Generics
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive>> record in _locomotivesStorage)
foreach (KeyValuePair<LocomotivesCollectionInfo, LocomotivesGenericCollection<DrawningLocomotive, DrawningObjectLocomotive>> record in _locomotivesStorage)
{
StringBuilder records = new();
foreach (DrawningLocomotive? elem in record.Value.GetLocomotives)
@ -152,7 +151,6 @@ namespace ElectricLocomotive.Generics
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
if (strs == null)
{
throw new FileNotFoundException("Нет данных для загрузки");
@ -176,7 +174,7 @@ namespace ElectricLocomotive.Generics
}
}
}
_locomotivesStorage.Add(record[0], collection);
_locomotivesStorage.Add(new LocomotivesCollectionInfo(record[0], string.Empty), collection);
}
return;
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectricLocomotive.Generics
{
internal class LocomotivesCollectionInfo : IEquatable<LocomotivesCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public LocomotivesCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(LocomotivesCollectionInfo other)
{
if (Name != other?.Name)
return false;
return true;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override string ToString()
{
return Name;
}
}
}

View File

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ElectricLocomotive.DrawningObject;
using ElectricLocomotive.DrawningObject;
using ElectricLocomotive.MovementStrategy;
using ProjectElectricLocomotive.Generics;
@ -19,6 +14,8 @@ namespace ElectricLocomotive.Generics
private readonly int _placeSizeHeight = 90;
private readonly SetGeneric<T> _collection;
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public LocomotivesGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
@ -33,10 +30,8 @@ namespace ElectricLocomotive.Generics
{
return -1;
}
return collect._collection.Insert(locomotive);
return collect._collection.Insert(locomotive, new DrawningLocomotiveEqutables());
}
/// Перегрузка оператора вычитания
public static T? operator -(LocomotivesGenericCollection<T, U> collect, int pos)
{

View File

@ -1,11 +1,12 @@
using ProjectElectricLocomotive.Exceptions;
using ProjectElectricLocomotive;
using ProjectElectricLocomotive.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Generics
namespace ElectricLocomotive
{
internal class SetGeneric<T> where T : class
{
@ -13,25 +14,38 @@ namespace ProjectElectricLocomotive.Generics
public int Count => _places.Count;
/// Максимальное количество объектов в списке
private readonly int _maxCount;
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public int Insert(T loco)
public int Insert(T loco, IEqualityComparer<T?>? equal = null)
{
return Insert(loco, 0);
if (_places.Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
return Insert(loco, 0, equal);
}
public int Insert(T loco, int position)
public int Insert(T loco, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
{
return -1;
}
if (equal != null)
{
foreach (var secondLoco in _places)
{
if (equal.Equals(loco, secondLoco))
{
throw new ArgumentException();
}
}
}
_places.Insert(position, loco);
return position;
}

View File

@ -5,7 +5,7 @@ using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive
namespace ElectricLocomotive
{
[Serializable]
internal class StorageOverflowException : ApplicationException