Compare commits

...

5 Commits

Author SHA1 Message Date
SAliulov
e982b77a38 Тест03 2024-04-20 21:45:37 +03:00
SAliulov
f2bfec6818 Компания 2024-04-20 21:12:03 +03:00
81fa7e8de7 LabWork03 2024-04-18 14:50:08 +04:00
SAliulov
6252645c1e Компания 2024-04-18 00:17:12 +03:00
SAliulov
f8fac0b875 Компания 2024-04-17 23:45:20 +03:00
16 changed files with 925 additions and 113 deletions

View File

@ -0,0 +1,116 @@
using ProjectAirBomber.Drawnings;
namespace ProjectAirBomber.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию самолетов
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 300;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 180;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция самолётов
/// </summary>
protected ICollectionGenericObjects<DrawningBomber>? _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<DrawningBomber> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="bomber">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningBomber bomber)
{
return company._collection.Insert(bomber);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningBomber? operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningBomber? 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)
{
DrawningBomber? 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,63 @@
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.Entities;
using System;
namespace ProjectAirBomber.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - Ангар самолёта
/// </summary>
public class BomberHungarService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public BomberHungarService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBomber> collection) : base(picWidth, picHeight, collection)
{
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
///
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black, 2);
for (int i = 0; i < _pictureWidth / _placeSizeWidth + 1; i++)
{
for(int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * j));
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
}
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.7f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
}
}
/// <summary>
/// Установка объекта в Ангар
/// </summary>
protected override void SetObjectsPosition()
{
int n = 0;
for (int i = _pictureWidth / _placeSizeWidth; i > 0; i--)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
DrawningBomber? drawningBomber = _collection?.Get(n);
n++;
if (drawningBomber != null)
{
drawningBomber.SetPictureSize(_pictureWidth, _pictureHeight);
drawningBomber.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
}
}
}

View File

@ -0,0 +1,50 @@
using ProjectAirBomber.Drawnings;
namespace ProjectAirBomber.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
}

View File

@ -0,0 +1,134 @@
using System.Runtime.Remoting;
using ProjectAirBomber.Drawnings;
namespace ProjectAirBomber.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 >= 0 && position < Count)
{
return _collection[position];
}
return null;
}
public int Insert(T obj)
{
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
return -1;
}
public int Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return -1;
}
// проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
if (_collection[position] != null)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
return position;
}
}
// вставка
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
if (_collection[position] == null) return null;
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
}

View File

@ -5,6 +5,9 @@
/// </summary> /// </summary>
public enum DirectionType public enum DirectionType
{ {
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1, Unknow = -1,
/// <summary> /// <summary>
/// Вверх /// Вверх

View File

@ -5,6 +5,7 @@ namespace ProjectAirBomber.Drawnings;
/// <summary> /// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary> /// </summary>
///
public class DrawningAirBomber : DrawningBomber public class DrawningAirBomber : DrawningBomber
{ {
@ -19,16 +20,12 @@ public class DrawningAirBomber : DrawningBomber
/// <param name="bombs">Признак наличия бомб</param> /// <param name="bombs">Признак наличия бомб</param>
//TO DO!!!
//TO DO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public DrawningAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool fuelTanks, bool bombs) : base(200, 160) public DrawningAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool fuelTanks, bool bombs) : base(200, 160)
{ {
EntityBomber = new EntityAirBomber(speed, weight, bodyColor, additionalColor, fuelTanks, bombs); EntityBomber = new EntityAirBomber(speed, weight, bodyColor, additionalColor, fuelTanks, bombs);
} }
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
if (EntityBomber == null || EntityBomber is not EntityAirBomber airBomber || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityBomber == null || EntityBomber is not EntityAirBomber airBomber || !_startPosX.HasValue || !_startPosY.HasValue)
@ -63,13 +60,10 @@ public class DrawningAirBomber : DrawningBomber
new Point(_startPosX.Value + 80, _startPosY.Value + 100) new Point(_startPosX.Value + 80, _startPosY.Value + 100)
}); });
} }
_startPosX += 10; _startPosX += 10;
_startPosY += 5; _startPosY += 5;
base.DrawTransport(g); base.DrawTransport(g);
_startPosX -= 10; _startPosX -= 10;
_startPosY -= 5; _startPosY -= 5;
} }
} }

View File

@ -30,7 +30,7 @@ public class EntityBomber
/// <param name="weight">Вес бомбардировщика</param> /// <param name="weight">Вес бомбардировщика</param>
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
/// ///
/// TO DO?!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// TO DO
public EntityBomber(int speed, double weight, Color bodyColor) public EntityBomber(int speed, double weight, Color bodyColor)
{ {
Speed = speed; Speed = speed;

View File

@ -33,43 +33,30 @@ namespace ProjectAirBomber
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxAirBomber = new PictureBox(); pictureBoxAirBomber = new PictureBox();
buttonCreateAirBomber = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreateCar = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button(); buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxElectroTrans // pictureBoxAirBomber
// //
pictureBoxAirBomber.Dock = DockStyle.Fill; pictureBoxAirBomber.Dock = DockStyle.Fill;
pictureBoxAirBomber.Location = new Point(0, 0); pictureBoxAirBomber.Location = new Point(0, 0);
pictureBoxAirBomber.Name = "pictureBoxElectroTrans"; pictureBoxAirBomber.Name = "pictureBoxAirBomber";
pictureBoxAirBomber.Size = new Size(923, 597); pictureBoxAirBomber.Size = new Size(920, 597);
pictureBoxAirBomber.TabIndex = 0; pictureBoxAirBomber.TabIndex = 0;
pictureBoxAirBomber.TabStop = false; pictureBoxAirBomber.TabStop = false;
// //
// buttonCreateElectroTrans
//
buttonCreateAirBomber.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirBomber.Location = new Point(12, 562);
buttonCreateAirBomber.Name = "buttonCreateAirBomber";
buttonCreateAirBomber.Size = new Size(223, 23);
buttonCreateAirBomber.TabIndex = 1;
buttonCreateAirBomber.Text = "Создать бомбардировщик";
buttonCreateAirBomber.UseVisualStyleBackColor = true;
buttonCreateAirBomber.Click += ButtonCreateAirBomber_Click;
//
// buttonLeft // buttonLeft
// //
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft; buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(787, 550); buttonLeft.Location = new Point(784, 550);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35); buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2; buttonLeft.TabIndex = 2;
@ -81,7 +68,7 @@ namespace ProjectAirBomber
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp; buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch; buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(828, 509); buttonUp.Location = new Point(825, 509);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35); buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 3; buttonUp.TabIndex = 3;
@ -93,7 +80,7 @@ namespace ProjectAirBomber
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown; buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch; buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(828, 550); buttonDown.Location = new Point(825, 550);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35); buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 4; buttonDown.TabIndex = 4;
@ -105,24 +92,13 @@ namespace ProjectAirBomber
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight; buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch; buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(869, 550); buttonRight.Location = new Point(866, 550);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35); buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 5; buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreateCar
//
buttonCreateCar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateCar.Location = new Point(250, 562);
buttonCreateCar.Name = "buttonCreateTrans";
buttonCreateCar.Size = new Size(223, 23);
buttonCreateCar.TabIndex = 6;
buttonCreateCar.Text = "Создать военный самолет";
buttonCreateCar.UseVisualStyleBackColor = true;
buttonCreateCar.Click += ButtonCreateBomber_Click;
//
// comboBoxStrategy // comboBoxStrategy
// //
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
@ -143,21 +119,19 @@ namespace ProjectAirBomber
buttonStrategyStep.UseVisualStyleBackColor = true; buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click; buttonStrategyStep.Click += ButtonStrategyStep_Click;
// //
// FormElectroTrans // FormAirBomber
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(923, 597); ClientSize = new Size(920, 597);
Controls.Add(buttonStrategyStep); Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateCar);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreateAirBomber);
Controls.Add(pictureBoxAirBomber); Controls.Add(pictureBoxAirBomber);
Name = "FormElectroTrans"; Name = "FormAirBomber";
Text = "Электропоезд"; Text = "Электропоезд";
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).EndInit();
ResumeLayout(false); ResumeLayout(false);
@ -166,12 +140,10 @@ namespace ProjectAirBomber
#endregion #endregion
private PictureBox pictureBoxAirBomber; private PictureBox pictureBoxAirBomber;
private Button buttonCreateAirBomber;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreateCar;
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button buttonStrategyStep; private Button buttonStrategyStep;
} }

View File

@ -2,19 +2,39 @@
using ProjectAirBomber.MovementStrategy; using ProjectAirBomber.MovementStrategy;
namespace ProjectAirBomber; namespace ProjectAirBomber;
/// <summary>
/// Форма работы с объектом "Бомбардировщик"
/// </summary>
public partial class FormAirBomber : Form public partial class FormAirBomber : Form
{ {
/// <summary> /// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà /// Поле-объект для прорисовки объекта
/// </summary> /// </summary>
private DrawningBomber? _drawingBomber; private DrawningBomber? _drawningBomber;
/// <summary> /// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ /// Стратегия перемещения
/// </summary> /// </summary>
private AbstractStrategy? _strategy; private AbstractStrategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawningBomber SetBomber
{
set
{
_drawningBomber = value;
_drawningBomber.SetPictureSize(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// Конструктор формы
/// </summary>
public FormAirBomber() public FormAirBomber()
{ {
InitializeComponent(); InitializeComponent();
@ -22,66 +42,29 @@ public partial class FormAirBomber : Form
} }
/// <summary> /// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû /// Метод прорисовки бомбардировщика
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawingBomber == null) if (_drawningBomber == 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);
_drawingBomber.DrawTransport(gr); _drawningBomber.DrawTransport(gr);
pictureBoxAirBomber.Image = bmp; pictureBoxAirBomber.Image = bmp;
} }
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningBomber):
_drawingBomber = new DrawningBomber(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(DrawningAirBomber):
_drawingBomber = new DrawningAirBomber(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;
}
_drawingBomber.SetPictureSize(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
_drawingBomber.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü ñïîðòèâíûé àâòîìîáèëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateAirBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirBomber));
/// <summary> /// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîìîáèëü" /// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBomber));
/// <summary>
/// Ïåðåìåùåíèå îáúåêòà ïî ôîðìå (íàæàòèå êíîïîê íàâèãàöèè)
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawingBomber == null) if (_drawningBomber == null)
{ {
return; return;
} }
@ -91,16 +74,16 @@ public partial class FormAirBomber : Form
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawingBomber.MoveTransport(DirectionType.Up); result = _drawningBomber.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawingBomber.MoveTransport(DirectionType.Down); result = _drawningBomber.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawingBomber.MoveTransport(DirectionType.Left); result = _drawningBomber.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = _drawingBomber.MoveTransport(DirectionType.Right); result = _drawningBomber.MoveTransport(DirectionType.Right);
break; break;
} }
@ -110,13 +93,13 @@ public partial class FormAirBomber : Form
} }
} }
/// <summary> /// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã" /// Обработка нажатия кнопки "Шаг"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e) private void ButtonStrategyStep_Click(object sender, EventArgs e)
{ {
if (_drawingBomber == null) if (_drawningBomber == null)
{ {
return; return;
} }
@ -133,7 +116,7 @@ public partial class FormAirBomber : Form
{ {
return; return;
} }
_strategy.SetData(new MoveableTrans(_drawingBomber), pictureBoxAirBomber.Width, pictureBoxAirBomber.Height); _strategy.SetData(new MoveableBomber(_drawningBomber), pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
} }
if (_strategy == null) if (_strategy == null)

View File

@ -0,0 +1,173 @@
namespace ProjectAirBomber
{
partial class FormBomberCollection
{
/// <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();
buttonRemoveBomber = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddAirBomber = new Button();
buttonAddBomber = 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(buttonRemoveBomber);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddAirBomber);
groupBoxTools.Controls.Add(buttonAddBomber);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1136, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(268, 835);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(20, 567);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(236, 42);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(20, 314);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(236, 42);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRemoveBomber
//
buttonRemoveBomber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveBomber.Location = new Point(20, 255);
buttonRemoveBomber.Name = "buttonRemoveBomber";
buttonRemoveBomber.Size = new Size(236, 42);
buttonRemoveBomber.TabIndex = 4;
buttonRemoveBomber.Text = "Удалить военный самолёт";
buttonRemoveBomber.UseVisualStyleBackColor = true;
buttonRemoveBomber.Click += ButtonRemoveBomber_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(20, 210);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(236, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonAddAirBomber
//
buttonAddAirBomber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAirBomber.Location = new Point(20, 149);
buttonAddAirBomber.Name = "buttonAddAirBomber";
buttonAddAirBomber.Size = new Size(236, 42);
buttonAddAirBomber.TabIndex = 2;
buttonAddAirBomber.Text = "Добавление бомбардировщика";
buttonAddAirBomber.UseVisualStyleBackColor = true;
buttonAddAirBomber.Click += ButtonAddAirBomber_Click;
//
// buttonAddBomber
//
buttonAddBomber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBomber.Location = new Point(20, 91);
buttonAddBomber.Name = "buttonAddBomber";
buttonAddBomber.Size = new Size(236, 42);
buttonAddBomber.TabIndex = 1;
buttonAddBomber.Text = "Добавление военного самолёта";
buttonAddBomber.UseVisualStyleBackColor = true;
buttonAddBomber.Click += ButtonAddBomber_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(20, 22);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(236, 23);
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(1136, 835);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// FormBomberCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1404, 835);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormBomberCollection";
Text = "Коллекция самолетов";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddAirBomber;
private Button buttonAddBomber;
private PictureBox pictureBox;
private Button buttonGoToCheck;
private Button buttonRemoveBomber;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,199 @@
using ProjectAirBomber.CollectionGenericObjects;
using ProjectAirBomber.Drawnings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectAirBomber;
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormBomberCollection : Form
{
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormBomberCollection()
{
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 BomberHungarService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningBomber>());
break;
}
}
/// <summary>
/// Добавление обычного военного самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningBomber));
/// <summary>
/// Добавление бомбардировщика
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAirBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirBomber));
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningBomber drawningBomber;
switch (type)
{
case nameof(DrawningBomber):
drawningBomber = new DrawningBomber(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningAirBomber):
// вызов диалогового окна для выбора цвета
drawningBomber = new DrawningAirBomber(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 + drawningBomber != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
_ = MessageBox.Show(drawningBomber.ToString());
}
}
/// <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 ButtonRemoveBomber_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;
}
DrawningBomber? bomber = null;
int counter = 100;
while (bomber == null)
{
bomber = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (bomber == null)
{
return;
}
FormAirBomber form = new()
{
SetBomber = bomber
};
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

@ -1,7 +1,9 @@
using ProjectAirBomber.MovementStrategy; using ProjectAirBomber.MovementStrategy;
namespace ProjectAirBomber.MovementStrategy; namespace ProjectAirBomber.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в край экрана
/// </summary>
public class MoveToBorder : AbstractStrategy public class MoveToBorder : AbstractStrategy
{ {
protected override bool IsTargetDestinaion() protected override bool IsTargetDestinaion()
@ -17,6 +19,7 @@ public class MoveToBorder : AbstractStrategy
&& objParams.ObjectMiddleVertical + GetStep() >= FieldHeight; && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
} }
protected override void MoveToTarget() protected override void MoveToTarget()
{ {
ObjectParameters? objParams = GetObjectParameters; ObjectParameters? objParams = GetObjectParameters;

View File

@ -1,6 +1,10 @@
 
namespace ProjectAirBomber.MovementStrategy; namespace ProjectAirBomber.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy public class MoveToCenter : AbstractStrategy
{ {
protected override bool IsTargetDestinaion() protected override bool IsTargetDestinaion()

View File

@ -1,18 +1,18 @@
using ProjectAirBomber.Drawnings; using ProjectAirBomber.Drawnings;
namespace ProjectAirBomber.MovementStrategy; namespace ProjectAirBomber.MovementStrategy;
public class MoveableTrans : IMoveableObject
public class MoveableBomber : IMoveableObject
{ {
/// <summary> /// <summary>
/// Поле-объект класса DrawningTrans или его наследника /// Поле-объект класса DrawningBomber или его наследника
/// </summary> /// </summary>
private readonly DrawningBomber? _bomber = null; private readonly DrawningBomber? _bomber = null;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="bomber">Объект класса DrawningTrans</param> /// <param name="bomber">Объект класса DrawningTrans</param>
public MoveableTrans(DrawningBomber bomber) public MoveableBomber(DrawningBomber bomber)
{ {
_bomber = bomber; _bomber = bomber;
} }
@ -55,6 +55,4 @@ public class MoveableTrans : IMoveableObject
_ => DirectionType.Unknow, _ => DirectionType.Unknow,
}; };
} }
} }

View File

@ -11,7 +11,7 @@ namespace ProjectAirBomber
// 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 FormAirBomber()); Application.Run(new FormBomberCollection());
} }
} }
} }