Merge branch 'lab8' into lab7

This commit is contained in:
rinat 2024-05-21 11:14:32 +04:00
commit 0320c06148
13 changed files with 600 additions and 345 deletions

View File

@ -1,5 +1,6 @@
using WarmlyShip.CollectionGenericObjects;
using WarmlyShip.Drawnings;
using WarmlyShip.Drawningsp;
namespace WarmlyShip.CollectionGenericObjects;
@ -35,7 +36,7 @@ public abstract class AbstractCompany
public static int operator +(AbstractCompany company, DrawningShip ship)
{
return company._collection.Insert(ship);
return company._collection.Insert(ship, new DrawningShipEqutables());
}
public static DrawningShip operator -(AbstractCompany company, int position)
@ -67,6 +68,7 @@ public abstract class AbstractCompany
return bitmap;
}
public void Sort(IComparer<DrawningShip?> comparer) => _collection?.CollectionSort(comparer);
protected abstract void DrawBackgroud(Graphics g);

View File

@ -0,0 +1,76 @@
namespace WarmlyShip.CollectionGenericObjects;
/// <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

@ -11,10 +11,10 @@ public interface ICollectionGenericObjects<T>
int MaxCount { set; get; }
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
T Remove(int position);
@ -26,4 +26,6 @@ public interface ICollectionGenericObjects<T>
IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -40,8 +40,16 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@ -50,8 +58,16 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@ -82,4 +98,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,5 +1,6 @@
using WarmlyShip.Exceptions;
using WarmlyShip.Drawnings;
using WarmlyShip.Exceptions;
using WarmlyShip.Scripts.Exceptions;
namespace WarmlyShip.CollectionGenericObjects;
@ -52,8 +53,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningShip>).Equals(obj as DrawningShip, item as DrawningShip))
{
throw new ObjectNotUniqueException();
}
}
}
// TODO вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
@ -67,7 +78,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count)
@ -127,4 +138,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -8,9 +8,9 @@ namespace WarmlyShip.CollectionGenericObjects;
public class StorageCollection<T> where T : DrawningShip
{
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage";
@ -23,33 +23,36 @@ public class StorageCollection<T> where T : DrawningShip
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name) || collectionType == CollectionType.None)
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo) || collectionInfo.CollectionType == CollectionType.None)
{
return;
}
switch (collectionType)
switch (collectionInfo.CollectionType)
{
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
break;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
break;
}
}
public void DelCollection(string name)
{
if (_storages.ContainsKey(name) && name != null)
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo) && collectionInfo != null)
{
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
}
@ -57,9 +60,10 @@ public class StorageCollection<T> where T : DrawningShip
{
get
{
if (_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return _storages[name];
return _storages[collectionInfo];
}
return null;
}
@ -79,7 +83,7 @@ public class StorageCollection<T> where T : DrawningShip
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
@ -92,8 +96,6 @@ public class StorageCollection<T> where T : DrawningShip
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
@ -111,15 +113,9 @@ public class StorageCollection<T> where T : DrawningShip
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
@ -146,18 +142,18 @@ public class StorageCollection<T> where T : DrawningShip
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции: " + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningShip() is T ship)
@ -175,7 +171,7 @@ public class StorageCollection<T> where T : DrawningShip
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,20 @@
namespace WarmlyShip.Drawnings;
public class DrawningShipCompareByColor : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null) return 1;
if (y == null || y.EntityShip == null) return -1;
var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
if (bodycolorCompare != 0) return bodycolorCompare;
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0) return speedCompare;
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -0,0 +1,19 @@
namespace WarmlyShip.Drawnings;
public class DrawningShipCompareByType : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null) return 1;
if (y == null || y.EntityShip == null) return -1;
if (x.GetType().Name != y.GetType().Name) return x.GetType().Name.CompareTo(y.GetType().Name);
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0) return speedCompare;
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -0,0 +1,42 @@
using WarmlyShip.Entities;
using System.Diagnostics.CodeAnalysis;
using WarmlyShip.Drawnings;
namespace WarmlyShip.Drawningsp;
public class DrawningShipEqutables : IEqualityComparer<DrawningShip?>
{
public bool Equals(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null) return false;
if (y == null || y.EntityShip == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.EntityShip.Speed != y.EntityShip.Speed) return false;
if (x.EntityShip.Weight != y.EntityShip.Weight) return false;
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor) return false;
if (x is DrawningWarmlyShip bigX && y is DrawningWarmlyShip bigY)
{
EntityWarmlyShip _x = (EntityWarmlyShip)x.EntityShip;
EntityWarmlyShip _y = (EntityWarmlyShip)y.EntityShip;
if (_x.FuelHole != _y.FuelHole) return false;
if (_x.Pipes != _y.Pipes) return false;
if (_x.SeckondColor != _y.SeckondColor) return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip obj)
{
return obj.GetHashCode();
}
}

View File

@ -1,6 +1,6 @@
using System.Runtime.Serialization;
namespace WarmlyShip.Exceptions;
namespace WarmlyShip.Scripts.Exceptions;
[Serializable]

View File

@ -0,0 +1,18 @@
using System.Runtime.Serialization;
namespace WarmlyShip.Exceptions;
[Serializable]
internal class ObjectNotUniqueException : ApplicationException
{
public ObjectNotUniqueException(int i) : base("В коллекции есть такой же элемент на позиции: " + i) { }
public ObjectNotUniqueException() : base() { }
public ObjectNotUniqueException(string message) : base(message) { }
public ObjectNotUniqueException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotUniqueException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStoreage.SuspendLayout();
@ -68,22 +70,24 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(961, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(187, 521);
groupBoxTools.Size = new Size(187, 532);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveShip);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 292);
panelCompanyTools.Location = new Point(6, 283);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(178, 234);
panelCompanyTools.Size = new Size(178, 249);
panelCompanyTools.TabIndex = 4;
//
// buttonAddShip
@ -100,7 +104,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.None;
buttonRefresh.Location = new Point(3, 156);
buttonRefresh.Location = new Point(3, 162);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(169, 28);
buttonRefresh.TabIndex = 7;
@ -110,7 +114,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(6, 45);
maskedTextBoxPosition.Location = new Point(3, 45);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(169, 23);
@ -120,7 +124,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(6, 116);
buttonGoToCheck.Location = new Point(3, 116);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(166, 36);
buttonGoToCheck.TabIndex = 6;
@ -131,7 +135,7 @@
// buttonRemoveShip
//
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(6, 74);
buttonRemoveShip.Location = new Point(3, 74);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(166, 36);
buttonRemoveShip.TabIndex = 5;
@ -141,7 +145,7 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 263);
buttonCreateCompany.Location = new Point(6, 254);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(175, 23);
buttonCreateCompany.TabIndex = 7;
@ -161,12 +165,12 @@
panelStoreage.Dock = DockStyle.Top;
panelStoreage.Location = new Point(3, 19);
panelStoreage.Name = "panelStoreage";
panelStoreage.Size = new Size(181, 213);
panelStoreage.Size = new Size(181, 200);
panelStoreage.TabIndex = 9;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(0, 186);
buttonCollectionDel.Location = new Point(0, 171);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(175, 23);
buttonCollectionDel.TabIndex = 6;
@ -180,7 +184,7 @@
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 101);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(175, 79);
listBoxCollection.Size = new Size(175, 64);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
@ -234,7 +238,7 @@
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 234);
comboBoxSelectorCompany.Location = new Point(6, 225);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(175, 23);
comboBoxSelectorCompany.TabIndex = 8;
@ -245,7 +249,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(961, 521);
pictureBox.Size = new Size(961, 532);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
@ -290,11 +294,33 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.None;
buttonSortByType.Location = new Point(3, 196);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(169, 22);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.None;
buttonSortByColor.Location = new Point(3, 221);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(169, 22);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1148, 545);
ClientSize = new Size(1148, 556);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -339,5 +365,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -1,17 +1,8 @@
using WarmlyShip.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WarmlyShip.Drawnings;
using Microsoft.Extensions.Logging;
using WarmlyShip.Exceptions;
using WarmlyShip.Scripts.Exceptions;
namespace WarmlyShip;
@ -70,6 +61,11 @@ public partial class FormShipCollection : Form
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotUniqueException ex)
{
MessageBox.Show("Такой объект уже присутствует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -235,7 +231,7 @@ public partial class FormShipCollection : Form
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@ -279,4 +275,25 @@ public partial class FormShipCollection : Form
}
RefreshListBoxItems();
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompareByColor());
}
private void CompareShips(IComparer<DrawningShip?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}