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

This commit is contained in:
ikswi 2024-04-07 18:12:35 +04:00
parent 2ceb123bf2
commit 85ac980f74
16 changed files with 849 additions and 128 deletions

View File

@ -0,0 +1,116 @@
using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию военных самолётов
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 100;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 105;
/// <summary>
/// Ширина окна2
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция военных самолётов
/// </summary>
protected ICollectionGenericObjects<DrawningMilitaryAircraft>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция военных самолётов</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningMilitaryAircraft> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="militaryAircraft">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningMilitaryAircraft militaryAircraft)
{
return company._collection.Insert(militaryAircraft);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningMilitaryAircraft operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningMilitaryAircraft? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningMilitaryAircraft? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,64 @@
using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - ангар
/// </summary>
public class Angar : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public Angar(int picWidth, int picHeight, ICollectionGenericObjects<DrawningMilitaryAircraft> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 2);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth + 5, j * _placeSizeHeight, i * _placeSizeWidth + 5 + _placeSizeWidth - 30, j * _placeSizeHeight);
g.DrawLine(pen, i * _placeSizeWidth + 5, j * _placeSizeHeight, i * _placeSizeWidth + 5, j * _placeSizeHeight - _placeSizeHeight);
}
}
}
protected override void SetObjectsPosition()
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1;
int curHeight = height - 1;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
if (curWidth > 0)
curWidth--;
else
{
curWidth = width - 1;
curHeight--;
}
if (curHeight > height)
{
return;
}
}
}
}

View File

@ -0,0 +1,108 @@
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
{
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position >= _collection.Length || position < 0)
{ return null; }
return _collection[position];
}
public int Insert(T obj)
{
int index = 0;
while (index < _collection.Length)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index++;
}
return -1;
}
public int Insert(T obj, int position)
{
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
}
public T? Remove(int position)
{
if (position >= _collection.Length || position < 0)
{
return null;
}
T obj = _collection[position];
_collection[position] = null;
return obj;
}
}

View File

@ -5,7 +5,7 @@ namespace ProjectAirFighter.Drawnings;
/// <summary> /// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary> /// </summary>
public class DrawningAirFighter : DrawningFighter public class DrawningAirFighter : DrawningMilitaryAircraft
{ {
/// <summary> /// <summary>
@ -17,14 +17,14 @@ public class DrawningAirFighter : DrawningFighter
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="wings">Признак наличия доп крыльев</param> /// <param name="wings">Признак наличия доп крыльев</param>
/// <param name="rockets">Признак наличия ракет</param> /// <param name="rockets">Признак наличия ракет</param>
public DrawningAirFighter (int speed, double weight, Color bodyColor, Color additionalColor, bool wings, bool rockets) : base (70, 70) public DrawningAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool wings, bool rockets) : base(70, 70)
{ {
EntityFighter = new EntityAirFighter(speed, weight, bodyColor, additionalColor, wings, rockets); EntityMilitaryAircraft = new EntityAirFighter(speed, weight, bodyColor, additionalColor, wings, rockets);
} }
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
if (EntityFighter == null || EntityFighter is not EntityAirFighter airFighter || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityMilitaryAircraft == null || EntityMilitaryAircraft is not EntityAirFighter airFighter || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }

View File

@ -5,12 +5,12 @@ namespace ProjectAirFighter.Drawnings;
/// <summary> /// <summary>
/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности /// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
/// </summary> /// </summary>
public class DrawningFighter public class DrawningMilitaryAircraft
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityFighter? EntityFighter { get; protected set; } public EntityMilitaryAircraft? EntityMilitaryAircraft { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@ -28,19 +28,19 @@ public class DrawningFighter
protected int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя кооридната прорисовки самолёта /// Верхняя кооридната прорисовки военного самолёта
/// </summary> /// </summary>
protected int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки самолёта /// Ширина прорисовки военного самолёта
/// </summary> /// </summary>
private readonly int _drawningFighterWidth = 70; private readonly int _drawningMilitaryAircraftWidth = 70;
/// <summary> /// <summary>
/// Высота прорисовки самолёта /// Высота прорисовки военного самолёта
/// </summary> /// </summary>
private readonly int _drawningFighterHeight = 70; private readonly int _drawningMilitaryAircraftHeight = 70;
/// <summary> /// <summary>
/// Координата X объекта /// Координата X объекта
@ -55,17 +55,17 @@ public class DrawningFighter
/// <summary> /// <summary>
/// Ширина объекта /// Ширина объекта
/// </summary> /// </summary>
public int GetWidth => _drawningFighterWidth; public int GetWidth => _drawningMilitaryAircraftWidth;
/// <summary> /// <summary>
/// Высота объекта /// Высота объекта
/// </summary> /// </summary>
public int GetHeight => _drawningFighterHeight; public int GetHeight => _drawningMilitaryAircraftHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
/// </summary> /// </summary>
private DrawningFighter() private DrawningMilitaryAircraft()
{ {
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
@ -79,25 +79,25 @@ public class DrawningFighter
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param> /// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
public DrawningFighter (int speed, double weight, Color bodyColor) : this() public DrawningMilitaryAircraft(int speed, double weight, Color bodyColor) : this()
{ {
EntityFighter = new EntityFighter(speed, weight, bodyColor); EntityMilitaryAircraft = new EntityMilitaryAircraft(speed, weight, bodyColor);
} }
/// <summary> /// <summary>
/// Конструктор для наследников /// Конструктор для наследников
/// </summary> /// </summary>
/// <param name="drawningCarWidth">Ширина прорисовки самолёта</param> /// <param name="drawningCarWidth">Ширина прорисовки военного самолёта</param>
/// <param name="drawningCarHeight">Высота прорисовки самолёта</param> /// <param name="drawningCarHeight">Высота прорисовки военного самолёта</param>
protected DrawningFighter(int drawningFighterWidth, int drawningFighterHeight) : this() protected DrawningMilitaryAircraft(int drawningMilitaryAircraftWidth, int drawningMilitaryAircraftHeight) : this()
{ {
_drawningFighterWidth = drawningFighterWidth; _drawningMilitaryAircraftWidth = drawningMilitaryAircraftWidth;
_drawningFighterHeight = drawningFighterHeight; _drawningMilitaryAircraftHeight = drawningMilitaryAircraftHeight;
} }
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {
if (_drawningFighterWidth < width && _drawningFighterHeight < height) if (_drawningMilitaryAircraftWidth < width && _drawningMilitaryAircraftHeight < height)
{ {
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
@ -118,9 +118,9 @@ public class DrawningFighter
return; return;
} }
if (x + _drawningFighterWidth > _pictureWidth) if (x + _drawningMilitaryAircraftWidth > _pictureWidth)
{ {
_startPosX = _pictureWidth - _drawningFighterWidth; _startPosX = _pictureWidth - _drawningMilitaryAircraftWidth;
} }
else if (x < 0) else if (x < 0)
{ {
@ -130,9 +130,9 @@ public class DrawningFighter
{ {
_startPosX = x; _startPosX = x;
} }
if (y + _drawningFighterHeight > _pictureHeight) if (y + _drawningMilitaryAircraftHeight > _pictureHeight)
{ {
_startPosY = _pictureHeight - _drawningFighterHeight; _startPosY = _pictureHeight - _drawningMilitaryAircraftHeight;
} }
else if (y < 0) else if (y < 0)
{ {
@ -146,7 +146,7 @@ public class DrawningFighter
public bool MoveTransport(DirectionType direction) public bool MoveTransport(DirectionType direction)
{ {
if (EntityFighter == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityMilitaryAircraft == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return false; return false;
} }
@ -154,27 +154,27 @@ public class DrawningFighter
switch (direction) switch (direction)
{ {
case DirectionType.Left: case DirectionType.Left:
if (_startPosX.Value - EntityFighter.Step > 0) if (_startPosX.Value - EntityMilitaryAircraft.Step > 0)
{ {
_startPosX -= (int)EntityFighter.Step; _startPosX -= (int)EntityMilitaryAircraft.Step;
} }
return true; return true;
case DirectionType.Up: case DirectionType.Up:
if (_startPosY.Value - EntityFighter.Step > 0) if (_startPosY.Value - EntityMilitaryAircraft.Step > 0)
{ {
_startPosY -= (int)EntityFighter.Step; _startPosY -= (int)EntityMilitaryAircraft.Step;
} }
return true; return true;
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + _drawningFighterWidth + EntityFighter.Step < _pictureWidth) if (_startPosX.Value + _drawningMilitaryAircraftWidth + EntityMilitaryAircraft.Step < _pictureWidth)
{ {
_startPosX += (int)EntityFighter.Step; _startPosX += (int)EntityMilitaryAircraft.Step;
} }
return true; return true;
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + _drawningFighterHeight + EntityFighter.Step < _pictureHeight) if (_startPosY.Value + _drawningMilitaryAircraftHeight + EntityMilitaryAircraft.Step < _pictureHeight)
{ {
_startPosY += (int)EntityFighter.Step; _startPosY += (int)EntityMilitaryAircraft.Step;
} }
return true; return true;
default: default:
@ -184,13 +184,13 @@ public class DrawningFighter
public virtual void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntityFighter == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityMilitaryAircraft == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush br = new SolidBrush(EntityFighter.BodyColor); Brush br = new SolidBrush(EntityMilitaryAircraft.BodyColor);
g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value + 30, 60, 10); g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value + 30, 60, 10);
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 30, 60, 10); g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 30, 60, 10);

View File

@ -3,7 +3,7 @@
/// <summary> /// <summary>
/// Класс-сущность "Истребитель" /// Класс-сущность "Истребитель"
/// </summary> /// </summary>
public class EntityAirFighter : EntityFighter public class EntityAirFighter : EntityMilitaryAircraft
{ {
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
@ -11,7 +11,7 @@ public class EntityAirFighter : EntityFighter
public bool Rockets { get; private set; } public bool Rockets { get; private set; }
public EntityAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool wings, bool rockets) : base(5, 45, Color.Black) public EntityAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool wings, bool rockets) : base(speed, weight, bodyColor)
{ {
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Rockets = rockets; Rockets = rockets;

View File

@ -1,9 +1,9 @@
namespace ProjectAirFighter.Entities; namespace ProjectAirFighter.Entities;
/// <summary> /// <summary>
/// Класс-сущность "Истребитель" /// Класс-сущность "Военный самолёт"
/// </summary> /// </summary>
public class EntityFighter public class EntityMilitaryAircraft
{ {
public int Speed { get; private set; } public int Speed { get; private set; }
@ -20,7 +20,7 @@ public class EntityFighter
/// <param name="weight">Вес автомобиля</param> /// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
public EntityFighter (int speed, double weight, Color bodyColor) public EntityMilitaryAircraft(int speed, double weight, Color bodyColor)
{ {
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;

View File

@ -22,12 +22,10 @@
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxAirFighter = new PictureBox(); pictureBoxAirFighter = new PictureBox();
buttonCreateAirFighter = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonCreateFighter = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button(); buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirFighter).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAirFighter).BeginInit();
@ -42,17 +40,6 @@
pictureBoxAirFighter.TabIndex = 0; pictureBoxAirFighter.TabIndex = 0;
pictureBoxAirFighter.TabStop = false; pictureBoxAirFighter.TabStop = false;
// //
// buttonCreateAirFighter
//
buttonCreateAirFighter.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirFighter.Location = new Point(12, 409);
buttonCreateAirFighter.Name = "buttonCreateAirFighter";
buttonCreateAirFighter.Size = new Size(169, 29);
buttonCreateAirFighter.TabIndex = 1;
buttonCreateAirFighter.Text = "Создать истребитель";
buttonCreateAirFighter.UseVisualStyleBackColor = true;
buttonCreateAirFighter.Click += buttonCreateAirFighter_Click;
//
// buttonDown // buttonDown
// //
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
@ -101,17 +88,6 @@
buttonUp.UseVisualStyleBackColor = true; buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click; buttonUp.Click += ButtonMove_Click;
// //
// buttonCreateFighter
//
buttonCreateFighter.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateFighter.Location = new Point(196, 409);
buttonCreateFighter.Name = "buttonCreateFighter";
buttonCreateFighter.Size = new Size(169, 29);
buttonCreateFighter.TabIndex = 6;
buttonCreateFighter.Text = "Создать самолёт";
buttonCreateFighter.UseVisualStyleBackColor = true;
buttonCreateFighter.Click += buttonCreateAir_Click;
//
// comboBoxStrategy // comboBoxStrategy
// //
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
@ -139,12 +115,10 @@
ClientSize = new Size(800, 450); ClientSize = new Size(800, 450);
Controls.Add(buttonStrategyStep); Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateFighter);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonCreateAirFighter);
Controls.Add(pictureBoxAirFighter); Controls.Add(pictureBoxAirFighter);
Name = "FormAirFighter"; Name = "FormAirFighter";
Text = "Истребитель"; Text = "Истребитель";
@ -155,12 +129,10 @@
#endregion #endregion
private PictureBox pictureBoxAirFighter; private PictureBox pictureBoxAirFighter;
private Button buttonCreateAirFighter;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonCreateFighter;
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button buttonStrategyStep; private Button buttonStrategyStep;
} }

View File

@ -5,7 +5,7 @@ namespace ProjectAirFighter;
public partial class FormAirFighter : Form public partial class FormAirFighter : Form
{ {
private DrawningFighter? _drawningFighter; private DrawningMilitaryAircraft? _drawningMilitaryAircraft;
private AbstractStrategy? _strategy; private AbstractStrategy? _strategy;
@ -15,52 +15,34 @@ public partial class FormAirFighter : Form
_strategy = null; _strategy = null;
} }
public DrawningMilitaryAircraft SetAir
{
set
{
_drawningMilitaryAircraft = value;
_drawningMilitaryAircraft.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
private void Draw() private void Draw()
{ {
if (_drawningFighter == null) if (_drawningMilitaryAircraft == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height); Bitmap bmp = new(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningFighter.DrawTransport(gr); _drawningMilitaryAircraft.DrawTransport(gr);
pictureBoxAirFighter.Image = bmp; pictureBoxAirFighter.Image = bmp;
} }
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningFighter):
_drawningFighter = new DrawningFighter(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(DrawningAirFighter):
_drawningFighter = new DrawningAirFighter(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_drawningFighter.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
_drawningFighter.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
private void buttonCreateAirFighter_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirFighter));
private void buttonCreateAir_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningFighter));
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawningFighter == null) if (_drawningMilitaryAircraft == null)
{ {
return; return;
} }
@ -70,16 +52,16 @@ public partial class FormAirFighter : Form
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawningFighter.MoveTransport(DirectionType.Up); result = _drawningMilitaryAircraft.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawningFighter.MoveTransport(DirectionType.Down); result = _drawningMilitaryAircraft.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawningFighter.MoveTransport(DirectionType.Left); result = _drawningMilitaryAircraft.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = _drawningFighter.MoveTransport(DirectionType.Right); result = _drawningMilitaryAircraft.MoveTransport(DirectionType.Right);
break; break;
} }
@ -91,7 +73,7 @@ public partial class FormAirFighter : Form
private void ButtonStrategyStep_Click(object sender, EventArgs e) private void ButtonStrategyStep_Click(object sender, EventArgs e)
{ {
if (_drawningFighter == null) if (_drawningMilitaryAircraft == null)
{ {
return; return;
} }
@ -108,7 +90,7 @@ public partial class FormAirFighter : Form
{ {
return; return;
} }
_strategy.SetData(new MoveableAir(_drawningFighter), pictureBoxAirFighter.Width, pictureBoxAirFighter.Height); _strategy.SetData(new MoveableMilitaryAircraft(_drawningMilitaryAircraft), pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
} }
if (_strategy == null) if (_strategy == null)

View File

@ -0,0 +1,174 @@
namespace ProjectAirFighter
{
partial class FormMilitaryAircraftCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonRemoveMilitaryAircraft = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddAirFighter = new Button();
buttonAddMilitaryAircraft = new Button();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonRefresh);
groupBoxTools.Controls.Add(buttonGoToCheck);
groupBoxTools.Controls.Add(buttonRemoveMilitaryAircraft);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddAirFighter);
groupBoxTools.Controls.Add(buttonAddMilitaryAircraft);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(610, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(190, 450);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(9, 389);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(175, 49);
buttonRefresh.TabIndex = 7;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(9, 316);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(175, 49);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonRemoveMilitaryAircraft
//
buttonRemoveMilitaryAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMilitaryAircraft.Location = new Point(9, 234);
buttonRemoveMilitaryAircraft.Name = "buttonRemoveMilitaryAircraft";
buttonRemoveMilitaryAircraft.Size = new Size(175, 49);
buttonRemoveMilitaryAircraft.TabIndex = 5;
buttonRemoveMilitaryAircraft.Text = "Удаление военного самолёта";
buttonRemoveMilitaryAircraft.UseVisualStyleBackColor = true;
buttonRemoveMilitaryAircraft.Click += buttonRemoveMilitaryAircraft_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(9, 201);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(175, 27);
maskedTextBoxPosition.TabIndex = 4;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonAddAirFighter
//
buttonAddAirFighter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAirFighter.Location = new Point(9, 128);
buttonAddAirFighter.Name = "buttonAddAirFighter";
buttonAddAirFighter.Size = new Size(175, 49);
buttonAddAirFighter.TabIndex = 2;
buttonAddAirFighter.Text = "Добавление истребителя";
buttonAddAirFighter.UseVisualStyleBackColor = true;
buttonAddAirFighter.Click += buttonAddAirFighter_Click;
//
// buttonAddMilitaryAircraft
//
buttonAddMilitaryAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddMilitaryAircraft.Location = new Point(9, 73);
buttonAddMilitaryAircraft.Name = "buttonAddMilitaryAircraft";
buttonAddMilitaryAircraft.Size = new Size(175, 49);
buttonAddMilitaryAircraft.TabIndex = 1;
buttonAddMilitaryAircraft.Text = "Добавление военного самолёта";
buttonAddMilitaryAircraft.UseVisualStyleBackColor = true;
buttonAddMilitaryAircraft.Click += buttonAddMilitaryAircraft_Click;
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(9, 26);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(175, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(610, 450);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
// FormMilitaryAircraftCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormMilitaryAircraftCollection";
Text = "FormMilitaryAircraftCollection";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddAirFighter;
private Button buttonAddMilitaryAircraft;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Button buttonRemoveMilitaryAircraft;
}
}

View File

@ -0,0 +1,181 @@
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter;
public partial class FormMilitaryAircraftCollection : Form
{
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormMilitaryAircraftCollection()
{
InitializeComponent();
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Angar(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningMilitaryAircraft>());
break;
}
}
/// <summary>
/// Добавление самолёта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddMilitaryAircraft_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMilitaryAircraft));
/// <summary>
/// Добавление истребителя
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddAirFighter_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirFighter));
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningMilitaryAircraft drawningMilitaryAircraft;
switch (type)
{
case nameof(DrawningMilitaryAircraft):
drawningMilitaryAircraft = new DrawningMilitaryAircraft(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningAirFighter):
drawningMilitaryAircraft = new DrawningAirFighter(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningMilitaryAircraft != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemoveMilitaryAircraft_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningMilitaryAircraft? militaryAircraft = null;
int counter = 100;
while (militaryAircraft == null)
{
militaryAircraft = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (militaryAircraft == null)
{
return;
}
FormAirFighter form = new()
{
SetAir = militaryAircraft
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -10,8 +10,10 @@ public class MoveToBorder : AbstractStrategy
return false; return false;
} }
return objParams.RightBorder <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth && return objParams.RightBorder <= FieldWidth &&
objParams.DownBorder <= FieldHeight && objParams.DownBorder + GetStep() >= FieldHeight; objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
} }
protected override void MoveToTarget() protected override void MoveToTarget()

View File

@ -13,8 +13,10 @@ public class MoveToCenter : AbstractStrategy
return false; return false;
} }
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
} }
protected override void MoveToTarget() protected override void MoveToTarget()

View File

@ -3,46 +3,46 @@
namespace ProjectAirFighter.MovementStrategy; namespace ProjectAirFighter.MovementStrategy;
/// <summary> /// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningCar /// Класс-реализация IMoveableObject с использованием DrawningMilitaryAircraft
/// </summary> /// </summary>
public class MoveableAir : IMoveableObject public class MoveableMilitaryAircraft : IMoveableObject
{ {
/// <summary> /// <summary>
/// Поле-объект класса DrawningCar или его наследника /// Поле-объект класса DrawningMilitaryAircraft или его наследника
/// </summary> /// </summary>
private readonly DrawningFighter? _air = null; private readonly DrawningMilitaryAircraft? _militaryAircraft = null;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="car">Объект класса DrawningCar</param> /// <param name="militaryAircraft">Объект класса DrawningMilitaryAircraft</param>
public MoveableAir(DrawningFighter air) public MoveableMilitaryAircraft(DrawningMilitaryAircraft militaryAircraft)
{ {
_air = air; _militaryAircraft = militaryAircraft;
} }
public ObjectParameters? GetObjectPosition public ObjectParameters? GetObjectPosition
{ {
get get
{ {
if (_air == null || _air.EntityFighter == null || !_air.GetPosX.HasValue || !_air.GetPosY.HasValue) if (_militaryAircraft == null || _militaryAircraft.EntityMilitaryAircraft == null || !_militaryAircraft.GetPosX.HasValue || !_militaryAircraft.GetPosY.HasValue)
{ {
return null; return null;
} }
return new ObjectParameters(_air.GetPosX.Value, _air.GetPosY.Value, _air.GetWidth, _air.GetHeight); return new ObjectParameters(_militaryAircraft.GetPosX.Value, _militaryAircraft.GetPosY.Value, _militaryAircraft.GetWidth, _militaryAircraft.GetHeight);
} }
} }
public int GetStep => (int)(_air?.EntityFighter?.Step ?? 0); public int GetStep => (int)(_militaryAircraft?.EntityMilitaryAircraft?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction) public bool TryMoveObject(MovementDirection direction)
{ {
if (_air == null || _air.EntityFighter == null) if (_militaryAircraft == null || _militaryAircraft.EntityMilitaryAircraft == null)
{ {
return false; return false;
} }
return _air.MoveTransport(GetDirectionType(direction)); return _militaryAircraft.MoveTransport(GetDirectionType(direction));
} }
/// <summary> /// <summary>

View File

@ -11,7 +11,7 @@ namespace ProjectAirFighter
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormAirFighter()); Application.Run(new FormMilitaryAircraftCollection());
} }
} }
} }