Compare commits

...

11 Commits

39 changed files with 6066 additions and 76 deletions

View File

@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawings;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
internal abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
/// <returns></returns>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestination())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалость переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалость переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалость переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалость переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
protected abstract bool IsTargetDestination();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат перемещения (true - удалость переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -8,4 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -0,0 +1,194 @@
namespace AccordionBus
{
partial class AccordionBusForm
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AccordionBusForm));
buttonCreateAccordionBus = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonUp = new Button();
pictureBoxAccordionBus = new PictureBox();
comboBoxStrategy = new ComboBox();
buttonCreateBus = new Button();
buttonStep = new Button();
buttonSelectBus = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit();
SuspendLayout();
//
// buttonCreateAccordionBus
//
buttonCreateAccordionBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAccordionBus.AutoSizeMode = AutoSizeMode.GrowAndShrink;
buttonCreateAccordionBus.Location = new Point(15, 409);
buttonCreateAccordionBus.Name = "buttonCreateAccordionBus";
buttonCreateAccordionBus.RightToLeft = RightToLeft.No;
buttonCreateAccordionBus.Size = new Size(124, 41);
buttonCreateAccordionBus.TabIndex = 0;
buttonCreateAccordionBus.Text = "Создать автобус-гармошку";
buttonCreateAccordionBus.UseVisualStyleBackColor = true;
buttonCreateAccordionBus.Click += buttonCreateAccordionBus_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.Right1;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(840, 420);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 1;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(804, 419);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 2;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(768, 420);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 3;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage");
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(804, 383);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 4;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// pictureBoxAccordionBus
//
pictureBoxAccordionBus.Dock = DockStyle.Fill;
pictureBoxAccordionBus.Location = new Point(0, 0);
pictureBoxAccordionBus.Name = "pictureBoxAccordionBus";
pictureBoxAccordionBus.Size = new Size(884, 461);
pictureBoxAccordionBus.TabIndex = 5;
pictureBoxAccordionBus.TabStop = false;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" });
comboBoxStrategy.Location = new Point(768, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(102, 23);
comboBoxStrategy.TabIndex = 6;
//
// buttonCreateBus
//
buttonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBus.AutoSizeMode = AutoSizeMode.GrowAndShrink;
buttonCreateBus.Location = new Point(145, 409);
buttonCreateBus.Name = "buttonCreateBus";
buttonCreateBus.RightToLeft = RightToLeft.No;
buttonCreateBus.Size = new Size(124, 41);
buttonCreateBus.TabIndex = 7;
buttonCreateBus.Text = "Создать автобус";
buttonCreateBus.UseVisualStyleBackColor = true;
buttonCreateBus.Click += buttonCreateBus_Click;
//
// buttonStep
//
buttonStep.Location = new Point(795, 41);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 30);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
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);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonCreateAccordionBus);
Controls.Add(pictureBoxAccordionBus);
Name = "AccordionBusForm";
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonCreateAccordionBus;
private Button buttonRight;
private Button buttonDown;
private Button buttonLeft;
private Button buttonUp;
private PictureBox pictureBoxAccordionBus;
private ComboBox comboBoxStrategy;
private Button buttonCreateBus;
private Button buttonStep;
private Button buttonSelectBus;
}
}

View File

@ -0,0 +1,210 @@
using AccordionBus.Drawings;
using AccordionBus.MovementStrategy;
using System;
using System.Diagnostics.PerformanceData;
namespace AccordionBus
{
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Àâòîáóñ"
/// </summary>
public partial class AccordionBusForm : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingBus? _drawingBus;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âûáðàííûé àâòîáóñ
/// </summary>
public DrawingBus? SelectedBus { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public AccordionBusForm()
{
InitializeComponent();
_abstractStrategy = null;
SelectedBus = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè àâòîáóñà
/// </summary>
private void Draw()
{
if (_drawingBus == null)
{
return;
}
Bitmap bmp = new(pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingBus.DrawTransport(gr);
pictureBoxAccordionBus.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîáóñ-ãàðìîøêó"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAccordionBus_Click(object sender, EventArgs e)
{
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),
bodyColor,
additionalColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
_drawingBus.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîáóñ"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateBus_Click(object sender, EventArgs e)
{
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),
bodyColor,
pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
_drawingBus.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà äâèæåíèÿ îáúåêòà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingBus == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingBus.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectBus(_drawingBus),
pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_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;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,240 @@
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();
buttonDeleteObject = new Button();
listBoxStorages = new ListBox();
maskedTextBoxStorageName = new MaskedTextBox();
buttonAddObject = new Button();
maskedTextBoxNumber = new MaskedTextBox();
buttonRefreshCollection = new Button();
buttonRemoveBus = new Button();
buttonAddBus = new Button();
labelTools = new Label();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
menuStrip.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(buttonDeleteObject);
panelTools.Controls.Add(listBoxStorages);
panelTools.Controls.Add(maskedTextBoxStorageName);
panelTools.Controls.Add(buttonAddObject);
panelTools.Controls.Add(maskedTextBoxNumber);
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;
//
// buttonDeleteObject
//
buttonDeleteObject.Location = new Point(30, 180);
buttonDeleteObject.Name = "buttonDeleteObject";
buttonDeleteObject.Size = new Size(120, 40);
buttonDeleteObject.TabIndex = 8;
buttonDeleteObject.Text = "Удалить набор";
buttonDeleteObject.UseVisualStyleBackColor = true;
buttonDeleteObject.Click += buttonDeleteObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(30, 110);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(120, 64);
listBoxStorages.TabIndex = 7;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// maskedTextBoxStorageName
//
maskedTextBoxStorageName.Location = new Point(30, 30);
maskedTextBoxStorageName.Name = "maskedTextBoxStorageName";
maskedTextBoxStorageName.Size = new Size(120, 23);
maskedTextBoxStorageName.TabIndex = 6;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(30, 60);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(120, 40);
buttonAddObject.TabIndex = 5;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += buttonAddObject_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(30, 300);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(120, 23);
maskedTextBoxNumber.TabIndex = 4;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(30, 400);
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, 330);
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, 250);
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 = "Инструменты";
//
// menuStrip
//
menuStrip.Dock = DockStyle.None;
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(176, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(180, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(180, 22);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// BusCollectionForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(menuStrip);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
MainMenuStrip = menuStrip;
Name = "BusCollectionForm";
Text = "BusCollectionForm";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panelTools;
private Label labelTools;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonRefreshCollection;
private Button buttonRemoveBus;
private Button buttonAddBus;
private MaskedTextBox maskedTextBoxStorageName;
private Button buttonAddObject;
private Button buttonDeleteObject;
private ListBox listBoxStorages;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,272 @@
using AccordionBus.Drawings;
using AccordionBus.Exceptions;
using AccordionBus.Generics;
using AccordionBus.MovementStrategy;
using Microsoft.Extensions.Logging;
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 BusGenericStorage _storage;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public BusCollectionForm(ILogger<BusCollectionForm> logger)
{
InitializeComponent();
_storage = new BusGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение ListBoxObject
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(buttonAddObject.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось добавить набор: {maskedTextBoxStorageName.Text}. Не все данные заполнены");
return;
}
_storage.AddSet(maskedTextBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {maskedTextBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDeleteObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Не выбран набор для удаления");
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
_logger.LogWarning("Отмена удаления набора");
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddBus_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Не выбран набор для добавления объекта");
return;
}
BusConfigForm form = new BusConfigForm();
form.AddEvent(bus =>
{
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Выбранный набор не существует");
return;
}
try
{
if (obj + bus > -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBuses();
_logger.LogInformation($"Добавлен объект: {bus}");
}
}
catch (Exception ex)
{
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
MessageBox.Show($"Не удалось добавить объект: {ex.Message}");
}
});
form.Show();
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemoveBus_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Не выбран набор для удаления объекта");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Выбранный набор не существует");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos != false)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowBuses();
_logger.LogInformation($"Удален объект с позиции {pos}");
}
}
catch(Exception ex)
{
_logger.LogWarning($"Не удалось удалить объект: {ex.Message}");
MessageBox.Show($"Не удалось удалить объект: {ex.Message}");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowBuses();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение данных в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось сохранить данные: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить данные в файл: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загружены данные из файла: {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось загрузить данные: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить данные из файла: {ex.Message}");
}
}
}
}
}

View File

@ -0,0 +1,129 @@
<?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>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,369 @@
namespace AccordionBus
{
partial class BusConfigForm
{
/// <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()
{
groupBoxParameters = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
groupBoxColors = new GroupBox();
panelMagenta = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxAdditionalDoor = new CheckBox();
checkBoxAdditionalBody = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
panelObject = new Panel();
pictureBoxObject = new PictureBox();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxParameters.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxParameters
//
groupBoxParameters.Controls.Add(labelModifiedObject);
groupBoxParameters.Controls.Add(labelSimpleObject);
groupBoxParameters.Controls.Add(groupBoxColors);
groupBoxParameters.Controls.Add(checkBoxAdditionalDoor);
groupBoxParameters.Controls.Add(checkBoxAdditionalBody);
groupBoxParameters.Controls.Add(numericUpDownWeight);
groupBoxParameters.Controls.Add(labelWeight);
groupBoxParameters.Controls.Add(numericUpDownSpeed);
groupBoxParameters.Controls.Add(labelSpeed);
groupBoxParameters.Dock = DockStyle.Left;
groupBoxParameters.Location = new Point(0, 0);
groupBoxParameters.Name = "groupBoxParameters";
groupBoxParameters.Size = new Size(553, 231);
groupBoxParameters.TabIndex = 0;
groupBoxParameters.TabStop = false;
groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Font = new Font("Segoe UI", 12F, FontStyle.Regular, GraphicsUnit.Point);
labelModifiedObject.Location = new Point(410, 185);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(120, 30);
labelModifiedObject.TabIndex = 8;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += labelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Font = new Font("Segoe UI", 12F, FontStyle.Regular, GraphicsUnit.Point);
labelSimpleObject.Location = new Point(270, 185);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(120, 30);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += labelObject_MouseDown;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelMagenta);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(260, 30);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(280, 140);
groupBoxColors.TabIndex = 6;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelMagenta
//
panelMagenta.BackColor = Color.Magenta;
panelMagenta.BorderStyle = BorderStyle.FixedSingle;
panelMagenta.Location = new Point(220, 80);
panelMagenta.Name = "panelMagenta";
panelMagenta.Size = new Size(50, 50);
panelMagenta.TabIndex = 7;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.BorderStyle = BorderStyle.FixedSingle;
panelBlack.Location = new Point(150, 80);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(50, 50);
panelBlack.TabIndex = 6;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.BorderStyle = BorderStyle.FixedSingle;
panelGray.Location = new Point(80, 80);
panelGray.Name = "panelGray";
panelGray.Size = new Size(50, 50);
panelGray.TabIndex = 5;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.BorderStyle = BorderStyle.FixedSingle;
panelWhite.Location = new Point(10, 80);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(50, 50);
panelWhite.TabIndex = 4;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.BorderStyle = BorderStyle.FixedSingle;
panelYellow.Location = new Point(220, 20);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(50, 50);
panelYellow.TabIndex = 3;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.BorderStyle = BorderStyle.FixedSingle;
panelBlue.Location = new Point(150, 20);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(50, 50);
panelBlue.TabIndex = 2;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.BorderStyle = BorderStyle.FixedSingle;
panelGreen.Location = new Point(80, 20);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(50, 50);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.BorderStyle = BorderStyle.FixedSingle;
panelRed.Location = new Point(10, 20);
panelRed.Name = "panelRed";
panelRed.Size = new Size(50, 50);
panelRed.TabIndex = 0;
//
// checkBoxAdditionalDoor
//
checkBoxAdditionalDoor.AutoSize = true;
checkBoxAdditionalDoor.Location = new Point(30, 180);
checkBoxAdditionalDoor.Name = "checkBoxAdditionalDoor";
checkBoxAdditionalDoor.Size = new Size(154, 34);
checkBoxAdditionalDoor.TabIndex = 5;
checkBoxAdditionalDoor.Text = "Признак наличия\r\nдополнительной двери";
checkBoxAdditionalDoor.UseVisualStyleBackColor = true;
//
// checkBoxAdditionalBody
//
checkBoxAdditionalBody.AutoSize = true;
checkBoxAdditionalBody.Location = new Point(30, 140);
checkBoxAdditionalBody.Name = "checkBoxAdditionalBody";
checkBoxAdditionalBody.Size = new Size(163, 34);
checkBoxAdditionalBody.TabIndex = 4;
checkBoxAdditionalBody.Text = "Признак наличия\r\nдополнительного отсека";
checkBoxAdditionalBody.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(110, 70);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(120, 23);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(30, 70);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 2;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(110, 30);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(120, 23);
numericUpDownSpeed.TabIndex = 1;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(30, 30);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(pictureBoxObject);
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Location = new Point(549, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(335, 188);
panelObject.TabIndex = 10;
panelObject.DragDrop += panelObject_DragDrop;
panelObject.DragEnter += panelObject_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(20, 50);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(302, 124);
pictureBoxObject.TabIndex = 10;
pictureBoxObject.TabStop = false;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Font = new Font("Segoe UI", 12F, FontStyle.Regular, GraphicsUnit.Point);
labelAdditionalColor.Location = new Point(200, 10);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(120, 30);
labelAdditionalColor.TabIndex = 9;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Font = new Font("Segoe UI", 12F, FontStyle.Regular, GraphicsUnit.Point);
labelBodyColor.Location = new Point(20, 10);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(120, 30);
labelBodyColor.TabIndex = 8;
labelBodyColor.Text = "Осн. цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelColor_DragEnter;
//
// buttonAdd
//
buttonAdd.Location = new Point(569, 196);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(120, 30);
buttonAdd.TabIndex = 11;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(749, 196);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(120, 30);
buttonCancel.TabIndex = 12;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// BusConfigForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 231);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxParameters);
Name = "BusConfigForm";
Text = "Создание объекта";
groupBoxParameters.ResumeLayout(false);
groupBoxParameters.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private CheckBox checkBoxAdditionalBody;
private GroupBox groupBoxColors;
private Panel panelRed;
private CheckBox checkBoxAdditionalDoor;
private Panel panelGreen;
private Panel panelMagenta;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Label labelSimpleObject;
private Label labelModifiedObject;
private Panel panelObject;
private PictureBox pictureBoxObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AccordionBus.Drawings;
namespace AccordionBus
{
public partial class BusConfigForm : Form
{
/// <summary>
/// Переменная-выбранный автобус
/// </summary>
DrawingBus? _bus = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingBus> EventAddBus;
/// <summary>
/// Конструктор
/// </summary>
public BusConfigForm()
{
InitializeComponent();
panelRed.MouseDown += panelColor_MouseDown;
panelGreen.MouseDown += panelColor_MouseDown;
panelBlue.MouseDown += panelColor_MouseDown;
panelYellow.MouseDown += panelColor_MouseDown;
panelWhite.MouseDown += panelColor_MouseDown;
panelGray.MouseDown += panelColor_MouseDown;
panelBlack.MouseDown += panelColor_MouseDown;
panelMagenta.MouseDown += panelColor_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Отрисовать автобус
/// </summary>
private void DrawBus()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_bus?.SetPosition((pictureBoxObject.Width - _bus.GetWidth) / 2, (pictureBoxObject.Height - _bus.GetHeight) / 2);
_bus?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Событие</param>
public void AddEvent(Action<DrawingBus> ev)
{
if (EventAddBus == null)
{
EventAddBus = ev;
}
else
{
EventAddBus += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_bus = new DrawingBus((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.White,
900,
500);
break;
case "labelModifiedObject":
_bus = new DrawingAccordionBus((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.White,
Color.Black,
checkBoxAdditionalBody.Checked,
checkBoxAdditionalDoor.Checked,
900,
500);
break;
}
DrawBus();
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Получение основного цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_bus is DrawingBus bus)
{
labelBodyColor.BackColor = (Color)e.Data.GetData(typeof(Color));
bus.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
}
DrawBus();
}
/// <summary>
/// Получение дополнительного цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_bus is DrawingAccordionBus bus)
{
labelAdditionalColor.BackColor = (Color)e.Data.GetData(typeof(Color));
bus.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawBus();
}
/// <summary>
/// Добавление автобуса
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
EventAddBus?.Invoke(_bus);
Close();
}
}
}

View File

@ -1,24 +1,24 @@
<?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
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="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>
@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,15 @@
using AccordionBus.Drawings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus
{
/// <summary>
/// Делегат для передачи объекта-автобуса
/// </summary>
/// <param name="bus">Объект-автобус</param>
public delegate void BusDelegate(DrawingBus bus);
}

View File

@ -0,0 +1,158 @@
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>
public IEnumerable<T?> GetBuses => _collection.GetBuses();
/// <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)
{
throw new NullReferenceException();
}
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)
{
try
{
return collect._collection.Remove(pos);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos">Позиция</param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[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[i];
// Установка позиции
obj?.SetPosition(
(int)((width - 1) * _placeSizeWidth - (i % width * _placeSizeWidth)),
(int)((height - 1) * _placeSizeHeight - (i / width * _placeSizeHeight))
);
// Прорисовка объекта
obj?.DrawTransport(g);
}
}
}
}

View File

@ -0,0 +1,201 @@
using AccordionBus.Drawings;
using AccordionBus.Generics;
using AccordionBus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class BusGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, BusGenericCollection<DrawingBus, DrawingObjectBus>> _busStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _busStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth">Ширина картинки</param>
/// <param name="pictureHeight">Высота картинки</param>
public BusGenericStorage(int pictureWidth, int pictureHeight)
{
_busStorages = new Dictionary<string, BusGenericCollection<DrawingBus, DrawingObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_busStorages.Add(name, new BusGenericCollection<DrawingBus, DrawingObjectBus>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
// Проверка наличия ключа
if (!_busStorages.ContainsKey(name))
{
return;
}
_busStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BusGenericCollection<DrawingBus, DrawingObjectBus>? this[string ind]
{
get
{
// Проверка наличия ключа
if (_busStorages.ContainsKey(ind))
{
return _busStorages[ind];
}
return null;
}
}
/// <summary>
/// Сохранение информации по автобусам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, BusGenericCollection<DrawingBus, DrawingObjectBus>> record in _busStorages)
{
StringBuilder records = new();
foreach (DrawingBus? elem in record.Value.GetBuses)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения!");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"BusStorage{Environment.NewLine}{data}");
}
return true;
}
/// <summary>
/// Загрузка информации по автобусам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден!");
}
using (StreamReader reader = new StreamReader(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
// Если строка пустая
throw new IOException("Нет данных для загрузки!");
}
if (!line.StartsWith("BusStorage"))
{
// Если нет записи "BusStorage", то это не те данные
throw new FileFormatException("Неверный формат данных!");
}
_busStorages.Clear();
line = reader.ReadLine();
while (line != null && line.Length != 0)
{
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
BusGenericCollection<DrawingBus, DrawingObjectBus> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingBus? bus = elem?.CreateDrawingBus(_separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
if (collection + bus == -1)
{
throw new Exception("Ошибка добавления в коллекцию!");
}
}
}
_busStorages.Add(record[0], collection);
line = reader.ReadLine();
}
}
return true;
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Exceptions
{
[Serializable]
public class BusNotFoundException : ApplicationException
{
public BusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BusNotFoundException() : base() { }
public BusNotFoundException (string message) : base(message) { }
public BusNotFoundException(string message, Exception exception) : base(message, exception) { }
protected BusNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus
{
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Entities;
namespace AccordionBus.Drawings
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
internal class DrawingAccordionBus : DrawingBus
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalBody">Дополнительный отсек</param>
/// <param name="additionalDoor">Дополнительная дверь</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor, int width, int height) : base(speed, weight, bodyColor, width, height, 215, 50)
{
if (EntityBus != null)
{
EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, additionalBody, additionalDoor);
}
}
/// <summary>
/// Смена дополнительного цвета
/// </summary>
/// <param name="additionalColor">Дополнительный цвет</param>
public void SetAdditionalColor(Color additionalColor)
{
if (EntityBus is EntityAccordionBus accordionBus)
{
accordionBus.SetAdditionalColor(additionalColor);
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityBus is not EntityAccordionBus accordionBus)
{
return;
}
base.DrawTransport(g);
Pen pen = new Pen(Color.Black, 3);
Brush brush = new SolidBrush(Color.White);
Brush additionalBrush = new SolidBrush(accordionBus.AdditionalColor);
// Дополнительный отсек
if (accordionBus.AdditionalBody)
{
// Граница дополнительного отсека
pen = new Pen(Color.Black, 3);
g.DrawRectangle(pen, _startPosX + 115, _startPosY, 100, 40);
// Кузов дополнитльного отсека
g.FillRectangle(additionalBrush, _startPosX + 116, _startPosY + 1, 99, 39);
// Колеса дополнительного отсека
g.DrawEllipse(pen, _startPosX + 130, _startPosY + 33, 15, 15);
g.FillEllipse(brush, _startPosX + 131, _startPosY + 34, 14, 14);
g.DrawEllipse(pen, _startPosX + 185, _startPosY + 33, 15, 15);
g.FillEllipse(brush, _startPosX + 186, _startPosY + 34, 14, 14);
// Дверь дополнительного отсека
if (accordionBus.AdditionalDoor)
{
pen = new Pen(Color.Black, 2);
g.DrawRectangle(pen, _startPosX + 160, _startPosY + 10, 15, 30);
g.FillRectangle(brush, _startPosX + 161, _startPosY + 11, 14, 29);
}
// Окна дополнительного отсека
pen = new Pen(Color.DodgerBlue, 2);
g.DrawEllipse(pen, _startPosX + 120, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 121, _startPosY + 6, 14, 19);
g.DrawEllipse(pen, _startPosX + 140, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 141, _startPosY + 6, 14, 19);
g.DrawEllipse(pen, _startPosX + 185, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 186, _startPosY + 6, 14, 19);
// Гармошка
pen = new Pen(Color.Black, 2);
for (int i = 0; i < 5; i++)
{
g.DrawLine(pen, _startPosX + 100 + i * 3, _startPosY, _startPosX + 100 + i * 3, _startPosY + 40);
}
}
}
}
}

View File

@ -0,0 +1,255 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Entities;
using AccordionBus.MovementStrategy;
namespace AccordionBus.Drawings
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBus? EntityBus { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автобуса
/// </summary>
protected int _startPosX;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Верхняя координата прорисовки автобуса
/// </summary>
protected int _startPosY;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина прорисовки автобуса
/// </summary>
private readonly int _busWidth = 100;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _busWidth;
/// <summary>
/// Высота прорисовки автобуса
/// </summary>
private readonly int _busHeight = 50;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _busHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectBus(this);
/// <summary>
/// Проверка, что объект может перемещаться по указанному направлению
/// </summary>
/// <param name="direction">направление</param>
/// <returns>true - может переместиться по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityBus == null)
{
return false;
}
return direction switch
{
// Влево
DirectionType.Left => _startPosX - EntityBus.Step > 0,
// Вверх
DirectionType.Up => _startPosY - EntityBus.Step > 0,
// Вправо
DirectionType.Right => _startPosX + EntityBus.Step < _pictureWidth - _busWidth,
// Вниз
DirectionType.Down => _startPosY + EntityBus.Step < _pictureHeight - _busHeight,
_ => false
};
}
/// <summary>
/// Смена основного цвета
/// </summary>
/// <param name="bodyColor">Основной цвет</param>
public void SetBodyColor(Color bodyColor)
{
EntityBus.SetBodyColor(bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <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);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="busWidth">Ширинка прорисовки автобуса</param>
/// <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);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x < 0 || y < 0)
{
_startPosX = 0;
_startPosY = 0;
}
else if ((x + _busWidth > _pictureWidth) || (y + _busHeight > _pictureHeight))
{
_startPosX = _pictureWidth - _busWidth;
_startPosY = _pictureHeight - _busHeight;
}
else
{
_startPosX = x;
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityBus == null)
{
return;
}
switch (direction)
{
// Влево
case DirectionType.Left:
_startPosX -= (int)EntityBus.Step;
break;
// Вверх
case DirectionType.Up:
_startPosY -= (int)EntityBus.Step;
break;
// Вправо
case DirectionType.Right:
_startPosX += (int)EntityBus.Step;
break;
// Вниз
case DirectionType.Down:
_startPosY += (int)EntityBus.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityBus == null)
{
return;
}
Pen pen = new Pen(Color.Black, 3);
Brush brush = new SolidBrush(Color.White);
Brush bodyBrush = new SolidBrush(EntityBus.BodyColor);
// Граница главного отсека
g.DrawRectangle(pen, _startPosX, _startPosY, 100, 40);
// Кузов главного отсека
g.FillRectangle(bodyBrush, _startPosX + 1, _startPosY + 1, 99, 39);
// Колеса главного отсека
g.DrawEllipse(pen, _startPosX + 15, _startPosY + 33, 15, 15);
g.FillEllipse(brush, _startPosX + 16, _startPosY + 34, 14, 14);
g.DrawEllipse(pen, _startPosX + 70, _startPosY + 33, 15, 15);
g.FillEllipse(brush, _startPosX + 71, _startPosY + 34, 14, 14);
// Дверь главного отсека
pen = new Pen(Color.Black, 2);
g.DrawRectangle(pen, _startPosX + 35, _startPosY + 10, 15, 30);
g.FillRectangle(brush, _startPosX + 36, _startPosY + 11, 14, 29);
// Окна главного отсека
pen = new Pen(Color.DodgerBlue, 2);
g.DrawEllipse(pen, _startPosX + 10, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 11, _startPosY + 6, 14, 19);
g.DrawEllipse(pen, _startPosX + 55, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 56, _startPosY + 6, 14, 19);
g.DrawEllipse(pen, _startPosX + 75, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 76, _startPosY + 6, 14, 19);
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawings;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IMoveableObject для работы с объектом DrawingBus (паттерн Adapter)
/// </summary>
internal class DrawingObjectBus : IMoveableObject
{
private readonly DrawingBus? _drawingBus = null;
public DrawingObjectBus(DrawingBus drawingBus)
{
_drawingBus = drawingBus;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingBus == null || _drawingBus.EntityBus == null)
{
return null;
}
return new ObjectParameters(_drawingBus.GetPosX, _drawingBus.GetPosY, _drawingBus.GetWidth, _drawingBus.GetHeight);
}
}
public int GetStep => (int)(_drawingBus?.EntityBus?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawingBus?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawingBus?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Entities
{
/// <summary>
/// Класс-сущность "Автобус-гармошка"
/// </summary>
internal class EntityAccordionBus : EntityBus
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Дополнительный отсек
/// </summary>
public bool AdditionalBody { get; private set; }
/// <summary>
/// Дополнительная дверь
/// </summary>
public bool AdditionalDoor { get; private set; }
/// <summary>
/// Смена дополнительного цвета
/// </summary>
/// <param name="additionalColor">Дополнительный цвет</param>
public void SetAdditionalColor(Color additionalColor)
{
AdditionalColor = additionalColor;
}
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalBody">Дополнительный отсек</param>
/// <param name="additionalDoor">Дополнительная дверь</param>
public EntityAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
AdditionalBody = additionalBody;
AdditionalDoor = additionalDoor;
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Entities
{
/// <summary>
/// Класс-сущность "Автобус"
/// </summary>
public class EntityBus
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения автобуса
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Смена основного цвета
/// </summary>
/// <param name="bodyColor">Основной цвет</param>
public void SetBodyColor(Color bodyColor)
{
BodyColor = bodyColor;
}
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityBus(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -0,0 +1,69 @@
using AccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawings
{
/// <summary>
/// Расширение для класса EntityBus
/// </summary>
public static class ExtensionDrawingBus
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель данных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingBus? CreateDrawingBus(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingBus(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
width, height);
}
if (strs.Length == 6)
{
return new DrawingAccordionBus(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingBus">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель данных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingBus drawingBus, char separatorForObject)
{
var bus = drawingBus.EntityBus;
if (bus == null)
{
return string.Empty;
}
var str = $"{bus.Speed}{separatorForObject}{bus.Weight}{separatorForObject}{bus.BodyColor.Name}";
if (bus is not EntityAccordionBus accordionBus)
{
return str;
}
return $"{str}{separatorForObject}{accordionBus.AdditionalColor.Name}{separatorForObject}{accordionBus.AdditionalBody}{separatorForObject}{accordionBus.AdditionalDoor}";
}
}
}

View File

@ -1,39 +0,0 @@
namespace AccordionBus
{
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
}
}

View File

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

View File

@ -0,0 +1,39 @@
using AccordionBus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawings;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления перемещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
// Стратегия перемещения объекта в правый нижний угол экрана
internal class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
var diffY = objParams.ObjectMiddleVertical - FieldWidth;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
// Стратегия перемещения объекта в центр экрана
internal class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AccordionBus
{
internal static class Program
@ -11,7 +16,34 @@ 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 Form1());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<BusCollectionForm>());
}
}
/// <summary>
/// Íàñòðîéêà ëîããåðà
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<BusCollectionForm>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appSettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -0,0 +1,83 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AccordionBus.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AccordionBus.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Right {
get {
object obj = ResourceManager.GetObject("Right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Right1 {
get {
object obj = ResourceManager.GetObject("Right1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,127 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="Right" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Right.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Right1" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Right.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Exceptions;
namespace AccordionBus.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T> where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<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 (_places.Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
// Проверка позиции
if (position < 0 || position >= _maxCount)
{
return -1;
}
// Вставка по позиции
_places.Insert(position, bus);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position">Позициия</param>
/// <returns></returns>
public bool Remove(int position)
{
if (position >= Count && position < _maxCount)
{
throw new BusNotFoundException(position);
}
// Проверка позиции
if (position < 0 || position >= _maxCount)
{
return false;
}
// Удаление объекта из списка
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns></returns>
public T? this[int position]
{
get
{
// Проверка позиции
if (position < 0 || position >= _maxCount)
{
return null;
}
return _places[position];
}
set
{
// Проверка позиции
if (position < 0 || position >= _maxCount)
{
return;
}
_places.Insert(position, value);
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <param name="maxBuses"></param>
/// <returns></returns>
public IEnumerable<T?> GetBuses(int? maxBuses = null)
{
for (int i = 0; i < _places.Count; i++)
{
yield return _places[i];
if (maxBuses.HasValue && i == maxBuses.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
internal enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Exceptions
{
[Serializable]
public class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "AccordionBus"
}
}
}