Compare commits

...

13 Commits

35 changed files with 3431 additions and 75 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

@ -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,270 @@
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 System.Windows.Forms.OpenFileDialog();
saveFileDialog = new System.Windows.Forms.SaveFileDialog();
toolsPanel.SuspendLayout();
panelSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// toolsPanel
//
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(8, 379);
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(48, 346);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(125, 27);
maskedTextBoxNumber.TabIndex = 2;
//
// ButtonAddBus
//
ButtonAddBus.Location = new Point(8, 284);
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;
//
// menuStrip1
//
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(224, 26);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(224, 26);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// 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;
}
}

View File

@ -0,0 +1,239 @@
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;
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]);
}
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();
}
/// <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)
{
_storage.DelSet(listBoxObjects.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
}
}
/// <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((m) =>
{
bool isAdditionSuccessful = (obj + m);
if (isAdditionSuccessful)
{
MessageBox.Show("Объект добавлен");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowTheBuses();
}
else
{
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;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTheBuses();
}
else
{
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)
{
if (_storage.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", 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)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys)
{
listBoxObjects.Items.Add(collection);
}
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,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,134 @@
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="bus">Добавляемый автобус</param>
/// <returns></returns>
public bool Insert(T bus)
{
if (_places.Count == _maxCount)
{
return false;
}
Insert(bus, 0);
return true;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T bus, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
{
return false;
}
_places.Insert(position, bus);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
}
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (position < 0 || position >= _maxCount)
{
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
return;
}
}
/// <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,159 @@
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>
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)
{
return false;
}
return collect?._collection.Insert(obj) ?? false;
}
/// <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];
if (obj != null)
{
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,196 @@
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<string, TheBusesGenericCollection<DrawningBus,
DrawningObjectBus>> _busStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _busStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public TheBusesGenericStorage(int pictureWidth, int pictureHeight)
{
_busStorages = new Dictionary<string, TheBusesGenericCollection<DrawningBus, DrawningObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Сохранение информации по автобусам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, 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}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
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);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автобусам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
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)
{
return false;
}
if (!strs[0].StartsWith("BusStorage"))
{
return false;
}
_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))
{
return false;
}
}
}
_busStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
return true;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_busStorages.Add(name, new TheBusesGenericCollection<DrawningBus, DrawningObjectBus>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_busStorages.ContainsKey(name))
{
return;
}
_busStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public TheBusesGenericCollection<DrawningBus, DrawningObjectBus>? this[string ind]
{
get
{
if (_busStorages.ContainsKey(ind))
{
return _busStorages[ind];
}
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,19 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<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

@ -11,7 +11,7 @@ namespace PIbd_23_Ivanov_V.N._DoubleDeckerBus._Base
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
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