2 лабораторная

This commit is contained in:
sardq 2023-10-21 21:47:58 +04:00
parent 05d5b82867
commit 467726e7d3
14 changed files with 500 additions and 61 deletions

View File

@ -0,0 +1,88 @@
namespace HoistingCrane.MovementStrategy
{
public abstract class AbstractStrategy
{
// Перемещаемый объект
private IMoveableObject? _moveableObject;
// Статус перемещения
private Status _state = Status.NotInit;
// Ширина поля
protected int FieldWidth { get; private set; }
// Высота поля
protected int FieldHeight { get; private set; }
// Статус перемещения
public Status GetStatus() { return _state; }
/// <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;
}
// Шаг перемещения
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
// Перемещение влевo
// <returns>Результат перемещения (true - удалось переместиться, false -неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
// Перемещение вправо false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
// Перемещение вверх
// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
// Перемещение вниз
// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
// Параметры объекта
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
// Шаг объекта
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
// Перемещение к цели
protected abstract void MoveToTarget();
// Достигнута ли цель
protected abstract bool IsTargetDestinaion();
// Попытка перемещения в требуемом направлении
// <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,18 @@
namespace HoistingCrane.Entities
{
public class AdditionEntityCrane : EntityCrane
{
//дополнительный
public Color AdditionalColor { get; private set; }
//противовес
public bool CounterWeight { get; private set; }
//кран
public bool Crane { get; private set; }
public AdditionEntityCrane(int speed, double weight, Color bodyColor, Color additionalColor, bool counterWeight, bool crane) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
CounterWeight = counterWeight;
Crane = crane;
}
}
}

View File

@ -0,0 +1,41 @@
using HoistingCrane.Entities;
namespace HoistingCrane.DrawningObjects
{
public class AdditionalDrawingCrane : DrawingCrane
{
// Конструктор
public AdditionalDrawingCrane(int speed, double weight, Color bodyColor, Color additionalColor, bool counterWeight, bool crane, int width, int height) : base(speed, weight, bodyColor, width, height)
{
if (EntityCrane != null)
{
EntityCrane = new AdditionEntityCrane(speed, weight, bodyColor, additionalColor, counterWeight, crane);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityCrane is not AdditionEntityCrane transportCrane)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(transportCrane.AdditionalColor);
//противовес
if (transportCrane.CounterWeight)
{
g.DrawRectangle(pen, _startPositionX + 185, _startPositionY + 20, 15, 45);
}
//кран
if (transportCrane.Crane)
{
g.DrawRectangle(pen, _startPositionX + 20, _startPositionY, 30, 65);
g.DrawRectangle(pen, _startPositionX, _startPositionY, 20, 30);
g.FillRectangle(additionalBrush, _startPositionX + 20, _startPositionY, 30, 65);
g.FillRectangle(additionalBrush, _startPositionX, _startPositionY, 20, 30);
}
base.DrawTransport(g);
}
}
}

View File

@ -35,6 +35,9 @@
this.buttonRight = new System.Windows.Forms.Button(); this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button(); this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button(); this.buttonUp = new System.Windows.Forms.Button();
this.buttonStep = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonCreateAdditional = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCrane)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCrane)).BeginInit();
this.SuspendLayout(); this.SuspendLayout();
// //
@ -50,7 +53,7 @@
// buttonCreate // buttonCreate
// //
this.buttonCreate.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.buttonCreate.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.buttonCreate.Location = new System.Drawing.Point(0, 385); this.buttonCreate.Location = new System.Drawing.Point(254, 378);
this.buttonCreate.Name = "buttonCreate"; this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(170, 59); this.buttonCreate.Size = new System.Drawing.Size(170, 59);
this.buttonCreate.TabIndex = 24; this.buttonCreate.TabIndex = 24;
@ -106,11 +109,49 @@
this.buttonUp.UseVisualStyleBackColor = true; this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click); this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
// //
// buttonStep
//
this.buttonStep.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.buttonStep.Location = new System.Drawing.Point(787, 45);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(80, 35);
this.buttonStep.TabIndex = 27;
this.buttonStep.Text = "шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"0",
"1"});
this.comboBoxStrategy.Location = new System.Drawing.Point(695, 6);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(182, 33);
this.comboBoxStrategy.TabIndex = 26;
//
// buttonCreateAdditional
//
this.buttonCreateAdditional.Font = new System.Drawing.Font("Segoe UI", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.buttonCreateAdditional.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.buttonCreateAdditional.Location = new System.Drawing.Point(0, 378);
this.buttonCreateAdditional.Name = "buttonCreateAdditional";
this.buttonCreateAdditional.Size = new System.Drawing.Size(248, 59);
this.buttonCreateAdditional.TabIndex = 25;
this.buttonCreateAdditional.Text = "создать кран с утяжелителем и краном";
this.buttonCreateAdditional.UseVisualStyleBackColor = true;
this.buttonCreateAdditional.Click += new System.EventHandler(this.ButtonCreateAdditional_Click);
//
// CraneVisual // CraneVisual
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(878, 444); this.ClientSize = new System.Drawing.Size(878, 444);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonCreateAdditional);
this.Controls.Add(this.buttonCreate); this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.buttonDown); this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonRight); this.Controls.Add(this.buttonRight);
@ -132,5 +173,8 @@
private Button buttonRight; private Button buttonRight;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button buttonCreateAdditional;
} }
} }

View File

@ -1,8 +1,12 @@
using HoistingCrane.DrawningObjects;
using HoistingCrane.MovementStrategy;
namespace HoistingCrane namespace HoistingCrane
{ {
public partial class CraneVisual : Form public partial class CraneVisual : Form
{ {
private DrawingCrane? _drawingCrane; private DrawingCrane? _drawingCrane;
private AbstractStrategy? _abstractStrategy;
public CraneVisual() public CraneVisual()
{ {
InitializeComponent(); InitializeComponent();
@ -16,11 +20,15 @@ namespace HoistingCrane
pictureBoxCrane.Image = btm; pictureBoxCrane.Image = btm;
} }
private void ButtonCreate_Click(object sender, EventArgs e) private void ButtonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawingCrane = new DrawingCrane(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), pictureBoxCrane.Width, pictureBoxCrane.Height); _drawingCrane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonCreateAdditional_Click(object sender, EventArgs e)
{ {
Random random = new Random(); Random random = new Random();
_drawingCrane = new DrawingCrane(); _drawingCrane = new AdditionalDrawingCrane(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)), pictureBoxCrane.Width, pictureBoxCrane.Height);
_drawingCrane.Init(random.Next(100, 300), random.Next(1000, 3000), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), 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)), pictureBoxCrane.Width, pictureBoxCrane.Height);
_drawingCrane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
} }
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
@ -44,5 +52,41 @@ namespace HoistingCrane
} }
Draw(); Draw();
} }
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingCrane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectsCrane(_drawingCrane), pictureBoxCrane.Width,
pictureBoxCrane.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
} }
} }

View File

@ -1,10 +1,4 @@
using System; namespace HoistingCrane
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HoistingCrane
{ {
public enum DirectionType public enum DirectionType
{ {

View File

@ -1,34 +1,36 @@
using HoistingCrane; using HoistingCrane.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HoistingCrane namespace HoistingCrane.DrawningObjects
{ {
internal class DrawingCrane public class DrawingCrane
{ {
public EntityCrane? EntityCrane { get; private set; } public EntityCrane? EntityCrane { get; protected set; }
private int _pictureWidth; private int _pictureWidth;
private int _pictureHeight; private int _pictureHeight;
private int _startPositionX; protected int _startPositionX;
private int _startPositionY; protected int _startPositionY;
private readonly int _craneWidth = 200; protected readonly int _craneWidth = 200;
private readonly int _craneHeight = 150; protected readonly int _craneHeight = 150;
public bool Init(int speed, double weight, bool counterWeight, bool crane, Color bodyColor, Color additionalColor, int width, int height) public DrawingCrane(int speed, double weight, Color bodyColor, int width, int height)
{ {
if ((_craneWidth > width) || (_craneHeight > height)) return false; if ((_craneWidth > width) || (_craneHeight > height)) return;
_pictureHeight = height; _pictureHeight = height;
_pictureWidth = width; _pictureWidth = width;
EntityCrane = new EntityCrane(); EntityCrane = new EntityCrane(speed, weight, bodyColor);
EntityCrane.Init(speed, weight, counterWeight, crane, bodyColor, additionalColor); }
protected DrawingCrane(int speed, double weight, Color bodyColor, int width, int height, int craneWidth, int craneHeight)
{
if ((craneWidth > width) || (craneHeight > height)) return;
_pictureHeight = height;
_pictureWidth = width;
_craneHeight = craneHeight;
_craneWidth = craneWidth;
EntityCrane = new EntityCrane(speed, weight, bodyColor);
return true;
} }
public void SetPosition(int x, int y) public void SetPosition(int x, int y)
{ {
@ -75,11 +77,60 @@ namespace HoistingCrane
} }
} }
public void DrawTransport(Graphics g) public int GetPosX => _startPositionX;
public int GetPosY => _startPositionY;
public int GetWidth => _craneWidth;
public int GetHeight => _craneHeight;
public bool CanMove(DirectionType direction)
{
if (EntityCrane == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPositionX - EntityCrane.Step > 0,
//вверх
DirectionType.Up => _startPositionY - EntityCrane.Step > 0,
// вправо
DirectionType.Right => _startPositionX + EntityCrane.Step - _craneWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPositionY + EntityCrane.Step - _craneHeight < _pictureHeight
};
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityCrane == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPositionX -= (int)EntityCrane.Step;
break;
//вверх
case DirectionType.Up:
_startPositionY -= (int)EntityCrane.Step;
break;
// вправо
case DirectionType.Right:
_startPositionX += (int)EntityCrane.Step;
break;
//вниз
case DirectionType.Down:
_startPositionY += (int)EntityCrane.Step;
break;
}
}
public virtual void DrawTransport(Graphics g)
{ {
if (EntityCrane == null) return; if (EntityCrane == null) return;
Pen pen = new Pen(Color.Black); Pen pen = new Pen(Color.Black);
Brush additionalBrush = new SolidBrush(EntityCrane.AdditionalColor);
Brush bodybrush = new SolidBrush(EntityCrane.BodyColor); Brush bodybrush = new SolidBrush(EntityCrane.BodyColor);
// Гусеницы // Гусеницы
g.DrawLine(pen, _startPositionX + 5, _startPositionY + 110, _startPositionX + 195, _startPositionY + 110); g.DrawLine(pen, _startPositionX + 5, _startPositionY + 110, _startPositionX + 195, _startPositionY + 110);
@ -104,18 +155,6 @@ namespace HoistingCrane
//кабинка и выхлоп //кабинка и выхлоп
g.DrawRectangle(pen, _startPositionX + 60, _startPositionY + 10, 20, 55); g.DrawRectangle(pen, _startPositionX + 60, _startPositionY + 10, 20, 55);
g.DrawRectangle(pen, _startPositionX + 110, _startPositionY, 75, 65); g.DrawRectangle(pen, _startPositionX + 110, _startPositionY, 75, 65);
if (EntityCrane.CounterWeight)
{
g.DrawRectangle(pen, _startPositionX + 185, _startPositionY + 20, 15, 45);
}
if (EntityCrane.Crane)
{
g.DrawRectangle(pen, _startPositionX + 20, _startPositionY, 30, 65);
g.DrawRectangle(pen, _startPositionX, _startPositionY, 20, 30);
g.FillRectangle(additionalBrush, _startPositionX + 20, _startPositionY, 30, 65);
g.FillRectangle(additionalBrush, _startPositionX, _startPositionY, 20, 30);
}
} }
} }
} }

View File

@ -0,0 +1,27 @@
using HoistingCrane.DrawningObjects;
namespace HoistingCrane.MovementStrategy
{
public class DrawningObjectsCrane : IMoveableObject
{
private readonly DrawingCrane? _drawingCrane = null;
public DrawningObjectsCrane(DrawingCrane drawingCrane)
{
_drawingCrane = drawingCrane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingCrane == null || _drawingCrane.EntityCrane == null)
{
return null;
}
return new ObjectParameters(_drawingCrane.GetPosX, _drawingCrane.GetPosY, _drawingCrane.GetWidth, _drawingCrane.GetHeight);
}
}
public int GetStep => (int)(_drawingCrane?.EntityCrane?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawingCrane?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawingCrane?.MoveTransport(direction);
}
}

View File

@ -1,12 +1,6 @@
using System; namespace HoistingCrane.Entities
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HoistingCrane
{ {
internal class EntityCrane public class EntityCrane
{ {
//скорость //скорость
public int Speed { get; private set; } public int Speed { get; private set; }
@ -14,22 +8,13 @@ namespace HoistingCrane
public double Weight { get; private set; } public double Weight { get; private set; }
//основной цввет //основной цввет
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
//дополнительный
public Color AdditionalColor { get; private set; }
//противовес
public bool CounterWeight { get; private set; }
//Кран
public bool Crane { get; private set; }
//шаг перемещения //шаг перемещения
public double Step => (double)Speed * 100 / Weight; public double Step => (double)Speed * 100 / Weight;
public void Init(int speed, double weight, bool counterWeight, bool crane, Color bodyColor, Color additionalColor) public EntityCrane(int speed, double weight, Color bodyColor)
{ {
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;
CounterWeight = counterWeight;
Crane = crane;
BodyColor = bodyColor; BodyColor = bodyColor;
AdditionalColor = additionalColor;
} }
} }
} }

View File

@ -0,0 +1,13 @@
namespace HoistingCrane.MovementStrategy
{
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
/// Шаг объекта
int GetStep { get; }
/// Проверка, можно ли переместиться по нужному направлению
bool CheckCanMove(DirectionType direction);
/// Изменение направления перещения объекта
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,47 @@
namespace HoistingCrane.MovementStrategy
{
internal class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth && objParams.ObjectMiddleHorizontal <= FieldHeight && objParams.ObjectMiddleHorizontal + 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,47 @@
namespace HoistingCrane.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,42 @@
namespace HoistingCrane.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;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -0,0 +1,10 @@
namespace HoistingCrane.MovementStrategy
{
// Статус выполнения операции перемещения
public enum Status
{
NotInit,
InProgress,
Finish
}
}