Compare commits

...

17 Commits

43 changed files with 3783 additions and 77 deletions

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
/// <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,249 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Entities;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.MovementStrategy;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBus? EntityBus { get; protected set; }
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectBus(this);
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автобуса
/// </summary>
///
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автобуса
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автобуса
/// </summary>
protected readonly int _busWidth = 110;
/// <summary>
/// Высота прорисовки автобуса
/// </summary>
protected readonly int _busHeight = 70;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _busWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _busHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningBus(int speed, double weight, Color bodyColor, int
width, int height)
{
if (width < _busWidth || height < _busHeight)
{
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 DrawningBus(int speed, double weight, Color bodyColor, int
width, int height, int busWidth, int busHeight)
{
if (width <= _busWidth || height <= _busHeight)
{
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 || x + _busWidth > _pictureWidth)
{
x = Math.Max(0, _pictureWidth - _busWidth);
}
if (y < 0 || y + _busHeight > _pictureHeight)
{
y = Math.Max(0, _pictureHeight - _busHeight);
}
_startPosX = x;
_startPosY = y;
}
/// <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 + _busWidth + EntityBus.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _busHeight + EntityBus.Step < _pictureHeight,
_ => false,
};
}
/// <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(Color.Black);
// Границы первого этажа автобуса
g.DrawRectangle(pen, _startPosX, _startPosY + 30, 100, 30);
Brush brBodyColor = new SolidBrush(EntityBus.BodyColor);
g.FillRectangle(brBodyColor, _startPosX, _startPosY + 30, 100, 30);
// Дверь
g.DrawRectangle(pen, _startPosX + 30, _startPosY + 40, 10, 20);
Brush brBlack = new SolidBrush(Color.Black);
g.FillRectangle(brBlack, _startPosX + 30, _startPosY + 40, 10, 20);
// Колеса
g.DrawEllipse(pen, _startPosX + 7, _startPosY + 55, 10, 10);
g.DrawEllipse(pen, _startPosX + 77, _startPosY + 55, 10, 10);
g.FillEllipse(brBlack, _startPosX + 7, _startPosY + 55, 10, 10);
g.FillEllipse(brBlack, _startPosX + 77, _startPosY + 55, 10, 10);
// Окна
Brush brBlue = new SolidBrush(Color.Blue);
g.FillEllipse(brBlue, _startPosX + 10, _startPosY + 35, 10, 15);
g.FillEllipse(brBlue, _startPosX + 50, _startPosY + 35, 10, 15);
g.FillEllipse(brBlue, _startPosX + 70, _startPosY + 35, 10, 15);
g.FillEllipse(brBlue, _startPosX + 90, _startPosY + 35, 10, 15);
}
public void SetColor(Color color)
{
if (EntityBus == null)
{
return;
}
EntityBus.BodyColor = color;
}
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
}
}

View File

@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Entities;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningDoubleDeckerBus : DrawningBus
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="secondFloor">Признак наличия второго этажа</param>
/// <param name="ladder">Признак наличия лестницы на второй этаж</param>
/// <param name="lineBetweenFloor">Признак наличия полосы между этажами</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена,
/// нельзя создать объект в этих размерах</returns>
public DrawningDoubleDeckerBus(int speed, double weight, Color bodyColor, Color
additionalColor, bool secondFloor, bool ladder, bool lineBetweenFloor, int width, int height) :
base(speed, weight, bodyColor, width, height, 120, 85)
{
if (EntityBus != null)
{
EntityBus = new EntityDoubleDeckerBus(speed, weight, bodyColor,
additionalColor, secondFloor, ladder, lineBetweenFloor);
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityBus is not EntityDoubleDeckerBus doubleDeckerBus)
{
return;
}
Pen pen = new(Color.Black);
Brush brAdditionalColor = new SolidBrush(doubleDeckerBus.AdditionalColor);
Brush brBlue = new SolidBrush(Color.Blue);
Brush brBlack = new SolidBrush(Color.Black);
// второй этаж
if (doubleDeckerBus.SecondFloor)
{
// Границы второго этажа автобуса
g.FillRectangle(brAdditionalColor, _startPosX, _startPosY, 100, 30);
// Дверь второго этажа
g.DrawRectangle(pen, _startPosX, _startPosY + 10, 10, 20);
g.FillRectangle(brAdditionalColor, _startPosX, _startPosY + 10, 10, 20);
// Окна второго этажа
g.FillEllipse(brBlue, _startPosX + 12, _startPosY + 5, 10, 15);
g.FillEllipse(brBlue, _startPosX + 30, _startPosY + 5, 10, 15);
g.FillEllipse(brBlue, _startPosX + 50, _startPosY + 5, 10, 15);
g.FillEllipse(brBlue, _startPosX + 70, _startPosY + 5, 10, 15);
g.FillEllipse(brBlue, _startPosX + 90, _startPosY + 5, 10, 15);
}
base.DrawTransport(g);
// лестница на второй этаж
if (doubleDeckerBus.Ladder)
{
if (doubleDeckerBus.SecondFloor == true)
{
//Вертикальные прямые
g.DrawLine(pen, new Point(_startPosX, _startPosY + 55), new Point(_startPosX, _startPosY + 25));
g.DrawLine(pen, new Point(_startPosX + 10, _startPosY + 55), new Point(_startPosX + 10, _startPosY + 25));
//Горизонтальные прямые
g.DrawLine(pen, new Point(_startPosX, _startPosY + 35), new Point(_startPosX + 10, _startPosY + 35));
g.DrawLine(pen, new Point(_startPosX, _startPosY + 45), new Point(_startPosX + 10, _startPosY + 45));
g.DrawLine(pen, new Point(_startPosX, _startPosY + 55), new Point(_startPosX + 10, _startPosY + 55));
}
}
// полоса между этажами
if (doubleDeckerBus.LineBetweenFloor)
{
g.FillRectangle(brBlack, _startPosX, _startPosY + 30, 100, 3);
}
}
public void SetAddColor(Color color)
{
((EntityDoubleDeckerBus)EntityBus).AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,61 @@
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityBus
/// </summary>
public static class ExtentionDrawningBus
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningBus? CreateDrawningBus(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningBus(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawningDoubleDeckerBus(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBus drawningbus, char separatorForObject)
{
var bus = drawningbus.EntityBus;
if (bus == null)
{
return string.Empty;
}
var str = $"{bus.Speed}{separatorForObject}{bus.Weight}{separatorForObject}{bus.BodyColor.Name}";
if (bus is not EntityDoubleDeckerBus doubleDeckerBus)
{
return str;
}
return
$"{str}{separatorForObject}{doubleDeckerBus.AdditionalColor.Name}{separatorForObject}{doubleDeckerBus.SecondFloor}" +
$"{separatorForObject}{doubleDeckerBus.Ladder}{separatorForObject}{doubleDeckerBus.LineBetweenFloor}";
}
}
}

View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.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; set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <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,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Entities
{
/// <summary>
/// Класс-сущность "Двухэтажный автобус"
/// </summary>
public class EntityDoubleDeckerBus : EntityBus
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия второго этажа
/// </summary>
public bool SecondFloor { get; private set; }
/// <summary>
/// Признак (опция) наличия лестницы на второй этаж
/// </summary>
public bool Ladder { get; private set; }
/// <summary>
/// Признак (опция) наличия полосы между этажами
/// </summary>
public bool LineBetweenFloor { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса двухэтажного автобуса
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автобуса</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="secondFloor">Признак наличия второго этажа</param>
/// <param name="ladder">Признак наличия лестницы на второй этаж</param>
/// <param name="lineBetweenFloor">Признак наличия полосы между этажами</param>
public EntityDoubleDeckerBus(int speed, double weight, Color bodyColor, Color
additionalColor, bool secondFloor, bool ladder, bool lineBetweenFloor) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
SecondFloor = secondFloor;
Ladder = ladder;
LineBetweenFloor = lineBetweenFloor;
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Exceptions
{
[Serializable]
internal 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 contex) : base(info, contex) { }
}
}

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 PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Exceptions
{
[Serializable]
internal 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

@ -1,39 +0,0 @@
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
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 PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,296 @@
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
partial class FormBusCollection
{
/// <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()
{
toolsPanel = new Panel();
panelSets = new Panel();
textBoxStorageName = new TextBox();
listBoxObjects = new ListBox();
ButtonAddObject = new Button();
ButtonDelObject = new Button();
SetsLabel = new Label();
ButtonRefreshCollection = new Button();
ButtonDeleteBus = new Button();
maskedTextBoxNumber = new TextBox();
ButtonAddBus = new Button();
LabelTools = new Label();
pictureBoxCollection = new PictureBox();
menuStrip = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
ButtonSortByType = new Button();
ButtonSortByColor = new Button();
toolsPanel.SuspendLayout();
panelSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// toolsPanel
//
toolsPanel.Controls.Add(ButtonSortByColor);
toolsPanel.Controls.Add(ButtonSortByType);
toolsPanel.Controls.Add(panelSets);
toolsPanel.Controls.Add(ButtonRefreshCollection);
toolsPanel.Controls.Add(ButtonDeleteBus);
toolsPanel.Controls.Add(maskedTextBoxNumber);
toolsPanel.Controls.Add(ButtonAddBus);
toolsPanel.Controls.Add(LabelTools);
toolsPanel.Location = new Point(662, -2);
toolsPanel.Name = "toolsPanel";
toolsPanel.Size = new Size(221, 504);
toolsPanel.TabIndex = 0;
//
// panelSets
//
panelSets.Controls.Add(textBoxStorageName);
panelSets.Controls.Add(listBoxObjects);
panelSets.Controls.Add(ButtonAddObject);
panelSets.Controls.Add(ButtonDelObject);
panelSets.Controls.Add(SetsLabel);
panelSets.Location = new Point(8, 20);
panelSets.Name = "panelSets";
panelSets.Size = new Size(210, 208);
panelSets.TabIndex = 6;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(10, 27);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(190, 27);
textBoxStorageName.TabIndex = 12;
//
// listBoxObjects
//
listBoxObjects.FormattingEnabled = true;
listBoxObjects.ItemHeight = 20;
listBoxObjects.Location = new Point(10, 99);
listBoxObjects.Name = "listBoxObjects";
listBoxObjects.Size = new Size(190, 64);
listBoxObjects.TabIndex = 11;
listBoxObjects.SelectedIndexChanged += listBoxObjects_SelectedIndexChanged;
//
// ButtonAddObject
//
ButtonAddObject.Location = new Point(10, 60);
ButtonAddObject.Name = "ButtonAddObject";
ButtonAddObject.Size = new Size(191, 33);
ButtonAddObject.TabIndex = 8;
ButtonAddObject.Text = "Добавить набор";
ButtonAddObject.UseVisualStyleBackColor = true;
ButtonAddObject.Click += ButtonAddObject_Click;
//
// ButtonDelObject
//
ButtonDelObject.Location = new Point(10, 169);
ButtonDelObject.Name = "ButtonDelObject";
ButtonDelObject.Size = new Size(192, 33);
ButtonDelObject.TabIndex = 7;
ButtonDelObject.Text = "Удалить набор\r\n";
ButtonDelObject.UseVisualStyleBackColor = true;
ButtonDelObject.Click += ButtonDelObject_Click;
//
// SetsLabel
//
SetsLabel.AutoSize = true;
SetsLabel.Location = new Point(3, 4);
SetsLabel.Name = "SetsLabel";
SetsLabel.Size = new Size(66, 20);
SetsLabel.TabIndex = 0;
SetsLabel.Text = "Наборы";
//
// ButtonRefreshCollection
//
ButtonRefreshCollection.Location = new Point(8, 452);
ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(197, 41);
ButtonRefreshCollection.TabIndex = 4;
ButtonRefreshCollection.Text = "Обновить коллекцию";
ButtonRefreshCollection.UseVisualStyleBackColor = true;
ButtonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// ButtonDeleteBus
//
ButtonDeleteBus.Location = new Point(13, 406);
ButtonDeleteBus.Name = "ButtonDeleteBus";
ButtonDeleteBus.Size = new Size(197, 41);
ButtonDeleteBus.TabIndex = 3;
ButtonDeleteBus.Text = "Удалить автобус";
ButtonDeleteBus.UseVisualStyleBackColor = true;
ButtonDeleteBus.Click += ButtonDeleteBus_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(53, 373);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(125, 27);
maskedTextBoxNumber.TabIndex = 2;
//
// ButtonAddBus
//
ButtonAddBus.Location = new Point(13, 311);
ButtonAddBus.Name = "ButtonAddBus";
ButtonAddBus.Size = new Size(197, 41);
ButtonAddBus.TabIndex = 1;
ButtonAddBus.Text = "Добавить автобус";
ButtonAddBus.UseVisualStyleBackColor = true;
ButtonAddBus.Click += ButtonAddBus_Click;
//
// LabelTools
//
LabelTools.AutoSize = true;
LabelTools.Location = new Point(5, 0);
LabelTools.Name = "LabelTools";
LabelTools.Size = new Size(103, 20);
LabelTools.TabIndex = 0;
LabelTools.Text = "Инструменты";
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(1, 31);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(663, 471);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(882, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(59, 24);
FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(177, 26);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(177, 26);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(18, 234);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(187, 32);
ButtonSortByType.TabIndex = 7;
ButtonSortByType.Text = "Сортировать по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(18, 272);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(187, 32);
ButtonSortByColor.TabIndex = 8;
ButtonSortByColor.Text = "Сортировать по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 510);
Controls.Add(pictureBoxCollection);
Controls.Add(toolsPanel);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormBusCollection";
Text = "Набор автобусов";
toolsPanel.ResumeLayout(false);
toolsPanel.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
private void LoadToolStripMenuItem_Click1(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private Panel toolsPanel;
private Label LabelTools;
private Button ButtonDeleteBus;
private Button ButtonAddBus;
private Button ButtonRefreshCollection;
private PictureBox pictureBoxCollection;
public TextBox maskedTextBoxNumber;
private Panel panelSets;
private Label SetsLabel;
private Button ButtonDelObject;
private Button ButtonAddObject;
private ListBox listBoxObjects;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@ -0,0 +1,279 @@
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Generics;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.MovementStrategy;
using Microsoft.Extensions.Logging;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningBus
/// </summary>
public partial class FormBusCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly TheBusesGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormBusCollection()
{
InitializeComponent();
_storage = new TheBusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxObjects.SelectedIndex;
listBoxObjects.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxObjects.Items.Add(_storage.Keys[i].Name);
}
if (listBoxObjects.Items.Count > 0 && (index == -1 || index >= listBoxObjects.Items.Count))
{
listBoxObjects.SelectedIndex = 0;
}
else if (listBoxObjects.Items.Count > 0 && index > -1 && index < listBoxObjects.Items.Count)
{
listBoxObjects.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxObjects.SelectedItem?.ToString() ?? string.Empty]?.ShowTheBuses();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект{listBoxObjects.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
string name = (listBoxObjects.SelectedItem.ToString() ?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddBus_Click(object sender, EventArgs e)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxObjects.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormBusConfig form = new();
form.Show();
Action<DrawningBus>? busDelegate = new((bus) =>
{
try
{
bool isAdditionSuccessful = obj + bus;
MessageBox.Show("Объект добавлен");
bus.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowTheBuses();
Log.Information($"Добавлен объект в коллекцию {listBoxObjects.SelectedItem.ToString() ?? string.Empty}");
}
catch (ArgumentException)
{
Log.Warning($"Добавляемый объект уже существует в коллекции {listBoxObjects.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
form.AddEvent(busDelegate);
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteBus_Click(object sender, EventArgs e)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxObjects.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var isAdditionSuccessful = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxObjects.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowTheBuses();
}
catch (BusNotFoundException ex)
{
Log.Warning($"Не получилось удалить объект из коллекции {listBoxObjects.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxObjects.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowTheBuses();
}
/// <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);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <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);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxObjects.Items.Add(collection);
}
ReloadObjects();
}
catch (Exception ex)
{
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareBuses(new BusCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareBuses(new BusCompareByColor());
private void CompareBuses(IComparer<DrawningBus?> comparer)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxObjects.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowTheBuses();
}
}
}

View File

@ -0,0 +1,368 @@
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
partial class FormBusConfig
{
/// <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();
groupBoxColor = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelYellow = new Panel();
panelGray = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxLineBetweenFloor = new CheckBox();
checkBoxLadder = new CheckBox();
checkBoxSecondFloor = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
panelObject = new Panel();
buttonAdd = new Button();
buttonCancel = new Button();
labelColor = new Label();
labelExtraColor = new Label();
pictureBoxObject = new PictureBox();
groupBoxParameters.SuspendLayout();
groupBoxColor.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(groupBoxColor);
groupBoxParameters.Controls.Add(checkBoxLineBetweenFloor);
groupBoxParameters.Controls.Add(checkBoxLadder);
groupBoxParameters.Controls.Add(checkBoxSecondFloor);
groupBoxParameters.Controls.Add(numericUpDownWeight);
groupBoxParameters.Controls.Add(numericUpDownSpeed);
groupBoxParameters.Controls.Add(labelWeight);
groupBoxParameters.Controls.Add(labelSpeed);
groupBoxParameters.Location = new Point(25, 12);
groupBoxParameters.Name = "groupBoxParameters";
groupBoxParameters.Size = new Size(673, 266);
groupBoxParameters.TabIndex = 0;
groupBoxParameters.TabStop = false;
groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(528, 196);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(101, 43);
labelModifiedObject.TabIndex = 9;
labelModifiedObject.Text = "Сложный";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(412, 196);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(101, 43);
labelSimpleObject.TabIndex = 8;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
//
// groupBoxColor
//
groupBoxColor.Controls.Add(panelPurple);
groupBoxColor.Controls.Add(panelBlack);
groupBoxColor.Controls.Add(panelYellow);
groupBoxColor.Controls.Add(panelGray);
groupBoxColor.Controls.Add(panelBlue);
groupBoxColor.Controls.Add(panelGreen);
groupBoxColor.Controls.Add(panelWhite);
groupBoxColor.Controls.Add(panelRed);
groupBoxColor.Location = new Point(385, 32);
groupBoxColor.Name = "groupBoxColor";
groupBoxColor.Size = new Size(272, 151);
groupBoxColor.TabIndex = 7;
groupBoxColor.TabStop = false;
groupBoxColor.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(207, 92);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(47, 47);
panelPurple.TabIndex = 4;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(143, 92);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(47, 47);
panelBlack.TabIndex = 4;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(207, 32);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(47, 47);
panelYellow.TabIndex = 3;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(81, 92);
panelGray.Name = "panelGray";
panelGray.Size = new Size(47, 47);
panelGray.TabIndex = 2;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(143, 32);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(47, 47);
panelBlue.TabIndex = 3;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(81, 32);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(47, 47);
panelGreen.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(18, 92);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(47, 47);
panelWhite.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(18, 32);
panelRed.Name = "panelRed";
panelRed.Size = new Size(47, 47);
panelRed.TabIndex = 0;
//
// checkBoxLineBetweenFloor
//
checkBoxLineBetweenFloor.AutoSize = true;
checkBoxLineBetweenFloor.Location = new Point(17, 232);
checkBoxLineBetweenFloor.Name = "checkBoxLineBetweenFloor";
checkBoxLineBetweenFloor.Size = new Size(315, 24);
checkBoxLineBetweenFloor.TabIndex = 6;
checkBoxLineBetweenFloor.Text = "Признак наличия линии между этажами";
checkBoxLineBetweenFloor.UseVisualStyleBackColor = true;
//
// checkBoxLadder
//
checkBoxLadder.AutoSize = true;
checkBoxLadder.Location = new Point(17, 184);
checkBoxLadder.Name = "checkBoxLadder";
checkBoxLadder.Size = new Size(336, 24);
checkBoxLadder.TabIndex = 5;
checkBoxLadder.Text = "Признак наличия лестницы на второй этаж";
checkBoxLadder.UseVisualStyleBackColor = true;
//
// checkBoxSecondFloor
//
checkBoxSecondFloor.AutoSize = true;
checkBoxSecondFloor.Location = new Point(17, 138);
checkBoxSecondFloor.Name = "checkBoxSecondFloor";
checkBoxSecondFloor.Size = new Size(258, 24);
checkBoxSecondFloor.TabIndex = 4;
checkBoxSecondFloor.Text = "Признак наличия второго этажа";
checkBoxSecondFloor.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(108, 94);
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(86, 27);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(108, 44);
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(86, 27);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(17, 94);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(17, 44);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(pictureBoxObject);
panelObject.Controls.Add(labelExtraColor);
panelObject.Controls.Add(labelColor);
panelObject.Location = new Point(714, 12);
panelObject.Name = "panelObject";
panelObject.Size = new Size(329, 214);
panelObject.TabIndex = 1;
panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// buttonAdd
//
buttonAdd.Location = new Point(717, 232);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(160, 46);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonCancel
//
buttonCancel.Location = new Point(883, 232);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(160, 46);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(13, 14);
labelColor.Name = "labelColor";
labelColor.Size = new Size(150, 35);
labelColor.TabIndex = 0;
labelColor.Text = "Цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
labelColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelExtraColor
//
labelExtraColor.AllowDrop = true;
labelExtraColor.BorderStyle = BorderStyle.FixedSingle;
labelExtraColor.Location = new Point(169, 14);
labelExtraColor.Name = "labelExtraColor";
labelExtraColor.Size = new Size(150, 35);
labelExtraColor.TabIndex = 1;
labelExtraColor.Text = "Доп. цвет";
labelExtraColor.TextAlign = ContentAlignment.MiddleCenter;
labelExtraColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
labelExtraColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(13, 52);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(306, 154);
pictureBoxObject.TabIndex = 2;
pictureBoxObject.TabStop = false;
//
// FormBusConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1048, 290);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxParameters);
Name = "FormBusConfig";
Text = "Создание объекта";
groupBoxParameters.ResumeLayout(false);
groupBoxParameters.PerformLayout();
groupBoxColor.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 Label labelWeight;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private CheckBox checkBoxSecondFloor;
private CheckBox checkBoxLadder;
private CheckBox checkBoxLineBetweenFloor;
private GroupBox groupBoxColor;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelYellow;
private Panel panelGray;
private Panel panelBlue;
private Label labelSimpleObject;
private Label labelModifiedObject;
private Panel panelObject;
private Button buttonAdd;
private Button buttonCancel;
private PictureBox pictureBoxObject;
private Label labelExtraColor;
private Label labelColor;
}
}

View File

@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormBusConfig : Form
{
/// <summary>
/// Переменная-выбранный автобус
/// </summary>
DrawningBus? _bus = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningBus>? EventAddBus;
/// <summary>
/// Конструктор
/// </summary>
public FormBusConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать автобус
/// </summary>
private void DrawBus()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_bus?.SetPosition(5, 5);
_bus?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawningBus> 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 DrawningBus((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value,
Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelModifiedObject":
_bus = new DrawningDoubleDeckerBus((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value,
Color.White, Color.Black, checkBoxSecondFloor.Checked, checkBoxLadder.Checked,
checkBoxLineBetweenFloor.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
labelColor.BackColor = Color.Empty;
labelExtraColor.BackColor = Color.Empty;
DrawBus();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_bus == null)
{
return;
}
labelColor.BackColor = (Color)e.Data.GetData(typeof(Color));
_bus.SetColor(labelColor.BackColor);
DrawBus();
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if ((_bus == null) || (_bus is DrawningDoubleDeckerBus == false))
{
return;
}
labelExtraColor.BackColor = (Color)e.Data.GetData(typeof(Color));
((DrawningDoubleDeckerBus)_bus).SetAddColor(labelExtraColor.BackColor);
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

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

View File

@ -0,0 +1,192 @@
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
partial class FormDoubleDeckerBus
{
/// <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()
{
pictureBoxDoubleDeckerBus = new PictureBox();
buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonCreateDoubleDeckerBus = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonCreateBus = new Button();
ButtonSelectedBus = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxDoubleDeckerBus).BeginInit();
SuspendLayout();
//
// pictureBoxDoubleDeckerBus
//
pictureBoxDoubleDeckerBus.BackgroundImageLayout = ImageLayout.Zoom;
pictureBoxDoubleDeckerBus.Dock = DockStyle.Fill;
pictureBoxDoubleDeckerBus.Location = new Point(0, 0);
pictureBoxDoubleDeckerBus.Name = "pictureBoxDoubleDeckerBus";
pictureBoxDoubleDeckerBus.Size = new Size(882, 453);
pictureBoxDoubleDeckerBus.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxDoubleDeckerBus.TabIndex = 0;
pictureBoxDoubleDeckerBus.TabStop = false;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.LeftArrow;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(768, 412);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.UpArrow;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(804, 375);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.DownArrow;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(804, 411);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.RightArrow;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(840, 412);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonCreateDoubleDeckerBus
//
buttonCreateDoubleDeckerBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateDoubleDeckerBus.Location = new Point(12, 389);
buttonCreateDoubleDeckerBus.Name = "buttonCreateDoubleDeckerBus";
buttonCreateDoubleDeckerBus.Size = new Size(167, 52);
buttonCreateDoubleDeckerBus.TabIndex = 6;
buttonCreateDoubleDeckerBus.Text = "Создать двухэтажный автобус";
buttonCreateDoubleDeckerBus.UseVisualStyleBackColor = true;
buttonCreateDoubleDeckerBus.Click += ButtonCreateDoubleDeckerBus_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(768, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(102, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Location = new Point(804, 46);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(66, 26);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// buttonCreateBus
//
buttonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBus.Location = new Point(185, 389);
buttonCreateBus.Name = "buttonCreateBus";
buttonCreateBus.Size = new Size(167, 52);
buttonCreateBus.TabIndex = 10;
buttonCreateBus.Text = "Создать автобус";
buttonCreateBus.UseVisualStyleBackColor = true;
buttonCreateBus.Click += buttonCreateBus_Click;
//
// ButtonSelectedBus
//
ButtonSelectedBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonSelectedBus.Location = new Point(358, 389);
ButtonSelectedBus.Name = "ButtonSelectedBus";
ButtonSelectedBus.Size = new Size(167, 52);
ButtonSelectedBus.TabIndex = 11;
ButtonSelectedBus.Text = "Добавить автобус";
ButtonSelectedBus.UseVisualStyleBackColor = true;
ButtonSelectedBus.Click += ButtonSelectedBus_Click;
//
// FormDoubleDeckerBus
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(ButtonSelectedBus);
Controls.Add(buttonCreateBus);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateDoubleDeckerBus);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxDoubleDeckerBus);
Name = "FormDoubleDeckerBus";
StartPosition = FormStartPosition.CenterScreen;
Text = "Двухэтажный автобус";
((System.ComponentModel.ISupportInitialize)pictureBoxDoubleDeckerBus).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxDoubleDeckerBus;
private Button buttonLeft;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateDoubleDeckerBus;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonCreateBus;
private Button ButtonSelectedBus;
}
}

View File

@ -0,0 +1,178 @@
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.MovementStrategy;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
public partial class FormDoubleDeckerBus : Form
{
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Äâóõýòàæíûé àâòîáóñ"
/// </summary>
private DrawningBus? _drawningBus;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Âûáðàííûé àâòîáóñ
/// </summary>
public DrawningBus? SelectedBus { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormDoubleDeckerBus()
{
InitializeComponent();
_strategy = null;
SelectedBus = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû
/// </summary>
private void Draw()
{
if (_drawningBus == null)
{
return;
}
Bitmap bmp = new(pictureBoxDoubleDeckerBus.Width, pictureBoxDoubleDeckerBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningBus.DrawTransport(gr);
pictureBoxDoubleDeckerBus.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü äâóõýòàæíûé àâòîáóñ"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateDoubleDeckerBus_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDopColor = new();
if (dialogDopColor.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDopColor.Color;
}
_drawningBus = new DrawningDoubleDeckerBus(random.Next(100, 300),
random.Next(1000, 3000), color, dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxDoubleDeckerBus.Width, pictureBoxDoubleDeckerBus.Height);
_drawningBus.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 color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
_drawningBus = new DrawningBus(random.Next(100, 300), random.Next(1000, 3000),
color, pictureBoxDoubleDeckerBus.Width, pictureBoxDoubleDeckerBus.Height);
_drawningBus.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 (_drawningBus == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningBus.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(_drawningBus.GetMoveableObject,
pictureBoxDoubleDeckerBus.Width, pictureBoxDoubleDeckerBus.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
private void ButtonSelectedBus_Click(object sender, EventArgs e)
{
SelectedBus = _drawningBus;
DialogResult = DialogResult.OK;
}
}
}

View File

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

View File

@ -0,0 +1,38 @@
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Generics
{
internal class BusCompareByColor : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityBus.BodyColor.Name != y.EntityBus.BodyColor.Name)
{
return x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}
}

View File

@ -0,0 +1,34 @@
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Generics
{
internal class BusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Generics
{
internal class BusesCollectionInfo : IEquatable<BusesCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public BusesCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(BusesCollectionInfo? other)
{
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,69 @@
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Generics
{
internal class DrawiningBusEqutables : IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBus.Speed != y.EntityBus.Speed)
{
return false;
}
if (x.EntityBus.Weight != y.EntityBus.Weight)
{
return false;
}
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
return false;
}
if (x is DrawningDoubleDeckerBus && y is DrawningDoubleDeckerBus)
{
EntityDoubleDeckerBus EntityX = (EntityDoubleDeckerBus)x.EntityBus;
EntityDoubleDeckerBus EntityY = (EntityDoubleDeckerBus)y.EntityBus;
if (EntityX.Ladder != EntityY.Ladder)
{
return false;
}
if (EntityX.LineBetweenFloor != EntityY.LineBetweenFloor)
{
return false;
}
if (EntityX.SecondFloor != EntityY.SecondFloor)
{
return false;
}
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus? obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,145 @@
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в cписке
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в cписке
/// </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="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <returns></returns>
public void Insert(T bus, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
Insert(bus, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public void Insert(T bus, int position, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (!(position >= 0 && position <= Count))
{
throw new Exception("Неверная позиция для вставки");
}
if (equal != null)
{
if (_places.Contains(bus, equal))
{
throw new ArgumentException(nameof(bus));
}
}
_places.Insert(position, bus);
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public void Remove(int position)
{
if (!(position >= 0 && position < Count))
{
throw new BusNotFoundException(position);
}
_places.RemoveAt(position);
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (!(position >= 0 && position < Count))
{
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetTheBuses(int? maxTheBuses = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxTheBuses.HasValue && i == maxTheBuses.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,162 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.MovementStrategy;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningBus
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class TheBusesGenericCollection<T, U>
where T : DrawningBus
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTheBuses => _collection.GetTheBuses();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public TheBusesGenericCollection(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 bool operator +(TheBusesGenericCollection<T, U> collect, T? obj)
{
if (obj == null || collect == null)
{
return false;
}
collect?._collection.Insert(obj, new DrawiningBusEqutables());
return true;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(TheBusesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
}
/// <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 ShowTheBuses()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
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);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int i = 0;
foreach (var bus in _collection.GetTheBuses())
{
if (bus != null)
{
int inRow = _pictureWidth / _placeSizeWidth;
bus.SetPosition((inRow - 1 - (i % inRow)) * _placeSizeWidth, i / inRow * _placeSizeHeight);
bus.DrawTransport(g);
}
i++;
}
}
}
}

View File

@ -0,0 +1,195 @@
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.DrawningObjects;
using PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class TheBusesGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<BusesCollectionInfo, TheBusesGenericCollection<DrawningBus,
DrawningObjectBus>> _busStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<BusesCollectionInfo> 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 TheBusesGenericStorage(int pictureWidth, int pictureHeight)
{
_busStorages = new Dictionary<BusesCollectionInfo, TheBusesGenericCollection<DrawningBus, DrawningObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Сохранение информации по автобусам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<BusesCollectionInfo, TheBusesGenericCollection<DrawningBus, DrawningObjectBus>> record in _busStorages)
{
StringBuilder records = new();
foreach (DrawningBus? elem in record.Value.GetTheBuses)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new IOException("Невалидная операция, нет данных для сохранения");
}
string toWrite = $"BusStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
}
}
/// <summary>
/// Загрузка информации по автобусам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("BusStorage"))
{
throw new IOException("Неверный формат данных");
}
_busStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
TheBusesGenericCollection<DrawningBus, DrawningObjectBus> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningBus? bus =
elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
if (!(collection + bus))
{
throw new IOException("Ошибка добавления в коллекцию");
}
}
}
_busStorages.Add(new BusesCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine();
} while (str != null);
}
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_busStorages.Add(new BusesCollectionInfo(name, string.Empty), new TheBusesGenericCollection<DrawningBus, DrawningObjectBus>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_busStorages.ContainsKey(new BusesCollectionInfo(name, string.Empty)))
{
return;
}
_busStorages.Remove(new BusesCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public TheBusesGenericCollection<DrawningBus, DrawningObjectBus>? this[string ind]
{
get
{
BusesCollectionInfo indObj = new BusesCollectionInfo(ind, string.Empty);
if (_busStorages.ContainsKey(indObj))
{
return _busStorages[indObj];
}
return null;
}
}
}
}

View File

@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public 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>
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 (IsTargetDestinaion())
{
_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>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <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

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

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.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,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в правый нижний край экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
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())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
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,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.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

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

View File

@ -9,4 +9,31 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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.7" />
<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

@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
{
internal static class Program
@ -8,10 +16,24 @@ namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormBusCollection());
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.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("PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base.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 DownArrow {
get {
object obj = ResourceManager.GetObject("DownArrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap LeftArrow {
get {
object obj = ResourceManager.GetObject("LeftArrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap RightArrow {
get {
object obj = ResourceManager.GetObject("RightArrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap UpArrow {
get {
object obj = ResourceManager.GetObject("UpArrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,133 @@
<?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="DownArrow" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\DownArrow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="RightArrow" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\RightArrow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="UpArrow" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\UpArrow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="LeftArrow" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\LeftArrow.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: 414 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 439 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 439 B

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>