Добавление стратегии

This commit is contained in:
Vladislave 2024-03-20 00:43:30 +03:00
parent 615fcfb69f
commit 3c230081c5
16 changed files with 907 additions and 262 deletions

View File

@ -1,211 +0,0 @@
using ProjectAirBomber;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber;
/// <summary>
///
/// </summary>
public class DrawingAirBomber
{
/// <summary>
/// класс-сущность
/// </summary>
public EntityAirBomber? EntityAirBomber { get; private set; }
/// <summary>
/// ширина окна
/// </summary>
private int? _pictureWight;
/// <summary>
/// высота окна
/// </summary>
private int? _pictureHight;
/// <summary>
/// левая координата прорисовки самолета
/// </summary>
private int? _startPosX;
/// <summary>
/// верхняя координата прорисовки самолета
/// </summary>
private int? _startPosY;
/// <summary>
/// ширина прорисовки самолета
/// </summary>
private readonly int _drawingPlaneWidth = 115;
/// <summary>
/// высота прорисовки самолета
/// </summary>
private readonly int _drawingPlaneHeight = 170;
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engine">наличие двигателя</param>
/// <param name="bomb">наличие двигателя</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool engine, bool bomb)
{
EntityAirBomber = new EntityAirBomber();
EntityAirBomber.Init(speed, weight, bodyColor, additionalColor, engine, bomb);
_pictureWight = null;
_pictureHight = null;
_startPosX = null;
_startPosY = null;
}
public bool SetPictureSize(int width, int height)
{
_pictureWight = width;
_pictureHight = height;
return true;
}
public void SetPosition(int x, int y)
{
if (!_pictureWight.HasValue || !_pictureHight.HasValue)
{
return;
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityAirBomber == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityAirBomber.Step > 0)
{
_startPosX -= (int)EntityAirBomber.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityAirBomber.Step > 0)
{
_startPosY -= (int)EntityAirBomber.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + _drawingPlaneWidth < _pictureWight)
_startPosX += (int)EntityAirBomber.Step;
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + _drawingPlaneHeight < _pictureHight)
_startPosY += (int)EntityAirBomber.Step;
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
///
public void DrawAirBomber(Graphics g)
{
if (EntityAirBomber == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
//главная часть
Brush br = new SolidBrush(EntityAirBomber.BodyColor);
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 50, 100, 30);
g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value + 50, 100, 30);
//носовая часть
Brush brBlack = new SolidBrush(Color.Black);
Point point1 = new Point(_startPosX.Value - 15, _startPosY.Value + 65);
Point point2 = new Point(_startPosX.Value + 10, _startPosY.Value + 80);
Point point3 = new Point(_startPosX.Value + 10, _startPosY.Value + 50);
Point[] curvePointsNos = { point1, point2, point3 };
g.DrawPolygon(pen, curvePointsNos);
g.FillPolygon(brBlack, curvePointsNos);
//верхнее левое крыло
Point point4 = new Point(_startPosX.Value + 60, _startPosY.Value);
Point point5 = new Point(_startPosX.Value + 60, _startPosY.Value + 50);
Point point6 = new Point(_startPosX.Value + 75, _startPosY.Value + 50);
Point point7 = new Point(_startPosX.Value + 65, _startPosY.Value);
Point[] Wings1 = { point4, point5, point6, point7 };
g.DrawPolygon(pen, Wings1);
g.FillPolygon(br, Wings1);
//нижнее левое крыло
Point point8 = new Point(_startPosX.Value + 60, _startPosY.Value + 140);
Point point9 = new Point(_startPosX.Value + 60, _startPosY.Value + 80);
Point point10 = new Point(_startPosX.Value + 75, _startPosY.Value + 80);
Point point11 = new Point(_startPosX.Value + 65, _startPosY.Value + 140);
Point[] Wings2 = { point8, point9, point10, point11 };
g.DrawPolygon(pen, Wings2);
g.FillPolygon(br, Wings2);
//нижнее правое крыло
Point point12 = new Point(_startPosX.Value + 110, _startPosY.Value + 100);
Point point13 = new Point(_startPosX.Value + 110, _startPosY.Value + 80);
Point point14 = new Point(_startPosX.Value + 95, _startPosY.Value + 80);
Point point15 = new Point(_startPosX.Value + 100, _startPosY.Value + 100);
Point[] Wings3 = { point12, point13, point14, point15 };
g.DrawPolygon(pen, Wings3);
g.FillPolygon(br, Wings3);
//верхнее правое крыло
Point point16 = new Point(_startPosX.Value + 110, _startPosY.Value + 30);
Point point17 = new Point(_startPosX.Value + 110, _startPosY.Value + 50);
Point point18 = new Point(_startPosX.Value + 95, _startPosY.Value + 50);
Point point19 = new Point(_startPosX.Value + 100, _startPosY.Value + 30);
Point[] Wings4 = { point16, point17, point18, point19 };
g.DrawPolygon(pen, Wings4);
g.FillPolygon(br, Wings4);
//наличие топливных баков
if (EntityAirBomber.Engine)
{
Brush brBrown = new SolidBrush(Color.Brown);
g.DrawRectangle(pen, _startPosX.Value + 75, _startPosY.Value + 45, 20, 5);
g.DrawRectangle(pen, _startPosX.Value + 75, _startPosY.Value + 80, 20, 5);
g.FillRectangle(brBrown, _startPosX.Value + 75, _startPosY.Value + 45, 20, 5);
g.FillRectangle(brBrown, _startPosX.Value + 75, _startPosY.Value + 80, 20, 5);
}
//наличие дополнительных бомб
if (EntityAirBomber.Bomb)
{
Brush brGreen = new SolidBrush(Color.Green);
g.DrawRectangle(pen, _startPosX.Value + 40, _startPosY.Value + 20, 20, 8);
g.DrawRectangle(pen, _startPosX.Value + 40, _startPosY.Value + 100, 20, 8);
g.FillRectangle(brGreen, _startPosX.Value + 40, _startPosY.Value + 20, 20, 8);
g.FillRectangle(brGreen, _startPosX.Value + 40, _startPosY.Value + 100, 20, 8);
}
}
}

View File

@ -1,5 +1,4 @@
 namespace ProjectAirBomber.Drawnings;
namespace ProjectAirBomber;
public enum DirectionType public enum DirectionType
{ {
@ -18,6 +17,8 @@ public enum DirectionType
/// <summary> /// <summary>
/// Вправо /// Вправо
/// </summary> /// </summary>
Right = 4 Right = 4,
Unknow = -1
} }

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using ProjectAirBomber.Entities;
namespace ProjectAirBomber.Drawnings;
public class DrawingAirBomber : DrawningPlane
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engine">Дополнительный цвет</param>
/// <param name="bomb">Дополнительный цвет</param>
public DrawingAirBomber(int speed, double weight, Color bodyColor, Color
additionalColor, bool engine, bool bomb) : base(100, 130)
{
EntityPlane = new EntityAirBomber(speed, weight, bodyColor, additionalColor,
engine, bomb);
}
public override void DrawPlane(Graphics g)
{
if (EntityPlane == null || EntityPlane is not EntityAirBomber airBomber || !_startPosX.HasValue || !_startPosY.HasValue)
return;
base.DrawPlane(g);
Pen pen = new(Color.Black);
//наличие топливных баков
if (airBomber.Engine)
{
Brush brBrown = new SolidBrush(Color.Brown);
g.DrawRectangle(pen, _startPosX.Value + 65, _startPosY.Value + 35, 20, 5);
g.DrawRectangle(pen, _startPosX.Value + 65, _startPosY.Value + 70, 20, 5);
g.FillRectangle(brBrown, _startPosX.Value + 65, _startPosY.Value + 35, 20, 5);
g.FillRectangle(brBrown, _startPosX.Value + 65, _startPosY.Value + 70, 20, 5);
}
//наличие дополнительных бомб
if (airBomber.Bomb)
{
Brush brGreen = new SolidBrush(Color.Green);
g.DrawRectangle(pen, _startPosX.Value + 30, _startPosY.Value + 10, 20, 8);
g.DrawRectangle(pen, _startPosX.Value + 30, _startPosY.Value + 90, 20, 8);
g.FillRectangle(brGreen, _startPosX.Value + 30, _startPosY.Value + 10, 20, 8);
g.FillRectangle(brGreen, _startPosX.Value + 30, _startPosY.Value + 90, 20, 8);
}
}
}

View File

@ -0,0 +1,230 @@
using ProjectAirBomber.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.Drawnings;
public class DrawningPlane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityPlane? EntityPlane { 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 _drawningPlaneWidth = 95;
/// <summary>
/// Высота прорисовки самолета
/// </summary>
private readonly int _drawningPlaneHeight = 130;
/// <summary>
/// Координата X
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningPlaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningPlaneHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningPlane()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningPlane(int speed, double weight, Color bodyColor) : this()
{
EntityPlane = new EntityPlane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследования
/// </summary>
/// <param name="drawningPlaneWidth">ширина самолета</param>
/// <param name="drawningPlaneHeight">высота самолета</param>
protected DrawningPlane(int drawningPlaneWidth, int drawningPlaneHeight) : this()
{
_drawningPlaneWidth = drawningPlaneWidth;
_drawningPlaneHeight = drawningPlaneHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя
public bool SetPictureSize(int width, int height)
{
if (_drawningPlaneWidth <= width && _drawningPlaneHeight <= height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningPlaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningPlaneWidth;
}
if (_startPosY + _drawningPlaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningPlaneHeight;
}
}
return true;
}
return false;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x < 0) x = 0;
else if (x + _drawningPlaneWidth > _pictureWidth) x = _pictureWidth.Value - _drawningPlaneWidth;
if (y < 0) y = 0;
else if (y + _drawningPlaneHeight > _pictureHeight) y = _pictureHeight.Value - _drawningPlaneHeight;
_startPosX = x;
_startPosY = y;
}
public bool MoveTransport(DirectionType direction)
{
if (EntityPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
return false;
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityPlane.Step > 0)
_startPosX -= (int)EntityPlane.Step;
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityPlane.Step > 0)
_startPosY -= (int)EntityPlane.Step;
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + _drawningPlaneWidth + EntityPlane.Step < _pictureWidth)
_startPosX += (int)EntityPlane.Step;
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + _drawningPlaneHeight + EntityPlane.Step < _pictureHeight)
_startPosY += (int)EntityPlane.Step;
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
///
public virtual void DrawPlane(Graphics g)
{
if (EntityPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
//главная часть
Brush br = new SolidBrush(EntityPlane.BodyColor);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 40, 100, 30);
g.FillRectangle(br, _startPosX.Value, _startPosY.Value + 40, 100, 30);
//носовая часть
Brush brBlack = new SolidBrush(Color.Black);
Point point1 = new Point(_startPosX.Value -25, _startPosY.Value + 55);
Point point2 = new Point(_startPosX.Value, _startPosY.Value + 70);
Point point3 = new Point(_startPosX.Value, _startPosY.Value + 40);
Point[] curvePointsNos = { point1, point2, point3 };
g.DrawPolygon(pen, curvePointsNos);
g.FillPolygon(brBlack, curvePointsNos);
//верхнее левое крыло
Point point4 = new Point(_startPosX.Value + 50, _startPosY.Value);
Point point5 = new Point(_startPosX.Value + 50, _startPosY.Value + 40);
Point point6 = new Point(_startPosX.Value + 65, _startPosY.Value + 40);
Point point7 = new Point(_startPosX.Value + 55, _startPosY.Value);
Point[] Wings1 = { point4, point5, point6, point7 };
g.DrawPolygon(pen, Wings1);
g.FillPolygon(br, Wings1);
//нижнее левое крыло
Point point8 = new Point(_startPosX.Value + 50, _startPosY.Value + 130);
Point point9 = new Point(_startPosX.Value + 50, _startPosY.Value + 70);
Point point10 = new Point(_startPosX.Value + 65, _startPosY.Value + 70);
Point point11 = new Point(_startPosX.Value + 55, _startPosY.Value + 130);
Point[] Wings2 = { point8, point9, point10, point11 };
g.DrawPolygon(pen, Wings2);
g.FillPolygon(br, Wings2);
//нижнее правое крыло
Point point12 = new Point(_startPosX.Value + 100, _startPosY.Value + 90);
Point point13 = new Point(_startPosX.Value + 100, _startPosY.Value + 70);
Point point14 = new Point(_startPosX.Value + 85, _startPosY.Value + 70);
Point point15 = new Point(_startPosX.Value + 90, _startPosY.Value + 90);
Point[] Wings3 = { point12, point13, point14, point15 };
g.DrawPolygon(pen, Wings3);
g.FillPolygon(br, Wings3);
//верхнее правое крыло
Point point16 = new Point(_startPosX.Value + 100, _startPosY.Value + 20);
Point point17 = new Point(_startPosX.Value + 100, _startPosY.Value + 40);
Point point18 = new Point(_startPosX.Value + 85, _startPosY.Value + 40);
Point point19 = new Point(_startPosX.Value + 90, _startPosY.Value + 20);
Point[] Wings4 = { point16, point17, point18, point19 };
g.DrawPolygon(pen, Wings4);
g.FillPolygon(br, Wings4);
}
}

View File

@ -1,18 +1,10 @@
namespace ProjectAirBomber; namespace ProjectAirBomber.Entities;
public class EntityAirBomber
/// <summary>
/// Класс сущность бомбардировщик
/// </summary>
public class EntityAirBomber : EntityPlane
{ {
/// <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>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
@ -27,27 +19,15 @@ public class EntityAirBomber
/// наличие бомб /// наличие бомб
/// </summary> /// </summary>
public bool Bomb { get; private set; } public bool Bomb { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary> /// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля /// Инициализация полей объекта-класса спортивного автомобиля
/// </summary> /// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engine">наличие двигателя</param> /// <param name="engine">наличие двигателя</param>
/// <param name="bomb">наличие двигателя</param> /// <param name="bomb">наличие двигателя</param>
/// ///
public void Init(int speed, double weight, Color bodyColor, Color public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool engine, bool bomb) : base (speed,weight,bodyColor)
additionalColor, bool engine, bool bomb)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Engine = engine; Engine = engine;
Bomb = bomb; Bomb = bomb;

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.Entities;
/// <summary>
/// Класс сущность самолет
/// </summary>
public class EntityPlane
{
/// <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 EntityPlane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -38,6 +38,9 @@ namespace ProjectAirBomber
buttonUp = new Button(); buttonUp = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreatePlane = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -55,9 +58,9 @@ namespace ProjectAirBomber
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(0, 655); buttonCreate.Location = new Point(0, 655);
buttonCreate.Name = "buttonCreate"; buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29); buttonCreate.Size = new Size(247, 29);
buttonCreate.TabIndex = 1; buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать"; buttonCreate.Text = "Создать бомбардировщик";
buttonCreate.UseVisualStyleBackColor = true; buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click; buttonCreate.Click += ButtonCreate_Click;
// //
@ -94,7 +97,7 @@ namespace ProjectAirBomber
buttonDown.Location = new Point(1452, 637); buttonDown.Location = new Point(1452, 637);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35); buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 4; buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click; buttonDown.Click += ButtonMove_Click;
// //
@ -110,11 +113,45 @@ namespace ProjectAirBomber
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreatePlane
//
buttonCreatePlane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreatePlane.Location = new Point(253, 655);
buttonCreatePlane.Name = "buttonCreatePlane";
buttonCreatePlane.Size = new Size(247, 29);
buttonCreatePlane.TabIndex = 6;
buttonCreatePlane.Text = "Создать самолет";
buttonCreatePlane.UseVisualStyleBackColor = true;
buttonCreatePlane.Click += ButtonCreatePlane_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(1392, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(1434, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// ProjectAirBomber // ProjectAirBomber
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1555, 684); ClientSize = new Size(1555, 684);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreatePlane);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp); Controls.Add(buttonUp);
@ -135,5 +172,8 @@ namespace ProjectAirBomber
private Button buttonUp; private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreatePlane;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,45 +1,92 @@
using ProjectAirBomber; using ProjectAirBomber.Drawnings;
using ProjectAirBomber.MovementStrategy;
using System.Windows.Forms; using System.Windows.Forms;
namespace ProjectAirBomber namespace ProjectAirBomber
{ {
public partial class ProjectAirBomber : Form public partial class ProjectAirBomber : Form
{ {
private DrawingAirBomber? _drawingAirBomber; /// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningPlane? _drawningPlane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public ProjectAirBomber() public ProjectAirBomber()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
private void Draw() private void Draw()
{ {
if (_drawingAirBomber == null) if (_drawningPlane == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height); Bitmap bmp = new(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawingAirBomber.DrawAirBomber(gr); _drawningPlane.DrawPlane(gr);
pictureBoxAirBomber.Image = bmp; pictureBoxAirBomber.Image = bmp;
} }
private void ButtonCreate_Click(object sender, EventArgs e) private void CreateObject(string type)
{ {
Random random = new(); Random rnd = new Random();
_drawingAirBomber = new DrawingAirBomber(); switch (type)
_drawingAirBomber.Init(random.Next(100, 300), random.Next(1000, 3000), {
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), case nameof(DrawningPlane):
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), _drawningPlane = new DrawningPlane(rnd.Next(100, 300), rnd.Next(1000, 3000),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_drawingAirBomber.SetPictureSize(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height); break;
_drawingAirBomber.SetPosition(random.Next(10, 100), random.Next(10, 100)); case nameof(DrawingAirBomber):
_drawningPlane = new DrawingAirBomber(rnd.Next(650, 700), rnd.Next(15760, 16130),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Convert.ToBoolean(rnd.Next(0, 2)),
Convert.ToBoolean(rnd.Next(0, 2)));
break;
default:
return;
}
_drawningPlane.SetPictureSize(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
_drawningPlane.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100));
_strategy = null;
Draw(); Draw();
} }
/// <summary>
/// Обработка нажатия кнопки "Создать автобус с гармошкой"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingAirBomber));
/// <summary>
/// Обработка нажатия кнопки "Создать автобус"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void ButtonCreatePlane_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningPlane));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawingAirBomber == null) if (_drawningPlane == null)
{ {
return; return;
} }
@ -49,16 +96,16 @@ namespace ProjectAirBomber
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawingAirBomber.MoveTransport(DirectionType.Up); result = _drawningPlane.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawingAirBomber.MoveTransport(DirectionType.Down); result = _drawningPlane.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawingAirBomber.MoveTransport(DirectionType.Left); result = _drawningPlane.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = _drawingAirBomber.MoveTransport(DirectionType.Right); result = _drawningPlane.MoveTransport(DirectionType.Right);
break; break;
} }
@ -67,5 +114,42 @@ namespace ProjectAirBomber
Draw(); Draw();
} }
} }
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
{
if (_drawningPlane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveablePlane(_drawningPlane),
pictureBoxAirBomber.Width, pictureBoxAirBomber.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,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public abstract class AbstractStategy
{
/// <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 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public class MoveToBorder : AbstractStategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight && objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
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 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public class MoveToCenter : AbstractStategy
{
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 ProjectAirBomber.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public class MoveablePlane : IMoveableObject
{
/// <summary>
/// Поле-объект класса Drawningplane или его наследника
/// </summary>
private readonly DrawningPlane? _plane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="plane">Объект класса Drawningplane</param>
public MoveablePlane(DrawningPlane plane)
{
_plane = plane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_plane == null || _plane.EntityPlane == null ||
!_plane.GetPosX.HasValue || !_plane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_plane.GetPosX.Value,
_plane.GetPosY.Value, _plane.GetWidth, _plane.GetHeight);
}
}
public int GetStep => (int)(_plane?.EntityPlane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_plane == null || _plane.EntityPlane == null)
{
return false;
}
return _plane.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,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public enum MovementDirection
{
Up = 1, Down = 2, Left = 3, Right = 4
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.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,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public enum StrategyStatus
{
///<summary>
///Всё готово к началу
///</summary>
NotInit,
///<summary>
///Выполняется
///</summary>
InProgress,
///<summary>
///Завершено
///</summary>
Finish
}