Хорошо когда собака друг, плохо когда друг собака

This commit is contained in:
Камилия Сафиулова 2023-12-19 22:39:15 +04:00
parent 8e6becc7b1
commit 6c507a6877
11 changed files with 299 additions and 53 deletions

View File

@ -0,0 +1,49 @@
using Catamaran.DrawningObjects;
using Catamaran.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Generics
{
internal class CatamaranCompareByColor : IComparer<DrawningCatamaran?>
{
public int Compare(DrawningCatamaran? x, DrawningCatamaran? y)
{
if (x == null || x.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityCatamaran.BodyColor.Name.CompareTo(y.EntityCatamaran.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityCatamaran is EntitySailCatamaran xEntitySailCatamaran && y.EntityCatamaran is EntitySailCatamaran yEntitySailCatamaran)
{
var BodyColorCompare = xEntitySailCatamaran.BodyColor.Name.CompareTo(yEntitySailCatamaran.BodyColor.Name);
if (BodyColorCompare != 0)
{
return BodyColorCompare;
}
var AdditionalColorCompare = xEntitySailCatamaran.AdditionalColor.Name.CompareTo(yEntitySailCatamaran.AdditionalColor.Name);
if (AdditionalColorCompare != 0)
{
return AdditionalColorCompare;
}
}
var speedCompare = x.EntityCatamaran.Speed.CompareTo(y.EntityCatamaran.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityCatamaran.Weight.CompareTo(y.EntityCatamaran.Weight);
}
}
}

View File

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

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.Generics
{
internal class CatamaransCollectionInfo : IEquatable<CatamaransCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public CatamaransCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(CatamaransCollectionInfo? other)
{
// TODO прописать логику сравнения по свойству Name
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic.Logging;
using Catamaran.DrawningObjects;
using Catamaran.MovementStrategy;
namespace Catamaran.Generics
@ -66,7 +66,7 @@ namespace Catamaran.Generics
{
return false;
}
return collect?._collection.Insert(obj) ?? false;
return collect?._collection.Insert(obj, new DrawningCatamaranEqutables()) ?? false;
}
/// <summary>
/// Перегрузка оператора вычитания
@ -106,6 +106,12 @@ namespace Catamaran.Generics
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Метод отрисовки фона
/// </summary>
@ -132,7 +138,6 @@ namespace Catamaran.Generics
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
{
// TODO получение объекта
// TODO установка позиции

View File

@ -12,12 +12,12 @@ namespace Catamaran.Generics
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, CatamaransGenericCollection<DrawningCatamaran,
readonly Dictionary<CatamaransCollectionInfo, CatamaransGenericCollection<DrawningCatamaran,
DrawningObjectCatamaran>> _catamaranStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _catamaranStorages.Keys.ToList();
public List<CatamaransCollectionInfo> Keys => _catamaranStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -45,7 +45,7 @@ namespace Catamaran.Generics
/// <param name="pictureHeight"></param>
public CatamaransGenericStorage(int pictureWidth, int pictureHeight)
{
_catamaranStorages = new Dictionary<string,
_catamaranStorages = new Dictionary<CatamaransCollectionInfo,
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
@ -57,8 +57,7 @@ namespace Catamaran.Generics
public void AddSet(string name)
{
// TODO Прописать логику для добавления
if (_catamaranStorages.ContainsKey(name)) return;
_catamaranStorages[name] = new CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>(_pictureWidth, _pictureHeight);
_catamaranStorages.Add(new CatamaransCollectionInfo(name, string.Empty), new CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
@ -67,9 +66,9 @@ namespace Catamaran.Generics
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (!_catamaranStorages.ContainsKey(name))
if (!_catamaranStorages.ContainsKey(new CatamaransCollectionInfo(name, string.Empty)))
return;
_catamaranStorages.Remove(name);
_catamaranStorages.Remove(new CatamaransCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
@ -82,8 +81,9 @@ namespace Catamaran.Generics
get
{
// TODO Продумать логику получения набора
if (_catamaranStorages.ContainsKey(ind))
return _catamaranStorages[ind];
CatamaransCollectionInfo indObj = new CatamaransCollectionInfo(ind, string.Empty);
if (_catamaranStorages.ContainsKey(indObj))
return _catamaranStorages[indObj];
return null;
}
}
@ -99,14 +99,14 @@ namespace Catamaran.Generics
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>> record in _catamaranStorages)
foreach (KeyValuePair<CatamaransCollectionInfo, CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>> record in _catamaranStorages)
{
StringBuilder records = new();
foreach (DrawningCatamaran? elem in record.Value.GetCatamarans)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
@ -173,7 +173,7 @@ namespace Catamaran.Generics
}
}
}
_catamaranStorages.Add(record[0], collection);
_catamaranStorages.Add(new CatamaransCollectionInfo(record[0],string.Empty), collection);
}
}
}

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.DrawningObjects;
using Catamaran.Entities;
using System.Diagnostics.CodeAnalysis;
namespace Catamaran.Generics
{
internal class DrawningCatamaranEqutables : IEqualityComparer<DrawningCatamaran?>
{
public bool Equals(DrawningCatamaran? x, DrawningCatamaran? y)
{
if (x == null || x.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCatamaran == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityCatamaran.Speed != y.EntityCatamaran.Speed)
{
return false;
}
if (x.EntityCatamaran.Weight != y.EntityCatamaran.Weight)
{
return false;
}
if (x.EntityCatamaran.BodyColor != y.EntityCatamaran.BodyColor)
{
return false;
}
if (x is DrawningSailCatamaran && y is DrawningSailCatamaran)
{
// TODO доделать логику сравнения дополнительных параметров
EntitySailCatamaran EntityX = (EntitySailCatamaran)x.EntityCatamaran;
EntitySailCatamaran EntityY = (EntitySailCatamaran)y.EntityCatamaran;
if (EntityX.Sail != EntityY.Sail)
return false;
if (EntityX.FloatDetail != EntityY.FloatDetail)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningCatamaran obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -30,6 +30,8 @@
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBoxTools = new System.Windows.Forms.GroupBox();
this.ButtonSortByColor = new System.Windows.Forms.Button();
this.ButtonSortByType = new System.Windows.Forms.Button();
this.groupBoxSets = new System.Windows.Forms.GroupBox();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.buttonDelObject = new System.Windows.Forms.Button();
@ -61,6 +63,8 @@
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.ButtonSortByColor);
this.groupBoxTools.Controls.Add(this.ButtonSortByType);
this.groupBoxTools.Controls.Add(this.groupBoxSets);
this.groupBoxTools.Controls.Add(this.maskedTextBoxNumber);
this.groupBoxTools.Controls.Add(this.ButtonRefreshCollection);
@ -74,13 +78,33 @@
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
//
// ButtonSortByColor
//
this.ButtonSortByColor.Location = new System.Drawing.Point(0, 287);
this.ButtonSortByColor.Name = "ButtonSortByColor";
this.ButtonSortByColor.Size = new System.Drawing.Size(139, 23);
this.ButtonSortByColor.TabIndex = 7;
this.ButtonSortByColor.Text = "Сортировка по цвету";
this.ButtonSortByColor.UseVisualStyleBackColor = true;
this.ButtonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// ButtonSortByType
//
this.ButtonSortByType.Location = new System.Drawing.Point(1, 255);
this.ButtonSortByType.Name = "ButtonSortByType";
this.ButtonSortByType.Size = new System.Drawing.Size(140, 23);
this.ButtonSortByType.TabIndex = 6;
this.ButtonSortByType.Text = "Сортировка по типу";
this.ButtonSortByType.UseVisualStyleBackColor = true;
this.ButtonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBoxSets
//
this.groupBoxSets.Controls.Add(this.textBoxStorageName);
this.groupBoxSets.Controls.Add(this.buttonDelObject);
this.groupBoxSets.Controls.Add(this.listBoxStorages);
this.groupBoxSets.Controls.Add(this.buttonAddObject);
this.groupBoxSets.Location = new System.Drawing.Point(3, 63);
this.groupBoxSets.Location = new System.Drawing.Point(3, 46);
this.groupBoxSets.Name = "groupBoxSets";
this.groupBoxSets.Size = new System.Drawing.Size(138, 203);
this.groupBoxSets.TabIndex = 4;
@ -126,14 +150,14 @@
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(3, 321);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(0, 356);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(137, 23);
this.maskedTextBoxNumber.TabIndex = 3;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(0, 420);
this.ButtonRefreshCollection.Location = new System.Drawing.Point(0, 425);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(140, 34);
this.ButtonRefreshCollection.TabIndex = 2;
@ -143,7 +167,7 @@
//
// ButtonRemoveCatamaran
//
this.ButtonRemoveCatamaran.Location = new System.Drawing.Point(0, 363);
this.ButtonRemoveCatamaran.Location = new System.Drawing.Point(0, 385);
this.ButtonRemoveCatamaran.Name = "ButtonRemoveCatamaran";
this.ButtonRemoveCatamaran.Size = new System.Drawing.Size(140, 34);
this.ButtonRemoveCatamaran.TabIndex = 1;
@ -153,7 +177,7 @@
//
// ButtonAddCatamaran
//
this.ButtonAddCatamaran.Location = new System.Drawing.Point(3, 270);
this.ButtonAddCatamaran.Location = new System.Drawing.Point(0, 316);
this.ButtonAddCatamaran.Name = "ButtonAddCatamaran";
this.ButtonAddCatamaran.Size = new System.Drawing.Size(137, 34);
this.ButtonAddCatamaran.TabIndex = 0;
@ -183,14 +207,14 @@
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@ -238,5 +262,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@ -49,7 +49,7 @@ namespace Catamaran
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))
@ -88,23 +88,34 @@ namespace Catamaran
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Не удалось добавить объект: набор пуст");
return;
}
try
{
if (obj + drawningCatamaran)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowCatamarans();
_logger.LogInformation($"Объект {obj.GetType()} добавлен");
_logger.LogInformation($"Объект добавлен {drawningCatamaran}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation($"Не удалось добавить объект");
}
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
/// <summary>
/// Выбор набора
/// </summary>
@ -275,5 +286,38 @@ namespace Catamaran
ReloadObjects();
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareCatamarans(new CatamaranCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareCatamarans(new CatamaranCompareByColor()); // TODO продумать логику
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareCatamarans(IComparer<DrawningCatamaran?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowCatamarans();
}
}
}

View File

@ -67,6 +67,6 @@
<value>254, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>96</value>
<value>25</value>
</metadata>
</root>

View File

@ -1,6 +1,5 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;

View File

@ -36,19 +36,19 @@ namespace Catamaran.Generics
_maxCount = count;
_places = new List<T?>(_maxCount);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый катамаран</param>
/// <returns></returns>
public bool Insert(T catamaran)
public bool Insert(T catamaran, IEqualityComparer<T?>? equal = null)
{
// TODO вставка в начало набора
if (_places.Count == _maxCount)
{
return false;
}
Insert(catamaran, 0);
throw new StorageOverflowException(_maxCount);
Insert(catamaran, 0, equal);
return true;
}
/// <summary>
@ -57,20 +57,21 @@ namespace Catamaran.Generics
/// <param name="catamaran">Добавляемый катамаран</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T catamaran, int position)
public bool Insert(T catamaran, int position, IEqualityComparer<T?>? equal = null)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой,
//если нет, то проверка, что после вставляемого элемента в массиве есть пустой элемент
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
// TODO вставка по позиции
if (Count >= _maxCount)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
if (!(position >= 0 && position <= Count))
return false;
if (equal != null)
{
throw new StorageOverflowException("Impossible to insert");
if (_places.Contains(catamaran, equal))
throw new ArgumentException(nameof(catamaran));
}
_places.Insert(position, catamaran);
return true;
@ -84,14 +85,8 @@ namespace Catamaran.Generics
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= Count || position < 0)
{
throw new CatamaranNotFoundException("Invalid operation");
}
if (_places[position] == null)
{
if (!(position >= 0 && position < Count))
throw new CatamaranNotFoundException(position);
}
_places.RemoveAt(position);
return true;
}