PIbd-21_MasenkinMS_LabWork03 #4

Closed
Factorino73 wants to merge 3 commits from LabWork03 into LabWork02
12 changed files with 719 additions and 26 deletions

View File

@ -38,6 +38,7 @@
comboBoxStrategy = new ComboBox();
buttonCreateBus = new Button();
buttonStep = new Button();
buttonSelectBus = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit();
SuspendLayout();
//
@ -144,11 +145,25 @@
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonSelectBus
//
buttonSelectBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSelectBus.AutoSizeMode = AutoSizeMode.GrowAndShrink;
buttonSelectBus.Location = new Point(275, 409);
buttonSelectBus.Name = "buttonSelectBus";
buttonSelectBus.RightToLeft = RightToLeft.No;
buttonSelectBus.Size = new Size(124, 41);
buttonSelectBus.TabIndex = 9;
buttonSelectBus.Text = "Выбрать автобус";
buttonSelectBus.UseVisualStyleBackColor = true;
buttonSelectBus.Click += buttonSelectBus_Click;
//
// AccordionBusForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(buttonSelectBus);
Controls.Add(buttonStep);
Controls.Add(buttonCreateBus);
Controls.Add(comboBoxStrategy);
@ -174,5 +189,6 @@
private ComboBox comboBoxStrategy;
private Button buttonCreateBus;
private Button buttonStep;
private Button buttonSelectBus;
}
}

View File

@ -20,12 +20,19 @@ namespace AccordionBus
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âűáđŕííűé ŕâňîáóń
/// </summary>
public DrawingBus? SelectedBus { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public AccordionBusForm()
{
InitializeComponent();
_abstractStrategy = null;
SelectedBus = null;
}
/// <summary>
@ -52,11 +59,28 @@ namespace AccordionBus
/// <param name="e"></param>
private void buttonCreateAccordionBus_Click(object sender, EventArgs e)
{
Random random = new Random();
Random random = new();
// Âűáîđ îńíîâíîăî öâĺňŕ
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
bodyColor = dialog.Color;
}
// Âűáîđ äîďîëíčňĺëüíîăî öâĺňŕ
Color additionalColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
additionalColor = dialog.Color;
}
_drawingBus = new DrawingAccordionBus(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
bodyColor,
additionalColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxAccordionBus.Width,
@ -74,10 +98,19 @@ namespace AccordionBus
/// <param name="e"></param>
private void buttonCreateBus_Click(object sender, EventArgs e)
{
Random random = new Random();
Random random = new();
// Âűáîđ îńíîâíîăî öâĺňŕ
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
bodyColor = dialog.Color;
}
_drawingBus = new DrawingBus(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
bodyColor,
pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
@ -162,5 +195,16 @@ namespace AccordionBus
_abstractStrategy = null;
}
}
/// <summary>
/// Âűáîđ ŕâňîáóńŕ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSelectBus_Click(object sender, EventArgs e)
{
SelectedBus = _drawingBus;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,133 @@
namespace AccordionBus
{
partial class BusCollectionForm
{
/// <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()
{
pictureBoxCollection = new PictureBox();
panelTools = new Panel();
maskedTextBox = new MaskedTextBox();
buttonRefreshCollection = new Button();
buttonRemoveBus = new Button();
buttonAddBus = new Button();
labelTools = new Label();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(700, 461);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// panelTools
//
panelTools.Controls.Add(maskedTextBox);
panelTools.Controls.Add(buttonRefreshCollection);
panelTools.Controls.Add(buttonRemoveBus);
panelTools.Controls.Add(buttonAddBus);
panelTools.Controls.Add(labelTools);
panelTools.Location = new Point(706, 0);
panelTools.Name = "panelTools";
panelTools.Size = new Size(174, 461);
panelTools.TabIndex = 1;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(30, 160);
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(120, 23);
maskedTextBox.TabIndex = 4;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(30, 290);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(120, 40);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// buttonRemoveBus
//
buttonRemoveBus.Location = new Point(30, 190);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(120, 40);
buttonRemoveBus.TabIndex = 2;
buttonRemoveBus.Text = "Удалить автобус";
buttonRemoveBus.UseVisualStyleBackColor = true;
buttonRemoveBus.Click += buttonRemoveBus_Click;
//
// buttonAddBus
//
buttonAddBus.Location = new Point(30, 60);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(120, 40);
buttonAddBus.TabIndex = 1;
buttonAddBus.Text = "Добавить автобус";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += buttonAddBus_Click;
//
// labelTools
//
labelTools.AutoSize = true;
labelTools.Location = new Point(0, 0);
labelTools.Name = "labelTools";
labelTools.Size = new Size(83, 15);
labelTools.TabIndex = 0;
labelTools.Text = "Инструменты";
//
// BusCollectionForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
Name = "BusCollectionForm";
Text = "BusCollectionForm";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panelTools;
private Label labelTools;
private MaskedTextBox maskedTextBox;
private Button buttonRefreshCollection;
private Button buttonRemoveBus;
private Button buttonAddBus;
}
}

View File

@ -0,0 +1,92 @@
using AccordionBus.Drawings;
using AccordionBus.Generics;
using AccordionBus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccordionBus
{
/// <summary>
/// Форма для работы с набором объектов класса DrawingBus
/// </summary>
public partial class BusCollectionForm : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly BusGenericCollection<DrawingBus, DrawingObjectBus> _buses;
/// <summary>
/// Конструктор
/// </summary>
public BusCollectionForm()
{
InitializeComponent();
_buses = new BusGenericCollection<DrawingBus, DrawingObjectBus>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddBus_Click(object sender, EventArgs e)
{
AccordionBusForm form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_buses + form.SelectedBus > -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _buses.ShowBuses();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemoveBus_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_buses - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _buses.ShowBuses();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _buses.ShowBuses();
}
}
}

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>

View File

@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawings;
using AccordionBus.MovementStrategy;
namespace AccordionBus.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawingBus
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class BusGenericCollection<T, U>
where T : DrawingBus
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 215;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 50;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина картинки</param>
/// <param name="picHeight">Высота картинки</param>
public BusGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(BusGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
}
return collect?._collection.Insert(obj) ?? -1;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool operator -(BusGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
return collect._collection.Remove(pos);
}
return false;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos">Позиция</param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowBuses()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics g = Graphics.FromImage(bmp);
DrawBackground(g);
DrawObjects(g);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; j++)
{
// Линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void DrawObjects(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
{
// Получение объекта
var obj = _collection.Get(i);
// Установка позиции
obj?.SetPosition(
(int)((width - 1) * _placeSizeWidth - (i % width * _placeSizeWidth)),
(int)((height - 1) * _placeSizeHeight - (i / width * _placeSizeHeight))
);
// Прорисовка объекта
obj?.DrawTransport(g);
}
}
}
}

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Entities;
using AccordionBus.MovementStrategy;
namespace AccordionBus.Drawings
{
@ -65,7 +66,12 @@ namespace AccordionBus.Drawings
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeigth => _busHeight;
public int GetHeight => _busHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectBus(this);
/// <summary>
/// Проверка, что объект может перемещаться по указанному направлению
@ -103,16 +109,15 @@ namespace AccordionBus.Drawings
/// <param name="height">Высота картинки</param>
public DrawingBus(int speed, int weight, Color bodyColor, int width, int height)
{
// Проверка на вместимость объекта в размеры картинки
if ((_busWidth >= width) || (_busHeight >= height))
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityBus = new EntityBus(speed, weight, bodyColor);
// Проверка на вместимость объекта в размеры картинки
if ((_busWidth >= _pictureWidth) || (_busHeight >= _pictureHeight))
{
Console.WriteLine("Ошибка! Нельзя создать рбъект такого размера!");
return;
}
}
/// <summary>
@ -127,18 +132,17 @@ namespace AccordionBus.Drawings
/// <param name="busHeight">Выоста прорисовки автобуса</param>
protected DrawingBus(int speed, double weight, Color bodyColor, int width, int height, int busWidth, int busHeight)
{
// Проверка на вместимость объекта в размеры картинки
if ((_busWidth >= width) || (_busHeight >= height))
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_busWidth = busWidth;
_busHeight = busHeight;
EntityBus = new EntityBus(speed, weight, bodyColor);
// Проверка на вместимость объекта в размеры картинки
if ((_busWidth >= _pictureWidth) || (_busHeight >= _pictureHeight))
{
Console.WriteLine("Ошибка! Нельзя создать рбъект такого размера!");
return;
}
}
/// <summary>
@ -148,7 +152,12 @@ namespace AccordionBus.Drawings
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if ((x + _busWidth > _pictureWidth) || (y + _busHeight > _pictureHeight))
if (x < 0 || y < 0)
{
_startPosX = 0;
_startPosY = 0;
}
else if ((x + _busWidth > _pictureWidth) || (y + _busHeight > _pictureHeight))
{
_startPosX = _pictureWidth - _busWidth;
_startPosY = _pictureHeight - _busHeight;

View File

@ -27,7 +27,7 @@ namespace AccordionBus.MovementStrategy
{
return null;
}
return new ObjectParameters(_drawingBus.GetPosX, _drawingBus.GetPosY, _drawingBus.GetWidth, _drawingBus.GetHeigth);
return new ObjectParameters(_drawingBus.GetPosX, _drawingBus.GetPosY, _drawingBus.GetWidth, _drawingBus.GetHeight);
}
}

View File

@ -11,7 +11,7 @@ namespace AccordionBus.MovementStrategy
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
internal interface IMoveableObject
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта

View File

@ -7,9 +7,9 @@ using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Параметры-координаты рбъекта
/// Параметры-координаты объекта
/// </summary>
internal class ObjectParameters
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;

View File

@ -11,7 +11,7 @@ namespace AccordionBus
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new AccordionBusForm());
Application.Run(new BusCollectionForm());
}
}
}

View File

@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T> where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <returns></returns>
public int Insert(T bus)
{
return Insert(bus, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T bus, int position)
{
// Проверка позиции
if (position < 0 || position >= Count)
{
return -1;
}
// Проверка, что элемент массива по этой позиции пустой
if (_places[position] != null)
{
// Проверка, что после вставляемого элемента в массиве есть пустой элемент
int index = -1;
for (int i = position + 1; i < Count; i++)
{
if (_places[i] == null)
{
index = i;
break;
}
}
// Проверка, если пустого элемента нет
if (index == -1)
{
return -1;
}
// Сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
int j = index - 1;
while (j >= position)
{
_places[j + 1] = _places[j];
j--;
}
}
// Вставка по позиции
_places[position] = bus;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position">Позициия</param>
/// <returns></returns>
public bool Remove(int position)
{
// Проверка позиции
if (position < 0 || position >= Count)
{
return false;
}
// Удаление объекта из массива, присвоив элементу массива значение null
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns></returns>
public T? Get(int position)
{
// Проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
}
}