lab2 commit

This commit is contained in:
zum 2024-03-04 18:15:31 +04:00
parent ef4e357f91
commit b9691cc763
17 changed files with 1040 additions and 397 deletions

View File

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

View File

@ -1,307 +0,0 @@
using System.DirectoryServices;
namespace ProjectStormTrooper;
public class DrawningStormTrooper
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityStormTrooper? EntityStormTrooper { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки штурмовика
/// </summary>
private int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки штурмовика
/// </summary>
private int? _startPosY;
/// <summary>
/// Ширина прорисовки штурмовика
/// </summary>
private readonly int _drawningStormTrooperWidth = 140;
/// <summary>
/// Высота прорисовки штурмовика
/// </summary>
private readonly int _drawningStormTrooperHeight =95;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rockets">Признак наличия ракет</param>
/// <param name="bombs">Признак наличия бомб</param>
public void Init(int speed, double weight, Color bodyColor, Color colorOfHead, Color additionalColor, bool bombs, bool rockets)
{
EntityStormTrooper = new EntityStormTrooper();
EntityStormTrooper.Init(speed, weight, bodyColor, colorOfHead, additionalColor, bombs,rockets);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта,
//если она была уже установлена
if (width <= _drawningStormTrooperWidth || height <= _drawningStormTrooperHeight) {
return false;
};
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningStormTrooperWidth > _pictureWidth)
{
_startPosX = _pictureWidth.Value - _drawningStormTrooperWidth;
}
if (_startPosY + _drawningStormTrooperHeight > _pictureHeight)
{
_startPosY = _pictureHeight.Value - _drawningStormTrooperHeight;
}
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
// TODO если при установке объекта в эти координаты, он будет
//"выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
_startPosX = x;
_startPosY = y;
if (_drawningStormTrooperHeight + y > _pictureHeight || y < 0)
{
_startPosY = 0;
}
if (_drawningStormTrooperWidth + x > _pictureWidth || x < 0)
{
_startPosX = 0;
}
return;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityStormTrooper == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityStormTrooper.Step > 0)
{
_startPosX -= (int)EntityStormTrooper.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityStormTrooper.Step > 0)
{
_startPosY -= (int)EntityStormTrooper.Step;
}
return true;
// вправо
case DirectionType.Right:
if(_startPosX.Value + EntityStormTrooper.Step + _drawningStormTrooperWidth < _pictureWidth)
{
_startPosX += (int)EntityStormTrooper.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityStormTrooper.Step + _drawningStormTrooperHeight < _pictureHeight)
{
_startPosY += (int)EntityStormTrooper.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntityStormTrooper == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityStormTrooper.AdditionalColor);
Brush mainBrush = new SolidBrush(EntityStormTrooper.BodyColor);
Brush headBrush = new SolidBrush(EntityStormTrooper.ColorOfHead);
// флюзеляж
Rectangle bodyOfFighter = new Rectangle(_startPosX.Value, _startPosY.Value+40, 120,20);
g.DrawRectangle(pen, bodyOfFighter);
g.FillRectangle(mainBrush, bodyOfFighter);
Point topOfNose = new Point(bodyOfFighter.Right, bodyOfFighter.Top);
Point bottomOfNose = new Point(bodyOfFighter.Right, bodyOfFighter.Bottom);
Point edgeOfNose = new Point(bodyOfFighter.Right+20, (bodyOfFighter.Top + bodyOfFighter.Bottom)/2);
Point[] nose = new Point[] { topOfNose, bottomOfNose, edgeOfNose };
g.DrawPolygon(pen, nose);
g.FillPolygon(headBrush, nose);
// крылья штурмовика
int middleOfBody = (bodyOfFighter.X + bodyOfFighter.Right)/2;
// верхнее крыло
Point topWingRightBottom = new Point(middleOfBody+30, bodyOfFighter.Top);
Point topWingRightTop = new Point(middleOfBody, bodyOfFighter.Top-40);
Point topWingLeftTop = new Point(middleOfBody - 10, bodyOfFighter.Top-40);
Point topWingLeftBottom = new Point(middleOfBody-10, bodyOfFighter.Top);
Point[] topWing = new Point[] { topWingRightBottom, topWingRightTop,topWingLeftTop, topWingLeftBottom };
g.DrawPolygon(pen, topWing);
g.FillPolygon(mainBrush, topWing);
//нижнее крыло
Point bottomWingRightTop = new Point(middleOfBody + 30, bodyOfFighter.Bottom);
Point bottomWingRightBottom = new Point(middleOfBody, bodyOfFighter.Bottom + 40);
Point bottomWingLeftBottom = new Point(middleOfBody - 10, bodyOfFighter.Bottom + 40);
Point bottomWingLeftTop = new Point(middleOfBody - 10, bodyOfFighter.Bottom);
Point[] bottomWing = new Point[] { bottomWingRightTop, bottomWingRightBottom, bottomWingLeftBottom, bottomWingLeftTop };
g.DrawPolygon(pen, bottomWing);
g.FillPolygon(mainBrush, bottomWing);
//задние стабилизаторы
//верхний
Point topStabRightBottom = new Point(bodyOfFighter.X + 30, bodyOfFighter.Top);
Point topStabRightTop = new Point(bodyOfFighter.X +10, bodyOfFighter.Top-20);
Point topStabLeftTop = new Point(bodyOfFighter.X, bodyOfFighter.Top - 20);
Point topStabLeftBottom = new Point(bodyOfFighter.X, bodyOfFighter.Top);
Point[] topStable = new Point[] { topStabRightBottom, topStabRightTop, topStabLeftTop, topStabLeftBottom };
g.DrawPolygon(pen, topStable);
g.FillPolygon(mainBrush, topStable);
//нижний
Point bottomStabRightBottom = new Point(bodyOfFighter.X + 30, bodyOfFighter.Bottom);
Point bottomStabRightTop = new Point(bodyOfFighter.X + 10, bodyOfFighter.Bottom + 20);
Point bottomStabLeftTop = new Point(bodyOfFighter.X, bodyOfFighter.Bottom + 20);
Point bottomStabLeftBottom = new Point(bodyOfFighter.X, bodyOfFighter.Bottom);
Point[] bottomStable = new Point[] { bottomStabRightBottom, bottomStabRightTop, bottomStabLeftTop, bottomStabLeftBottom };
g.DrawPolygon(pen, bottomStable);
g.FillPolygon(mainBrush, bottomStable);
// ракеты
if (EntityStormTrooper.Rockets)
{
//верхняя ракета
int middleOfWingX = (middleOfBody + 30 + middleOfBody) / 2;
int middleOfTopWingY = (2*bodyOfFighter.Top - 50) / 2;
Point topLeftTopRocket = new Point(middleOfWingX-1, middleOfTopWingY+3);
Point bottomLeftTopRocket = new Point(middleOfWingX+6, middleOfTopWingY+12);
Point edgeOfTopRocket = new Point(middleOfWingX+12, middleOfTopWingY+6);
Point[] headOfTopRocket = new Point[] { topLeftTopRocket, bottomLeftTopRocket,edgeOfTopRocket};
g.DrawPolygon(pen,headOfTopRocket);
g.FillPolygon(additionalBrush, headOfTopRocket);
//нижняя ракета
int middleOfBottomWingY = (bodyOfFighter.Top + bodyOfFighter.Top + 50) / 2;
Point topLeftBottomRocket = new Point(middleOfWingX+8, middleOfBottomWingY + 2);
Point bottomLeftBottomRocket = new Point(middleOfWingX+4, middleOfBottomWingY+12);
Point edgeOfBottomRocket = new Point(middleOfWingX + 16, middleOfBottomWingY + 6);
Point[] headOfBottomRocket = new Point[] { topLeftBottomRocket, bottomLeftBottomRocket, edgeOfBottomRocket};
g.DrawPolygon(pen, headOfBottomRocket);
g.FillPolygon (additionalBrush, headOfBottomRocket);
}
// бомбы
if (EntityStormTrooper.Bombs)
{
Rectangle topBombBody = new Rectangle(middleOfBody + 40, bodyOfFighter.Top-10, 10, 10);
Rectangle bottomBombBody = new Rectangle(middleOfBody + 40, bodyOfFighter.Bottom, 10, 10);
//голова верхней бомбы
Point topTopBomb = new Point(topBombBody.Right+1, topBombBody.Top);
Point bottomTopBomb = new Point(topBombBody.Right+1, topBombBody.Bottom);
Point edgeTopBomb = new Point(topBombBody.Right+10, (topBombBody.Top+ topBombBody.Bottom)/2);
Point[] headOfTopBomb = new Point[] {topTopBomb, bottomTopBomb,edgeTopBomb};
g.DrawPolygon(pen, headOfTopBomb);
g.FillPolygon(additionalBrush,headOfTopBomb);
Point topBottomBomb = new Point(bottomBombBody.Right + 1, bottomBombBody.Top);
Point bottomBottomBomb = new Point(bottomBombBody.Right + 1, bottomBombBody.Bottom);
Point edgeBottomBomb = new Point(bottomBombBody.Right + 10, (bottomBombBody.Top + bottomBombBody.Bottom) / 2);
Point[] headOfBottomBomb = new Point[] { topBottomBomb, bottomBottomBomb, edgeBottomBomb };
g.DrawPolygon (pen, headOfBottomBomb);
g.FillPolygon (additionalBrush, headOfBottomBomb);
g.DrawRectangle(pen, topBombBody);
g.DrawRectangle(pen, bottomBombBody);
g.FillRectangle(additionalBrush, topBombBody);
g.FillRectangle (additionalBrush, bottomBombBody);
}
}
}

View File

@ -0,0 +1,31 @@
namespace ProjectStormTrooper.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

@ -0,0 +1,102 @@
using System.DirectoryServices;
using ProjectStormTrooper.Drawnings;
using ProjectStormTrooper.Entities;
namespace ProjectStormTrooper.Drawnings;
public class DrawningStormTrooper : DrawningWarPlane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rockets">Признак наличия ракет</param>
/// <param name="bombs">Признак наличия бомб</param>
public DrawningStormTrooper(int speed, double weight, Color bodyColor, Color colorOfHead, Color additionalColor, bool bombs, bool rockets)
{
EntityWarPlane = new EntityStormTrooper(speed, weight, bodyColor, colorOfHead, additionalColor, bombs, rockets);
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityWarPlane == null || EntityWarPlane is not EntityStormTrooper stormTrooper|| !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(stormTrooper.AdditionalColor);
Brush mainBrush = new SolidBrush(EntityWarPlane.BodyColor);
Brush headBrush = new SolidBrush(EntityWarPlane.ColorOfHead);
Rectangle bodyOfFighter = new Rectangle(_startPosX.Value, _startPosY.Value + 40, 120, 20);
int middleOfBody = (bodyOfFighter.X + bodyOfFighter.Right) / 2;
base.DrawTransport(g);
// ракеты
if (stormTrooper.Rockets)
{
//верхняя ракета
int middleOfWingX = (2*middleOfBody + 30 ) /2;
int middleOfTopWingY = (2 * bodyOfFighter.Top - 50) / 2;
Point topLeftTopRocket = new Point(middleOfWingX - 1, middleOfTopWingY + 3);
Point bottomLeftTopRocket = new Point(middleOfWingX + 6, middleOfTopWingY + 12);
Point edgeOfTopRocket = new Point(middleOfWingX + 12, middleOfTopWingY + 6);
Point[] headOfTopRocket = new Point[] { topLeftTopRocket, bottomLeftTopRocket, edgeOfTopRocket };
g.DrawPolygon(pen, headOfTopRocket);
g.FillPolygon(additionalBrush, headOfTopRocket);
//нижняя ракета
int middleOfBottomWingY = (2*bodyOfFighter.Top + 50) / 2;
Point topLeftBottomRocket = new Point(middleOfWingX + 8, middleOfBottomWingY + 2);
Point bottomLeftBottomRocket = new Point(middleOfWingX + 4, middleOfBottomWingY + 12);
Point edgeOfBottomRocket = new Point(middleOfWingX + 16, middleOfBottomWingY + 6);
Point[] headOfBottomRocket = new Point[] { topLeftBottomRocket, bottomLeftBottomRocket, edgeOfBottomRocket };
g.DrawPolygon(pen, headOfBottomRocket);
g.FillPolygon(additionalBrush, headOfBottomRocket);
}
// бомбы
if (stormTrooper.Bombs)
{
Rectangle topBombBody = new Rectangle(middleOfBody + 40, bodyOfFighter.Top - 10, 10, 10);
Rectangle bottomBombBody = new Rectangle(middleOfBody + 40, bodyOfFighter.Bottom, 10, 10);
//голова верхней бомбы
Point topTopBomb = new Point(topBombBody.Right + 1, topBombBody.Top);
Point bottomTopBomb = new Point(topBombBody.Right + 1, topBombBody.Bottom);
Point edgeTopBomb = new Point(topBombBody.Right + 10, (topBombBody.Top + topBombBody.Bottom) / 2);
Point[] headOfTopBomb = new Point[] { topTopBomb, bottomTopBomb, edgeTopBomb };
g.DrawPolygon(pen, headOfTopBomb);
g.FillPolygon(additionalBrush, headOfTopBomb);
Point topBottomBomb = new Point(bottomBombBody.Right + 1, bottomBombBody.Top);
Point bottomBottomBomb = new Point(bottomBombBody.Right + 1, bottomBombBody.Bottom);
Point edgeBottomBomb = new Point(bottomBombBody.Right + 10, (bottomBombBody.Top + bottomBombBody.Bottom) / 2);
Point[] headOfBottomBomb = new Point[] { topBottomBomb, bottomBottomBomb, edgeBottomBomb };
g.DrawPolygon(pen, headOfBottomBomb);
g.FillPolygon(additionalBrush, headOfBottomBomb);
g.DrawRectangle(pen, topBombBody);
g.DrawRectangle(pen, bottomBombBody);
g.FillRectangle(additionalBrush, topBombBody);
g.FillRectangle(additionalBrush, bottomBombBody);
}
}
}

View File

@ -0,0 +1,264 @@
using ProjectStormTrooper.Entities;
using ProjectStormTrooper.Drawnings;
namespace ProjectStormTrooper.Drawnings
{
public class DrawningWarPlane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityWarPlane? EntityWarPlane { 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>
private readonly int _drawningWarPlaneWidth = 140;
/// <summary>
/// Высота прорисовки самолета
/// </summary>
private readonly int _drawningWarPlaneHeight = 95;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningWarPlaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningWarPlaneHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
public DrawningWarPlane()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
public DrawningWarPlane(int speed, double weight, Color bodyColor, Color colorOfHead)
{
EntityWarPlane = new EntityWarPlane(speed, weight, bodyColor, colorOfHead);
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта,
//если она была уже установлена
if (width <= _drawningWarPlaneWidth || height <= _drawningWarPlaneHeight)
{
return false;
};
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningWarPlaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth.Value - _drawningWarPlaneWidth;
}
if (_startPosY + _drawningWarPlaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight.Value - _drawningWarPlaneHeight;
}
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
// TODO если при установке объекта в эти координаты, он будет
//"выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
_startPosX = x;
_startPosY = y;
if (_drawningWarPlaneHeight + y > _pictureHeight || y < 0)
{
_startPosY = 0;
}
if (_drawningWarPlaneWidth + x > _pictureWidth || x < 0)
{
_startPosX = 0;
}
return;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityWarPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityWarPlane.Step > 0)
{
_startPosX -= (int)EntityWarPlane.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityWarPlane.Step > 0)
{
_startPosY -= (int)EntityWarPlane.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + EntityWarPlane.Step + _drawningWarPlaneWidth < _pictureWidth)
{
_startPosX += (int)EntityWarPlane.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityWarPlane.Step + _drawningWarPlaneHeight < _pictureHeight)
{
_startPosY += (int)EntityWarPlane.Step;
}
return true;
default:
return false;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityWarPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush mainBrush = new SolidBrush(EntityWarPlane.BodyColor);
Brush headBrush = new SolidBrush(EntityWarPlane.ColorOfHead);
// флюзеляж
Rectangle bodyOfFighter = new Rectangle(_startPosX.Value, _startPosY.Value + 40, 120, 20);
g.DrawRectangle(pen, bodyOfFighter);
g.FillRectangle(mainBrush, bodyOfFighter);
Point topOfNose = new Point(bodyOfFighter.Right, bodyOfFighter.Top);
Point bottomOfNose = new Point(bodyOfFighter.Right, bodyOfFighter.Bottom);
Point edgeOfNose = new Point(bodyOfFighter.Right + 20, (bodyOfFighter.Top + bodyOfFighter.Bottom) / 2);
Point[] nose = new Point[] { topOfNose, bottomOfNose, edgeOfNose };
g.DrawPolygon(pen, nose);
g.FillPolygon(headBrush, nose);
// крылья штурмовика
int middleOfBody = (bodyOfFighter.X + bodyOfFighter.Right) / 2;
// верхнее крыло
Point topWingRightBottom = new Point(middleOfBody + 30, bodyOfFighter.Top);
Point topWingRightTop = new Point(middleOfBody, bodyOfFighter.Top - 40);
Point topWingLeftTop = new Point(middleOfBody - 10, bodyOfFighter.Top - 40);
Point topWingLeftBottom = new Point(middleOfBody - 10, bodyOfFighter.Top);
Point[] topWing = new Point[] { topWingRightBottom, topWingRightTop, topWingLeftTop, topWingLeftBottom };
g.DrawPolygon(pen, topWing);
g.FillPolygon(mainBrush, topWing);
//нижнее крыло
Point bottomWingRightTop = new Point(middleOfBody + 30, bodyOfFighter.Bottom);
Point bottomWingRightBottom = new Point(middleOfBody, bodyOfFighter.Bottom + 40);
Point bottomWingLeftBottom = new Point(middleOfBody - 10, bodyOfFighter.Bottom + 40);
Point bottomWingLeftTop = new Point(middleOfBody - 10, bodyOfFighter.Bottom);
Point[] bottomWing = new Point[] { bottomWingRightTop, bottomWingRightBottom, bottomWingLeftBottom, bottomWingLeftTop };
g.DrawPolygon(pen, bottomWing);
g.FillPolygon(mainBrush, bottomWing);
//задние стабилизаторы
//верхний
Point topStabRightBottom = new Point(bodyOfFighter.X + 30, bodyOfFighter.Top);
Point topStabRightTop = new Point(bodyOfFighter.X + 10, bodyOfFighter.Top - 20);
Point topStabLeftTop = new Point(bodyOfFighter.X, bodyOfFighter.Top - 20);
Point topStabLeftBottom = new Point(bodyOfFighter.X, bodyOfFighter.Top);
Point[] topStable = new Point[] { topStabRightBottom, topStabRightTop, topStabLeftTop, topStabLeftBottom };
g.DrawPolygon(pen, topStable);
g.FillPolygon(mainBrush, topStable);
//нижний
Point bottomStabRightBottom = new Point(bodyOfFighter.X + 30, bodyOfFighter.Bottom);
Point bottomStabRightTop = new Point(bodyOfFighter.X + 10, bodyOfFighter.Bottom + 20);
Point bottomStabLeftTop = new Point(bodyOfFighter.X, bodyOfFighter.Bottom + 20);
Point bottomStabLeftBottom = new Point(bodyOfFighter.X, bodyOfFighter.Bottom);
Point[] bottomStable = new Point[] { bottomStabRightBottom, bottomStabRightTop, bottomStabLeftTop, bottomStabLeftBottom };
g.DrawPolygon(pen, bottomStable);
g.FillPolygon(mainBrush, bottomStable);
}
}
}

View File

@ -1,33 +1,15 @@
namespace ProjectStormTrooper;
namespace ProjectStormTrooper.Entities;
public class EntityStormTrooper
public class EntityStormTrooper : EntityWarPlane
{
/// <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 Color ColorOfHead { get; private set; }
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
@ -40,11 +22,8 @@ public class EntityStormTrooper
public bool Rockets { get; private set; }
/// <summary>
/// Шаг перемещения штурмовика
/// </summary>
public double Step => Speed * 200 / Weight;
/// <summary>
@ -57,15 +36,12 @@ public class EntityStormTrooper
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="rockets">Признак наличия ракет</param>
public void Init(int speed, double weight, Color bodyColor, Color colorOfHead, Color additionalColor, bool bombs, bool rockets)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
ColorOfHead = colorOfHead;
AdditionalColor = additionalColor;
Bombs = bombs;
Rockets = rockets;
public EntityStormTrooper(int speed, double weight, Color bodyColor, Color colorOfHead, Color additionalColor, bool bombs, bool rockets) : base(speed, weight, bodyColor, colorOfHead)
{
AdditionalColor = additionalColor;
Bombs = bombs;
Rockets = rockets;
}
}
}

View File

@ -0,0 +1,41 @@

namespace ProjectStormTrooper.Entities
{
public class EntityWarPlane
{
/// <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 ColorOfHead { get; private set; }
/// <summary>
/// Шаг перемещения штурмовика
/// </summary>
public double Step => Speed * 200 / Weight;
public EntityWarPlane(int speed, double weight, Color bodyColor, Color colorOfHead) {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
ColorOfHead = colorOfHead;
}
}
}

View File

@ -34,6 +34,9 @@
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttoтCreateWarPlane = new Button();
buttonStrategyStep = new Button();
comboBoxStrategy = new ComboBox();
((System.ComponentModel.ISupportInitialize)pictureBoxStormTrooper).BeginInit();
SuspendLayout();
//
@ -53,9 +56,9 @@
buttonCreateStormTrooper.Location = new Point(14, 493);
buttonCreateStormTrooper.Margin = new Padding(3, 4, 3, 4);
buttonCreateStormTrooper.Name = "buttonCreateStormTrooper";
buttonCreateStormTrooper.Size = new Size(86, 31);
buttonCreateStormTrooper.Size = new Size(168, 31);
buttonCreateStormTrooper.TabIndex = 1;
buttonCreateStormTrooper.Text = "Создать";
buttonCreateStormTrooper.Text = "Создать штурмовик";
buttonCreateStormTrooper.UseVisualStyleBackColor = true;
buttonCreateStormTrooper.Click += ButtonCreateStormTrooper_Click;
//
@ -111,11 +114,44 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttoтCreateWarPlane
//
buttoтCreateWarPlane.Location = new Point(205, 493);
buttoтCreateWarPlane.Name = "buttoтCreateWarPlane";
buttoтCreateWarPlane.Size = new Size(237, 31);
buttoтCreateWarPlane.TabIndex = 6;
buttoтCreateWarPlane.Text = "Создать военный самолет";
buttoтCreateWarPlane.UseVisualStyleBackColor = true;
buttoтCreateWarPlane.Click += ButtonCreateWarPlane;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(851, 63);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(87, 29);
buttonStrategyStep.TabIndex = 7;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(820, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(125, 28);
comboBoxStrategy.TabIndex = 8;
//
// FormStormTrooper
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(950, 540);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStrategyStep);
Controls.Add(buttoтCreateWarPlane);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
@ -137,5 +173,8 @@
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private Button buttoтCreateWarPlane;
private Button buttonStrategyStep;
private ComboBox comboBoxStrategy;
}
}

View File

@ -1,4 +1,8 @@
namespace ProjectStormTrooper;

using ProjectStormTrooper.Drawnings;
using ProjectStormTrooper.MovementStrategy;
namespace ProjectStormTrooper;
public partial class FormStormTrooper : Form
@ -7,7 +11,12 @@ public partial class FormStormTrooper : Form
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningStormTrooper? _drawningStormTrooper;
private DrawningWarPlane? _drawningWarPlane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Инициализация формы
/// </summary>
@ -16,6 +25,7 @@ public partial class FormStormTrooper : Form
public FormStormTrooper()
{
InitializeComponent();
_strategy = null;
}
@ -25,41 +35,53 @@ public partial class FormStormTrooper : Form
private void Draw()
{
if (_drawningStormTrooper == null)
if (_drawningWarPlane == null)
{
return;
}
Bitmap bmp = new(pictureBoxStormTrooper.Width, pictureBoxStormTrooper.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningStormTrooper.DrawTransport(gr);
_drawningWarPlane.DrawTransport(gr);
pictureBoxStormTrooper.Image = bmp;
}
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningWarPlane):
_drawningWarPlane = new DrawningWarPlane(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)));
break;
case nameof(DrawningStormTrooper):
_drawningWarPlane = new DrawningStormTrooper(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)),
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;
}
_drawningWarPlane.SetPictureSize(pictureBoxStormTrooper.Width, pictureBoxStormTrooper.Height);
_drawningWarPlane.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 ButtonCreateStormTrooper_Click(object sender, EventArgs e)
{
Random random = new();
_drawningStormTrooper = new DrawningStormTrooper();
_drawningStormTrooper.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)),
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)));
_drawningStormTrooper.SetPictureSize(pictureBoxStormTrooper.Width, pictureBoxStormTrooper.Height);
_drawningStormTrooper.SetPosition(random.Next(15,100), random.Next(10,120));
Draw();
}
private void ButtonCreateStormTrooper_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningStormTrooper));
private void ButtonCreateWarPlane(object sender, EventArgs e) => CreateObject(nameof(DrawningWarPlane));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
@ -68,7 +90,7 @@ public partial class FormStormTrooper : Form
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningStormTrooper == null)
if (_drawningWarPlane == null)
{
return;
}
@ -78,16 +100,16 @@ public partial class FormStormTrooper : Form
switch (name)
{
case "buttonUp":
result = _drawningStormTrooper.MoveTransport(DirectionType.Up);
result = _drawningWarPlane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningStormTrooper.MoveTransport(DirectionType.Down);
result = _drawningWarPlane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningStormTrooper.MoveTransport(DirectionType.Left);
result = _drawningWarPlane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningStormTrooper.MoveTransport(DirectionType.Right);
result = _drawningWarPlane.MoveTransport(DirectionType.Right);
break;
}
@ -96,4 +118,46 @@ public partial class FormStormTrooper : Form
Draw();
}
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningWarPlane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableCar(_drawningWarPlane), pictureBoxStormTrooper.Width, pictureBoxStormTrooper.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,139 @@
namespace ProjectStormTrooper.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,25 @@
namespace ProjectStormTrooper.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,54 @@

using System.Runtime.Remoting;
namespace ProjectStormTrooper.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.DownBorder + GetStep() >= FieldHeight && objParams.RightBorder + GetStep() >= FieldWidth;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,56 @@

namespace ProjectStormTrooper.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,65 @@

using ProjectStormTrooper.Drawnings;
namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningCar
/// </summary>
public class MoveableCar : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// </summary>
private readonly DrawningWarPlane? _warPlane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="warPlane">Объект класса DrawningWarPlane</param>
public MoveableCar(DrawningWarPlane warPlane)
{
_warPlane = warPlane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_warPlane == null || _warPlane.EntityWarPlane == null || !_warPlane.GetPosX.HasValue || !_warPlane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_warPlane.GetPosX.Value, _warPlane.GetPosY.Value, _warPlane.GetWidth, _warPlane.GetHeight);
}
}
public int GetStep => (int)(_warPlane?.EntityWarPlane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_warPlane == null || _warPlane.EntityWarPlane == null)
{
return false;
}
return _warPlane.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,27 @@
namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

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