LabWork08

This commit is contained in:
Osyagina_Anna 2024-05-16 12:16:23 +04:00
parent e5657c372e
commit 181f1c8dff
31 changed files with 729 additions and 229 deletions

25
Kurs/BinarTree.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kurs", "Kurs\Kurs.csproj", "{94C1974E-4EC3-48C5-A512-D5417A368FF7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{94C1974E-4EC3-48C5-A512-D5417A368FF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94C1974E-4EC3-48C5-A512-D5417A368FF7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94C1974E-4EC3-48C5-A512-D5417A368FF7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94C1974E-4EC3-48C5-A512-D5417A368FF7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {39688B3A-AC5C-4AC2-9E32-EABC073DCE9D}
EndGlobalSection
EndGlobal

39
Kurs/Kurs/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,39 @@
namespace Kurs
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

10
Kurs/Kurs/Form1.cs Normal file
View File

@ -0,0 +1,10 @@
namespace Kurs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

120
Kurs/Kurs/Form1.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

11
Kurs/Kurs/Kurs.csproj Normal file
View File

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

134
Kurs/Kurs/Program.cs Normal file
View File

@ -0,0 +1,134 @@
namespace BinarTree;
class Node
{
public int Data;
public Node Left, Right;
public Node(int item)
{
Data = item;
Left = Right = null;
}
}
class BinaryTree
{
Node root;
BinaryTree()
{
root = null;
}
void Insert(int key)
{
root = InsertRec(root, key);
}
Node InsertRec(Node root, int key)
{
if (root == null)
{
root = new Node(key);
return root;
}
if (key < root.Data)
root.Left = InsertRec(root.Left, key);
else if (key > root.Data)
root.Right = InsertRec(root.Right, key);
return root;
}
void Delete(int key)
{
root = DeleteRec(root, key);
}
Node DeleteRec(Node root, int key)
{
if (root == null) return root;
if (key < root.Data)
root.Left = DeleteRec(root.Left, key);
else if (key > root.Data)
root.Right = DeleteRec(root.Right, key);
else
{
if (root.Left == null)
return root.Right;
else if (root.Right == null)
return root.Left;
root.Data = MinValue(root.Right);
root.Right = DeleteRec(root.Right, root.Data);
}
return root;
}
int MinValue(Node root)
{
int minv = root.Data;
while (root.Left != null)
{
minv = root.Left.Data;
root = root.Left;
}
return minv;
}
void Inorder()
{
InorderRec(root);
}
void InorderRec(Node root)
{
if (root != null)
{
InorderRec(root.Left);
Console.Write(root.Data + " ");
InorderRec(root.Right);
}
}
public static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
// Âñòàâêà ýëåìåíòîâ
tree.Insert(50);
tree.Insert(30);
tree.Insert(20);
tree.Insert(40);
tree.Insert(70);
tree.Insert(60);
tree.Insert(80);
Console.WriteLine("Binary Tree äî óäàëåíèÿ ýëåìåíòîâ : ");
tree.Inorder();
// Óäàëåíèå ýëåìåíòîâ
Console.WriteLine("\n\nÓäàëåíèå 20");
tree.Delete(20);
Console.WriteLine("Binary Tree ïîñëå óäàëåíèÿ 20: ");
tree.Inorder();
Console.WriteLine("\n\nÓäàëåíèå 30");
tree.Delete(30);
Console.WriteLine("Binary Tree ïîñëå óäàëåíèÿ 30: ");
tree.Inorder();
Console.WriteLine("\n\nÓäàëåíèå 50");
tree.Delete(50);
Console.WriteLine("Binary Tree ïîñëå óäàëåíèÿ 50: ");
tree.Inorder();
}
}

View File

@ -1,5 +1,4 @@

using ProjectMotorboat.Drownings;
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
@ -28,7 +27,7 @@ public abstract class AbstractCompany
}
public static int operator +(AbstractCompany company, DrawningBoat boat)
{
return company._collection.Insert(boat);
return company._collection.Insert(boat, new DrawningBoatEqutables());
}
public static DrawningBoat operator -(AbstractCompany company, int position)
@ -62,6 +61,7 @@ public abstract class AbstractCompany
return bitmap;
}
public void Sort(IComparer<DrawningBoat?> comparer) => _collection?.CollectionSort(comparer);
protected abstract void DrawBackgound(Graphics g);
protected abstract void SetObjectsPosition();

View File

@ -0,0 +1,45 @@
namespace ProjectMotorboat.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
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

@ -1,8 +1,6 @@
namespace ProjectMotorboat.CollectionGenericObjects;
public enum CollectionType
{
None = 0,
Massive = 1,
List = 2

View File

@ -2,8 +2,6 @@
using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
public class HarborService : AbstractCompany
{
public HarborService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBoat> collection) : base(picWidth, picHeight, collection)

View File

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

View File

@ -40,17 +40,40 @@ where T : class
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new CollectionOverflowException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new CollectionOverflowException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
_collection.Insert(position, obj);
return position;
}
@ -71,4 +94,8 @@ where T : class
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,6 +1,4 @@

using ProjectMotorboat.Exceptions;
using ProjectMotorboat.Exceptions;
namespace ProjectMotorboat.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
@ -46,9 +44,30 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
for (int i = 0; i < Count; i++)
return Insert(obj, 0, comparer);
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new CollectionOverflowException();
}
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
for (int i = position + 1; i < Count; i++)
{
if (_collection[i] == null)
{
@ -56,47 +75,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
for (int i = position - 1; i >= 0; i--)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
if (_collection[i] == null)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
_collection[i] = obj;
return i;
}
}
_collection[position] = obj;
return position;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
@ -115,6 +104,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -1,55 +1,57 @@
using ProjectMotorboat.Drownings;
using ProjectMotorboat.Exceptions;
using System.Text;
namespace ProjectMotorboat.CollectionGenericObjects;
public class StorageCollection<T>
where T : DrawningBoat
{
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
private Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name)) { return; }
switch (collectionType)
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
return;
return;
}
if (collectionType == CollectionType.None)
{
return;
}
else if (collectionType == CollectionType.Massive)
{
_storages[collectionInfo] = new MassiveGenericObjects<T>();
}
else if (collectionType == CollectionType.List)
{
_storages[collectionInfo] = new ListGenericObjects<T>();
}
}
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(collectionInfo);
}
}
public ICollectionGenericObjects<T>? this[string name]
{
get
{
// TODO Продумать логику получения объекта
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return _storages[collectionInfo];
}
return null;
}
}
@ -58,39 +60,33 @@ public class StorageCollection<T>
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
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();
sb.Append(Environment.NewLine);
writer.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -98,78 +94,72 @@ public class StorageCollection<T>
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
writer.Write(data);
writer.Write(_separatorItems);
}
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
using (StreamReader read = File.OpenText(filename))
{
string str = fs.ReadLine();
string str = read.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
throw new FormatException("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
throw new FormatException("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
while ((strs = read.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);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new InvalidOperationException("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBoat() is T track)
if (elem?.CreateDrawningBoat() is T boat)
{
try
{
if (collection.Insert(track) == -1)
if (collection.Insert(boat) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch

View File

@ -1,6 +1,4 @@

namespace ProjectMotorboat.Drownings
namespace ProjectMotorboat.Drownings
{
public enum DirectionType
{

View File

@ -1,6 +1,4 @@
using ProjectMotorboat.Entities;
namespace ProjectMotorboat.Drownings;
public class DrawningBoat
@ -142,8 +140,6 @@ public class DrawningBoat
return false;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityBoat == null || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -0,0 +1,30 @@
namespace ProjectMotorboat.Drownings;
public class DrawningBoatCompareByColor : IComparer<DrawningBoat?>
{
public int Compare(DrawningBoat? x, DrawningBoat? y)
{
if (x == null || x.EntityBoat == null)
{
return -1;
}
if (y == null || y.EntityBoat == null)
{
return 1;
}
if (x.EntityBoat.BodyColor.Name != y.EntityBoat.BodyColor.Name)
{
return x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name);
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}

View File

@ -0,0 +1,30 @@
namespace ProjectMotorboat.Drownings;
public class DrawningBoatCompareByType : IComparer<DrawningBoat?>
{
public int Compare(DrawningBoat? x, DrawningBoat? y)
{
if (x == null || x.EntityBoat == null)
{
return -1;
}
if (y == null || y.EntityBoat == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}

View File

@ -0,0 +1,66 @@
using ProjectMotorboat.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectMotorboat.Drownings;
public class DrawningBoatEqutables : IEqualityComparer<DrawningBoat>
{
public bool Equals(DrawningBoat? x, DrawningBoat? y)
{
if (x == null || x.EntityBoat == null)
{
return false;
}
if (y == null || y.EntityBoat == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBoat.Speed != y.EntityBoat.Speed)
{
return false;
}
if (x.EntityBoat.Weight != y.EntityBoat.Weight)
{
return false;
}
if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor)
{
return false;
}
if (x is DrawningMotorboat && y is DrawningMotorboat)
{
EntityMotorboat EntityX = (EntityMotorboat)x.EntityBoat;
EntityMotorboat EntityY = (EntityMotorboat)y.EntityBoat;
if (EntityX.Glass != EntityY.Glass)
{
return false;
}
if (EntityX.Motor != EntityY.Motor)
{
return false;
}
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBoat obj)
{
return obj.GetHashCode();
}
}

View File

@ -1,5 +1,4 @@
using ProjectMotorboat.Entities;
namespace ProjectMotorboat.Drownings;
public class DrawningMotorboat : DrawningBoat

View File

@ -1,10 +1,4 @@
using ProjectMotorboat.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.Drownings;
public static class ExtentionDrawningBoat
{

View File

@ -1,11 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMotorboat.Entities;
namespace ProjectMotorboat.Entities;
public class EntityBoat
{
public int Speed { get; private set; }
@ -30,12 +23,6 @@ public class EntityBoat
{
return new[] { nameof(EntityBoat), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBoat? CreateEntityBoat(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityBoat))

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectMotorboat.Exceptions;
[Serializable]
internal class ObjectNotFoundException : ApplicationException

View File

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ProjectMotorboat.Exceptions;
[Serializable]

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -66,15 +68,17 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1027, 28);
groupBoxTools.Location = new Point(967, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(231, 718);
groupBoxTools.Size = new Size(231, 681);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddBoat);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -82,9 +86,9 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 390);
panelCompanyTools.Location = new Point(3, 359);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(225, 325);
panelCompanyTools.Size = new Size(225, 319);
panelCompanyTools.TabIndex = 7;
//
// buttonAddBoat
@ -92,7 +96,7 @@
buttonAddBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBoat.Location = new Point(3, 3);
buttonAddBoat.Name = "buttonAddBoat";
buttonAddBoat.Size = new Size(219, 54);
buttonAddBoat.Size = new Size(219, 30);
buttonAddBoat.TabIndex = 1;
buttonAddBoat.Text = "Добавление лодки";
buttonAddBoat.UseVisualStyleBackColor = true;
@ -100,7 +104,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(3, 123);
maskedTextBox.Location = new Point(3, 39);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(219, 27);
@ -110,9 +114,9 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 276);
buttonRefresh.Location = new Point(3, 156);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(219, 54);
buttonRefresh.Size = new Size(219, 31);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -121,9 +125,9 @@
// buttonDelBoat
//
buttonDelBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelBoat.Location = new Point(3, 156);
buttonDelBoat.Location = new Point(3, 72);
buttonDelBoat.Name = "buttonDelBoat";
buttonDelBoat.Size = new Size(222, 54);
buttonDelBoat.Size = new Size(222, 37);
buttonDelBoat.TabIndex = 4;
buttonDelBoat.Text = "удалить лодку";
buttonDelBoat.UseVisualStyleBackColor = true;
@ -132,9 +136,9 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 216);
buttonGoToCheck.Location = new Point(3, 115);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(219, 54);
buttonGoToCheck.Size = new Size(219, 35);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -142,7 +146,7 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 383);
buttonCreateCompany.Location = new Point(3, 324);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(222, 29);
buttonCreateCompany.TabIndex = 8;
@ -162,12 +166,12 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 23);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(225, 320);
panelStorage.Size = new Size(225, 261);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(0, 251);
buttonCollectionDel.Location = new Point(0, 220);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(222, 29);
buttonCollectionDel.TabIndex = 6;
@ -178,14 +182,14 @@
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.Location = new Point(3, 141);
listBoxCollection.Location = new Point(3, 130);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(213, 104);
listBoxCollection.Size = new Size(213, 84);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 106);
buttonCollectionAdd.Location = new Point(0, 95);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(222, 29);
buttonCollectionAdd.TabIndex = 4;
@ -196,7 +200,7 @@
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(121, 76);
radioButtonList.Location = new Point(136, 65);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 3;
@ -207,7 +211,7 @@
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(13, 76);
radioButtonMassive.Location = new Point(14, 65);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2;
@ -217,7 +221,7 @@
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 43);
textBoxCollectionName.Location = new Point(3, 32);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(219, 27);
textBoxCollectionName.TabIndex = 1;
@ -225,7 +229,7 @@
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(43, 20);
labelCollectionName.Location = new Point(31, 9);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(158, 20);
labelCollectionName.TabIndex = 0;
@ -237,7 +241,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 349);
comboBoxSelectorCompany.Location = new Point(6, 290);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(213, 28);
comboBoxSelectorCompany.TabIndex = 0;
@ -248,7 +252,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1027, 718);
pictureBox.Size = new Size(967, 681);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -258,7 +262,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1258, 28);
menuStrip.Size = new Size(1198, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
@ -289,11 +293,33 @@
//
saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 259);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(219, 31);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 218);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(219, 35);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormBoatCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1258, 746);
ClientSize = new Size(1198, 709);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -338,5 +364,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -1,7 +1,6 @@
using Microsoft.Extensions.Logging;
using ProjectMotorboat.CollectionGenericObjects;
using ProjectMotorboat.Drownings;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectMotorboat;
@ -50,7 +49,7 @@ public partial class FormBoatCollection : Form
}
catch (Exception ex)
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBox.Show($"Такой объект уже присутствует в коллекции", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
@ -185,7 +184,7 @@ public partial class FormBoatCollection : 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);
@ -257,4 +256,22 @@ public partial class FormBoatCollection : Form
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareBoat(new DrawningBoatCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareBoat(new DrawningBoatCompareByColor());
}
private void CompareBoat(IComparer<DrawningBoat?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

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

View File

@ -1,25 +1,16 @@

namespace ProjectMotorboat.MovementStrategy;
namespace ProjectMotorboat.MovementStrategy;
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private StrategyStatus _state = StrategyStatus.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public StrategyStatus GetStatus() { return _state; }
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
@ -34,7 +25,6 @@ public abstract class AbstractStrategy
FieldHeight = height;
}
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
@ -51,22 +41,16 @@ public abstract class AbstractStrategy
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
protected bool MoveRight() => MoveTo(MovementDirection.Right);
protected bool MoveUp() => MoveTo(MovementDirection.Up);
protected bool MoveDown() => MoveTo(MovementDirection.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
@ -76,13 +60,10 @@ public abstract class AbstractStrategy
return _moveableObject?.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestinaion();
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)

View File

@ -1,6 +1,4 @@

namespace ProjectMotorboat.MovementStrategy;
namespace ProjectMotorboat.MovementStrategy;
public interface IMoveableObject
{
@ -8,7 +6,6 @@ public interface IMoveableObject
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
bool TryMoveObject(MovementDirection direction);
}

View File

@ -1,6 +1,4 @@

namespace ProjectMotorboat.MovementStrategy;
namespace ProjectMotorboat.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()

View File

@ -1,6 +1,5 @@
using ProjectMotorboat.Drownings;
namespace ProjectMotorboat.MovementStrategy;
public class MoveableBoat : IMoveableObject