LabWork08

This commit is contained in:
Сафия Мухамадиева 2024-05-16 05:12:44 +03:00
parent 1fe1d75be5
commit bcbc9f28b8
24 changed files with 326 additions and 29 deletions

View File

@ -55,7 +55,7 @@ public abstract class AbstractCompany
public static int operator +(AbstractCompany company, public static int operator +(AbstractCompany company,
DrawingWarship warship) DrawingWarship warship)
{ {
return company._collection?.Insert(warship) ?? 0; return company._collection?.Insert(warship, new DrawiningWarshipEqutables()) ?? 0;
} }
/// <summary> /// <summary>
/// Перегрузка оператора удаления для класса /// Перегрузка оператора удаления для класса
@ -78,6 +78,11 @@ public abstract class AbstractCompany
return _collection?.Get(rnd.Next(GetMaxCount)); return _collection?.Get(rnd.Next(GetMaxCount));
} }
/// <summary> /// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningAircraft?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод всей коллекции /// Вывод всей коллекции
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>

View File

@ -1,4 +1,6 @@
namespace ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.DrawingObject;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary> /// <summary>
/// Интерфейс описания действий для набора хранимых объектов /// Интерфейс описания действий для набора хранимых объектов
/// </summary> /// </summary>
@ -20,16 +22,18 @@ where T : class
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -55,4 +59,10 @@ where T : class
/// </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,4 +1,5 @@
using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.DrawingObject;
using ProjectBattleship.Exceptions; using ProjectBattleship.Exceptions;
@ -52,17 +53,42 @@ where T : class
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); 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); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
@ -82,4 +108,9 @@ where T : class
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -1,5 +1,6 @@
using ProjectBattleship.Exceptions; using ProjectBattleship.Exceptions;
using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.DrawingObject;
namespace Battleship.CollectionGenericObjects; namespace Battleship.CollectionGenericObjects;
/// <summary> /// <summary>
@ -60,8 +61,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<DrawingWarship?>? comparer = null)
{ {
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
// вставка в свободное место набора // вставка в свободное место набора
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
@ -75,11 +87,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<DrawingWarship?>? comparer = null)
{ {
// проверка позиции // проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
if (_collection[position] != null) if (_collection[position] != null)
{ {
bool pushed = false; bool pushed = false;
@ -135,4 +158,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> value = new List<T?>(_collection);
value.Sort(comparer);
value.CopyTo(_collection, 0);
}
} }

View File

@ -0,0 +1,37 @@
using ProjectBattleship.DrawingObject;
namespace Battleship;
public class DrawingWarshipCompareByColor : IComparer<DrawingWarship?>
{
public int Compare(DrawingWarship? x, DrawingWarship? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityWarship == null)
{
return 1;
}
if (y == null || y.EntityWarship == null)
{
return -1;
}
if (ToHex(x.EntityWarship.BodyColor) != ToHex(y.EntityWarship.BodyColor))
{
return String.Compare(ToHex(x.EntityWarship.BodyColor), ToHex(y.EntityWarship.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityWarship.Speed.CompareTo(y.EntityWarship.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarship.Weight.CompareTo(y.EntityWarship.Weight);
}
private static String ToHex(Color c)
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}

View File

@ -0,0 +1,32 @@
using ProjectBattleship.DrawingObject;
namespace Battleship;
public class DrawingWarshipCompareByType : IComparer<DrawingWarship?>
{
public int Compare(DrawingWarship? x, DrawingWarship? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityWarship == null)
{
return 1;
}
if (y == null || y.EntityWarship == null)
{
return -1;
}
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,59 @@
using ProjectBattleship.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectBattleship.DrawingObject;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningWarshipEqutables : IEqualityComparer<DrawingWarship?>
{
public bool Equals(DrawingWarship? x, DrawingWarship? y)
{
if (x == null || x.EntityWarship == null)
{
return false;
}
if (y == null || y.EntityWarship == null)
{
return false;
}
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 DrawingBattleship && y is DrawingBattleship)
{
if (((EntityBattleship)x.EntityWarship).AdditionalColor !=
((EntityBattleship)y.EntityWarship).AdditionalColor)
{
return false;
}
if (((EntityBattleship)x.EntityWarship).RocketCompartment !=
((EntityBattleship)y.EntityWarship).RocketCompartment)
{
return false;
}
if (((EntityBattleship)x.EntityWarship).Turret !=
((EntityBattleship)y.EntityWarship).Turret)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingWarship obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,12 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.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,13 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
public class CollectionInfoException : Exception
{
public CollectionInfoException() : base() { }
public CollectionInfoException(string message) : base(message) { }
public CollectionInfoException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionInfoException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
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

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
public class CollectionTypeException : Exception
{
public CollectionTypeException() : base() { }
public CollectionTypeException(string message) : base(message) { }
public CollectionTypeException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionTypeException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
public class DrawningEquitablesException : Exception
{
public DrawningEquitablesException() : base("Объекты прорисовки одинаковые") { }
public DrawningEquitablesException(string message) : base(message) { }
public DrawningEquitablesException(string message, Exception exception) :
base(message, exception)
{ }
protected DrawningEquitablesException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) :
base(message, exception)
{ }
protected EmptyFileExeption(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
public class FileFormatException : Exception
{
public FileFormatException() : base() { }
public FileFormatException(string message) : base(message) { }
public FileFormatException(string name, Exception exception) :
base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception)
{ }
protected FileFormatException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace ProjectBattleship.Exceptions;
public class FileNotFoundException : Exception
{
public FileNotFoundException(string name) : base($"Файл {name} не существует ") { }
public FileNotFoundException() : base() { }
public FileNotFoundException(string name, string message) : base(message) { }
public FileNotFoundException(string name, string message, Exception exception) :
base(message, exception)
{ }
protected FileNotFoundException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -33,7 +33,6 @@ namespace ProjectBattleship
groupBoxCollectionTools = new GroupBox(); groupBoxCollectionTools = new GroupBox();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonRefresh = new Button(); buttonRefresh = new Button();
buttonAddBattleship = new Button();
maskedTextBoxPosition = new MaskedTextBox(); maskedTextBoxPosition = new MaskedTextBox();
buttonAddWarship = new Button(); buttonAddWarship = new Button();
buttonGoToCheck = new Button(); buttonGoToCheck = new Button();
@ -71,7 +70,7 @@ namespace ProjectBattleship
groupBoxCollectionTools.Controls.Add(panelCollection); groupBoxCollectionTools.Controls.Add(panelCollection);
groupBoxCollectionTools.Location = new Point(699, 27); groupBoxCollectionTools.Location = new Point(699, 27);
groupBoxCollectionTools.Name = "groupBoxCollectionTools"; groupBoxCollectionTools.Name = "groupBoxCollectionTools";
groupBoxCollectionTools.Size = new Size(279, 618); groupBoxCollectionTools.Size = new Size(279, 653);
groupBoxCollectionTools.TabIndex = 1; groupBoxCollectionTools.TabIndex = 1;
groupBoxCollectionTools.TabStop = false; groupBoxCollectionTools.TabStop = false;
groupBoxCollectionTools.Text = "Инструменты"; groupBoxCollectionTools.Text = "Инструменты";
@ -79,7 +78,6 @@ namespace ProjectBattleship
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonAddBattleship);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonAddWarship); panelCompanyTools.Controls.Add(buttonAddWarship);
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
@ -87,12 +85,12 @@ namespace ProjectBattleship
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 354); panelCompanyTools.Location = new Point(6, 354);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(267, 234); panelCompanyTools.Size = new Size(267, 208);
panelCompanyTools.TabIndex = 11; panelCompanyTools.TabIndex = 11;
// //
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Location = new Point(8, 203); buttonRefresh.Location = new Point(8, 163);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(251, 34); buttonRefresh.Size = new Size(251, 34);
buttonRefresh.TabIndex = 7; buttonRefresh.TabIndex = 7;
@ -100,19 +98,9 @@ namespace ProjectBattleship
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click; buttonRefresh.Click += ButtonRefresh_Click;
// //
// buttonAddBattleship
//
buttonAddBattleship.Location = new Point(8, 46);
buttonAddBattleship.Name = "buttonAddBattleship";
buttonAddBattleship.Size = new Size(251, 34);
buttonAddBattleship.TabIndex = 3;
buttonAddBattleship.Text = "Добавить линкор";
buttonAddBattleship.UseVisualStyleBackColor = true;
buttonAddBattleship.Click += ButtonAddBattleship_Click;
//
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(8, 86); maskedTextBoxPosition.Location = new Point(8, 46);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(251, 31); maskedTextBoxPosition.Size = new Size(251, 31);
@ -131,7 +119,7 @@ namespace ProjectBattleship
// //
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Location = new Point(8, 163); buttonGoToCheck.Location = new Point(8, 123);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(251, 34); buttonGoToCheck.Size = new Size(251, 34);
buttonGoToCheck.TabIndex = 6; buttonGoToCheck.TabIndex = 6;
@ -141,7 +129,7 @@ namespace ProjectBattleship
// //
// buttonRemoveWarship // buttonRemoveWarship
// //
buttonRemoveWarship.Location = new Point(8, 123); buttonRemoveWarship.Location = new Point(8, 83);
buttonRemoveWarship.Name = "buttonRemoveWarship"; buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(251, 34); buttonRemoveWarship.Size = new Size(251, 34);
buttonRemoveWarship.TabIndex = 5; buttonRemoveWarship.TabIndex = 5;
@ -256,7 +244,7 @@ namespace ProjectBattleship
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
pictureBox.Location = new Point(0, 51); pictureBox.Location = new Point(0, 51);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(688, 567); pictureBox.Size = new Size(688, 602);
pictureBox.TabIndex = 2; pictureBox.TabIndex = 2;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -305,7 +293,7 @@ namespace ProjectBattleship
// //
AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(978, 618); ClientSize = new Size(978, 653);
Controls.Add(groupBoxCollectionTools); Controls.Add(groupBoxCollectionTools);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -326,7 +314,6 @@ namespace ProjectBattleship
#endregion #endregion
private GroupBox groupBoxCollectionTools; private GroupBox groupBoxCollectionTools;
private Button buttonAddBattleship;
private Button buttonAddWarship; private Button buttonAddWarship;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private Button buttonRefresh; private Button buttonRefresh;