Compare commits

...

4 Commits

Author SHA1 Message Date
7de3fe8c3c PIbd-21_MasenkinMS_LabWork03 2023-10-24 15:23:25 +04:00
ea0d1b3981 PIbd-21_MasenkinMS_LabWork03 2023-10-24 15:02:37 +04:00
82f43f1c07 PIbd-21_MasenkinMS_LabWork02 2023-10-10 23:19:35 +04:00
bd0f0a28c3 Bug fix 2023-10-10 23:13:45 +04:00
20 changed files with 1650 additions and 203 deletions

View File

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

View File

@ -29,25 +29,34 @@
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AccordionBusForm));
buttonCreate = new Button();
buttonCreateAccordionBus = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonUp = new Button();
pictureBoxAccordionBus = new PictureBox();
comboBoxStrategy = new ComboBox();
buttonCreateBus = new Button();
buttonStep = new Button();
<<<<<<< HEAD
buttonSelectBus = new Button();
=======
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit();
SuspendLayout();
//
// buttonCreate
// buttonCreateAccordionBus
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(10, 420);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 30);
buttonCreate.TabIndex = 0;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
buttonCreateAccordionBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAccordionBus.AutoSizeMode = AutoSizeMode.GrowAndShrink;
buttonCreateAccordionBus.Location = new Point(15, 409);
buttonCreateAccordionBus.Name = "buttonCreateAccordionBus";
buttonCreateAccordionBus.RightToLeft = RightToLeft.No;
buttonCreateAccordionBus.Size = new Size(124, 41);
buttonCreateAccordionBus.TabIndex = 0;
buttonCreateAccordionBus.Text = "Создать автобус-гармошку";
buttonCreateAccordionBus.UseVisualStyleBackColor = true;
buttonCreateAccordionBus.Click += buttonCreateAccordionBus_Click;
//
// buttonRight
//
@ -106,16 +115,72 @@
pictureBoxAccordionBus.TabIndex = 5;
pictureBoxAccordionBus.TabStop = false;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" });
comboBoxStrategy.Location = new Point(768, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(102, 23);
comboBoxStrategy.TabIndex = 6;
//
// buttonCreateBus
//
buttonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBus.AutoSizeMode = AutoSizeMode.GrowAndShrink;
buttonCreateBus.Location = new Point(145, 409);
buttonCreateBus.Name = "buttonCreateBus";
buttonCreateBus.RightToLeft = RightToLeft.No;
buttonCreateBus.Size = new Size(124, 41);
buttonCreateBus.TabIndex = 7;
buttonCreateBus.Text = "Создать автобус";
buttonCreateBus.UseVisualStyleBackColor = true;
buttonCreateBus.Click += buttonCreateBus_Click;
//
// buttonStep
//
buttonStep.Location = new Point(795, 41);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 30);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
<<<<<<< HEAD
// buttonSelectBus
//
buttonSelectBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSelectBus.AutoSizeMode = AutoSizeMode.GrowAndShrink;
buttonSelectBus.Location = new Point(275, 409);
buttonSelectBus.Name = "buttonSelectBus";
buttonSelectBus.RightToLeft = RightToLeft.No;
buttonSelectBus.Size = new Size(124, 41);
buttonSelectBus.TabIndex = 9;
buttonSelectBus.Text = "Выбрать автобус";
buttonSelectBus.UseVisualStyleBackColor = true;
buttonSelectBus.Click += buttonSelectBus_Click;
//
=======
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
// AccordionBusForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
<<<<<<< HEAD
Controls.Add(buttonSelectBus);
=======
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
Controls.Add(buttonStep);
Controls.Add(buttonCreateBus);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonCreate);
Controls.Add(buttonCreateAccordionBus);
Controls.Add(pictureBoxAccordionBus);
Name = "AccordionBusForm";
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).EndInit();
@ -124,11 +189,18 @@
#endregion
private Button buttonCreate;
private Button buttonCreateAccordionBus;
private Button buttonRight;
private Button buttonDown;
private Button buttonLeft;
private Button buttonUp;
private PictureBox pictureBoxAccordionBus;
private ComboBox comboBoxStrategy;
private Button buttonCreateBus;
private Button buttonStep;
<<<<<<< HEAD
private Button buttonSelectBus;
=======
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
}
}

View File

@ -1,3 +1,8 @@
using AccordionBus.Drawings;
using AccordionBus.MovementStrategy;
using System;
using System.Diagnostics.PerformanceData;
namespace AccordionBus
{
/// <summary>
@ -8,7 +13,20 @@ namespace AccordionBus
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingAccordionBus? _drawingAccordionBus;
private DrawingBus? _drawingBus;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
<<<<<<< HEAD
/// <summary>
/// Âûáðàííûé àâòîáóñ
/// </summary>
public DrawingBus? SelectedBus { get; private set; }
=======
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
@ -16,6 +34,8 @@ namespace AccordionBus
public AccordionBusForm()
{
InitializeComponent();
_abstractStrategy = null;
SelectedBus = null;
}
/// <summary>
@ -23,7 +43,7 @@ namespace AccordionBus
/// </summary>
private void Draw()
{
if (_drawingAccordionBus == null)
if (_drawingBus == null)
{
return;
}
@ -31,33 +51,87 @@ namespace AccordionBus
Bitmap bmp = new(pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingAccordionBus.DrawTransport(gr);
_drawingBus.DrawTransport(gr);
pictureBoxAccordionBus.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîáóñ-ãàðìîøêó"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
private void buttonCreateAccordionBus_Click(object sender, EventArgs e)
{
<<<<<<< HEAD
Random random = new();
// Âûáîð îñíîâíîãî öâåòà
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
bodyColor = dialog.Color;
}
// Âûáîð äîïîëíèòåëüíîãî öâåòà
Color additionalColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
additionalColor = dialog.Color;
}
=======
Random random = new Random();
_drawingAccordionBus = new DrawingAccordionBus();
_drawingAccordionBus.Init(random.Next(100, 300),
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
_drawingBus = new DrawingAccordionBus(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
bodyColor,
additionalColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
_drawingAccordionBus.SetPosition(random.Next(10, 100),
random.Next(10, 100));
_drawingBus.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîáóñ"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateBus_Click(object sender, EventArgs e)
{
<<<<<<< HEAD
Random random = new();
// Âûáîð îñíîâíîãî öâåòà
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
bodyColor = dialog.Color;
}
_drawingBus = new DrawingBus(random.Next(100, 300),
random.Next(1000, 3000),
bodyColor,
=======
Random random = new Random();
_drawingBus = new DrawingBus(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
_drawingBus.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà äâèæåíèÿ îáúåêòà
@ -66,7 +140,7 @@ namespace AccordionBus
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingAccordionBus == null)
if (_drawingBus == null)
{
return;
}
@ -75,19 +149,79 @@ namespace AccordionBus
switch (name)
{
case "buttonUp":
_drawingAccordionBus.MoveTransport(DirectionType.Up);
_drawingBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingAccordionBus.MoveTransport(DirectionType.Down);
_drawingBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingAccordionBus.MoveTransport(DirectionType.Left);
_drawingBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingAccordionBus.MoveTransport(DirectionType.Right);
_drawingBus.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectBus(_drawingBus),
pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
<<<<<<< HEAD
/// <summary>
/// Âûáîð àâòîáóñà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSelectBus_Click(object sender, EventArgs e)
{
SelectedBus = _drawingBus;
DialogResult = DialogResult.OK;
}
=======
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
}
}

View File

@ -121,7 +121,7 @@
<data name="buttonDown.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAA4QAAAOECAYAAAD5Tv87AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAS
cgAAEnIBXmVb4wAAxL5JREFUeF7s/VHO3Ii6Xdke97+fuxuuCvuwKkwPUTMilZkSuRYwcIC7M+bTL/Ij
cQAAEnEB89x6jgAAxL5JREFUeF7s/VHO3Ii6Xdke97+fuxuuCvuwKkwPUTMilZkSuRYwcIC7M+bTL/Ij
XMD9r/+5bdv24P3Xf/3X//wf/+N/XHr9N99Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr7rq
bNu23WV7om3b9uidjz45H4KfUK9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq+66mzbtt1le6Jt
2/bonY8+OR+Cn1CvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1KvUq9Sr1Kvumps27bdZXuibdv26L0Ou/fj
@ -966,7 +966,7 @@
<data name="buttonLeft.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAA4QAAAOECAYAAAD5Tv87AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAS
cgAAEnIBXmVb4wAAtdhJREFUeF7s3QFyG4mVbdvu8b4R9oQ8jf8bFaADnV6SNkgkRTLPiVjh91zgdkkE
cQAAEnEB89x6jgAAtdhJREFUeF7s3QFyG4mVbdvu8b4R9oQ8jf8bFaADnV6SNkgkRTLPiVjh91zgdkkE
wnmD7tJ//X/btm3btm3btm3bJbeDcNu2bdu2bdu27aLbQbht27Zt27Zt23bR7SDctm3btm3btm276HYQ
btu2bdu2bdu2XXQ7CLdt27Zt27Zt2y66HYTbtm3btm3btm0X3Q7Cbdu2bdu2bdu2i24H4bZt27Zt27Zt
20W3g3Dbtm3btm3btu2i20G4bdu2bdu2bdt20e0g3LZt27Zt27Ztu+h2EG7btm3btm3btl10Owi3bdu2
@ -1748,7 +1748,7 @@
<data name="buttonUp.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAA4QAAAOECAYAAAD5Tv87AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAS
cgAAEnIBXmVb4wAAw+5JREFUeF7s3VFyI9liZdmq8WqEb0I5je5yVbmEBy0itoOMCBI4x2zZMxOA3f1B
cQAAEnEB89x6jgAAw+5JREFUeF7s3VFyI9liZdmq8WqEb0I5je5yVbmEBy0itoOMCBI4x2zZMxOA3f1B
Xly3ZGX+r/9v27Zt27Zt27Zte8vtgXDbtm3btm3btu1NtwfCbdu2bdu2bdu2N90eCLdt27Zt27Zt2950
eyDctm3btm3btm170+2BcNu2bdu2bdu27U23B8Jt27Zt27Zt27Y33R4It23btm3btm3b3nR7INy2bdu2
bdu2bXvT7YFw27Zt27Zt27btTbcHwm3btm3btm3btjfdHgi3bdu2bdu2bdvedHsg3LZt27Zt27Zte9Pt

View File

@ -0,0 +1,133 @@
namespace AccordionBus
{
partial class BusCollectionForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
pictureBoxCollection = new PictureBox();
panelTools = new Panel();
maskedTextBox = new MaskedTextBox();
buttonRefreshCollection = new Button();
buttonRemoveBus = new Button();
buttonAddBus = new Button();
labelTools = new Label();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(700, 461);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// panelTools
//
panelTools.Controls.Add(maskedTextBox);
panelTools.Controls.Add(buttonRefreshCollection);
panelTools.Controls.Add(buttonRemoveBus);
panelTools.Controls.Add(buttonAddBus);
panelTools.Controls.Add(labelTools);
panelTools.Location = new Point(706, 0);
panelTools.Name = "panelTools";
panelTools.Size = new Size(174, 461);
panelTools.TabIndex = 1;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(30, 160);
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(120, 23);
maskedTextBox.TabIndex = 4;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(30, 290);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(120, 40);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// buttonRemoveBus
//
buttonRemoveBus.Location = new Point(30, 190);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(120, 40);
buttonRemoveBus.TabIndex = 2;
buttonRemoveBus.Text = "Удалить автобус";
buttonRemoveBus.UseVisualStyleBackColor = true;
buttonRemoveBus.Click += buttonRemoveBus_Click;
//
// buttonAddBus
//
buttonAddBus.Location = new Point(30, 60);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(120, 40);
buttonAddBus.TabIndex = 1;
buttonAddBus.Text = "Добавить автобус";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += buttonAddBus_Click;
//
// labelTools
//
labelTools.AutoSize = true;
labelTools.Location = new Point(0, 0);
labelTools.Name = "labelTools";
labelTools.Size = new Size(83, 15);
labelTools.TabIndex = 0;
labelTools.Text = "Инструменты";
//
// BusCollectionForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
Name = "BusCollectionForm";
Text = "BusCollectionForm";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panelTools;
private Label labelTools;
private MaskedTextBox maskedTextBox;
private Button buttonRefreshCollection;
private Button buttonRemoveBus;
private Button buttonAddBus;
}
}

View File

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

View File

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

View File

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

View File

@ -1,53 +1,20 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Entities;
namespace AccordionBus
namespace AccordionBus.Drawings
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingAccordionBus
internal class DrawingAccordionBus : DrawingBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAccordionBus? EntityAccordionBus { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автобуса
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя координата прорисовки автобуса
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки автобуса
/// </summary>
private readonly int _busWidth = 200;
/// <summary>
/// Высота прорисовки автобуса
/// </summary>
private readonly int _busHeight = 50;
/// <summary>
/// Инициализация свойств
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
@ -55,81 +22,13 @@ namespace AccordionBus
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalBody">Дополнительный отсек</param>
/// <param name="additionalDoor">Дополнительная дверь</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах<</returns>
public bool Init(int speed, int weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor, int width, int height)
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor, int width, int height) : base(speed, weight, bodyColor, width, height, 215, 50)
{
_pictureWidth = width;
_pictureHeight = height;
EntityAccordionBus = new EntityAccordionBus();
EntityAccordionBus.Init(speed, weight,
bodyColor, additionalColor,
additionalBody, additionalDoor);
// Проверка на вместимость объекта в размеры картинки
if ((_busWidth >= _pictureWidth) || (_busHeight >= _pictureHeight))
if (EntityBus != null)
{
Console.WriteLine("Ошибка! Нельзя создать рбъект такого размера");
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if ((x + _busWidth > _pictureWidth) || (y + _busHeight > _pictureHeight))
{
_startPosX = _pictureWidth - _busWidth;
_startPosY = _pictureHeight - _busHeight;
}
else
{
_startPosX = x;
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityAccordionBus == null)
{
return;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX - EntityAccordionBus.Step > 0)
{
_startPosX -= (int)EntityAccordionBus.Step;
}
break;
case DirectionType.Up:
if (_startPosY - EntityAccordionBus.Step > 0)
{
_startPosY -= (int)EntityAccordionBus.Step;
}
break;
case DirectionType.Right:
if (_startPosX + EntityAccordionBus.Step < _pictureWidth)
{
_startPosX += (int)EntityAccordionBus.Step;
}
break;
case DirectionType.Down:
if (_startPosY + EntityAccordionBus.Step < _pictureHeight)
{
_startPosY += (int)EntityAccordionBus.Step;
}
break;
EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, additionalBody, additionalDoor);
}
}
@ -137,46 +36,20 @@ namespace AccordionBus
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public override void DrawTransport(Graphics g)
{
if (EntityAccordionBus == null)
if (EntityBus is not EntityAccordionBus accordionBus)
{
return;
}
base.DrawTransport(g);
Pen pen = new Pen(Color.Black, 3);
Brush bodyBrush = new SolidBrush(EntityAccordionBus.BodyColor);
Brush additionalBrush = new SolidBrush(EntityAccordionBus.AdditionalColor);
// Граница главного отсека
g.DrawRectangle(pen, _startPosX, _startPosY, 100, 40);
// Кузов главного отсека
g.FillRectangle(bodyBrush, _startPosX + 1, _startPosY + 1, 99, 39);
// Колеса главного отсека
Brush brush = new SolidBrush(Color.White);
g.DrawEllipse(pen, _startPosX + 15, _startPosY + 33, 15, 15);
g.FillEllipse(brush, _startPosX + 16, _startPosY + 34, 14, 14);
g.DrawEllipse(pen, _startPosX + 70, _startPosY + 33, 15, 15);
g.FillEllipse(brush, _startPosX + 71, _startPosY + 34, 14, 14);
// Дверь главного отсека
pen = new Pen(Color.Black, 2);
g.DrawRectangle(pen, _startPosX + 35, _startPosY + 10, 15, 30);
g.FillRectangle(brush, _startPosX + 36, _startPosY + 11, 14, 29);
// Окна главного отсека
pen = new Pen(Color.DodgerBlue, 2);
g.DrawEllipse(pen, _startPosX + 10, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 11, _startPosY + 6, 14, 19);
g.DrawEllipse(pen, _startPosX + 55, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 56, _startPosY + 6, 14, 19);
g.DrawEllipse(pen, _startPosX + 75, _startPosY + 5, 15, 20);
g.FillEllipse(brush, _startPosX + 76, _startPosY + 6, 14, 19);
Brush additionalBrush = new SolidBrush(accordionBus.AdditionalColor);
// Дополнительный отсек
if (EntityAccordionBus.AdditionalBody)
if (accordionBus.AdditionalBody)
{
// Граница дополнительного отсека
pen = new Pen(Color.Black, 3);
@ -192,7 +65,7 @@ namespace AccordionBus
g.FillEllipse(brush, _startPosX + 186, _startPosY + 34, 14, 14);
// Дверь дополнительного отсека
if (EntityAccordionBus.AdditionalDoor)
if (accordionBus.AdditionalDoor)
{
pen = new Pen(Color.Black, 2);
g.DrawRectangle(pen, _startPosX + 160, _startPosY + 10, 15, 30);
@ -215,7 +88,6 @@ namespace AccordionBus
g.DrawLine(pen, _startPosX + 100 + i * 3, _startPosY, _startPosX + 100 + i * 3, _startPosY + 40);
}
}
}
}
}

View File

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

View File

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

View File

@ -4,25 +4,13 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus
namespace AccordionBus.Entities
{
public class EntityAccordionBus
/// <summary>
/// Класс-сущность "Автобус-гармошка"
/// </summary>
internal class EntityAccordionBus : EntityBus
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет
/// </summary>
@ -39,12 +27,7 @@ namespace AccordionBus
public bool AdditionalDoor { get; private set; }
/// <summary>
/// Шаг перемещения автобуса
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей обЪекта-класса автобуса
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
@ -52,11 +35,8 @@ namespace AccordionBus
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalBody">Дополнительный отсек</param>
/// <param name="additionalDoor">Дополнительная дверь</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor)
public EntityAccordionBus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalBody, bool additionalDoor) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
AdditionalBody = additionalBody;
AdditionalDoor = additionalDoor;

View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Entities
{
/// <summary>
/// Класс-сущность "Автобус"
/// </summary>
public class EntityBus
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения автобуса
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="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,43 @@
using AccordionBus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawings;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
<<<<<<< HEAD
public interface IMoveableObject
=======
internal interface IMoveableObject
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления перемещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

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

View File

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

View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
/// <summary>
<<<<<<< HEAD
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
=======
/// Параметры-координаты рбъекта
/// </summary>
internal class ObjectParameters
>>>>>>> 82f43f1c079e24d5df9441679bb15b3e230ddbee
{
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

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

View File

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

View File

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