Это победа! 2 лаба

This commit is contained in:
Ctepa 2024-02-26 14:20:56 +03:00
parent 064b7511c7
commit b8787908c3
17 changed files with 932 additions and 299 deletions

View File

@ -1,210 +0,0 @@
using ProjectSportCar;
namespace AntiAircraftGun;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта
/// </summary>
public class DrawningAntiAircraftGun
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAntiAircraftGun? EntityAntiAircraftGun { 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 _drawningGunWidth = 150;
/// <summary>
/// Высота прорисовки зенитной установки
/// </summary>
private readonly int _drawingGunHeight = 115;
/// <summary>
/// Иницилизация
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="optionalElementsColor"></param>
/// <param name="barrelLenth"></param>
/// <param name="hatchHeight"></param>
public void Init(int speed, double weight, Color bodyColor, Color optionalElementsColor, double barrelLenth, bool hatchHeight, bool radar)
{
EntityAntiAircraftGun = new EntityAntiAircraftGun();
EntityAntiAircraftGun.Init(speed, weight, bodyColor, optionalElementsColor, barrelLenth, hatchHeight, radar);
_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 (_drawningGunWidth > width || _drawingGunHeight > height) { return false; }
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX.Value + _drawningGunWidth > width)
{
_startPosX = width - _drawningGunWidth;
}
if (_startPosY.Value + _drawingGunHeight > height)
{
_startPosY = height - _drawingGunHeight;
}
}
_pictureHeight = height;
_pictureWidth = width;
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x + _drawningGunWidth > _pictureWidth.Value || x < 0)
{
Random random = new();
_startPosX = random.Next(0, _pictureWidth.Value - _drawningGunWidth);
}
else
{
_startPosX = x;
}
if (y + _drawingGunHeight > _drawingGunHeight)
{
Random rand = new();
_startPosY = rand.Next(0, _pictureHeight.Value - _drawingGunHeight);
}
else
{
_startPosY = y;
}
}
/// <summary>
/// Изменение напаравления перемещения
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityAntiAircraftGun == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityAntiAircraftGun.Step > 0)
{
_startPosX -= (int)EntityAntiAircraftGun.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityAntiAircraftGun.Step > 0)
{
_startPosY -= (int)EntityAntiAircraftGun.Step;
}
return true;
// вправо
case DirectionType.Right:
//TODO прописать логику сдвига в право
if (_startPosX.Value + EntityAntiAircraftGun.Step + _drawningGunWidth < _pictureWidth)
{
_startPosX += (int)EntityAntiAircraftGun.Step;
}
return true;
//вниз
case DirectionType.Down:
//TODO прописать логику сдвига в вниз
if (_startPosY.Value + EntityAntiAircraftGun.Step + _drawingGunHeight < _pictureHeight)
{
_startPosY += (int)EntityAntiAircraftGun.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntityAntiAircraftGun == null || !_startPosX.HasValue || !_startPosY.HasValue) return;
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityAntiAircraftGun.OptionalElementsColor);
Brush MainBrush = new SolidBrush(EntityAntiAircraftGun.BodyColor);
// Башня
g.FillRectangle(MainBrush, _startPosX.Value + 50, _startPosY.Value + 50, 60, 25);
g.FillRectangle(MainBrush, _startPosX.Value + 25, _startPosY.Value + 75, 110, 10);
// Гусеницы
g.DrawArc(pen, _startPosX.Value + 110, _startPosY.Value + 85, 40, 30, 270, 180);
g.DrawArc(pen, _startPosX.Value + 10, _startPosY.Value + 85, 40, 30, 90, 180);
g.DrawLine(pen, _startPosX.Value + 30, _startPosY.Value + 115, _startPosX.Value + 130, _startPosY.Value + 115);
// Катки большие
g.DrawEllipse(pen, _startPosX.Value + 13, _startPosY.Value + 93, 20, 20);
g.DrawEllipse(pen, _startPosX.Value + 126, _startPosY.Value + 93, 20, 20);
// Катки малые
g.DrawEllipse(pen, _startPosX.Value + 40, _startPosY.Value + 105, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 60, _startPosY.Value + 105, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 80, _startPosY.Value + 105, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 105, 10, 10);
// Орудие
Pen penWeapon = new Pen(Color.Black, 8);
g.DrawLine(penWeapon, _startPosX.Value + 100, _startPosY.Value + 70, _startPosX.Value + 150, _startPosY.Value + 10);
// Люк
if (EntityAntiAircraftGun.Hatch)
{
Random random = new();
g.FillRectangle(additionalBrush, _startPosX.Value + 85, _startPosY.Value + 45, 20, 5);
}
// Радар
if (EntityAntiAircraftGun.Radar)
{
Pen penRadar = new Pen(Color.Green, 3);
Brush brushRadar = new SolidBrush(Color.Black);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value + 50, _startPosX.Value + 65, _startPosY.Value + 25);
g.FillEllipse(brushRadar, _startPosX.Value + 35, _startPosY.Value, 60, 25);
g.DrawLine(penRadar, _startPosX.Value + 65, _startPosY.Value + 25, _startPosX.Value + 65, _startPosY.Value);
g.DrawLine(penRadar, _startPosX.Value + 35, _startPosY.Value + 13, _startPosX.Value + 95, _startPosY.Value + 13);
}
}
}

View File

@ -1,4 +1,4 @@
namespace ProjectSportCar;
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
@ -19,5 +19,9 @@ public enum DirectionType
/// <summary>
/// Вправо
/// </summary>
Right = 4
Right = 4,
/// <summary>
/// Неизвестно направление
/// </summary>
Unknow = -1
}

View File

@ -0,0 +1,53 @@
using AntiAircraftGun.Entities;
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта
/// </summary>
public class DrawningAntiAircraftGun:DrawningGun
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="optionalElementsColor"></param>
/// <param name="barrelLenth"></param>
/// <param name="hatchHeight"></param>
public DrawningAntiAircraftGun(int speed, double weight, Color bodyColor, Color optionalElementsColor, double barrelLenth, bool hatchHeight, bool radar) : base(150,115) //140, 65
{
EntityGun = new EntityAntiAircraftGun(speed,weight,bodyColor,optionalElementsColor,barrelLenth,hatchHeight,radar);
}
public override void DrawTransport(Graphics g)
{
_startPosX += 10;
_startPosY += 50;
base.DrawTransport(g);
_startPosX -= 10;
_startPosY -= 50;
if (EntityGun == null || !_startPosX.HasValue || !_startPosY.HasValue || EntityGun is not EntityAntiAircraftGun antiAircraftGun) return;
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(antiAircraftGun.OptionalElementsColor);
// Орудие
Pen penWeapon = new Pen(Color.Black, 8);
g.DrawLine(penWeapon, _startPosX.Value + 100, _startPosY.Value + 70, _startPosX.Value + 150, _startPosY.Value + 10);
// Люк
if (antiAircraftGun.Hatch)
{
Random random = new();
g.FillRectangle(additionalBrush, _startPosX.Value + 85, _startPosY.Value + 45, 20, 5);
}
// Радар
if (antiAircraftGun.Radar)
{
Pen penRadar = new Pen(Color.Green, 3);
Brush brushRadar = new SolidBrush(Color.Black);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value + 50, _startPosX.Value + 65, _startPosY.Value + 25);
g.FillEllipse(brushRadar, _startPosX.Value + 35, _startPosY.Value, 60, 25);
g.DrawLine(penRadar, _startPosX.Value + 65, _startPosY.Value + 25, _startPosX.Value + 65, _startPosY.Value);
g.DrawLine(penRadar, _startPosX.Value + 35, _startPosY.Value + 13, _startPosX.Value + 95, _startPosY.Value + 13);
}
}
}

View File

@ -0,0 +1,223 @@
using AntiAircraftGun.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Drawnings;
public class DrawningGun
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityGun? EntityGun { 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 _drawningGunWidth = 140;
/// <summary>
/// Высота прорисовки зенитной установки
/// </summary>
private readonly int _drawingGunHeight = 65;
/// <summary>
/// Координата Х объекта
/// </summary>
public int? GetPosX ()=> _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY() => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth() => _drawningGunWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight() => _drawingGunHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningGun()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Констурктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningGun(int speed, double weight, Color bodyColor):this()
{
EntityGun = new EntityGun(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningGunWidth">Ширина прорисовки ракетной установки</param>
/// <param name="drawningGunHeight">Высота прорисовки ракетной установки</param>
protected DrawningGun(int drawningGunWidth, int drawningGunHeight):this()
{
_drawingGunHeight = drawningGunHeight;
_drawningGunWidth = drawningGunWidth;
}
/// <summary>
/// Установка гранц поля
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (_drawningGunWidth > width || _drawingGunHeight > height) { return false; }
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX.Value + _drawningGunWidth > width)
{
_startPosX = width - _drawningGunWidth;
}
if (_startPosY.Value + _drawingGunHeight > height)
{
_startPosY = height - _drawingGunHeight;
}
}
_pictureHeight = height;
_pictureWidth = width;
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x + _drawningGunWidth > _pictureWidth.Value )
{
_startPosX = x - (x + _drawningGunWidth - _pictureWidth.Value);
}else if (x < 0)
{
_startPosX = 0;
}
else
{
_startPosX = x;
}
if (y + _drawingGunHeight > _pictureHeight.Value )
{
_startPosY = y - (y + _drawingGunHeight - _pictureHeight.Value);
}
else if (y < 0)
{
_startPosY = 0;
}
else
{
_startPosY = y;
}
}
/// <summary>
/// Изменение напаравления перемещения
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityGun == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityGun.Step > 0)
{
_startPosX -= (int)EntityGun.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityGun.Step > 0)
{
_startPosY -= (int)EntityGun.Step;
}
return true;
// вправо
case DirectionType.Right:
//TODO прописать логику сдвига в право
if (_startPosX.Value + EntityGun.Step + _drawningGunWidth < _pictureWidth)
{
_startPosX += (int)EntityGun.Step;
}
return true;
//вниз
case DirectionType.Down:
//TODO прописать логику сдвига в вниз
if (_startPosY.Value + EntityGun.Step + _drawingGunHeight < _pictureHeight)
{
_startPosY += (int)EntityGun.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityGun == null || !_startPosX.HasValue || !_startPosY.HasValue) return;
Pen pen = new(Color.Black);
Brush MainBrush = new SolidBrush(EntityGun.BodyColor);
// Башня
g.FillRectangle(MainBrush, _startPosX.Value + 50 - 10, _startPosY.Value + 50 - 50, 60, 25);
g.FillRectangle(MainBrush, _startPosX.Value + 25 - 10, _startPosY.Value + 75 - 50, 110, 10);
// Гусеницы
g.DrawArc(pen, _startPosX.Value + 110 - 10, _startPosY.Value + 85 - 50, 40, 30, 270, 180);
g.DrawArc(pen, _startPosX.Value + 10 - 10, _startPosY.Value + 85 - 50, 40, 30, 90, 180);
g.DrawLine(pen, _startPosX.Value + 30 - 10, _startPosY.Value + 115 - 50, _startPosX.Value + 130 - 10, _startPosY.Value + 115 - 50);
// Катки большие
g.DrawEllipse(pen, _startPosX.Value + 13 - 10, _startPosY.Value + 93 - 50, 20, 20);
g.DrawEllipse(pen, _startPosX.Value + 126 - 10, _startPosY.Value + 93 - 50, 20, 20);
// Катки малые
g.DrawEllipse(pen, _startPosX.Value + 40 - 10, _startPosY.Value + 105 - 50, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 60 - 10, _startPosY.Value + 105 - 50, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 80 - 10, _startPosY.Value + 105 - 50, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 100 - 10, _startPosY.Value + 105 - 50, 10, 10);
}
}

View File

@ -0,0 +1,30 @@
namespace AntiAircraftGun.Entities;
/// <summary>
/// Класс-сущность "Зенитная установка"
/// </summary>
public class EntityAntiAircraftGun:EntityGun
{
private EntityGun? EntityGun;
public Color OptionalElementsColor { get; private set; }
/// <summary>
/// Длинна ствола
/// </summary>
public double BarrelLength { get; private set; }
/// <summary>
/// Люк
/// </summary>
public bool Hatch { get; private set; }
/// <summary>
/// Радар
/// </summary>
public bool Radar { get; private set; }
public EntityAntiAircraftGun(int speed, double weight, Color bodyColor, Color optionalElementsColor, double barrelLenth, bool hatch, bool radar) : base(speed, weight, bodyColor)
{
EntityGun = new EntityGun(speed, weight, bodyColor);
OptionalElementsColor = optionalElementsColor;
BarrelLength = barrelLenth;
Radar = radar;
Hatch = hatch;
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace AntiAircraftGun.Entities;
/// <summary>
/// Класс-сущности "Орудие"
/// </summary>
public class EntityGun
{
/// <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 { get { return Speed * 100 / Weight; } private set { } }
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public EntityGun(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -1,59 +0,0 @@
namespace AntiAircraftGun;
/// <summary>
/// Класс-сущность "Зенитная установка"
/// </summary>
public class EntityAntiAircraftGun
{ /// <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 OptionalElementsColor { get; private set; }
/// <summary>
/// Длинна ствола
/// </summary>
public double BarrelLength { get; private set; }
/// <summary>
/// Люк
/// </summary>
public bool Hatch { get; private set; }
/// <summary>
/// Радар
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Шаг
/// </summary>
public double Step { get { return Speed * 100 / Weight; } private set { } }
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="optionalElementsColor"></param>
/// <param name="barrelLenth"></param>
/// <param name="hatch"></param>
/// <param name="radar"></param>
public void Init(int speed, double weight, Color bodyColor, Color optionalElementsColor, double barrelLenth, bool hatch,bool radar)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
OptionalElementsColor = optionalElementsColor;
BarrelLength = barrelLenth;
Hatch = hatch;
Radar = radar;
}
}

View File

@ -34,6 +34,9 @@
buttonLeft = new Button();
buttonUp = new Button();
buttonRight = new Button();
buttonCreateGun = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAntiAircraftGun).BeginInit();
SuspendLayout();
//
@ -43,7 +46,7 @@
pictureBoxAntiAircraftGun.Location = new Point(0, 0);
pictureBoxAntiAircraftGun.Name = "pictureBoxAntiAircraftGun";
pictureBoxAntiAircraftGun.Size = new Size(939, 393);
pictureBoxAntiAircraftGun.TabIndex = 6;
pictureBoxAntiAircraftGun.TabIndex = 8;
pictureBoxAntiAircraftGun.TabStop = false;
//
// buttonCreate
@ -51,9 +54,9 @@
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 352);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29);
buttonCreate.Size = new Size(261, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.Text = "Создать зенитную установку";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
@ -105,11 +108,46 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonCreateGun
//
buttonCreateGun.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateGun.Location = new Point(288, 352);
buttonCreateGun.Name = "buttonCreateGun";
buttonCreateGun.Size = new Size(203, 29);
buttonCreateGun.TabIndex = 7;
buttonCreateGun.Text = "Создать установку";
buttonCreateGun.UseVisualStyleBackColor = true;
buttonCreateGun.Click += buttonCreateGun_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(776, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 9;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonStrategyStep.Location = new Point(797, 65);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(130, 29);
buttonStrategyStep.TabIndex = 10;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormAntiAircraftGun
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(939, 393);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateGun);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
@ -130,5 +168,8 @@
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private Button buttonCreateGun;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,50 +1,90 @@
using ProjectSportCar;
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.MovementStrategy;
namespace AntiAircraftGun
{
public partial class FormAntiAircraftGun : Form
{
private DrawningAntiAircraftGun? _drawningAntiAircraftGun;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _abstractStrategy;
private DrawningGun? _drawningGun;
public FormAntiAircraftGun()
{
InitializeComponent();
_abstractStrategy = null;
}
/// <summary>
/// Метод рисования машины
/// </summary>
private void Draw()
{
if (_drawningAntiAircraftGun == null)
if (_drawningGun == null)
{
return;
}
Bitmap bmp = new(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningAntiAircraftGun.DrawTransport(gr);
_drawningGun.DrawTransport(gr);
pictureBoxAntiAircraftGun.Image = bmp;
_drawningAntiAircraftGun.DrawTransport(gr);
_drawningGun.DrawTransport(gr);
}
private void ButtonCreate_Click(object sender, EventArgs e)
private void CreateObj(string type)
{
Random random = new();
_drawningAntiAircraftGun = new DrawningAntiAircraftGun();
_drawningAntiAircraftGun.Init(
switch (type)
{
case nameof(DrawningGun):
_drawningGun = new DrawningGun(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(DrawningAntiAircraftGun):
_drawningGun = new DrawningAntiAircraftGun(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)),
random.Next(10, 100),
random.Next(10, 1000),
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)),
random.Next(10, 100),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningAntiAircraftGun.SetPictureSize(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
_drawningAntiAircraftGun.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)));
break;
}
_drawningGun.SetPictureSize(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
_drawningGun.SetPosition(random.Next(10, 100), random.Next(10, 100));
_abstractStrategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия "Создать зенитную установку"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
{
CreateObj(nameof(DrawningAntiAircraftGun));
}
/// <summary>
/// Обработка нажатия "Создать установку"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateGun_Click(object sender, EventArgs e)
{
CreateObj(nameof(DrawningGun));
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningAntiAircraftGun == null)
if (_drawningGun == null)
{
return;
}
@ -54,19 +94,19 @@ namespace AntiAircraftGun
{
case "buttonUp":
result =
_drawningAntiAircraftGun.MoveTransport(DirectionType.Up);
_drawningGun.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningAntiAircraftGun.MoveTransport(DirectionType.Down);
_drawningGun.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningAntiAircraftGun.MoveTransport(DirectionType.Left);
_drawningGun.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningAntiAircraftGun.MoveTransport(DirectionType.Right);
_drawningGun.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -75,5 +115,41 @@ namespace AntiAircraftGun
}
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningGun == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new MoveableGun(_drawningGun),
pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.MovementStrategy;
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,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.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,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objectParameters = GetObjectParameters();
if (objectParameters == null)
{
return false;
}
return objectParameters.RightBorder() <= FieldWidth && objectParameters.RightBorder() + GetStep() >= FieldWidth &&
objectParameters.DownBorder() <= FieldHeight && objectParameters.DownBorder() + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objectParameters=GetObjectParameters();
if(objectParameters == null) { return; }
if (objectParameters.RightBorder() < FieldWidth)
{
MoveRight();
}
if (objectParameters.DownBorder() <FieldHeight)
{
MoveDown();
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.MovementStrategy;
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,71 @@
using AntiAircraftGun.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с ипользованием DrawningGun
/// </summary>
public class MoveableGun : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningGun или его наследника
/// </summary>
private readonly DrawningGun? _drawningGun = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="drawningGun"></param>
public MoveableGun(DrawningGun? drawningGun)
{
_drawningGun = drawningGun;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningGun == null || _drawningGun.EntityGun == null ||
!_drawningGun.GetPosX().HasValue ||
!_drawningGun.GetPosY().HasValue)
{
return null;
}
return new ObjectParameters(
_drawningGun.GetPosX().Value,
_drawningGun.GetPosY().Value,
_drawningGun.GetWidth(),
_drawningGun.GetHeight());
}
}
public int GetStep => (int)(_drawningGun?.EntityGun?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_drawningGun == null || _drawningGun.EntityGun == null)
{
return false;
}
return _drawningGun.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns></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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.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,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.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"></param>
/// <param name="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 AntiAircraftGun.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполянется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}