PIbd-11 Kudyaeva.V.A LabWork02 Simple #2

Closed
Kudyaeva wants to merge 4 commits from LabWork02 into LabWork01
18 changed files with 806 additions and 222 deletions

View File

@ -0,0 +1,31 @@
namespace SelfPropelledArtilleryUnit.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -1,14 +1,20 @@
namespace SelfPropelledArtilleryUnit;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class DrawningSelfPropelledArtilleryUnit
namespace SelfPropelledArtilleryUnit.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
/// </summary>
public class DrawningPropelledArtillery
Review

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

Имя элемента проекта не соответствует указанному в задании
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntitySelfPropelledArtilleryUnit? EntitySelfPropelledArtilleryUnit { get; private set; }
public EntityPropelledArtillery? EntityPropelledArtillery { get; protected set; }
/// <summary>
/// Ширина окна
@ -23,43 +29,77 @@ public class DrawningSelfPropelledArtilleryUnit
/// <summary>
/// Левая координата прорисовки cамоходной арт. установки
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки cамоходной арт. установки
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки cамоходной арт. установки
/// </summary>
private readonly int _drawningSelfPropelledArtilleryUnitWidth = 135;
private readonly int _drawningPropelledArtilleryWidth = 135;
/// <summary>
/// Высота прорисовки cамоходной арт. установки
/// </summary>
private readonly int _drawningSelfPropelledArtilleryUnitHeight = 105;
private readonly int _drawningPropelledArtilleryHeight = 105;
/// <summary>
/// Инициализация полей объекта-класса Самоходная арт. установка
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="turretCannon">Признак наличия башни</param>
/// <param name="launchBattery">Признак наличия орудия</param>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool turretCannon, bool launchBattery)
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningPropelledArtilleryWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningPropelledArtilleryHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningPropelledArtillery()
{
EntitySelfPropelledArtilleryUnit = new EntitySelfPropelledArtilleryUnit();
EntitySelfPropelledArtilleryUnit.Init(speed, weight, bodyColor, additionalColor, turretCannon, launchBattery);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningPropelledArtillery(int speed, double weight, Color bodyColor): this()
{
EntityPropelledArtillery = new EntityPropelledArtillery(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningPropelledArtilleryWidth">Ширина прорисовки cамоходной арт. установки</param>
/// <param name="drawningPropelledArtilleryHeight">Высота прорисовки cамоходной арт. установки</param>
protected DrawningPropelledArtillery(int drawningPropelledArtilleryWidth, int drawningPropelledArtilleryHeight):this()
{
_drawningPropelledArtilleryWidth = drawningPropelledArtilleryWidth;
_drawningPropelledArtilleryHeight = drawningPropelledArtilleryHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
@ -68,7 +108,7 @@ public class DrawningSelfPropelledArtilleryUnit
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
if (_drawningSelfPropelledArtilleryUnitWidth > width || _drawningSelfPropelledArtilleryUnitHeight > height)
if (_drawningPropelledArtilleryWidth > width || _drawningPropelledArtilleryHeight > height)
{
return false;
}
@ -77,14 +117,14 @@ public class DrawningSelfPropelledArtilleryUnit
_pictureHeight = height;
if (_startPosX.HasValue || _startPosY.HasValue)
{
if (_startPosX + _drawningSelfPropelledArtilleryUnitWidth > _pictureWidth)
if (_startPosX + _drawningPropelledArtilleryWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningSelfPropelledArtilleryUnitWidth;
_startPosX = _pictureWidth - _drawningPropelledArtilleryWidth;
}
else if (_startPosX < 0) _startPosX = 0;
if (_startPosY + _drawningSelfPropelledArtilleryUnitHeight > _pictureHeight)
if (_startPosY + _drawningPropelledArtilleryHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningSelfPropelledArtilleryUnitHeight;
_startPosY = _pictureHeight - _drawningPropelledArtilleryHeight;
}
else if (_startPosY < 0) _startPosY = 0;
}
@ -105,16 +145,16 @@ public class DrawningSelfPropelledArtilleryUnit
// TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
if (x + _drawningSelfPropelledArtilleryUnitWidth > _pictureWidth)
if (x + _drawningPropelledArtilleryWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningSelfPropelledArtilleryUnitWidth;
_startPosX = _pictureWidth - _drawningPropelledArtilleryWidth;
}
else if (x < 0) _startPosX = 0;
else _startPosX = x;
if (y + _drawningSelfPropelledArtilleryUnitHeight > _pictureHeight)
if (y + _drawningPropelledArtilleryHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningSelfPropelledArtilleryUnitHeight;
_startPosY = _pictureHeight - _drawningPropelledArtilleryHeight;
}
else if (y < 0) _startPosY = 0;
else _startPosY = y;
@ -128,7 +168,7 @@ public class DrawningSelfPropelledArtilleryUnit
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntitySelfPropelledArtilleryUnit == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityPropelledArtillery == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@ -137,30 +177,30 @@ public class DrawningSelfPropelledArtilleryUnit
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntitySelfPropelledArtilleryUnit.Step > 0)
if (_startPosX.Value - EntityPropelledArtillery.Step > 0)
{
_startPosX -= (int)EntitySelfPropelledArtilleryUnit.Step;
_startPosX -= (int)EntityPropelledArtillery.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntitySelfPropelledArtilleryUnit.Step > 0)
if (_startPosY.Value - EntityPropelledArtillery.Step > 0)
{
_startPosY -= (int)EntitySelfPropelledArtilleryUnit.Step;
_startPosY -= (int)EntityPropelledArtillery.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX + _drawningSelfPropelledArtilleryUnitWidth + EntitySelfPropelledArtilleryUnit.Step < _pictureWidth)
if (_startPosX + _drawningPropelledArtilleryWidth + EntityPropelledArtillery.Step < _pictureWidth)
{
_startPosX += (int)EntitySelfPropelledArtilleryUnit.Step;
_startPosX += (int)EntityPropelledArtillery.Step;
}
return true;
// вниз
case DirectionType.Down:
if (_startPosY + _drawningSelfPropelledArtilleryUnitHeight + EntitySelfPropelledArtilleryUnit.Step < _pictureHeight)
if (_startPosY + _drawningPropelledArtilleryHeight + EntityPropelledArtillery.Step < _pictureHeight)
{
_startPosY += (int)EntitySelfPropelledArtilleryUnit.Step;
_startPosY += (int)EntityPropelledArtillery.Step;
}
return true;
default:
@ -173,37 +213,36 @@ public class DrawningSelfPropelledArtilleryUnit
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntitySelfPropelledArtilleryUnit == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityPropelledArtillery == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntitySelfPropelledArtilleryUnit.AdditionalColor);
Brush brush = new SolidBrush(EntityPropelledArtillery.BodyColor);
Brush brSlateGray = new SolidBrush(Color.SlateGray);
g.DrawEllipse(pen, _startPosX.Value + 0, _startPosY.Value + 75, 30, 30);
g.DrawEllipse(pen, _startPosX.Value + 90, _startPosY.Value + 75, 30, 30);
g.DrawRectangle(pen, _startPosX.Value + 15, _startPosY.Value + 75, 90, 30);
//границы ЦВЕТ
Brush brOlive = new SolidBrush(Color.Olive);
g.FillRectangle(brOlive, _startPosX.Value + 25, _startPosY.Value + 40, 35, 30);//башня
g.FillEllipse(brOlive, _startPosX.Value +0, _startPosY.Value + 75, 30, 30);
g.FillEllipse(brOlive, _startPosX.Value + 90, _startPosY.Value + 75, 30, 30);
g.FillRectangle(brOlive, _startPosX.Value + 15, _startPosY.Value + 75, 90, 30);
g.FillRectangle(brush, _startPosX.Value + 25, _startPosY.Value + 40, 35, 30);//башня
g.FillEllipse(brush, _startPosX.Value + 0, _startPosY.Value + 75, 30, 30);
g.FillEllipse(brush, _startPosX.Value + 90, _startPosY.Value + 75, 30, 30);
g.FillRectangle(brush, _startPosX.Value + 15, _startPosY.Value + 75, 90, 30);
// границы арт. установки
g.DrawRectangle(pen, _startPosX.Value + 25, _startPosY.Value + 40, 35, 30);
g.DrawRectangle(pen, _startPosX.Value + 0, _startPosY.Value + 65, 120, 13);//крыша
// верхние катки ЦВЕТ
Brush brCadetBlue = new SolidBrush(Color.CadetBlue);
g.FillEllipse(brCadetBlue, _startPosX.Value + 30, _startPosY.Value + 70, 20, 20);
g.FillEllipse(brCadetBlue, _startPosX.Value + 50, _startPosY.Value + 70, 20, 20);
g.FillEllipse(brCadetBlue, _startPosX.Value + 70, _startPosY.Value + 70, 20, 20);
g.FillEllipse(brSlateGray, _startPosX.Value + 30, _startPosY.Value + 70, 20, 20);
g.FillEllipse(brSlateGray, _startPosX.Value + 50, _startPosY.Value + 70, 20, 20);
g.FillEllipse(brSlateGray, _startPosX.Value + 70, _startPosY.Value + 70, 20, 20);
// верхние катки ОТРИСОВКА
g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 70, 20, 20);
@ -223,8 +262,6 @@ public class DrawningSelfPropelledArtilleryUnit
g.DrawEllipse(pen, _startPosX.Value + 60, _startPosY.Value + 90, 15, 15);
g.DrawEllipse(pen, _startPosX.Value + 75, _startPosY.Value + 90, 15, 15);
//Большие катки ЦВЕТ
Brush brSlateGray = new SolidBrush(Color.SlateGray);
g.FillEllipse(brSlateGray, _startPosX.Value + 3, _startPosY.Value + 78, 24, 24);
g.FillEllipse(brSlateGray, _startPosX.Value + 93, _startPosY.Value + 78, 24, 24);
@ -232,30 +269,9 @@ public class DrawningSelfPropelledArtilleryUnit
g.DrawEllipse(pen, _startPosX.Value + 3, _startPosY.Value + 78, 24, 24);
g.DrawEllipse(pen, _startPosX.Value + 93, _startPosY.Value + 78, 24, 24);
g.FillRectangle(brOlive, _startPosX.Value + 0, _startPosY.Value + 65, 120, 13);//
g.FillRectangle(brush, _startPosX.Value + 0, _startPosY.Value + 65, 120, 13);//
if (EntitySelfPropelledArtilleryUnit.TurretCannon)
{
g.FillEllipse(additionalBrush, _startPosX.Value + 26, _startPosY.Value + 35, 50, 30);
g.FillRectangle(additionalBrush, _startPosX.Value + 25, _startPosY.Value + 36, 20, 29);
g.FillRectangle(additionalBrush, _startPosX.Value + 60, _startPosY.Value + 45, 60, 5);
g.FillEllipse(additionalBrush, _startPosX.Value + 113, _startPosY.Value + 42, 20, 10);
}
if (EntitySelfPropelledArtilleryUnit.LaunchBattery)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 0, _startPosY.Value + 45, 20, 20);
g.FillPolygon(additionalBrush, new Point[]
{
new Point(_startPosX.Value + 0, _startPosY.Value + 15), new Point(_startPosX.Value + 0, _startPosY.Value + 65),
new Point(_startPosX.Value + 20, _startPosY.Value + 65), new Point(_startPosX.Value + 20, _startPosY.Value + 45),
new Point(_startPosX.Value + 0, _startPosY.Value + 15)
});
g.FillEllipse(additionalBrush, _startPosX.Value + 0, _startPosY.Value + 5, 10, 30);
g.FillRectangle(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 15, 20, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 25, 15, 5);
}
}
}
}

View File

@ -0,0 +1,57 @@
using SelfPropelledArtilleryUnit.Entities;
namespace SelfPropelledArtilleryUnit.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningSelfPropelledArtilleryUnit : DrawningPropelledArtillery
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="turretCannon">Признак наличия башни</param>
/// <param name="launchBattery">Признак наличия орудия</param>
public DrawningSelfPropelledArtilleryUnit(int speed, double weight, Color bodyColor, Color additionalColor, bool turretCannon, bool launchBattery) : base(135, 105)
{
EntityPropelledArtillery = new EntitySelfPropelledArtilleryUnit(speed, weight, bodyColor, additionalColor, turretCannon, launchBattery);
//дописать
}
public override void DrawTransport(Graphics g)
{
if (EntityPropelledArtillery == null || EntityPropelledArtillery is not EntitySelfPropelledArtilleryUnit selfpropelledartilleryunit || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush brush = new SolidBrush(selfpropelledartilleryunit.AdditionalColor);
base.DrawTransport(g);
if (selfpropelledartilleryunit.TurretCannon)
{
g.FillEllipse(brush, _startPosX.Value + 26, _startPosY.Value + 35, 50, 30);
g.FillRectangle(brush, _startPosX.Value + 25, _startPosY.Value + 36, 20, 29);
g.FillRectangle(brush, _startPosX.Value + 60, _startPosY.Value + 45, 60, 5);
g.FillEllipse(brush, _startPosX.Value + 113, _startPosY.Value + 42, 20, 10);
}
if (selfpropelledartilleryunit.LaunchBattery)
{
g.FillRectangle(brush, _startPosX.Value + 0, _startPosY.Value + 45, 20, 20);
g.FillPolygon(brush, new Point[]
{
new Point(_startPosX.Value + 0, _startPosY.Value + 15), new Point(_startPosX.Value + 0, _startPosY.Value + 65),
new Point(_startPosX.Value + 20, _startPosY.Value + 65), new Point(_startPosX.Value + 20, _startPosY.Value + 45),
new Point(_startPosX.Value + 0, _startPosY.Value + 15)
});
g.FillEllipse(brush, _startPosX.Value + 0, _startPosY.Value + 5, 10, 30);
g.FillRectangle(brush, _startPosX.Value + 10, _startPosY.Value + 15, 20, 5);
g.FillRectangle(brush, _startPosX.Value + 10, _startPosY.Value + 25, 15, 5);
}
}
}

View File

@ -0,0 +1,35 @@
namespace SelfPropelledArtilleryUnit.Entities;
/// <summary>
/// Класс-сущность "Бронированная машина"
/// </summary>
public class EntityPropelledArtillery
{
/// <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 EntityPropelledArtillery(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -0,0 +1,37 @@
namespace SelfPropelledArtilleryUnit.Entities;
/// <summary>
/// Класс-сущность "Самоходная арт. установка"
/// </summary>
public class EntitySelfPropelledArtilleryUnit : EntityPropelledArtillery
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак - Башня с орудием
/// </summary>
public bool TurretCannon { get; private set; }
/// <summary>
/// Признак - Залповая батарея сзади
/// </summary>
public bool LaunchBattery { get; private set; }
/// <summary>
/// Шаг перемещения артеллерийской установки
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса EntitySelfPropelledArtilleryUnit
/// </summary>
/// <param name="additionalcolor">Дополнительный цвет</param>
/// <param name="turretcannon">Башня с орудием</param>
/// <param name="launchbattery">Залповая батарея сзади</param>
public EntitySelfPropelledArtilleryUnit(int speed, double weight, Color bodycolor, Color additionalcolor, bool turretcannon, bool launchbattery) : base(speed, weight, bodycolor)
{
AdditionalColor = additionalcolor;
TurretCannon = turretcannon;
LaunchBattery = launchbattery;
}
}

View File

@ -1,61 +0,0 @@
namespace SelfPropelledArtilleryUnit;
/// <summary>
/// Класс-сущность "Самоходная арт. установка "
/// </summary>
public class EntitySelfPropelledArtilleryUnit
{
/// <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 TurretCannon { get; private set; }
/// <summary>
/// Признак - Залповая батарея сзади
/// </summary>
public bool LaunchBattery { 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="turretCannon">Башня с орудием</param>
/// <param name="launchBattery">Залповая батарея сзади</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool turretCannon, bool launchBattery)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
TurretCannon = turretCannon;
LaunchBattery = launchBattery;
}
}

View File

@ -1,39 +0,0 @@
namespace SelfPropelledArtilleryUnit
{
partial class FormSelfPropelledArtilleryUnit
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "FormSelfPropelledArtilleryUnit";
}
#endregion
}
}

View File

@ -1,20 +0,0 @@
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;
namespace SelfPropelledArtilleryUnit
{
public partial class FormSelfPropelledArtilleryUnit : Form
{
public FormSelfPropelledArtilleryUnit()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,139 @@
namespace SelfPropelledArtilleryUnit.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>
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,24 @@
namespace SelfPropelledArtilleryUnit.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
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,31 @@
namespace SelfPropelledArtilleryUnit.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
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 x = objParams.RightBorder;
if (x + GetStep() < FieldWidth) MoveRight();
int y = objParams.DownBorder;
if (y + GetStep() < FieldHeight) MoveDown();
}
}

View File

@ -0,0 +1,53 @@
namespace SelfPropelledArtilleryUnit.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
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,63 @@
using SelfPropelledArtilleryUnit.Drawnings;
namespace SelfPropelledArtilleryUnit.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningPropelledArtillery
/// </summary>
public class MoveablePropelledArtillery : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningPropelledArtillery или его наследника
/// </summary>
private readonly DrawningPropelledArtillery? _PropelledArtillery = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="PropelledArtillery">Объект класса DrawningPropelledArtillery</param>
public MoveablePropelledArtillery(DrawningPropelledArtillery PropelledArtillery)
{
_PropelledArtillery = PropelledArtillery;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_PropelledArtillery == null || _PropelledArtillery.EntityPropelledArtillery == null || !_PropelledArtillery.GetPosX.HasValue || !_PropelledArtillery.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_PropelledArtillery.GetPosX.Value, _PropelledArtillery.GetPosY.Value, _PropelledArtillery.GetWidth, _PropelledArtillery.GetHeight);
}
}
public int GetStep => (int)(_PropelledArtillery?.EntityPropelledArtillery?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_PropelledArtillery == null || _PropelledArtillery.EntityPropelledArtillery == null)
{
return false;
}
return _PropelledArtillery.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

@ -1,8 +1,8 @@
namespace SelfPropelledArtilleryUnit;
namespace SelfPropelledArtilleryUnit.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
public enum MovementDirection
{
/// <summary>
/// Вверх

View File

@ -0,0 +1,69 @@
namespace SelfPropelledArtilleryUnit.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,21 @@
namespace SelfPropelledArtilleryUnit.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@ -34,6 +34,9 @@
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
button1 = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSelfPropelledArtilleryUnit).BeginInit();
SuspendLayout();
//
@ -49,13 +52,13 @@
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 438);
buttonCreate.Location = new Point(12, 446);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 43);
buttonCreate.Size = new Size(226, 35);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.Text = "Создать самоходную арт. установку";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
buttonCreate.Click += buttonCreateSelfPropelledArtilleryUnit_Click;
//
// buttonLeft
//
@ -105,11 +108,46 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// button1
//
button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
button1.Location = new Point(253, 446);
button1.Name = "button1";
button1.Size = new Size(226, 35);
button1.TabIndex = 6;
button1.Text = "Создать бронированную машину";
button1.UseVisualStyleBackColor = true;
button1.Click += buttonCreatePropelledArtillery_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру ", "К краю" });
comboBoxStrategy.Location = new Point(784, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
comboBoxStrategy.SelectedIndexChanged += comboBoxStrategy_SelectedIndexChanged;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(829, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// SelfPropelledArtilleryUnit
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(923, 493);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(button1);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
@ -130,5 +168,8 @@
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private Button button1;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -7,45 +7,84 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.MovementStrategy;
namespace SelfPropelledArtilleryUnit
{
public partial class SelfPropelledArtilleryUnit : Form
{
private DrawningSelfPropelledArtilleryUnit? _drawningSelfPropelledArtilleryUnit;
private DrawningPropelledArtillery? _drawningPropelledArtillery;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public SelfPropelledArtilleryUnit()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
{
if (_drawningSelfPropelledArtilleryUnit == null)
if (_drawningPropelledArtillery == null)
{
return;
}
Bitmap bmp = new(pictureBoxSelfPropelledArtilleryUnit.Width, pictureBoxSelfPropelledArtilleryUnit.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningSelfPropelledArtilleryUnit.DrawTransport(gr);
_drawningPropelledArtillery.DrawTransport(gr);
pictureBoxSelfPropelledArtilleryUnit.Image = bmp;
}
private void buttonCreate_Click(object sender, EventArgs e)
private void CreateObject(string type)
{
Random random = new();
_drawningSelfPropelledArtilleryUnit = new DrawningSelfPropelledArtilleryUnit();
_drawningSelfPropelledArtilleryUnit.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)));
_drawningSelfPropelledArtilleryUnit.SetPictureSize(pictureBoxSelfPropelledArtilleryUnit.Width, pictureBoxSelfPropelledArtilleryUnit.Height);
_drawningSelfPropelledArtilleryUnit.SetPosition(random.Next(10, 100), random.Next(10, 100));
switch (type)
{
case nameof(DrawningPropelledArtillery):
_drawningPropelledArtillery = new DrawningPropelledArtillery(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(DrawningSelfPropelledArtilleryUnit):
_drawningPropelledArtillery = new DrawningSelfPropelledArtilleryUnit(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;
default:
return;
}
_drawningPropelledArtillery.SetPictureSize(pictureBoxSelfPropelledArtilleryUnit.Width, pictureBoxSelfPropelledArtilleryUnit.Height);
_drawningPropelledArtillery.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 buttonCreateSelfPropelledArtilleryUnit_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSelfPropelledArtilleryUnit));
/// <summary>
/// Обработка нажатия кнопки "Создать бронированную машину"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreatePropelledArtillery_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningPropelledArtillery));
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningSelfPropelledArtilleryUnit == null)
if (_drawningPropelledArtillery == null)
{
return;
}
@ -55,13 +94,13 @@ namespace SelfPropelledArtilleryUnit
switch (name)
{
case "buttonUp":
result = _drawningSelfPropelledArtilleryUnit.MoveTransport(DirectionType.Up); break;
result = _drawningPropelledArtillery.MoveTransport(DirectionType.Up); break;
case "buttonDown":
result = _drawningSelfPropelledArtilleryUnit.MoveTransport(DirectionType.Down); break;
result = _drawningPropelledArtillery.MoveTransport(DirectionType.Down); break;
case "buttonLeft":
result = _drawningSelfPropelledArtilleryUnit.MoveTransport(DirectionType.Left); break;
result = _drawningPropelledArtillery.MoveTransport(DirectionType.Left); break;
case "buttonRight":
result = _drawningSelfPropelledArtilleryUnit.MoveTransport(DirectionType.Right); break;
result = _drawningPropelledArtillery.MoveTransport(DirectionType.Right); break;
}
if (result)
@ -69,5 +108,53 @@ namespace SelfPropelledArtilleryUnit
Draw();
}
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningPropelledArtillery == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveablePropelledArtillery(_drawningPropelledArtillery), pictureBoxSelfPropelledArtilleryUnit.Width, pictureBoxSelfPropelledArtilleryUnit.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
private void comboBoxStrategy_SelectedIndexChanged(object sender, EventArgs e)
Review

Пустых методов быть не должно

Пустых методов быть не должно
{
}
}
}