PIbd-21. Kryukov A.I. Lab work 02 base #17

Closed
SooNooClose wants to merge 10 commits from lab_2 into lab_1
13 changed files with 711 additions and 91 deletions

View File

@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.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 (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>
/// <returns></returns>
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

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.Entities;
namespace ProjectExcavator.DrawningObjects
{
public class DrawningExcavarorBodyKits : DrawningExcavator
Review

Имя элемента проекта не соответствует указанному в задании

Имя элемента проекта не соответствует указанному в задании
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="bucket">Признак наличия антикрыла</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningExcavarorBodyKits(int speed, double weight,
Color bodyColor, Color additionalColor,
bool bodyKit, bool bucket,
int width, int height) :
base(speed, weight, bodyColor, width, height, 170, 100)
{
if(EntityExcavator != null)
{
EntityExcavator = new EntityExcavatorBodyKits(speed, weight,
bodyColor, additionalColor, bodyKit, bucket);
}
}
public override void DrawTransport(Graphics g)
{
if(EntityExcavator is not EntityExcavatorBodyKits excavator)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(excavator.AdditionalColor);
//ыспомогательные опоры
if (excavator.BodyKit)
{
g.FillRectangle(additionalBrush, _startPosX + 20, _startPosY + 50, 110, 10);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 50, 110, 10);
}
//отрисовка базы экскаватора
base.DrawTransport(g);
//ковш
if (excavator.Bucket)
{
Point[] pointsBacket = {
new Point(_startPosX + 150, _startPosY + 25),
new Point(_startPosX + 150, _startPosY + 85),
new Point(_startPosX + 195, _startPosY + 85),
};
g.FillPolygon(additionalBrush, pointsBacket);
g.DrawPolygon(pen, pointsBacket);
}
}
}
}

View File

@ -1,17 +1,18 @@
using System;
using ProjectExcavator.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator
namespace ProjectExcavator.DrawningObjects
{
public class DrawningExcavator
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityExcavator? EntityExcavator { get; private set; }
public EntityExcavator? EntityExcavator { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -23,11 +24,11 @@ namespace ProjectExcavator
/// <summary>
/// Левая координата прорисовки экскаватора
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки экскаватора
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки экскаватора
/// </summary>
@ -37,29 +38,66 @@ namespace ProjectExcavator
/// </summary>
protected readonly int _excavatorHeight = 80;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// Ширина объекта
/// </summary>
public int GetWidth => _excavatorWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _excavatorHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия вспомогательных опор</param>
/// <param name="backet">Признак наличия ковша</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool backet, int width, int height)
public DrawningExcavator(int speed, double weight,
Color bodyColor,
int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if(_pictureHeight < _excavatorHeight || _pictureWidth < _excavatorWidth)
{
return false;
return;
}
EntityExcavator = new EntityExcavator();
EntityExcavator.Init(speed, weight, bodyColor, additionalColor, bodyKit, backet);
return true;
_pictureWidth = width;
_pictureHeight = height;
EntityExcavator = new EntityExcavator(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="excavatorWidth">Ширина прорисовки экскаватора</param>
/// <param name="excavatorHeight">Высота прорисовки экскаватора</param>
protected DrawningExcavator(int speed, double weight,
Color bodyColor,
int width, int height,
int excavatorWidth, int excavatorHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_excavatorWidth = excavatorWidth;
_excavatorHeight = excavatorHeight;
if (_pictureHeight < _excavatorHeight || _pictureWidth < _excavatorWidth)
{
return;
}
EntityExcavator = new EntityExcavator(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
@ -73,6 +111,30 @@ namespace ProjectExcavator
_startPosY = Math.Min(y,_pictureHeight - _excavatorHeight);
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityExcavator == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityExcavator.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityExcavator.Step > 0,
//вправо
DirectionType.Right => _startPosX + EntityExcavator.Step < _pictureWidth - _excavatorWidth,
//вниз
DirectionType.Down => _startPosY + EntityExcavator.Step < _pictureHeight - _excavatorHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
@ -80,7 +142,7 @@ namespace ProjectExcavator
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityExcavator == null)
if (!CanMove(direction) || EntityExcavator == null)
{
return;
}
@ -88,10 +150,7 @@ namespace ProjectExcavator
{
//влево
case DirectionType.Left:
if (_startPosX - EntityExcavator.Step > 0)
{
_startPosX -= (int)EntityExcavator.Step;
}
_startPosX -= (int)EntityExcavator.Step;
break;
//вверх
case DirectionType.Up:
@ -102,10 +161,7 @@ namespace ProjectExcavator
break;
// вправо
case DirectionType.Right:
if (_startPosX + EntityExcavator.Step < _pictureWidth - _excavatorWidth)
{
_startPosX += (int)EntityExcavator.Step;
}
_startPosX += (int)EntityExcavator.Step;
break;
//вниз
case DirectionType.Down:
@ -120,19 +176,13 @@ namespace ProjectExcavator
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityExcavator == null)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityExcavator.AdditionalColor);
if (EntityExcavator.BodyKit)
{
g.FillRectangle(additionalBrush, _startPosX + 20, _startPosY + 70, 130, 10);
g.DrawLine(pen, _startPosX + 20, _startPosY + 70, _startPosX + 150, _startPosY + 70);
}
//корпус
Brush bodyBrush = new SolidBrush(EntityExcavator.BodyColor);
g.FillRectangle(bodyBrush, _startPosX + 20, _startPosY + 60, 130, 20);
@ -158,17 +208,7 @@ namespace ProjectExcavator
g.DrawEllipse(pen, _startPosX + 80, _startPosY + 80, 20, 20);
g.DrawEllipse(pen, _startPosX + 100, _startPosY + 80, 20, 20);
g.DrawEllipse(pen, _startPosX + 120, _startPosY + 80, 20, 20);
//ковш
if (EntityExcavator.Backet)
{
Point[] pointsBacket = {
new Point(_startPosX + 150, _startPosY + 25),
new Point(_startPosX + 150, _startPosY + 85),
new Point(_startPosX + 195, _startPosY + 85),
};
g.FillPolygon(additionalBrush, pointsBacket);
g.DrawPolygon(pen, pointsBacket);
}
}
}
}

View File

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

View File

@ -4,11 +4,11 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator
namespace ProjectExcavator.Entities
{
public class EntityExcavator
{
// <summary>
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
@ -21,40 +21,20 @@ namespace ProjectExcavator
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия вспомогательных опор
/// </summary>
public bool BodyKit { get; private set; }
/// <summary>
/// Признак (опция) наличия ковша
/// </summary>
public bool Backet { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// Шаг перемещения экскаватора
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="weight">Вес экскаватора</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="backet">Признак наличия антикрыла</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool backet)
public EntityExcavator(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Backet = backet;
}
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using ProjectExcavator.Entities;
namespace ProjectExcavator.Entities
{
/// <summary>
/// Класс-сущность "Спортивный автомобиль"
/// </summary>
public class EntityExcavatorBodyKits : EntityExcavator
Review

Имя элемента проекта не соответствует указанному в задании

Имя элемента проекта не соответствует указанному в задании
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// признак наличия вспомогательных опор
/// </summary>
public bool BodyKit { get; private set; }
/// <summary>
/// Признак (опция) наличия ковша
/// </summary>
public bool Bucket { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса экскаватора
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес экскаватора</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="bucket">Признак наличия ковша</param>
public EntityExcavatorBodyKits(int speed,
double weight,
Color bodyColor,
Color additionalColor,
bool bodyKit,
bool bucket) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Bucket = bucket;
}
}
}

View File

@ -34,6 +34,9 @@
buttonUp = new Button();
buttonLeft = new Button();
buttonRight = new Button();
comboBoxStrategy = new ComboBox();
buttonCreateExcavatorBodyKits = new Button();
buttonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxExcavator).BeginInit();
SuspendLayout();
//
@ -41,8 +44,9 @@
//
pictureBoxExcavator.Dock = DockStyle.Fill;
pictureBoxExcavator.Location = new Point(0, 0);
pictureBoxExcavator.Margin = new Padding(3, 4, 3, 4);
pictureBoxExcavator.Name = "pictureBoxExcavator";
pictureBoxExcavator.Size = new Size(800, 450);
pictureBoxExcavator.Size = new Size(914, 600);
pictureBoxExcavator.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxExcavator.TabIndex = 0;
pictureBoxExcavator.TabStop = false;
@ -50,11 +54,12 @@
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 415);
buttonCreate.Location = new Point(14, 529);
buttonCreate.Margin = new Padding(3, 4, 3, 4);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23);
buttonCreate.Size = new Size(177, 55);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.Text = "Создать простой экскаватор";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
@ -63,9 +68,10 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.down;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(722, 415);
buttonDown.Location = new Point(825, 553);
buttonDown.Margin = new Padding(3, 4, 3, 4);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.Size = new Size(34, 40);
buttonDown.TabIndex = 2;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
@ -75,9 +81,10 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.up;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(722, 379);
buttonUp.Location = new Point(825, 505);
buttonUp.Margin = new Padding(3, 4, 3, 4);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.Size = new Size(34, 40);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
@ -87,9 +94,10 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.left;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(686, 415);
buttonLeft.Location = new Point(784, 553);
buttonLeft.Margin = new Padding(3, 4, 3, 4);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.Size = new Size(34, 40);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
@ -99,24 +107,62 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.right;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(758, 415);
buttonRight.Location = new Point(866, 553);
buttonRight.Margin = new Padding(3, 4, 3, 4);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.Size = new Size(34, 40);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Двигаться в центр", "Двигаться к краю экрана" });
comboBoxStrategy.Location = new Point(762, 16);
comboBoxStrategy.Margin = new Padding(3, 4, 3, 4);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(138, 28);
comboBoxStrategy.TabIndex = 6;
//
// buttonCreateExcavatorBodyKits
//
buttonCreateExcavatorBodyKits.Location = new Point(198, 529);
buttonCreateExcavatorBodyKits.Margin = new Padding(3, 4, 3, 4);
buttonCreateExcavatorBodyKits.Name = "buttonCreateExcavatorBodyKits";
buttonCreateExcavatorBodyKits.Size = new Size(166, 55);
buttonCreateExcavatorBodyKits.TabIndex = 7;
buttonCreateExcavatorBodyKits.Text = "Создать Экскаватор с обвесами";
buttonCreateExcavatorBodyKits.UseVisualStyleBackColor = true;
buttonCreateExcavatorBodyKits.Click += buttonCreateExcavatorBodyKits_Click;
//
// buttonStep
//
buttonStep.Location = new Point(815, 55);
buttonStep.Margin = new Padding(3, 4, 3, 4);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(86, 31);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// ExcavatorForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(914, 600);
Controls.Add(buttonStep);
Controls.Add(buttonCreateExcavatorBodyKits);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonUp);
Controls.Add(buttonDown);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxExcavator);
Margin = new Padding(3, 4, 3, 4);
Name = "ExcavatorForm";
Text = "Excavator";
Click += buttonMove_Click;
@ -133,5 +179,8 @@
private Button buttonUp;
private Button buttonLeft;
private Button buttonRight;
private ComboBox comboBoxStrategy;
private Button buttonCreateExcavatorBodyKits;
private Button buttonStep;
}
}

View File

@ -1,3 +1,6 @@
using ProjectExcavator.DrawningObjects;
using ProjectExcavator.MovementStrategy;
namespace ProjectExcavator
{
public partial class ExcavatorForm : Form
@ -7,6 +10,10 @@ namespace ProjectExcavator
/// </summary>
private DrawningExcavator? _drawnigExcavator;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public ExcavatorForm()
@ -41,17 +48,12 @@ namespace ProjectExcavator
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawnigExcavator = new DrawningExcavator();
_drawnigExcavator.Init(random.Next(100, 300),
_drawnigExcavator = new DrawningExcavator(
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)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxExcavator.Width,
pictureBoxExcavator.Height);
_drawnigExcavator.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
@ -78,5 +80,56 @@ namespace ProjectExcavator
}
Draw();
}
private void buttonCreateExcavatorBodyKits_Click(object sender, EventArgs e)
{
Random random = new();
_drawnigExcavator = new DrawningExcavarorBodyKits(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)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxExcavator.Width,
pictureBoxExcavator.Height);
_drawnigExcavator.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawnigExcavator == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawningObjectExcavator(_drawnigExcavator),
pictureBoxExcavator.Width,
pictureBoxExcavator.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.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,49 @@
using ProjectExcavator.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
var objParams = GetObjectParameters;
if(objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth && objParams.DownBorder
+ GetStep() <= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if(objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth - 150;
var diffY = objParams.DownBorder - FieldHeight - 150;
if(diffX >= 0)
{
MoveDown();
}
else if (diffY >= 0)
{
MoveRight();
}
else if(Math.Abs(diffX) > Math.Abs(diffY))
{
MoveRight();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.MovementStrategy
{
public 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,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator.MovementStrategy
{
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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectExcavator
{
public enum Status
{
NotInit = 0,
InProgress = 1,
Finish = 2
}
}