Compare commits

...

4 Commits

Author SHA1 Message Date
da6a8237a8 v 2024-06-11 04:56:10 +04:00
7c4680b0f1 пробел 2024-06-10 11:42:46 +04:00
38b39ba55d исправление массива 2024-06-10 04:53:32 +04:00
2d339f7d20 все 2024-06-10 03:49:04 +04:00
13 changed files with 425 additions and 58 deletions

View File

@ -55,7 +55,7 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningBus bus) public static int operator +(AbstractCompany company, DrawningBus bus)
{ {
return company._collection.Insert(bus); return company._collection.Insert(bus,new DrawiningBusEqutables());
} }
/// <summary> /// <summary>
/// Перегрузка оператора удаления для класса /// Перегрузка оператора удаления для класса
@ -102,4 +102,5 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
public void Sort(IComparer<DrawningBus?> comparer) => _collection?.CollectionSort(comparer);
} }

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
namespace TrolleybusProject.CollectionGenericObjects;
public class DrawningBusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityBus == null)
{
return -1;
}
if (y == null || y.EntityBus == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

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

View File

@ -1,8 +1,10 @@
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions; using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects; namespace TrolleybusProject.CollectionGenericObjects;
@ -48,27 +50,48 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (Count + 1 > _maxCount) 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, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
{ {
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
_collection.Add(obj); if (position >= Count || position < 0)
return 1; {
} throw new PositionOutOfCollectionException(position);
public int Insert(T obj, int position) }
{
if (position < 0 || position > Count) if (comparer != null)
{
for (int i = 0; i < Count; i++)
{ {
throw new PositionOutOfCollectionException(position); if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
} }
if (Count + 1 > _maxCount) }
{
throw new CollectionOverflowException(Count); _collection.Insert(position, obj);
} return position;
_collection.Insert(position, obj);
return 1;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
@ -89,6 +112,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -3,8 +3,10 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions; using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects; namespace TrolleybusProject.CollectionGenericObjects;
internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T> internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
@ -51,13 +53,21 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
int index = Array.IndexOf(_collection, null);
if (_collection.Contains(obj, comparer))
{
throw new CollectionInsertException(obj);
}
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
@ -66,41 +76,48 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i; 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<T?>? comparer = null)
{ {
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection.Contains(obj, comparer))
{
throw new CollectionInsertException(obj);
}
if (position >= Count || position < 0)
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
int index = position + 1;
while (index < _collection.Length) int temp = position + 1;
while (temp < Count)
{ {
if (_collection[index] == null) if (_collection[temp] == null)
{ {
_collection[index] = obj; _collection[temp] = obj;
return index; return temp;
} }
++index; temp++;
} }
index = position - 1;
while (index >= 0) temp = position - 1;
while (temp > 0)
{ {
if (_collection[index] == null) if (_collection[temp] == null)
{ {
_collection[index] = obj; _collection[temp] = obj;
return index; return temp;
} }
--index; temp--;
} }
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
@ -117,4 +134,14 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
} }

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.CollectionGenericObjects;
namespace TrolleybusProject;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
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

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Entities;
namespace TrolleybusProject.Drawnings;
internal class DrawiningBusEqutables: IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return false;
}
if (y == null || y.EntityBus == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBus.Speed != y.EntityBus.Speed)
{
return false;
}
if (x.EntityBus.Weight != y.EntityBus.Weight)
{
return false;
}
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
return false;
}
if (x is DrawningTrolleybus && y is DrawningTrolleybus)
{
if (((EntityTrolleybus)x.EntityBus).AdditionalColor !=
((EntityTrolleybus)y.EntityBus).AdditionalColor)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Roga !=
((EntityTrolleybus)y.EntityBus).Roga)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Otsek !=
((EntityTrolleybus)y.EntityBus).Otsek)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Doors !=
((EntityTrolleybus)y.EntityBus).Doors)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrolleybusProject.Drawnings;
public class DrawningBusCompareByColor: IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityBus== null)
{
return -1;
}
if (y == null || y.EntityBus == null)
{
return 1;
}
var bodycolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
using TrolleybusProject;
namespace ProjectTrolleybus.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception)
{ }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
public class CollectionInsertException : Exception
{
public CollectionInsertException(object obj) : base($"Объект {obj} повторяется") { }
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionInsertException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -55,6 +55,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem(); LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonByType = new Button();
ByColor = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -71,7 +73,7 @@
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(904, 33); groupBoxTools.Location = new Point(904, 33);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(300, 623); groupBoxTools.Size = new Size(300, 702);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -88,7 +90,9 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonByType);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ByColor);
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddBus); panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Controls.Add(buttonDelTrolleybus); panelCompanyTools.Controls.Add(buttonDelTrolleybus);
@ -96,7 +100,7 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 397); panelCompanyTools.Location = new Point(0, 397);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(294, 259); panelCompanyTools.Size = new Size(294, 305);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonRefresh // buttonRefresh
@ -250,7 +254,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 33); pictureBox.Location = new Point(0, 33);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(904, 623); pictureBox.Size = new Size(904, 702);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -314,11 +318,33 @@
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonByType
//
buttonByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonByType.Location = new Point(6, 259);
buttonByType.Name = "buttonByType";
buttonByType.Size = new Size(268, 34);
buttonByType.TabIndex = 8;
buttonByType.Text = "Сравнить по типу";
buttonByType.UseVisualStyleBackColor = true;
buttonByType.Click += button1_Click;
//
// ByColor
//
ByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ByColor.Location = new Point(23, 215);
ByColor.Name = "ByColor";
ByColor.Size = new Size(247, 38);
ByColor.TabIndex = 7;
ByColor.Text = "Сравнить по цвету";
ByColor.UseVisualStyleBackColor = true;
ByColor.Click += ByColor_Click;
//
// FormBusCollection // FormBusCollection
// //
AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1204, 656); ClientSize = new Size(1204, 735);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -366,5 +392,7 @@
private ToolStripMenuItem файлToolStripMenuItem; private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem save_ToolStripMenuItem; private ToolStripMenuItem save_ToolStripMenuItem;
private ToolStripMenuItem load_ToolStripMenuItem; private ToolStripMenuItem load_ToolStripMenuItem;
private Button buttonByType;
private Button ByColor;
} }
} }

View File

@ -45,24 +45,26 @@ public partial class FormBusCollection : Form
} }
private void SetBus(DrawningBus bus) private void SetBus(DrawningBus bus)
{ {
if (_company == null || bus == null)
{
return;
}
try try
{ {
if (_company == null || bus == null) int addingObject = (_company + bus);
{ MessageBox.Show("Объект добавлен");
return; _logger.LogInformation($"Добавлен объект {bus.GetDataForSave()}");
} pictureBox.Image = _company.Show();
if (_company + bus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave());
}
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show("Не удалось добавить объект");
_logger.LogError($"Ошибка: {ex.Message}"); _logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (CollectionInsertException)
{
MessageBox.Show("Такой объект уже существует");
_logger.LogError("Ошибка:обьект повторяется {0}", bus);
} }
} }
@ -156,7 +158,7 @@ public partial class FormBusCollection : Form
private void buttonCollectionAdd_Click(object sender, EventArgs e) private void buttonCollectionAdd_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked)) (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -184,7 +186,7 @@ public partial class FormBusCollection : Form
listBoxCollection.Items.Clear(); 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)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -281,6 +283,31 @@ public partial class FormBusCollection : Form
} }
private void button1_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByType());
}
private void ByColor_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareBus(IComparer<DrawningBus?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }

View File

@ -63,6 +63,5 @@ namespace TrolleybusProject.MovementStrategy
_height = height; _height = height;
} }
} }
} }