лабВОСЕМЬ)

This commit is contained in:
Леонид Малафеев 2023-12-18 16:26:08 +04:00
parent 869f48fa15
commit 9c1aac79a6
9 changed files with 270 additions and 33 deletions

View File

@ -45,6 +45,8 @@
UploadToolStripMenuItem = new ToolStripMenuItem(); UploadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
buttonSortColor = new Button();
buttonSortType = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBoxStorage.SuspendLayout(); groupBoxStorage.SuspendLayout();
@ -110,6 +112,8 @@
// //
// groupBoxStorage // groupBoxStorage
// //
groupBoxStorage.Controls.Add(buttonSortType);
groupBoxStorage.Controls.Add(buttonSortColor);
groupBoxStorage.Controls.Add(listBoxStorages); groupBoxStorage.Controls.Add(listBoxStorages);
groupBoxStorage.Controls.Add(buttonDelObject); groupBoxStorage.Controls.Add(buttonDelObject);
groupBoxStorage.Controls.Add(textBoxStorageName); groupBoxStorage.Controls.Add(textBoxStorageName);
@ -127,7 +131,7 @@
listBoxStorages.ItemHeight = 15; listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(10, 117); listBoxStorages.Location = new Point(10, 117);
listBoxStorages.Name = "listBoxStorages"; listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(120, 124); listBoxStorages.Size = new Size(120, 64);
listBoxStorages.TabIndex = 7; listBoxStorages.TabIndex = 7;
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged; listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
// //
@ -198,6 +202,26 @@
saveFileDialog.FileName = "saveFileDialog"; saveFileDialog.FileName = "saveFileDialog";
saveFileDialog.Filter = "txt file | *.txt"; saveFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortColor
//
buttonSortColor.Location = new Point(6, 216);
buttonSortColor.Name = "buttonSortColor";
buttonSortColor.Size = new Size(122, 30);
buttonSortColor.TabIndex = 8;
buttonSortColor.Text = "Сорт. по цвету";
buttonSortColor.UseVisualStyleBackColor = true;
buttonSortColor.Click += ButtonSortByColor_Click;
//
// buttonSortType
//
buttonSortType.Location = new Point(6, 184);
buttonSortType.Name = "buttonSortType";
buttonSortType.Size = new Size(120, 26);
buttonSortType.TabIndex = 9;
buttonSortType.Text = "Сорт. по типу";
buttonSortType.UseVisualStyleBackColor = true;
buttonSortType.Click += ButtonSortByType_Click;
//
// FormCruiserCollection // FormCruiserCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -241,5 +265,7 @@
private ToolStripMenuItem UploadToolStripMenuItem; private ToolStripMenuItem UploadToolStripMenuItem;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private Button buttonSortType;
private Button buttonSortColor;
} }
} }

View File

@ -48,7 +48,7 @@ namespace Cruiser
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
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))
{ {
@ -137,10 +137,15 @@ namespace Cruiser
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
} }
} }
catch (ApplicationException ex) catch (ApplicationException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
} }
} }
/// <summary> /// <summary>
@ -168,7 +173,7 @@ namespace Cruiser
return; return;
} }
int pos = Convert.ToInt32(textBoxNumber.Text); int pos = Convert.ToInt32(textBoxNumber.Text);
try try
{ {
if (obj - pos != null) if (obj - pos != null)
{ {
@ -181,13 +186,13 @@ namespace Cruiser
_logger.LogWarning($"Удаление круизера не удалось(обьект не найден)"); _logger.LogWarning($"Удаление круизера не удалось(обьект не найден)");
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (CruiserNotFoundException ex) catch (CruiserNotFoundException ex)
{ {
_logger.LogWarning($"Удаление круизера не удалось {ex.Message}"); _logger.LogWarning($"Удаление круизера не удалось {ex.Message}");
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
} }
} }
/// <summary> /// <summary>
/// Обновление рисунка по набору /// Обновление рисунка по набору
@ -258,5 +263,35 @@ namespace Cruiser
} }
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareCruiser(new CruiserCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareCruiser(new CruiserCompareByColor());
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareCruiser(IComparer<DrawingCruiser?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowCruiser();
}
} }
} }

View File

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

View File

@ -0,0 +1,44 @@
using Cruiser.Entities;
using Cruiser.Drawing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Generics
{
internal class CruiserCompareByColor : IComparer<DrawingCruiser?>
{
public int Compare(DrawingCruiser? x, DrawingCruiser? y)
{
if (x == null || x.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityCruiser.BodyColor.Name.CompareTo(y.EntityCruiser.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityCruiser is EntityProCruiser _cruiserProX && y.EntityCruiser is EntityProCruiser _cruiserProY)
{
var ElementsColorCompare = _cruiserProX.ElementsColor.Name.CompareTo(_cruiserProY.ElementsColor.Name);
if (ElementsColorCompare != 0)
{
return ElementsColorCompare;
}
}
var speedCompare = x.EntityCruiser.Speed.CompareTo(y.EntityCruiser.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityCruiser.Weight.CompareTo(y.EntityCruiser.Weight);
}
}
}

View File

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

View File

@ -1,4 +1,5 @@
using Cruiser.MovementStrategy; using Cruiser.MovementStrategy;
using Cruiser.Generics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -22,6 +23,11 @@ namespace Cruiser.Generics
/// </summary> /// </summary>
public IEnumerable<T?> GetCruisers => _collection.GetCruisers(); public IEnumerable<T?> GetCruisers => _collection.GetCruisers();
/// <summary> /// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Ширина окна прорисовки /// Ширина окна прорисовки
/// </summary> /// </summary>
private readonly int _pictureWidth; private readonly int _pictureWidth;
@ -66,7 +72,7 @@ namespace Cruiser.Generics
{ {
return false; return false;
} }
return collect._collection.Insert(obj); return collect._collection.Insert(obj, new DrawiningCruiserEqutables());
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания

View File

@ -27,11 +27,11 @@ namespace Cruiser.Generics
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>> _cruiserStorages; readonly Dictionary<CruiserCollectionInfo, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>> _cruiserStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _cruiserStorages.Keys.ToList(); public List<CruiserCollectionInfo> Keys => _cruiserStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -47,7 +47,7 @@ namespace Cruiser.Generics
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public CruisersGenericStorage(int pictureWidth, int pictureHeight) public CruisersGenericStorage(int pictureWidth, int pictureHeight)
{ {
_cruiserStorages = new Dictionary<string, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>>(); _cruiserStorages = new Dictionary<CruiserCollectionInfo, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -57,8 +57,8 @@ namespace Cruiser.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void AddSet(string name) public void AddSet(string name)
{ {
if (_cruiserStorages.ContainsKey(name)) return; if (_cruiserStorages.ContainsKey(new CruiserCollectionInfo(name, string.Empty))) return;
_cruiserStorages[name] = new CarsGenericCollection<DrawingCruiser, DrawningObjectCar>(_pictureWidth, _pictureHeight); _cruiserStorages[new CruiserCollectionInfo(name, string.Empty)] = new CarsGenericCollection<DrawingCruiser, DrawningObjectCar>(_pictureWidth, _pictureHeight);
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -66,8 +66,8 @@ namespace Cruiser.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_cruiserStorages.ContainsKey(name)) return; if (!_cruiserStorages.ContainsKey(new CruiserCollectionInfo(name, string.Empty))) return;
_cruiserStorages.Remove(name); _cruiserStorages.Remove(new CruiserCollectionInfo(name, string.Empty));
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
@ -79,7 +79,7 @@ namespace Cruiser.Generics
{ {
get get
{ {
if (_cruiserStorages.ContainsKey(ind)) return _cruiserStorages[ind]; if (_cruiserStorages.ContainsKey(new CruiserCollectionInfo(ind, string.Empty))) return _cruiserStorages[new CruiserCollectionInfo(ind, string.Empty)];
return null; return null;
} }
} }
@ -95,7 +95,7 @@ namespace Cruiser.Generics
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>> record in _cruiserStorages) foreach (KeyValuePair<CruiserCollectionInfo, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>> record in _cruiserStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawingCruiser? elem in record.Value.GetCruisers) foreach (DrawingCruiser? elem in record.Value.GetCruisers)
@ -168,7 +168,7 @@ namespace Cruiser.Generics
} }
} }
_cruiserStorages.Add(name, collection); _cruiserStorages.Add(new CruiserCollectionInfo(name, string.Empty), collection);
} }
return true; return true;
} }

View File

@ -0,0 +1,64 @@
using Cruiser.Entities;
using Cruiser.Drawing;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Generics
{
internal class DrawiningCruiserEqutables : IEqualityComparer<DrawingCruiser?>
{
public bool Equals(DrawingCruiser? x, DrawingCruiser? y)
{
if (x == null || x.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityCruiser.Speed != y.EntityCruiser.Speed)
{
return false;
}
if (x.EntityCruiser.Weight != y.EntityCruiser.Weight)
{
return false;
}
if (x.EntityCruiser.BodyColor != y.EntityCruiser.BodyColor)
{
return false;
}
if (x is DrawingProCruiser && y is DrawingProCruiser)
{
EntityProCruiser _cruiserX = (EntityProCruiser)x.EntityCruiser;
EntityProCruiser _cruiserY = (EntityProCruiser)y.EntityCruiser;
if (_cruiserX.Helipad != _cruiserY.Helipad)
{
return false;
}
if (_cruiserX.RocketMines != _cruiserY.RocketMines)
{
return false;
}
if (_cruiserX.ElementsColor != _cruiserY.ElementsColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingCruiser obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -41,14 +41,13 @@ namespace Cruiser.Generics
/// </summary> /// </summary>
/// <param name="cruiser">Добавляемый лайнер</param> /// <param name="cruiser">Добавляемый лайнер</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T cruiser) //починил код, работал неправильно public bool Insert(T cruiser, IEqualityComparer<T?>? equal = null) //починил код, работал неправильно, переделал на инт
{ {
if (_places.Count >= _maxCount) if (_places.Count >= _maxCount)
{ {
throw new StorageOverflowException(_places.Count); throw new StorageOverflowException(_places.Count);
} }
_places.Insert(0, cruiser); return Insert(cruiser, 0, equal);
return true;
} }
/// <summary> /// <summary>
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
@ -70,16 +69,14 @@ namespace Cruiser.Generics
/// <param name="cruiser">Добавляемый автомобиль</param> /// <param name="cruiser">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T cruiser, int position) //починил код, работал неправильно public bool Insert(T cruiser, int position, IEqualityComparer<T?>? equal = null) //починил код, работал неправильно, переделал на инт
{ {
if (_places.Count >= _maxCount) if (position < 0 || position > Count)
{
throw new StorageOverflowException(_places.Count);
}
if (position < 0 || position > _places.Count)
{
throw new CruiserNotFoundException(position); throw new CruiserNotFoundException(position);
} if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (equal != null && _places.Contains(cruiser, equal))
throw new ArgumentException("Круизер уже имеется");
_places.Insert(position, cruiser); _places.Insert(position, cruiser);
return true; return true;
} }
@ -109,6 +106,6 @@ namespace Cruiser.Generics
} }
} }
} }
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
} }
} }