PIbd-21. Danilov V.V. Lab work 02 #2

Closed
VoOneChek wants to merge 1 commits from LabWork02 into LabWork01
13 changed files with 799 additions and 217 deletions

View File

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

View File

@ -3,195 +3,62 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project_DumpTruck.Entities;
namespace Project_DumpTruck
namespace Project_DumpTruck.DrawningObjects
{
internal class DrawningDumpTruck
public class DrawningDumpTruck: DrawningTruck
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityDumpTruck? EntityDumpTruck { get; private set; }
/// <summary>
/// Левая координата отрисовки автомобиля
/// </summary>
private float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки автомобиля
/// </summary>
private float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Ширина отрисовки автомобиля
/// </summary>
private readonly int _dumptruckWidth = 110;
/// <summary>
/// Высота отрисовки автомобиля
/// </summary>
private readonly int _dumptruckHeight = 60;
/// <summary>
/// Инициализация свойств
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor"></param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public bool Init(int speed, float weight, Color bodyColor, Color additionalColor, bool body, bool tent, int width, int height)
/// <param name="bodyKit">Признак наличия груза</param>
/// <param name="tent">Признак наличия тента</param>
public DrawningDumpTruck(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool tent, int width, int height) :
base(speed, weight, bodyColor, width, height, 110, 60)
{
// TODO: Продумать проверки
if (width < _dumptruckWidth || height < _dumptruckHeight)
return false;
_pictureWidth = width;
_pictureHeight = height;
EntityDumpTruck = new EntityDumpTruck();
EntityDumpTruck.Init(speed, weight, bodyColor, additionalColor, body, tent);
return true;
}
/// <summary>
/// Установка позиции автомобиля
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void SetPosition(int x, int y)
{
if (x < 0 || y < 0 || x > _pictureWidth || y > _pictureHeight)
if (EntityTruck != null)
{
_startPosX = 0;
_startPosY = 0;
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Изменение направления пермещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityDumpTruck == null)
{
return;
}
switch (direction)
{
// вправо
case DirectionType.Right:
if (_startPosX + _dumptruckWidth + EntityDumpTruck.Step < _pictureWidth)
{
_startPosX += (int)EntityDumpTruck.Step;
}
break;
//влево
case DirectionType.Left:
if (_startPosX - EntityDumpTruck.Step > 0)
{
_startPosX -= (int)EntityDumpTruck.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityDumpTruck.Step > 0)
{
_startPosY -= (int)EntityDumpTruck.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _dumptruckHeight + EntityDumpTruck.Step < _pictureHeight)
{
_startPosY += (int)EntityDumpTruck.Step;
}
break;
EntityTruck = new EntityDumpTruck(speed, weight, bodyColor, additionalColor, bodyKit, tent);
}
}
/// <summary>
/// Отрисовка автомобиля
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public override void DrawTransport(Graphics g)
{
if (EntityDumpTruck == null)
if (EntityTruck is not EntityDumpTruck dumpTruck)
{
return;
}
Pen penBlack = new Pen(Color.Black);
Brush brushBodyColor = new SolidBrush(EntityDumpTruck.BodyColor);
Brush brushAdditionalColor = new SolidBrush(EntityDumpTruck.AdditionalColor);
Brush brushBlack = new SolidBrush(Color.Black);
Brush brushAdditionalColor = new SolidBrush(dumpTruck.AdditionalColor);
Brush brushWhite = new SolidBrush(Color.White);
Pen penBlack = new Pen(Color.Black);
//Кабина
g.FillRectangle(brushBodyColor, _startPosX + 80, _startPosY, 20, 30);
g.DrawRectangle(penBlack, _startPosX + 80, _startPosY, 20, 30);
base.DrawTransport(g);
//Рама
g.FillRectangle(brushBodyColor, _startPosX, _startPosY + 30, 100, 5);
g.DrawRectangle(penBlack, _startPosX, _startPosY + 30, 100, 5);
//Колёса
g.FillEllipse(brushBlack, _startPosX, _startPosY + 35, 20, 20);
g.FillEllipse(brushBlack, _startPosX + 22, _startPosY + 35, 20, 20);
g.FillEllipse(brushBlack, _startPosX + 80, _startPosY + 35, 20, 20);
g.FillEllipse(brushWhite, _startPosX + 5, _startPosY + 40, 10, 10);
g.FillEllipse(brushWhite, _startPosX + 27, _startPosY + 40, 10, 10);
g.FillEllipse(brushWhite, _startPosX + 85, _startPosY + 40, 10, 10);
g.DrawEllipse(penBlack, _startPosX, _startPosY + 35, 20, 20);
g.DrawEllipse(penBlack, _startPosX + 22, _startPosY + 35, 20, 20);
g.DrawEllipse(penBlack, _startPosX + 80, _startPosY + 35, 20, 20);
if (EntityDumpTruck.BodyKit)
if (dumpTruck.BodyKit)
{
g.FillRectangle(brushAdditionalColor, _startPosX, _startPosY + 30, 100, 5);
g.FillRectangle(brushAdditionalColor, _startPosX, _startPosY + 10, 70, 20);
g.DrawRectangle(penBlack, _startPosX, _startPosY + 30, 100, 5);
g.DrawRectangle(penBlack, _startPosX, _startPosY + 10, 70, 20);
if (EntityDumpTruck.Tent)
if (dumpTruck.Tent)
{
g.FillRectangle(brushWhite, _startPosX, _startPosY + 10, 70, 5);
g.DrawRectangle(penBlack, _startPosX, _startPosY + 10, 70, 5);
}
}
}
/// <summary>
/// Смена границ формы отрисовки
/// </summary>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void ChangeBorders(int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth <= _dumptruckWidth || _pictureHeight <= _dumptruckHeight)
{
_pictureWidth = null;
_pictureHeight = null;
return;
}
if (_startPosX + _dumptruckWidth > _pictureWidth)
{
_startPosX = _pictureWidth.Value - _dumptruckWidth;
}
if (_startPosY + _dumptruckHeight > _pictureHeight)
{
_startPosY = _pictureHeight.Value - _dumptruckHeight;
}
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project_DumpTruck.DrawningObjects;
namespace Project_DumpTruck.MovementStrategy
{
public class DrawningObjectTruck : IMoveableObject
{
private readonly DrawningTruck? _drawningTruck = null;
public DrawningObjectTruck(DrawningTruck drawningTruck)
{
_drawningTruck = drawningTruck;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningTruck == null || _drawningTruck.EntityTruck == null)
{
return null;
}
return new ObjectParameters(_drawningTruck.GetPosX, _drawningTruck.GetPosY, _drawningTruck.GetWidth, _drawningTruck.GetHeight);
}
}
public int GetStep => (int)(_drawningTruck?.EntityTruck?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawningTruck?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawningTruck?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,223 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project_DumpTruck.Entities;
namespace Project_DumpTruck.DrawningObjects
{
public class DrawningTruck
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityTruck? EntityTruck { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
protected readonly int _truckWidth = 110;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
protected readonly int _truckHeight = 60;
/// <summary>
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _truckWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _truckHeight;
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningTruck(int speed, double weight, Color bodyColor, int width, int height)
{
if (width < _truckWidth || height < _truckHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityTruck = new EntityTruck(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="truckWidth">Ширина прорисовки автомобиля</param>
/// <param name="truckHeight">Высота прорисовки автомобиля</param>
protected DrawningTruck(int speed, double weight, Color bodyColor, int width, int height, int truckWidth, int truckHeight)
{
if (width <= _truckWidth || height <= _truckHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_truckWidth = truckWidth;
_truckHeight = truckHeight;
EntityTruck = new EntityTruck(speed, weight, bodyColor);
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityTruck == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityTruck.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityTruck.Step > 0,
// вправо
DirectionType.Right => _startPosX + _truckWidth + EntityTruck.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _truckHeight + EntityTruck.Step < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x < 0 || x + _truckWidth > _pictureWidth)
{
x = Math.Max(0, _pictureWidth - _truckWidth);
}
if (y < 0 || y + _truckHeight > _pictureHeight)
{
y = Math.Max(0, _pictureHeight - _truckHeight);
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityTruck == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX - EntityTruck.Step > 0)
{
_startPosX -= (int)EntityTruck.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityTruck.Step > 0)
{
_startPosY -= (int)EntityTruck.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + _truckWidth + EntityTruck.Step < _pictureWidth)
{
_startPosX += (int)EntityTruck.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _truckHeight + EntityTruck.Step < _pictureHeight)
{
_startPosY += (int)EntityTruck.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityTruck == null)
{
return;
}
Pen penBlack = new Pen(Color.Black);
Brush brushBodyColor = new SolidBrush(EntityTruck.BodyColor);
Brush brushBlack = new SolidBrush(Color.Black);
Brush brushWhite = new SolidBrush(Color.White);
//Кабина
g.FillRectangle(brushBodyColor, _startPosX + 80, _startPosY, 20, 30);
g.DrawRectangle(penBlack, _startPosX + 80, _startPosY, 20, 30);
//Рама
g.FillRectangle(brushBodyColor, _startPosX, _startPosY + 30, 100, 5);
g.DrawRectangle(penBlack, _startPosX, _startPosY + 30, 100, 5);
//Колёса
g.FillEllipse(brushBlack, _startPosX, _startPosY + 35, 20, 20);
g.FillEllipse(brushBlack, _startPosX + 22, _startPosY + 35, 20, 20);
g.FillEllipse(brushBlack, _startPosX + 80, _startPosY + 35, 20, 20);
g.FillEllipse(brushWhite, _startPosX + 5, _startPosY + 40, 10, 10);
g.FillEllipse(brushWhite, _startPosX + 27, _startPosY + 40, 10, 10);
g.FillEllipse(brushWhite, _startPosX + 85, _startPosY + 40, 10, 10);
g.DrawEllipse(penBlack, _startPosX, _startPosY + 35, 20, 20);
g.DrawEllipse(penBlack, _startPosX + 22, _startPosY + 35, 20, 20);
g.DrawEllipse(penBlack, _startPosX + 80, _startPosY + 35, 20, 20);
}
}
}

View File

@ -1,28 +1,14 @@
using System;
using Project_DumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_DumpTruck
namespace Project_DumpTruck.Entities
{
internal class EntityDumpTruck
internal class EntityDumpTruck: 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>
@ -38,11 +24,6 @@ namespace Project_DumpTruck
/// </summary>
public bool Tent { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса автомобиля
/// </summary>
@ -51,11 +32,9 @@ namespace Project_DumpTruck
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <returns></returns>
public void Init(int speed, float weight, Color bodyColor, Color additionalColor, bool bodyKit, bool tent)
public EntityDumpTruck(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool tent) :
base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Tent = tent;

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_DumpTruck.Entities
{
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 => (double)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

@ -29,11 +29,14 @@
private void InitializeComponent()
{
pictureBoxDumpTruck = new PictureBox();
buttonCreate = new Button();
buttonCreateTruck = new Button();
buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonCreateDumpTruck = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck).BeginInit();
SuspendLayout();
//
@ -47,16 +50,16 @@
pictureBoxDumpTruck.TabIndex = 0;
pictureBoxDumpTruck.TabStop = false;
//
// buttonCreate
// buttonCreateTruck
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 426);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
buttonCreateTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTruck.Location = new Point(12, 406);
buttonCreateTruck.Name = "buttonCreateTruck";
buttonCreateTruck.Size = new Size(107, 43);
buttonCreateTruck.TabIndex = 1;
buttonCreateTruck.Text = "Создать грузовик";
buttonCreateTruck.UseVisualStyleBackColor = true;
buttonCreateTruck.Click += buttonCreateTruck_Click;
//
// buttonLeft
//
@ -106,20 +109,56 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonCreateDumpTruck
//
buttonCreateDumpTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateDumpTruck.Location = new Point(125, 406);
buttonCreateDumpTruck.Name = "buttonCreateDumpTruck";
buttonCreateDumpTruck.Size = new Size(118, 43);
buttonCreateDumpTruck.TabIndex = 6;
buttonCreateDumpTruck.Text = "Создать грузовик с кузовом";
buttonCreateDumpTruck.UseVisualStyleBackColor = true;
buttonCreateDumpTruck.Click += buttonCreateDumpTruck_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Путь к центру", "Путь к правому нижнему углу" });
comboBoxStrategy.Location = new Point(751, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(797, 41);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 23);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// FormDumpTruck
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateDumpTruck);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonCreate);
Controls.Add(buttonCreateTruck);
Controls.Add(pictureBoxDumpTruck);
Name = "FormDumpTruck";
StartPosition = FormStartPosition.CenterScreen;
Text = "Form1";
Text = "Проект";
((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck).EndInit();
ResumeLayout(false);
PerformLayout();
@ -128,10 +167,13 @@
#endregion
private PictureBox pictureBoxDumpTruck;
private Button buttonCreate;
private Button buttonCreateTruck;
private Button buttonLeft;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateDumpTruck;
private ComboBox comboBoxStrategy;
private Button buttonStep;
}
}

View File

@ -1,11 +1,16 @@
namespace Project_DumpTruck
using Project_DumpTruck.DrawningObjects;
using Project_DumpTruck.MovementStrategy;
namespace Project_DumpTruck
{
public partial class FormDumpTruck : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningDumpTruck? _drawningDumpTruck;
private DrawningTruck? _drawningTruck;
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Инициализация формы
@ -20,33 +25,26 @@
/// </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>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать truck"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
private void buttonCreateTruck_Click(object sender, EventArgs e)
{
Random random = new();
_drawningDumpTruck = new DrawningDumpTruck();
_drawningDumpTruck.Init(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)),
_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)),
pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height);
_drawningDumpTruck.SetPosition(random.Next(10, 100),
random.Next(10, 100));
_drawningTruck.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
@ -58,7 +56,7 @@
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningDumpTruck == null)
if (_drawningTruck == null)
{
return;
}
@ -66,19 +64,68 @@
switch (name)
{
case "buttonUp":
_drawningDumpTruck.MoveTransport(DirectionType.Up);
_drawningTruck.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningDumpTruck.MoveTransport(DirectionType.Down);
_drawningTruck.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningDumpTruck.MoveTransport(DirectionType.Left);
_drawningTruck.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningDumpTruck.MoveTransport(DirectionType.Right);
_drawningTruck.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void buttonCreateDumpTruck_Click(object sender, EventArgs e)
{
Random random = new();
_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)),
pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height);
_drawningTruck.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningTruck == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectTruck(_drawningTruck), pictureBoxDumpTruck.Width,
pictureBoxDumpTruck.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,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_DumpTruck.MovementStrategy
{
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,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project_DumpTruck.MovementStrategy;
namespace Project_DumpTruck
{
internal class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

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

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_DumpTruck.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,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_DumpTruck.MovementStrategy
{
public enum Status
{
NotInit,
InProgress,
Finish
}
}