This commit is contained in:
DeerElk 2024-02-14 13:46:51 +04:00
parent d7068579dc
commit 3ea4e254bb
10 changed files with 264 additions and 40 deletions

View File

@ -0,0 +1,54 @@
using ProjectAircraftCarrier.DrawingObjects;
using ProjectAircraftCarrier.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectAircraftCarrier.Generics
{
internal class DrawingWarshipEqutables : IEqualityComparer<DrawingWarship?>
{
public bool Equals(DrawingWarship? x, DrawingWarship? y)
{
if (x == null || x.EntityWarship == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityWarship == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarship.Speed != y.EntityWarship.Speed)
{
return false;
}
if (x.EntityWarship.Weight != y.EntityWarship.Weight)
{
return false;
}
if (x.EntityWarship.BodyColor != y.EntityWarship.BodyColor)
{
return false;
}
if (x is DrawingAircraftCarrier && y is DrawingAircraftCarrier)
{
EntityAircraftCarrier EntityX =
(EntityAircraftCarrier)x.EntityWarship;
EntityAircraftCarrier EntityY =
(EntityAircraftCarrier)y.EntityWarship;
if (EntityX.Runway != EntityY.Runway)
return false;
if (EntityX.Cabin != EntityY.Cabin)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingWarship obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -29,6 +29,8 @@
private void InitializeComponent()
{
groupBoxCollectionTools = new GroupBox();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxCollectionSets = new GroupBox();
textBoxStorageName = new TextBox();
buttonDelObject = new Button();
@ -43,8 +45,8 @@
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new System.Windows.Forms.OpenFileDialog();
saveFileDialog = new System.Windows.Forms.SaveFileDialog();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxCollectionTools.SuspendLayout();
groupBoxCollectionSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
@ -54,6 +56,8 @@
// groupBoxCollectionTools
//
groupBoxCollectionTools.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
groupBoxCollectionTools.Controls.Add(buttonSortByColor);
groupBoxCollectionTools.Controls.Add(buttonSortByType);
groupBoxCollectionTools.Controls.Add(groupBoxCollectionSets);
groupBoxCollectionTools.Controls.Add(maskedTextBoxNumber);
groupBoxCollectionTools.Controls.Add(buttonRefreshCollection);
@ -68,6 +72,26 @@
groupBoxCollectionTools.TabStop = false;
groupBoxCollectionTools.Text = "Tools";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(15, 408);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(218, 41);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Sort by color";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(15, 361);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(218, 41);
buttonSortByType.TabIndex = 6;
buttonSortByType.Text = "Sort by type";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// groupBoxCollectionSets
//
groupBoxCollectionSets.Controls.Add(textBoxStorageName);
@ -120,7 +144,7 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(56, 468);
maskedTextBoxNumber.Location = new Point(56, 523);
maskedTextBoxNumber.Margin = new Padding(4, 5, 4, 5);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(141, 31);
@ -140,7 +164,7 @@
//
// buttonRemoveWarship
//
buttonRemoveWarship.Location = new Point(9, 509);
buttonRemoveWarship.Location = new Point(9, 564);
buttonRemoveWarship.Margin = new Padding(4, 5, 4, 5);
buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(230, 45);
@ -151,7 +175,7 @@
//
// buttonAddWarship
//
buttonAddWarship.Location = new Point(9, 413);
buttonAddWarship.Location = new Point(9, 468);
buttonAddWarship.Margin = new Padding(4, 5, 4, 5);
buttonAddWarship.Name = "buttonAddWarship";
buttonAddWarship.Size = new Size(230, 45);
@ -169,12 +193,12 @@
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// menuStrip1
// menuStrip
//
menuStrip.ImageScalingSize = new Size(24, 24);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip1";
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1143, 33);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
@ -250,5 +274,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -37,7 +37,7 @@ namespace ProjectAircraftCarrier
listBoxStorages.Items.Clear();
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))
@ -133,10 +133,18 @@ namespace ProjectAircraftCarrier
catch (StorageOverflowException ex)
{
_logger.LogWarning($"Collection " +
$"{listBoxStorages.SelectedItem.ToString() ?? string.Empty} " +
$"{listBoxStorages.SelectedItem.ToString() ?? string.Empty}" +
$"is full");
MessageBox.Show(ex.Message);
}
catch (ArgumentException)
{
_logger.LogWarning($"Object being added already exists in" +
$" the collection " +
$"{listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Object being added already exists in " +
"the collection");
}
});
form.AddEvent(warshipDelegate);
}
@ -263,5 +271,37 @@ namespace ProjectAircraftCarrier
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) =>
CompareWarships(new WarshipCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) =>
CompareWarships(new WarshipCompareByColor());
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareWarships(IComparer<DrawingWarship?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowWarships();
}
}
}

View File

@ -117,7 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<metadata name="menuStrip.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>165, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>351, 17</value>
</metadata>
</root>

View File

@ -33,41 +33,44 @@ namespace ProjectAircraftCarrier.Generics
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="warship">Добавляемый автомобиль</param>
/// <param name="warship">Добавляемый корабль</param>
/// <returns></returns>
public bool Insert(T warship)
public void Insert(T warship, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(warship, 0);
return true;
Insert(warship, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="warship">Добавляемый автомобиль</param>
/// <param name="warship">Добавляемый корабль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T warship, int position)
public void Insert(T warship, int position, IEqualityComparer<T?>?
equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false;
throw new Exception("Incorrect insertion position");
if (equal != null)
{
if (_places.Contains(warship, equal))
throw new ArgumentException(nameof(warship));
}
_places.Insert(position, warship);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
public void Remove(int position)
{
if (!(position >= 0 && position < Count))
throw new WarshipNotFoundException(position);
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
@ -84,11 +87,9 @@ namespace ProjectAircraftCarrier.Generics
}
set
{
if (!(position >= 0 && position < Count && _places.Count <
_maxCount))
if (!(position >= 0 && position < Count))
return;
_places.Insert(position, value);
return;
}
}
/// <summary>
@ -104,5 +105,10 @@ namespace ProjectAircraftCarrier.Generics
yield break;
}
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
}
}

View File

@ -0,0 +1,29 @@
using ProjectAircraftCarrier.DrawingObjects;
namespace ProjectAircraftCarrier.Generics
{
internal class WarshipCompareByColor : IComparer<DrawingWarship?>
{
public int Compare(DrawingWarship? x, DrawingWarship? y)
{
if (x == null || x.EntityWarship == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityWarship == null)
throw new ArgumentNullException(nameof(y));
if (x.EntityWarship.BodyColor.Name !=
y.EntityWarship.BodyColor.Name)
{
return x.EntityWarship.BodyColor.Name.CompareTo
(y.EntityWarship.BodyColor.Name);
}
var speedCompare = x.EntityWarship.Speed.CompareTo
(y.EntityWarship.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
}
}
}

View File

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

View File

@ -0,0 +1,24 @@
namespace ProjectAircraftCarrier.Generics
{
internal class WarshipsCollectionInfo : IEquatable<WarshipsCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public WarshipsCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(WarshipsCollectionInfo? other)
{
if (other == null || other.Name == null)
throw new ArgumentNullException(nameof(other));
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -56,7 +56,8 @@ namespace ProjectAircraftCarrier.Generics
{
if (obj == null || collect == null)
return false;
return collect._collection.Insert(obj);
collect._collection.Insert(obj, new DrawingWarshipEqutables());
return true;
}
/// <summary>
/// Перегрузка оператора вычитания
@ -138,5 +139,6 @@ namespace ProjectAircraftCarrier.Generics
i++;
}
}
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
}
}

View File

@ -11,12 +11,13 @@ namespace ProjectAircraftCarrier.Generics
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, WarshipsGenericCollection<DrawingWarship,
DrawingObjectWarship>> _warshipStorages;
readonly Dictionary<WarshipsCollectionInfo, WarshipsGenericCollection
<DrawingWarship, DrawingObjectWarship>> _warshipStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _warshipStorages.Keys.ToList();
public List<WarshipsCollectionInfo> Keys =>
_warshipStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -44,7 +45,7 @@ namespace ProjectAircraftCarrier.Generics
/// <param name="pictureHeight"></param>
public WarshipsGenericStorage(int pictureWidth, int pictureHeight)
{
_warshipStorages = new Dictionary<string,
_warshipStorages = new Dictionary<WarshipsCollectionInfo,
WarshipsGenericCollection<DrawingWarship,
DrawingObjectWarship>>();
_pictureWidth = pictureWidth;
@ -56,11 +57,13 @@ namespace ProjectAircraftCarrier.Generics
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (!_warshipStorages.ContainsKey(name))
if (!_warshipStorages.ContainsKey(new WarshipsCollectionInfo(name,
string.Empty)))
{
_warshipStorages.Add(name, new WarshipsGenericCollection
<DrawingWarship, DrawingObjectWarship>(_pictureWidth,
_pictureHeight));
_warshipStorages.Add(new WarshipsCollectionInfo(name,
string.Empty), new WarshipsGenericCollection
<DrawingWarship, DrawingObjectWarship>
(_pictureWidth, _pictureHeight));
}
else
{
@ -73,9 +76,10 @@ namespace ProjectAircraftCarrier.Generics
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_warshipStorages.ContainsKey(name))
if (!_warshipStorages.ContainsKey(new WarshipsCollectionInfo(name,
string.Empty)))
return;
_warshipStorages.Remove(name);
_warshipStorages.Remove(new WarshipsCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
@ -87,8 +91,10 @@ namespace ProjectAircraftCarrier.Generics
{
get
{
if (_warshipStorages.ContainsKey(ind))
return _warshipStorages[ind];
WarshipsCollectionInfo indObj = new WarshipsCollectionInfo(ind,
string.Empty);
if (_warshipStorages.ContainsKey(indObj))
return _warshipStorages[indObj];
return null;
}
}
@ -104,7 +110,8 @@ namespace ProjectAircraftCarrier.Generics
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, WarshipsGenericCollection
foreach (KeyValuePair<WarshipsCollectionInfo,
WarshipsGenericCollection
<DrawingWarship, DrawingObjectWarship>>
record in _warshipStorages)
{
@ -115,7 +122,7 @@ namespace ProjectAircraftCarrier.Generics
$"{elem?.GetDataForSave(_separatorForObject)}" +
$"{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}" +
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}" +
$"{records}");
}
if (data.Length == 0)
@ -124,7 +131,7 @@ namespace ProjectAircraftCarrier.Generics
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes
($"CarStorage{Environment.NewLine}{data}");
($"WarshipStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
@ -185,7 +192,8 @@ namespace ProjectAircraftCarrier.Generics
}
}
}
_warshipStorages.Add(record[0], collection);
_warshipStorages.Add(new WarshipsCollectionInfo(record[0],
string.Empty), collection);
}
}
}