PIbd-21_MasenkinMS_LabWork02 #2

Closed
Factorino73 wants to merge 1 commits from LabWork02 into LabWork01
14 changed files with 874 additions and 204 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,30 @@
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();
((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 +111,52 @@
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;
//
// AccordionBusForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
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 +165,14 @@
#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;
}
}

View File

@ -1,3 +1,8 @@
using AccordionBus.Drawings;
using AccordionBus.MovementStrategy;
using System;
using System.Diagnostics.PerformanceData;
namespace AccordionBus
{
/// <summary>
@ -8,7 +13,12 @@ namespace AccordionBus
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingAccordionBus? _drawingAccordionBus;
private DrawingBus? _drawingBus;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
@ -23,7 +33,7 @@ namespace AccordionBus
/// </summary>
private void Draw()
{
if (_drawingAccordionBus == null)
if (_drawingBus == null)
{
return;
}
@ -31,20 +41,19 @@ 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)
{
Random random = new Random();
_drawingAccordionBus = new DrawingAccordionBus();
_drawingAccordionBus.Init(random.Next(100, 300),
_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)),
@ -53,11 +62,29 @@ namespace AccordionBus
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)
{
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)),
pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height);
_drawingBus.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà äâèæåíèÿ îáúåêòà
@ -66,7 +93,7 @@ namespace AccordionBus
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingAccordionBus == null)
if (_drawingBus == null)
{
return;
}
@ -75,19 +102,65 @@ 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;
}
}
}
}

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

@ -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 int _busWidth = 100;
/// <summary>
/// Высота прорисовки автобуса
/// </summary>
private readonly int _busHeight = 50;
/// <summary>
/// Инициализация свойств
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
@ -55,85 +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();
if (additionalBody)
if (EntityBus != null)
{
_busWidth = 215;
}
EntityAccordionBus.Init(speed, weight,
bodyColor, additionalColor,
additionalBody, additionalDoor);
// Проверка на вместимость объекта в размеры картинки
if ((_busWidth >= _pictureWidth) || (_busHeight >= _pictureHeight))
{
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 - _busWidth)
{
_startPosX += (int)EntityAccordionBus.Step;
}
break;
case DirectionType.Down:
if (_startPosY + EntityAccordionBus.Step < _pictureHeight - _busHeight)
{
_startPosY += (int)EntityAccordionBus.Step;
}
break;
EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, additionalBody, additionalDoor);
}
}
@ -141,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);
@ -196,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);
@ -219,7 +88,6 @@ namespace AccordionBus
g.DrawLine(pen, _startPosX + 100 + i * 3, _startPosY, _startPosX + 100 + i * 3, _startPosY + 40);
}
}
}
}
}

View File

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

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawings;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IMoveableObject для работы с объектом DrawingBus (паттерн Adapter)
/// </summary>
internal class DrawingObjectBus : IMoveableObject
{
private readonly DrawingBus? _drawingBus = null;
public DrawingObjectBus(DrawingBus drawingBus)
{
_drawingBus = drawingBus;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingBus == null || _drawingBus.EntityBus == null)
{
return null;
}
return new ObjectParameters(_drawingBus.GetPosX, _drawingBus.GetPosY, _drawingBus.GetWidth, _drawingBus.GetHeigth);
}
}
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,39 @@
using AccordionBus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawings;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
internal interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления перемещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

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

View File

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

View File

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