This commit is contained in:
kirin 2023-12-12 13:58:32 +04:00
parent 145c0765f8
commit 56bcc98d9f
9 changed files with 224 additions and 41 deletions

View File

@ -0,0 +1,48 @@
using System.Diagnostics.CodeAnalysis;
namespace ElectricLocomotive;
public class DrawingLocomotivEqutables: IEqualityComparer<DrawingLocomotiv?>
{
public bool Equals(DrawingLocomotiv? x, DrawingLocomotiv? y)
{
if (x == null || x.EntityLocomotiv == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityLocomotiv == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityLocomotiv.Speed != y.EntityLocomotiv.Speed)
{
return false;
}
if (x.EntityLocomotiv.Weight != y.EntityLocomotiv.Weight)
{
return false;
}
if (x.EntityLocomotiv.ColorBody != y.EntityLocomotiv.ColorBody)
{
return false;
}
if (x is DrawingElectricLocomotiv && y is DrawingElectricLocomotiv)
{
EntityElectricLocomotiv EntityX = (EntityElectricLocomotiv)x.EntityLocomotiv;
EntityElectricLocomotiv EntityY = (EntityElectricLocomotiv)y.EntityLocomotiv;
if (EntityX.isBattery != EntityY.isBattery)
return false;
if (EntityX.isRoga != EntityY.isRoga)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingLocomotiv obj)
{
return obj.GetHashCode();
}
}

View File

@ -44,6 +44,8 @@ partial class FormLocomotivCollection {
LoadToolStripMenuItem = new ToolStripMenuItem(); LoadToolStripMenuItem = new ToolStripMenuItem();
loadFileDialog = new OpenFileDialog(); loadFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
toolsBox.SuspendLayout(); toolsBox.SuspendLayout();
collectionGroupBoxes.SuspendLayout(); collectionGroupBoxes.SuspendLayout();
((ISupportInitialize)collectionPictureBox).BeginInit(); ((ISupportInitialize)collectionPictureBox).BeginInit();
@ -52,6 +54,8 @@ partial class FormLocomotivCollection {
// //
// toolsBox // toolsBox
// //
toolsBox.Controls.Add(ButtonSortByType);
toolsBox.Controls.Add(ButtonSortByColor);
toolsBox.Controls.Add(collectionGroupBoxes); toolsBox.Controls.Add(collectionGroupBoxes);
toolsBox.Controls.Add(refreshCollection); toolsBox.Controls.Add(refreshCollection);
toolsBox.Controls.Add(deleteLoco); toolsBox.Controls.Add(deleteLoco);
@ -126,7 +130,7 @@ partial class FormLocomotivCollection {
// //
// deleteLoco // deleteLoco
// //
deleteLoco.Location = new Point(21, 559); deleteLoco.Location = new Point(21, 568);
deleteLoco.Name = "deleteLoco"; deleteLoco.Name = "deleteLoco";
deleteLoco.Size = new Size(271, 59); deleteLoco.Size = new Size(271, 59);
deleteLoco.TabIndex = 2; deleteLoco.TabIndex = 2;
@ -136,14 +140,14 @@ partial class FormLocomotivCollection {
// //
// locoIndexInput // locoIndexInput
// //
locoIndexInput.Location = new Point(53, 512); locoIndexInput.Location = new Point(54, 526);
locoIndexInput.Name = "locoIndexInput"; locoIndexInput.Name = "locoIndexInput";
locoIndexInput.Size = new Size(214, 27); locoIndexInput.Size = new Size(214, 27);
locoIndexInput.TabIndex = 1; locoIndexInput.TabIndex = 1;
// //
// addLocomotiv // addLocomotiv
// //
addLocomotiv.Location = new Point(21, 431); addLocomotiv.Location = new Point(21, 461);
addLocomotiv.Name = "addLocomotiv"; addLocomotiv.Name = "addLocomotiv";
addLocomotiv.Size = new Size(271, 59); addLocomotiv.Size = new Size(271, 59);
addLocomotiv.TabIndex = 0; addLocomotiv.TabIndex = 0;
@ -199,6 +203,26 @@ partial class FormLocomotivCollection {
// //
saveFileDialog.Filter = "txt file | *.txt"; saveFileDialog.Filter = "txt file | *.txt";
// //
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(21, 369);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(271, 32);
ButtonSortByColor.TabIndex = 7;
ButtonSortByColor.Text = "Сортировать по Цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(21, 407);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(271, 32);
ButtonSortByType.TabIndex = 8;
ButtonSortByType.Text = "Сортировать по Типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// FormLocomotivCollection // FormLocomotivCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
@ -240,4 +264,6 @@ partial class FormLocomotivCollection {
private ToolStripMenuItem LoadToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog loadFileDialog; private OpenFileDialog loadFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private Button ButtonSortByType;
private Button ButtonSortByColor;
} }

View File

@ -14,7 +14,7 @@ public partial class FormLocomotivCollection : Form {
int index = storageListBox.SelectedIndex; int index = storageListBox.SelectedIndex;
storageListBox.Items.Clear(); storageListBox.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) { for (int i = 0; i < _storage.Keys.Count; i++) {
storageListBox.Items.Add(_storage.Keys[i]); storageListBox.Items.Add(_storage.Keys[i].Name);
} }
if (storageListBox.Items.Count > 0 && (index == -1 || index if (storageListBox.Items.Count > 0 && (index == -1 || index
>= storageListBox.Items.Count)) { >= storageListBox.Items.Count)) {
@ -37,19 +37,21 @@ public partial class FormLocomotivCollection : Form {
FormLocoConfig form = new(); FormLocoConfig form = new();
form.Show(); form.Show();
Action<DrawingLocomotiv>? monorailDelegate = new((m) => { Action<DrawingLocomotiv>? monorailDelegate = new((m) => {
try try {
{
bool q = obj + m; bool q = obj + m;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {storageListBox.SelectedItem.ToString() ?? string.Empty}"); Log.Information($"Добавлен объект в коллекцию {storageListBox.SelectedItem.ToString() ?? string.Empty}");
m.ChangePictureBoxSize(collectionPictureBox.Width, collectionPictureBox.Height); m.ChangePictureBoxSize(collectionPictureBox.Width, collectionPictureBox.Height);
collectionPictureBox.Image = obj.ShowLocos(); collectionPictureBox.Image = obj.ShowLocos();
} }
catch (StorageOverflowException ex) catch (StorageOverflowException ex) {
{
Log.Warning($"Коллекция {storageListBox.SelectedItem.ToString() ?? string.Empty} переполнена"); Log.Warning($"Коллекция {storageListBox.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
} }
catch (ArgumentException ex) {
Log.Warning($"Добавляемый объект уже существует в коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
}); });
form.AddEvent(monorailDelegate); form.AddEvent(monorailDelegate);
} }
@ -67,21 +69,18 @@ public partial class FormLocomotivCollection : Form {
return; return;
} }
try try {
{
int pos = Convert.ToInt32(locoIndexInput.Text); int pos = Convert.ToInt32(locoIndexInput.Text);
var q = obj - pos; var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); Log.Information($"Удален объект из коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
collectionPictureBox.Image = obj.ShowLocos(); collectionPictureBox.Image = obj.ShowLocos();
} }
catch(LocoNotFoundException ex) catch (LocoNotFoundException ex) {
{
Log.Warning($"Не получилось удалить объект из коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty}"); Log.Warning($"Не получилось удалить объект из коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
} }
catch(FormatException ex) catch (FormatException ex) {
{
Log.Warning($"Было введено не число"); Log.Warning($"Было введено не число");
MessageBox.Show("Введите число"); MessageBox.Show("Введите число");
} }
@ -130,15 +129,13 @@ public partial class FormLocomotivCollection : Form {
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { private void SaveToolStripMenuItem_Click(object sender, EventArgs e) {
if (saveFileDialog.ShowDialog() == DialogResult.OK) { if (saveFileDialog.ShowDialog() == DialogResult.OK) {
try try {
{
_storage.SaveData(saveFileDialog.FileName); _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен"); Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
catch (Exception ex) catch (Exception ex) {
{
Log.Warning("Не удалось сохранить"); Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -148,24 +145,37 @@ public partial class FormLocomotivCollection : Form {
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { private void LoadToolStripMenuItem_Click(object sender, EventArgs e) {
if (loadFileDialog.ShowDialog() == DialogResult.OK) { if (loadFileDialog.ShowDialog() == DialogResult.OK) {
try try {
{
_storage.LoadData(loadFileDialog.FileName); _storage.LoadData(loadFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {loadFileDialog.FileName} успешно загружен"); Log.Information($"Файл {loadFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys) foreach (var collection in _storage.Keys) {
{
storageListBox.Items.Add(collection); storageListBox.Items.Add(collection);
} }
ReloadObjects(); ReloadObjects();
} }
catch (Exception ex) catch (Exception ex) {
{
Log.Warning("Не удалось загрузить"); Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", MessageBox.Show($"Не загрузилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
private void CompareLocos(IComparer<DrawingLocomotiv?> comparer) {
if (storageListBox.SelectedIndex == -1) {
return;
}
var obj = _storage[storageListBox.SelectedItem.ToString() ??
string.Empty];
if (obj == null) {
return;
}
obj.Sort(comparer);
collectionPictureBox.Image = obj.ShowLocos();
}
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareLocos(new LocomotivCompareByType());
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareLocos(new LocomotivCompareByColor());
} }

View File

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

View File

@ -0,0 +1,40 @@
namespace ElectricLocomotive;
public class LocomotivCompareByColor : IComparer<DrawingLocomotiv?>
{
public int Compare(DrawingLocomotiv? x, DrawingLocomotiv? y)
{
if (x == null || x.EntityLocomotiv == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityLocomotiv == null)
throw new ArgumentNullException(nameof(y));
if (x.EntityLocomotiv.ColorBody.Name != y.EntityLocomotiv.ColorBody.Name)
{
return x.EntityLocomotiv.ColorBody.GetBrightness().CompareTo(y.EntityLocomotiv.ColorBody.GetBrightness());
}
if (x.GetType().Name != y.GetType().Name)
{
if (x is DrawingLocomotiv)
return -1;
else
return 1;
}
if (x.GetType().Name == y.GetType().Name && x is DrawingLocomotiv)
{
EntityElectricLocomotiv EntityX = (EntityElectricLocomotiv)x.EntityLocomotiv;
EntityElectricLocomotiv EntityY = (EntityElectricLocomotiv)y.EntityLocomotiv;
if(EntityX.RogaColor.Name != EntityY.RogaColor.Name)
{
return EntityX.RogaColor.Name.CompareTo(EntityY.RogaColor.Name);
}
}
var speedCompare = x.EntityLocomotiv.Speed.CompareTo(y.EntityLocomotiv.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityLocomotiv.Weight.CompareTo(y.EntityLocomotiv.Weight);
}
}

View File

@ -0,0 +1,28 @@
namespace ElectricLocomotive;
public class LocomotivCompareByType: IComparer<DrawingLocomotiv?>
{
public int Compare(DrawingLocomotiv? x, DrawingLocomotiv? y)
{
if (x == null || x.EntityLocomotiv == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityLocomotiv == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare =
x.EntityLocomotiv.Speed.CompareTo(y.EntityLocomotiv.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotiv.Weight.CompareTo(y.EntityLocomotiv.Weight);
}
}

View File

@ -8,6 +8,8 @@ public class LocosGenericCollection <T, U> where T : DrawingLocomotiv where U :
private readonly int _placeSizeHeight = 110; private readonly int _placeSizeHeight = 110;
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetLocos => _collection.GetElectricLocos(); public IEnumerable<T?> GetLocos => _collection.GetElectricLocos();
public void Sort(IComparer<T?> comparer) =>
_collection.SortSet(comparer);
public LocosGenericCollection(int picWidth, int picHeight) public LocosGenericCollection(int picWidth, int picHeight)
{ {
int width = picWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;
@ -19,9 +21,9 @@ public class LocosGenericCollection <T, U> where T : DrawingLocomotiv where U :
public static bool operator +(LocosGenericCollection<T, U> collect, T? public static bool operator +(LocosGenericCollection<T, U> collect, T?
obj) obj)
{ {
if (obj == null) return false; if (obj == null)
return false;
return collect?._collection.Insert(obj) ?? false; return collect?._collection.Insert(obj, new DrawingLocomotivEqutables()) ?? false;
} }
public static T? operator -(LocosGenericCollection<T, U> collect, int public static T? operator -(LocosGenericCollection<T, U> collect, int

View File

@ -4,8 +4,8 @@ namespace ElectricLocomotive;
public class LocosGenericStorage public class LocosGenericStorage
{ {
readonly Dictionary<string, LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv>> _electricLocoStorages; readonly Dictionary<LocomotivCollectionInfo, LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv>> _electricLocoStorages;
public List<string> Keys => _electricLocoStorages.Keys.ToList(); public List<LocomotivCollectionInfo> Keys => _electricLocoStorages.Keys.ToList();
private readonly int _pictureWidth; private readonly int _pictureWidth;
@ -18,7 +18,7 @@ public class LocosGenericStorage
public LocosGenericStorage(int pictureWidth, int pictureHeight) public LocosGenericStorage(int pictureWidth, int pictureHeight)
{ {
_electricLocoStorages = new Dictionary<string, _electricLocoStorages = new Dictionary<LocomotivCollectionInfo,
LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv>>(); LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
@ -26,22 +26,23 @@ public class LocosGenericStorage
public void AddSet(string name) public void AddSet(string name)
{ {
_electricLocoStorages.Add(name, new LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv> (_pictureWidth, _pictureHeight)); _electricLocoStorages.Add(new LocomotivCollectionInfo(name, string.Empty), new LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv> (_pictureWidth, _pictureHeight));
} }
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_electricLocoStorages.ContainsKey(name)) if (!_electricLocoStorages.ContainsKey(new LocomotivCollectionInfo(name, string.Empty)))
return; return;
_electricLocoStorages.Remove(name); _electricLocoStorages.Remove(new LocomotivCollectionInfo(name, string.Empty));
} }
public LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv>? this[string ind] public LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv>? this[string ind]
{ {
get get
{ {
if (_electricLocoStorages.ContainsKey(ind)) LocomotivCollectionInfo indObj = new LocomotivCollectionInfo(ind, string.Empty);
return _electricLocoStorages[ind]; if (_electricLocoStorages.ContainsKey(indObj))
return _electricLocoStorages[indObj];
return null; return null;
} }
} }
@ -52,7 +53,7 @@ public class LocosGenericStorage
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, foreach (KeyValuePair<LocomotivCollectionInfo,
LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv>> record in _electricLocoStorages) LocosGenericCollection<DrawingLocomotiv, DrawingObjectLocomotiv>> record in _electricLocoStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
@ -125,7 +126,7 @@ public class LocosGenericStorage
} }
} }
} }
_electricLocoStorages.Add(record[0], collection); _electricLocoStorages.Add(new LocomotivCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine(); str = sr.ReadLine();
} while (str != null); } while (str != null);

View File

@ -14,21 +14,27 @@ public class SetGeneric <T> where T : class
_maxCount = count; _maxCount = count;
_places = new List<T>(count); _places = new List<T>(count);
} }
public bool Insert(T electricLocomotiv) public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public bool Insert(T electricLocomotiv, IEqualityComparer<T>? equal = null)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
Insert(electricLocomotiv, 0); Insert(electricLocomotiv, 0, equal);
return true; return true;
} }
public bool Insert(T electricLocomotiv, int position) public bool Insert(T electricLocomotiv, 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(electricLocomotiv, equal))
throw new ArgumentException(nameof(electricLocomotiv));
}
_places.Insert(position, electricLocomotiv); _places.Insert(position, electricLocomotiv);
return true; return true;
} }