Лабораторная работа №2

This commit is contained in:
Anitonchik 2024-03-13 23:41:35 +04:00
parent ec94d370ae
commit f0c31b34b3
16 changed files with 817 additions and 168 deletions

View File

@ -4,13 +4,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck;
namespace ProjectDumpTruck.Drawnings;
/// <summary>
/// Напривление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectDumpTruck.Entities;
namespace ProjectDumpTruck.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение
/// </summary>
public class DrawningDumpTruck : DrawningTruck
{
/// <summary>
/// </summary>
/// Конструктор
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="body">Признак наличия кузова</param>
/// <param name="tent">Признак наличия тента</param>
public DrawningDumpTruck(int speed, double weight, Color bodyColor, Color additionalColor, bool body, bool tent) : base(110, 100)
{
EntityTruck = new EntityDumpTruck(speed, weight, bodyColor, additionalColor, body, tent);
}
public override void DrawTransport(Graphics g)
{
if (EntityTruck == null || EntityTruck is not EntityDumpTruck entityTruck || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
_startPosX += 10;
base.DrawTransport(g);
_startPosX -= 10;
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(entityTruck.AdditionalColor);
Brush brBody = new SolidBrush(entityTruck.AdditionalColor);
if (entityTruck.Body)
{
Point[] body =
{
new Point (_startPosX.Value, _startPosY.Value + 15),
new Point (_startPosX.Value + 77, _startPosY.Value + 15),
new Point (_startPosX.Value + 77, _startPosY.Value + 50),
new Point (_startPosX.Value + 20, _startPosY.Value + 50)
};
g.DrawPolygon(pen, points: body);
g.FillPolygon(brBody, body);
}
if (entityTruck.Tent && entityTruck.Body)
{
Point[] tent =
{
new Point (_startPosX.Value, _startPosY.Value + 13),
new Point (_startPosX.Value + 39, _startPosY.Value),
new Point (_startPosX.Value + 77, _startPosY.Value + 13)
};
g.DrawPolygon(pen, points: tent);
g.FillPolygon(brBody, tent);
}
}
}

View File

@ -1,20 +1,18 @@
using System;
using ProjectDumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck;
namespace ProjectDumpTruck.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение
/// </summary>
public class DrawningDumpTruck
public class DrawningTruck
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityDumpTruck? EntityDumpTruck { get; private set; }
public EntityTruck? EntityTruck { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -26,41 +24,71 @@ public class DrawningDumpTruck
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
private int? _startPosX;
protected private int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
private int? _startPosY;
protected private int? _startPosY;
/// <summary>
/// Ширина прорисовки самосвала
/// </summary>
private readonly int _drawningDumpTruckWidth = 116;
private readonly int _drawningTruckWidth = 100;
/// <summary>
/// Высота прорисовки самосвала
/// </summary>
private readonly int _drawingDumpTruckHeight = 100;
private readonly int _drawningTruckHeight = 92;
/// <summary>
/// Координата Х объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата У объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningTruckWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningTruckHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
/// Инициализация свойств
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="body">Признак наличия кузова</param>
/// <param name="tent">Признак наличия тента</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool body, bool tent)
private DrawningTruck()
{
EntityDumpTruck = new EntityDumpTruck();
EntityDumpTruck.Init(speed, weight, bodyColor, additionalColor,
body, tent);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// </summary>
/// Конструктор
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningTruck(int speed, double weight, Color bodyColor) : this()
{
EntityTruck = new EntityTruck(speed, weight, bodyColor);
}
/// <summary>
/// </summary>
/// Конструктор для наследников
/// <param name="drawningTruckWidth">Ширина прорисовки самосвала</param>
/// <param name="drawningTruckHeight">Высота прорисовки самосвала</param>
protected DrawningTruck(int drawningTruckWidth, int drawningTruckHeight) : this()
{
_drawningTruckWidth = drawningTruckWidth;
_drawningTruckHeight = drawningTruckHeight;
}
/// <summary>
/// Установка границ поля
@ -72,21 +100,21 @@ public class DrawningDumpTruck
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (_drawningDumpTruckWidth > width || _drawingDumpTruckHeight > height)
if (_drawningTruckWidth > width || _drawningTruckHeight > height)
{
return false;
}
if (_pictureWidth.HasValue && width != _pictureWidth || _pictureHeight.HasValue && height != _pictureHeight)
{
if (_startPosX + _drawningDumpTruckWidth > width)
if (_startPosX + _drawningTruckWidth > width)
{
_startPosX -= _drawningDumpTruckWidth;
_startPosX -= _drawningTruckWidth;
}
if (_startPosY + _drawingDumpTruckHeight > height)
if (_startPosY + _drawningTruckHeight > height)
{
_startPosY -= _drawingDumpTruckHeight;
_startPosY -= _drawningTruckHeight;
}
}
@ -111,17 +139,17 @@ public class DrawningDumpTruck
{
x = 0;
}
if (x + _drawningDumpTruckWidth > _pictureWidth)
if (x + _drawningTruckWidth > _pictureWidth)
{
x = (int)_pictureWidth - _drawningDumpTruckWidth;
x = (int)_pictureWidth - _drawningTruckWidth;
}
if (y < 0)
{
y = 0;
}
if (y + _drawingDumpTruckHeight > _pictureHeight)
if (y + _drawningTruckHeight > _pictureHeight)
{
y = (int)_pictureHeight - _drawingDumpTruckHeight;
y = (int)_pictureHeight - _drawningTruckHeight;
}
@ -139,7 +167,7 @@ public class DrawningDumpTruck
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityDumpTruck == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityTruck == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@ -148,30 +176,30 @@ public class DrawningDumpTruck
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityDumpTruck.Step > 0)
if (_startPosX.Value - EntityTruck.Step > 0)
{
_startPosX -= (int)EntityDumpTruck.Step;
_startPosX -= (int)EntityTruck.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityDumpTruck.Step > 0)
if (_startPosY.Value - EntityTruck.Step > 0)
{
_startPosY -= (int)EntityDumpTruck.Step;
_startPosY -= (int)EntityTruck.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + _drawningDumpTruckWidth < _pictureWidth)
if (_startPosX.Value + _drawningTruckWidth < _pictureWidth)
{
_startPosX += (int)EntityDumpTruck.Step;
_startPosX += (int)EntityTruck.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + _drawingDumpTruckHeight < _pictureHeight)
if (_startPosY.Value + _drawningTruckHeight < _pictureHeight)
{
_startPosY += (int)EntityDumpTruck.Step;
_startPosY += (int)EntityTruck.Step;
}
return true;
default:
@ -183,70 +211,40 @@ public class DrawningDumpTruck
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityDumpTruck == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityTruck == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityDumpTruck.AdditionalColor);
Brush brBody = new SolidBrush(EntityDumpTruck.AdditionalColor);
if (EntityDumpTruck.Body)
{
Point[] body =
{
new Point (_startPosX.Value, _startPosY.Value + 15),
new Point (_startPosX.Value + 77, _startPosY.Value + 15),
new Point (_startPosX.Value + 77, _startPosY.Value + 50),
new Point (_startPosX.Value + 20, _startPosY.Value + 50)
};
g.DrawPolygon(pen, points: body);
g.FillPolygon(brBody, body);
}
if (EntityDumpTruck.Tent && EntityDumpTruck.Body)
{
Point[] tent =
{
new Point (_startPosX.Value, _startPosY.Value + 13),
new Point (_startPosX.Value + 39, _startPosY.Value),
new Point (_startPosX.Value + 77, _startPosY.Value + 13)
};
g.DrawPolygon(pen, points: tent);
g.FillPolygon(brBody, tent);
}
//Границы самосвала
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 53, 100, 13);
g.DrawRectangle(pen, _startPosX.Value + 80, _startPosY.Value + 15, 30, 36);
g.DrawRectangle(pen, _startPosX.Value + 85, _startPosY.Value + 20, 20, 20);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 53, 100, 13);
g.DrawRectangle(pen, _startPosX.Value + 70, _startPosY.Value + 15, 30, 36);
g.DrawRectangle(pen, _startPosX.Value + 75, _startPosY.Value + 20, 20, 20);
// Колеса
g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 67, 25, 25);
g.DrawEllipse(pen, _startPosX.Value + 38, _startPosY.Value + 67, 25, 25);
g.DrawEllipse(pen, _startPosX.Value + 83, _startPosY.Value + 67, 25, 25);
g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 67, 25, 25);
g.DrawEllipse(pen, _startPosX.Value + 28, _startPosY.Value + 67, 25, 25);
g.DrawEllipse(pen, _startPosX.Value + 73, _startPosY.Value + 67, 25, 25);
// Кузов
Brush br = new SolidBrush(EntityDumpTruck.BodyColor);
g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value + 53, 100, 13);
g.FillRectangle(br, _startPosX.Value + 80, _startPosY.Value + 15, 30, 36);
Brush br = new SolidBrush(EntityTruck.BodyColor);
g.FillRectangle(br, _startPosX.Value, _startPosY.Value + 53, 100, 13);
g.FillRectangle(br, _startPosX.Value + 70, _startPosY.Value + 15, 30, 36);
// Колеса
Brush brBlack = new SolidBrush(Color.Black);
g.FillEllipse(brBlack, _startPosX.Value + 10, _startPosY.Value + 67, 25, 25);
g.FillEllipse(brBlack, _startPosX.Value + 38, _startPosY.Value + 67, 25, 25);
g.FillEllipse(brBlack, _startPosX.Value + 83, _startPosY.Value + 67, 25, 25);
g.FillEllipse(brBlack, _startPosX.Value, _startPosY.Value + 67, 25, 25);
g.FillEllipse(brBlack, _startPosX.Value + 28, _startPosY.Value + 67, 25, 25);
g.FillEllipse(brBlack, _startPosX.Value + 73, _startPosY.Value + 67, 25, 25);
//Окно
Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBlue, _startPosX.Value + 85, _startPosY.Value + 20, 20, 20);
g.FillRectangle(brBlue, _startPosX.Value + 75, _startPosY.Value + 20, 20, 20);
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Entities;
/// <summary>
/// Класс-сущность Самосвала
/// </summary>
public class EntityDumpTruck : EntityTruck
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Наличие кузова
/// </summary>
public bool Body { get; private set; }
/// <summary>
/// Наличие тента
/// </summary>
public bool Tent { get; private set; }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самосвала</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="body">Признак наличия кузова</param>
/// <param name="tent">Признак наличия тента</param>
public EntityDumpTruck(int speed, double weight, Color bodyColor, Color additionalColor, bool body, bool tent) : base(speed, weight, bodyColor: bodyColor)
{
AdditionalColor = additionalColor;
Body = body;
Tent = tent;
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Entities;
/// <summary>
/// Класс-сущность "Грузовик"
/// </summary>
public class EntityTruck
{
/// <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 => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самосвала</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityTruck(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -1,58 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck;
public class EntityDumpTruck
{
/// <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 Color AdditionalColor { get; private set; }
/// <summary>
/// Наличие кузова
/// </summary>
public bool Body { get; private set; }
/// <summary>
/// Наличие тента
/// </summary>
public bool Tent { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="body">Признак наличия обвеса</param>
/// <param name="tent">Признак наличия антикрыла</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool body, bool tent)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Body = body;
Tent = tent;
}
}

View File

@ -34,6 +34,9 @@
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonCreateTruck = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck).BeginInit();
SuspendLayout();
//
@ -51,9 +54,9 @@
buttonCreateDumpTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateDumpTruck.Location = new Point(14, 505);
buttonCreateDumpTruck.Name = "buttonCreateDumpTruck";
buttonCreateDumpTruck.Size = new Size(94, 29);
buttonCreateDumpTruck.Size = new Size(237, 29);
buttonCreateDumpTruck.TabIndex = 1;
buttonCreateDumpTruck.Text = "Создать";
buttonCreateDumpTruck.Text = "Создать самосвал";
buttonCreateDumpTruck.UseVisualStyleBackColor = true;
buttonCreateDumpTruck.Click += ButtonCreateDumpTruck_Click;
//
@ -105,11 +108,46 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonCreateTruck
//
buttonCreateTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTruck.Location = new Point(269, 504);
buttonCreateTruck.Name = "buttonCreateTruck";
buttonCreateTruck.Size = new Size(237, 29);
buttonCreateTruck.TabIndex = 6;
buttonCreateTruck.Text = "Создать грузовик";
buttonCreateTruck.UseVisualStyleBackColor = true;
buttonCreateTruck.Click += ButtonCreateTruck_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(731, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//comboBoxStrategy.SelectedIndexChanged += comboBoxStrategy_SelectedIndexChanged;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(785, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ВuttonStrategyStep_Click;
//
// FormDumpTruck
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(894, 545);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateTruck);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
@ -122,6 +160,8 @@
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxDumpTruck;
@ -130,5 +170,8 @@
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateTruck;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -7,6 +7,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.MovementStrategy;
namespace ProjectDumpTruck
{
@ -15,49 +17,79 @@ namespace ProjectDumpTruck
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningDumpTruck? _drawningDumpTruck;
private DrawningTruck? _drawningTruck;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormDumpTruck()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки машины
/// </summary>
private void Draw()
{
if (_drawningDumpTruck == null)
if (_drawningTruck == null)
{
return;
}
Bitmap bmp = new(pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningDumpTruck.DrawTransport(gr);
_drawningTruck.DrawTransport(gr);
pictureBoxDumpTruck.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Сосздание объекста класса-перемещения
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateDumpTruck_Click(object sender, EventArgs e)
/// <param name="type"></param>
private void CreateObject(string type)
{
Random random = new();
_drawningDumpTruck = new DrawningDumpTruck();
_drawningDumpTruck.Init(random.Next(100, 300), random.Next(1000, 3000),
Random random = new Random();
switch (type)
{
case nameof(DrawningTruck):
_drawningTruck = new DrawningTruck(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningDumpTruck):
_drawningTruck = new DrawningDumpTruck(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)));
_drawningDumpTruck.SetPictureSize(pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height);
break;
default:
return;
}
_drawningDumpTruck.SetPosition(random.Next(10, 100), random.Next(10, 100));
_drawningTruck.SetPictureSize(pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height);
_drawningTruck.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать самосвал"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateDumpTruck_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningDumpTruck));
/// <summary>
/// Обработка нажатия кнопки "Создать грузовик"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTruck_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTruck));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
@ -65,7 +97,7 @@ namespace ProjectDumpTruck
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningDumpTruck == null)
if (_drawningTruck == null)
{
return;
}
@ -75,19 +107,19 @@ namespace ProjectDumpTruck
{
case "buttonUp":
result =
_drawningDumpTruck.MoveTransport(DirectionType.Up);
_drawningTruck.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningDumpTruck.MoveTransport(DirectionType.Down);
_drawningTruck.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningDumpTruck.MoveTransport(DirectionType.Left);
_drawningTruck.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningDumpTruck.MoveTransport(DirectionType.Right);
_drawningTruck.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -95,6 +127,42 @@ namespace ProjectDumpTruck
Draw();
}
}
private void ВuttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningTruck == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTruck(_drawningTruck), pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

View File

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

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
public interface IMoveableObject
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = FieldWidth - objParams.RightBorder;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
int diffY = FieldHeight - objParams.DownBorder;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,66 @@
using ProjectDumpTruck.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectDumpTruck.MovementStrategy;
namespace ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningCar
/// </summary>
public class MoveableTruck : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// </summary>
private readonly DrawningTruck? _truck = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="truck">Объект класса DrawningCar</param>
public MoveableTruck(DrawningTruck truck)
{
_truck = truck;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_truck == null || _truck.EntityTruck == null ||
!_truck.GetPosX.HasValue || !_truck.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_truck.GetPosX.Value, _truck.GetPosY.Value, _truck.GetWidth, _truck.GetHeight);
}
}
public int GetStep => (int)(_truck?.EntityTruck?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_truck == null || _truck.EntityTruck == null)
{
return false;
}
return _truck.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}