Compare commits

...

5 Commits

Author SHA1 Message Date
7402296ecd Лабораторная 2
vse cool
2024-03-15 00:32:50 +04:00
cd369bfe6e e boi 2024-03-14 20:48:51 +04:00
9c13440d18 op 2024-03-14 09:23:58 +04:00
a363f63d3b вот так вот 2024-03-13 23:10:53 +04:00
6a5e5fc3bb Первая часть 2024-03-13 21:00:22 +04:00
12 changed files with 618 additions and 64 deletions

View File

@ -8,7 +8,10 @@ namespace ProjectDumpTruck.Drawnings
{
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -1,9 +1,4 @@
using ProjectDumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Drawnings;
@ -37,6 +32,22 @@ public class DrawningTruck
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _drawningTruckHeight = 85;
/// <summary>
/// Координата x объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningTruckWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningTruckHeight;
/// <summary>
/// Пустой конструктор
@ -76,7 +87,6 @@ public class DrawningTruck
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public bool SetPictureSize(int width, int height)
{
if (width >= _drawningTruckWidth && height >= _drawningTruckHeight)

View File

@ -28,41 +28,35 @@
/// </summary>
private void InitializeComponent()
{
pictureBoxDumpTruck = new PictureBox();
buttonCreate = new Button();
buttonCreateDumpTruck = new Button();
buttonLeft = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonDown = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck).BeginInit();
buttonCreateTruck = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
pictureBoxDumpTruck1 = new PictureBox();
((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck1).BeginInit();
SuspendLayout();
//
// pictureBoxDumpTruck
// buttonCreateDumpTruck
//
pictureBoxDumpTruck.Dock = DockStyle.Fill;
pictureBoxDumpTruck.Location = new Point(0, 0);
pictureBoxDumpTruck.Name = "pictureBoxDumpTruck";
pictureBoxDumpTruck.Size = new Size(892, 514);
pictureBoxDumpTruck.TabIndex = 0;
pictureBoxDumpTruck.TabStop = false;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 473);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
buttonCreateDumpTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateDumpTruck.Location = new Point(12, 486);
buttonCreateDumpTruck.Name = "buttonCreateDumpTruck";
buttonCreateDumpTruck.Size = new Size(188, 29);
buttonCreateDumpTruck.TabIndex = 1;
buttonCreateDumpTruck.Text = "Создать самосвал";
buttonCreateDumpTruck.UseVisualStyleBackColor = true;
buttonCreateDumpTruck.Click += ButtonCreateDumpTruck_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.влево;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(738, 456);
buttonLeft.Location = new Point(852, 469);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(40, 40);
buttonLeft.TabIndex = 2;
@ -74,7 +68,7 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.вправо;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(830, 456);
buttonRight.Location = new Point(944, 469);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(40, 40);
buttonRight.TabIndex = 3;
@ -86,7 +80,7 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.вверх;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(784, 410);
buttonUp.Location = new Point(898, 423);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(40, 40);
buttonUp.TabIndex = 4;
@ -98,37 +92,85 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.вниз;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(784, 456);
buttonDown.Location = new Point(898, 469);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(40, 40);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonCreateTruck
//
buttonCreateTruck.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTruck.Location = new Point(206, 486);
buttonCreateTruck.Name = "buttonCreateTruck";
buttonCreateTruck.Size = new Size(188, 29);
buttonCreateTruck.TabIndex = 6;
buttonCreateTruck.Text = "Создать грузовик";
buttonCreateTruck.UseVisualStyleBackColor = true;
buttonCreateTruck.Click += ButtonCreateTruck_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(833, 21);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(890, 55);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 9;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// pictureBoxDumpTruck1
//
pictureBoxDumpTruck1.Dock = DockStyle.Fill;
pictureBoxDumpTruck1.Location = new Point(0, 0);
pictureBoxDumpTruck1.Name = "pictureBoxDumpTruck1";
pictureBoxDumpTruck1.Size = new Size(1006, 527);
pictureBoxDumpTruck1.TabIndex = 10;
pictureBoxDumpTruck1.TabStop = false;
//
// FormDumpTruck
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(892, 514);
ClientSize = new Size(1006, 527);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateTruck);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxDumpTruck);
Controls.Add(buttonCreateDumpTruck);
Controls.Add(pictureBoxDumpTruck1);
Name = "FormDumpTruck";
Text = "Самосвал";
((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxDumpTruck1).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxDumpTruck;
private Button buttonCreate;
private Button buttonCreateDumpTruck;
private Button buttonLeft;
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
private Button buttonCreateTruck;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
private PictureBox pictureBoxDumpTruck1;
}
}

View File

@ -1,73 +1,141 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.MovementStrategy;
namespace ProjectDumpTruck
{
public partial class FormDumpTruck : Form
{
private DrawningDumpTruck? _drawningDumpTruck;
private DrawningTruck? _drawningTruck;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
public FormDumpTruck()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
{
if (_drawningDumpTruck == null) return;
if (_drawningTruck == null) return;
Bitmap bmp = new(pictureBoxDumpTruck.Width,
pictureBoxDumpTruck.Height);
Bitmap bmp = new(pictureBoxDumpTruck1.Width,
pictureBoxDumpTruck1.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningDumpTruck.DrawTransport(gr);
pictureBoxDumpTruck.Image = bmp;
_drawningTruck.DrawTransport(gr);
pictureBoxDumpTruck1.Image = bmp;
}
private void ButtonCreate_Click(object sender, EventArgs e)
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <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),
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)));
break;
_drawningDumpTruck.SetPictureSize(pictureBoxDumpTruck.Width, pictureBoxDumpTruck.Height);
_drawningDumpTruck.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
default:
return;
}
_drawningTruck.SetPictureSize(pictureBoxDumpTruck1.Width, pictureBoxDumpTruck1.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));
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningDumpTruck == null) return;
if (_drawningTruck == null) return;
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonLeft":
result = _drawningDumpTruck.MoveTransport(DirectionType.Left); break;
result = _drawningTruck.MoveTransport(DirectionType.Left); break;
case "buttonDown":
result = _drawningDumpTruck.MoveTransport(DirectionType.Down); break;
result = _drawningTruck.MoveTransport(DirectionType.Down); break;
case "buttonUp":
result = _drawningDumpTruck.MoveTransport(DirectionType.Up); break;
result = _drawningTruck.MoveTransport(DirectionType.Up); break;
case "buttonRight":
result = _drawningDumpTruck.MoveTransport(DirectionType.Right); break;
result = _drawningTruck.MoveTransport(DirectionType.Right); break;
}
if (result) Draw();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_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), pictureBoxDumpTruck1.Width, pictureBoxDumpTruck1.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,140 @@

namespace ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Класс-страгетия перемещения объекта
/// </summary>
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>
/// <returns></returns>
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>
/// <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 MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результаты перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
///
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress) return;
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <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>
/// <returns></returns>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestination();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection"></param>
/// <returns></returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress) return false;
return _moveableObject?.TryMoveableObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,24 @@

namespace ProjectDumpTruck.MovementStrategy;
public interface IMoveableObject
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
bool TryMoveableObject(MovementDirection direction);
}

View File

@ -0,0 +1,41 @@

namespace ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта к углу
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.LeftBorder - GetStep() <= 0 || objParams.RightBorder + GetStep() >= FieldWidth ||
objParams.TopBorder - GetStep() <= 0 || objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,55 @@

namespace ProjectDumpTruck.MovementStrategy;
// <summary>
/// Стратегия перемещения объекта в центр
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
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,58 @@

using ProjectDumpTruck.Drawnings;
namespace ProjectDumpTruck.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningTruck
/// </summary>
public class MoveableTruck : IMoveableObject
{
private DrawningTruck? _truck=null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="truck">Объект класса DrawningTruck</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);
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
_ => DirectionType.Unknow
};
}
public bool TryMoveableObject(MovementDirection direction)
{
if (_truck == null || _truck.EntityTruck == null) return false;
return _truck.MoveTransport(GetDirectionType(direction));
}
}

View File

@ -0,0 +1,23 @@

namespace ProjectDumpTruck.MovementStrategy
{
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,70 @@

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">Координата Х</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 @@

namespace ProjectDumpTruck.MovementStrategy
{
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}
}