Compare commits

...

58 Commits

Author SHA1 Message Date
405fef33f9 Добавил warn логи на удаление пустого и переполнение 2023-12-05 12:12:19 +04:00
9bb3eb73a4 Фикс бага с удалением 2023-11-20 21:55:50 +04:00
494077af6a Какие-то изменения в файле проекта 2023-11-20 21:55:50 +04:00
5ed9877049 Переделал на Serilog 2023-11-20 21:55:50 +04:00
911543fd43 Добавлено логирование необходимых действий пользователя 2023-11-20 21:55:50 +04:00
6d3098d62b Добавлены логи уровня Warning 2023-11-20 21:55:50 +04:00
1b8f4113de Работает логирование 2023-11-20 21:55:50 +04:00
bbdd588a3d Фикс бага с удалением объекта 2023-11-20 21:55:50 +04:00
aa3ed0da58 Реализована обработка исключений в классе FormPlaneCollection 2023-11-20 21:55:50 +04:00
a99490c6df Выброс исключений при сохранении и загрузке данных 2023-11-20 21:55:50 +04:00
c6e16a8fc1 Добавлены выбросы исключений в методах добавления и удаления объектов 2023-11-20 21:55:49 +04:00
163355d57d Добавлены классы исключений 2023-11-20 21:55:49 +04:00
37aee9ad6a Фикс бага с цветами 2023-11-20 21:37:49 +04:00
b46a5f46b0 Переписал загрузку на StreamReader 2023-11-20 18:45:39 +04:00
ca9860ba86 Переписал сохранение на StreamWriter 2023-11-20 18:36:37 +04:00
262ac5cd8c Работает сохранение и загрузка 2023-11-20 18:23:43 +04:00
c9f8764af0 Добавлены методы сохранения и загрузки информации из файла 2023-11-20 17:53:29 +04:00
87c5a98333 Добавлен класс расширение ExtensionDrawingPlane 2023-11-20 17:36:21 +04:00
cd74aa1932 Фиксы по лабе и требованиям 2023-11-06 14:44:39 +04:00
5a616231fd Изменена логика добавления обхекта в классе FormPlaneCollection 2023-11-06 13:36:28 +04:00
0b208db4dd Добавлена форма FormPlaneConfig и реализована его логика 2023-11-06 13:31:26 +04:00
51a27f8e12 Доработана форма 2023-10-22 15:36:49 +04:00
bdc1823059 Добавлен класс PlanesGenericStorage 2023-10-22 15:20:44 +04:00
2a452af6b5 Внесены правки в PlanesGenericCollection 2023-10-22 15:11:20 +04:00
89c04361e4 Правлен класс SetGeneric 2023-10-22 15:05:34 +04:00
3194d59c46 Внесены правки в SetGeneric 2023-10-22 15:03:36 +04:00
45c7fb8ab3 Изменено направление вывода объектов на форме с коллекцией объектов 2023-10-10 11:59:02 +04:00
f652dfcd18 Допилена форма и подредактирована логика 2023-10-08 16:48:15 +04:00
5287002a6f Реализована логика в классе SetGeneric 2023-10-08 13:22:30 +04:00
3c728ee2e1 Изменена стартовая форма 2023-10-08 13:02:19 +04:00
7372ee4bd3 Добавлена форма FormPlaneCollection и реализована ее логика 2023-10-08 13:01:38 +04:00
854b4ac296 Внесены изменения в логику формы FormStormtrooper 2023-10-08 12:45:40 +04:00
b1a2751514 Добавлена функция получение объекта IMoveableObject из объекта DrawingPlane 2023-10-08 12:22:34 +04:00
0ab91a7bf3 Добавлен класс PlanesGenericCollection, необходимо реализовать его TODO 2023-10-08 12:21:15 +04:00
988d1da071 Добавлен класс SetGeneric, необходимо реализовать TODO код в нем 2023-10-08 12:15:13 +04:00
e789954950 Изменена логика второй стратегии перемещения 2023-09-26 12:19:42 +04:00
c0a5f08964 Реализована вторая стратегия перемещения 2023-09-26 00:42:01 +04:00
18e8449fdf Обновлена форма для отображения 2023-09-25 23:53:37 +04:00
32c55d0b57 Реализован класс стратегии MoveToCenter 2023-09-25 23:38:08 +04:00
4b53105c7b Реализован класс с интерфейсом IMoveableObject 2023-09-25 23:34:53 +04:00
b7a3f41598 Обновлены методы перемещения в классе отрисовки простого объекта 2023-09-25 23:29:14 +04:00
b595a788a9 Удалена лишняя переменная в методе отрисовки продвинутого объекта 2023-09-25 23:21:38 +04:00
78ba3286f0 Обновлен класс прорисовки продвинутого объекта 2023-09-25 23:20:48 +04:00
31a85c3479 Обновлен класс-сущность для продвинутого объекта 2023-09-25 23:06:49 +04:00
2182968867 Добавлен класс для прорисовки простого объекта 2023-09-25 23:03:12 +04:00
9c8cc5cd23 Добавлен родительский класс сущность для простого объекта 2023-09-25 22:47:40 +04:00
adc8030f38 Добавлен класс-стратегия перемещения объекта 2023-09-25 21:20:40 +04:00
aa9c8eb949 Добавлен интерфейс для работы с перемещаемым объектом 2023-09-25 21:17:24 +04:00
d88702a821 Добавлено перечисление cтатуса выполнения операции перемещения 2023-09-25 21:13:43 +04:00
f3949b87da Добавлен класс параметров координат объекта 2023-09-25 21:12:09 +04:00
1936a98d43 Исправлена ошибка в названии переменной 2023-09-13 10:56:22 +04:00
5f9528e536 Переименован файл и убраны лишние пустые строки 2023-09-13 09:53:26 +04:00
783360560c Переименованы переменные в методе отрисовки 2023-09-12 12:19:37 +04:00
ff8673a9fd Реализована отрисовка и убраны TODO 2023-09-11 18:56:04 +04:00
6f727fae32 Добавлены элементы формы и реализована недостающая логика с проверками 2023-09-11 16:29:39 +04:00
6aa4044f9e Добавлен класс для прорисовки объекта-сущности, необходимо реализовать проверки и метод прорисовки 2023-09-11 14:31:36 +04:00
efcd700b37 Добавлено перечисление направления перемещения и исправлены модификаторы доступа на public 2023-09-11 13:59:05 +04:00
bcda4554e3 Добавлен класс-сущность штурмовика и переименована основная форма 2023-09-11 13:55:13 +04:00
38 changed files with 3391 additions and 77 deletions

View File

@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status 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 = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningPlane (паттерн Adapter)
/// </summary>
public class DrawingObjectPlane : IMoveableObject
{
private readonly DrawingPlane? _drawingPlane = null;
public DrawingObjectPlane(DrawingPlane drawingPlane)
{
_drawingPlane = drawingPlane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingPlane == null || _drawingPlane.EntityPlane == null)
{
return null;
}
return new ObjectParameters(_drawingPlane.GetPosX, _drawingPlane.GetPosY, _drawingPlane.GetWidth, _drawingPlane.GetHeight);
}
}
public int GetStep => (int)(_drawingPlane?.EntityPlane?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawingPlane?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawingPlane?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,243 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingPlane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityPlane? EntityPlane{ get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
public int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
public int _pictureHeight;
/// <summary>
/// Левая координата начала прорисовки
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя координата начала прорисовки
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки
/// </summary>
protected readonly int _planeWidth = 110;
/// <summary>
/// Высота прорисовки
/// </summary>
protected readonly int _planeHeight = 110;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _planeWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _planeHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingPlane(int speed, double weight, Color bodyColor, int width, int height)
{
if (width < _planeWidth && height < _planeHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityPlane = new EntityPlane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина окна</param>
/// <param name="height">Высота окна</param>
/// <param name="planeWidth">Ширина объекта</param>
/// <param name="planeHeight">Высота объекта</param>
protected DrawingPlane(int speed, double weight, Color bodyColor,
int width, int height, int planeWidth, int planeHeight)
{
if (width < planeWidth && height < planeHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_planeWidth = planeWidth;
_planeHeight = planeHeight;
EntityPlane = new EntityPlane(speed, weight, bodyColor);
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityPlane == null)
{
return false;
}
return direction switch
{
//вверх
DirectionType.Up => _startPosY - EntityPlane.Step > 0,
//вниз
DirectionType.Down => _startPosY + _planeHeight + EntityPlane.Step < _pictureHeight,
//влево
DirectionType.Left => _startPosX - EntityPlane.Step > 0,
//вправо
DirectionType.Right => _startPosX + _planeWidth + EntityPlane.Step < _pictureWidth,
_ => false,
};
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x < 0)
{
x = 0;
}
else if (x > _pictureWidth - _planeWidth)
{
x = _pictureWidth - _planeWidth;
}
_startPosX = x;
if (y < 0)
{
y = 0;
}
else if (y > _pictureHeight - _planeHeight)
{
y = _pictureHeight - _planeHeight;
}
_startPosY = y;
}
/// <summary>
/// Перемещение объекта
/// </summary>
/// <param name="direction">Направление перемещения</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityPlane == null)
{
return;
}
switch (direction)
{
// Вверх
case DirectionType.Up:
_startPosY -= (int)EntityPlane.Step;
break;
// Вниз
case DirectionType.Down:
_startPosY += (int)EntityPlane.Step;
break;
// Влево
case DirectionType.Left:
_startPosX -= (int)EntityPlane.Step;
break;
// Вправо
case DirectionType.Right:
_startPosX += (int)EntityPlane.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityPlane == null)
{
return;
}
Pen penBlack = new Pen(Color.Black);
Brush brushBlack = new SolidBrush(Color.Black);
Brush brushBodyColor = new SolidBrush(EntityPlane.BodyColor);
// Высота фюзеляжа
int bodyHeight = _planeHeight / 9;
// Рисуем нос
Point[] pointsCockPit = {
new Point(_startPosX, _startPosY + _planeHeight / 2),
new Point(_startPosX + _planeWidth / 8, _startPosY + _planeHeight / 2 - bodyHeight / 2),
new Point(_startPosX + _planeWidth / 8, _startPosY + _planeHeight / 2 + bodyHeight / 2)
};
g.FillPolygon(brushBlack, pointsCockPit);
// Рисуем крылья
Point[] pointsWings = {
new Point(_startPosX + _planeWidth / 2, _startPosY),
new Point(_startPosX + _planeWidth / 2 + _planeWidth / 15, _startPosY),
new Point(_startPosX + _planeWidth / 2 + _planeWidth / 6, _startPosY + _planeHeight / 2),
new Point(_startPosX + _planeWidth / 2 + _planeWidth / 15, _startPosY + _planeHeight),
new Point(_startPosX + _planeWidth / 2 , _startPosY + _planeHeight)
};
g.FillPolygon(brushBodyColor, pointsWings);
g.DrawPolygon(penBlack, pointsWings);
// Рисуем хвостовое оперение
Point[] pointsTail = {
new Point(_startPosX + _planeWidth, _startPosY + _planeHeight / 2 - _planeHeight / 3),
new Point(_startPosX + _planeWidth - _planeWidth / 8, _startPosY + _planeHeight / 2 - _planeHeight / 8),
new Point(_startPosX + _planeWidth - _planeWidth / 8, _startPosY + _planeHeight / 2 + _planeHeight / 8),
new Point(_startPosX + _planeWidth, _startPosY + _planeHeight / 2 + _planeHeight / 3)
};
g.FillPolygon(brushBodyColor, pointsTail);
g.DrawPolygon(penBlack, pointsTail);
// Рисуем фюзеляж
g.FillRectangle(brushBodyColor, _startPosX + _planeWidth / 8, _startPosY + _planeHeight / 2 - bodyHeight / 2, _planeWidth - _planeWidth / 8, bodyHeight);
g.DrawRectangle(penBlack, _startPosX + _planeWidth / 8, _startPosY + _planeHeight / 2 - bodyHeight / 2, _planeWidth - _planeWidth / 8, bodyHeight);
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawingPlane
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectPlane(this);
}
}

View File

@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingStormtrooper : DrawingPlane
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rockets">Признак наличия ракет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingStormtrooper(int speed, double weight, Color bodyColor,
Color additionalColor, bool rockets, bool bombs,
int width, int height) : base(speed, weight, bodyColor, width, height, 140, 90)
{
if (EntityPlane != null)
{
EntityPlane = new EntityStormtrooper(speed, weight, bodyColor, additionalColor, rockets, bombs);
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityPlane is not EntityStormtrooper stormtrooper)
{
return;
}
Pen penBlack = new Pen(Color.Black);
Brush brushBlack = new SolidBrush(Color.Black);
Brush brushAdditionalColor = new SolidBrush(stormtrooper.AdditionalColor);
// Высота фюзеляжа
int bodyHeight = _planeHeight / 9;
// Рисуем бомбы
if (stormtrooper.Bombs)
{
Point[] pointsBombTail = {
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 8 + bodyHeight * 3 - 5,
_startPosY + _planeHeight / 2 - bodyHeight / 2 - _planeHeight / 3 + bodyHeight / 2),
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 8 + bodyHeight * 3 + 5,
_startPosY + _planeHeight / 2 - bodyHeight / 2 - _planeHeight / 3 + bodyHeight / 2 - 5),
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 8 + bodyHeight * 3 + 5,
_startPosY + _planeHeight / 2 - bodyHeight / 2 - _planeHeight / 3 + bodyHeight / 2 + 5),
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 8 + bodyHeight * 3 - 5,
_startPosY + _planeHeight / 2 - bodyHeight / 2 - _planeHeight / 3 + bodyHeight / 2)
};
g.FillPolygon(brushAdditionalColor, pointsBombTail);
g.DrawPolygon(penBlack, pointsBombTail);
for (int i = 0; i < pointsBombTail.Length; i++)
{
Point p = pointsBombTail[i];
p.Y = _startPosY + _planeHeight - (p.Y - _startPosY);
pointsBombTail[i] = p;
}
g.FillPolygon(brushAdditionalColor, pointsBombTail);
g.DrawPolygon(penBlack, pointsBombTail);
g.FillEllipse(brushAdditionalColor,
_startPosX + _planeWidth / 2 - _planeWidth / 8,
_startPosY + _planeHeight / 2 - bodyHeight / 2 - _planeHeight / 3,
bodyHeight * 3,
bodyHeight);
g.DrawEllipse(penBlack,
_startPosX + _planeWidth / 2 - _planeWidth / 8,
_startPosY + _planeHeight / 2 - bodyHeight / 2 - _planeHeight / 3,
bodyHeight * 3,
bodyHeight);
g.FillEllipse(brushAdditionalColor,
_startPosX + _planeWidth / 2 - _planeWidth / 8,
_startPosY + _planeHeight / 2 - bodyHeight / 2 + _planeHeight / 3,
bodyHeight * 3,
bodyHeight);
g.DrawEllipse(penBlack,
_startPosX + _planeWidth / 2 - _planeWidth / 8,
_startPosY + _planeHeight / 2 - bodyHeight / 2 + _planeHeight / 3,
bodyHeight * 3,
bodyHeight);
}
// Рисуем ракеты
if (stormtrooper.Rockets)
{
int rocketWidth = bodyHeight * 4;
int rocketHeight = bodyHeight / 2;
Brush brushRed = new SolidBrush(Color.Red);
Point[] pointsRocketCockPit = {
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 5 - rocketHeight,
_startPosY + _planeHeight / 2 - bodyHeight - bodyHeight / 2 + rocketHeight / 2),
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 5,
_startPosY + _planeHeight / 2 - bodyHeight - bodyHeight / 2),
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 5,
_startPosY + _planeHeight / 2 - bodyHeight - bodyHeight / 2 + rocketHeight)
};
Point[] pointsRocketTail = {
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 5 - rocketHeight + rocketWidth - 10,
_startPosY + _planeHeight / 2 - bodyHeight - bodyHeight / 2 + rocketHeight / 2),
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 5 + rocketWidth,
_startPosY + _planeHeight / 2 - bodyHeight * 2 + rocketHeight / 2),
new Point(_startPosX + _planeWidth / 2 - _planeWidth / 5 + rocketWidth,
_startPosY + _planeHeight / 2 - bodyHeight - bodyHeight / 2 + rocketHeight + bodyHeight / 2 - rocketHeight / 2)
};
g.FillPolygon(brushRed, pointsRocketCockPit);
g.DrawPolygon(penBlack, pointsRocketCockPit);
g.FillPolygon(brushBlack, pointsRocketTail);
g.DrawPolygon(penBlack, pointsRocketTail);
for (int i = 0; i < pointsRocketCockPit.Length; i++)
{
Point p = pointsRocketCockPit[i];
p.Y = _startPosY + _planeHeight - (p.Y - _startPosY);
pointsRocketCockPit[i] = p;
}
for (int i = 0; i < pointsRocketTail.Length; i++)
{
Point p = pointsRocketTail[i];
p.Y = _startPosY + _planeHeight - (p.Y - _startPosY);
pointsRocketTail[i] = p;
}
g.FillPolygon(brushRed, pointsRocketCockPit);
g.DrawPolygon(penBlack, pointsRocketCockPit);
g.FillPolygon(brushBlack, pointsRocketTail);
g.DrawPolygon(penBlack, pointsRocketTail);
g.FillRectangle(brushAdditionalColor,
_startPosX + _planeWidth / 2 - _planeWidth / 5,
_startPosY + _planeHeight / 2 - bodyHeight - bodyHeight / 2,
rocketWidth,
rocketHeight);
g.DrawRectangle(penBlack,
_startPosX + _planeWidth / 2 - _planeWidth / 5,
_startPosY + _planeHeight / 2 - bodyHeight - bodyHeight / 2,
rocketWidth,
rocketHeight);
g.FillRectangle(brushAdditionalColor,
_startPosX + _planeWidth / 2 - _planeWidth / 5,
_startPosY + _planeHeight / 2 + bodyHeight / 2 + bodyHeight / 2,
rocketWidth,
rocketHeight);
g.DrawRectangle(penBlack,
_startPosX + _planeWidth / 2 - _planeWidth / 5,
_startPosY + _planeHeight / 2 + bodyHeight / 2 + bodyHeight / 2,
rocketWidth,
rocketHeight);
}
base.DrawTransport(g);
}
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using static System.Reflection.Metadata.BlobBuilder;
namespace ProjectStormtrooper
{
/// <summary>
/// Класс-сущность "Самолет"
/// </summary>
public class EntityPlane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения
/// </summary>
public double Step => (double)Speed * 250 / Weight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public EntityPlane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
public void SetColor(Color color)
{
BodyColor = color;
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Класс-сущность "Штурмовик"
/// </summary>
public class EntityStormtrooper : EntityPlane
{
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия ракет
/// </summary>
public bool Rockets { get; private set; }
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
public EntityStormtrooper(int speed, double weight, Color bodyColor,
Color additionalColor, bool rockets, bool bombs) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Rockets = rockets;
Bombs = bombs;
}
public void SetAdditionalColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
public static class ExtensionDrawingPlane
{
/// <summary>
/// Создание объекта из строки
/// </summary>
public static DrawingPlane? CreateDrawingPlane(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingPlane(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingStormtrooper(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
width,
height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
public static string GetDataForSave(this DrawingPlane drawningPlane, char separatorForObject)
{
var plane = drawningPlane.EntityPlane;
if (plane == null)
{
return string.Empty;
}
var str = $"{plane.Speed}{separatorForObject}{plane.Weight}{separatorForObject}{plane.BodyColor.Name}";
if (plane is not EntityStormtrooper stormtrooper)
{
return str;
}
return $"{str}{separatorForObject}{stormtrooper.AdditionalColor.Name}{separatorForObject}{stormtrooper.Rockets}{separatorForObject}{stormtrooper.Bombs}";
}
}
}

View File

@ -1,39 +0,0 @@
namespace ProjectStormtrooper
{
partial class Form1
{
/// <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()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace ProjectStormtrooper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,250 @@
namespace ProjectStormtrooper
{
partial class FormPlaneCollection
{
/// <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();
groupBoxStorages = new GroupBox();
buttonRemoveStorage = new Button();
listBoxStorages = new ListBox();
buttonAddStorage = new Button();
textBoxStorageName = new TextBox();
maskedTextBoxNumber = new MaskedTextBox();
buttonRefreshCollection = new Button();
buttonRemovePlane = new Button();
buttonAddPlane = new Button();
pictureBoxCollection = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
сохранитьToolStripMenuItem = new ToolStripMenuItem();
загрузитьToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout();
groupBoxStorages.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(groupBoxStorages);
groupBoxTools.Controls.Add(maskedTextBoxNumber);
groupBoxTools.Controls.Add(buttonRefreshCollection);
groupBoxTools.Controls.Add(buttonRemovePlane);
groupBoxTools.Controls.Add(buttonAddPlane);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(787, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(230, 510);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// groupBoxStorages
//
groupBoxStorages.Controls.Add(buttonRemoveStorage);
groupBoxStorages.Controls.Add(listBoxStorages);
groupBoxStorages.Controls.Add(buttonAddStorage);
groupBoxStorages.Controls.Add(textBoxStorageName);
groupBoxStorages.Location = new Point(6, 26);
groupBoxStorages.Name = "groupBoxStorages";
groupBoxStorages.Size = new Size(218, 241);
groupBoxStorages.TabIndex = 5;
groupBoxStorages.TabStop = false;
groupBoxStorages.Text = "Наборы";
//
// buttonRemoveStorage
//
buttonRemoveStorage.Location = new Point(6, 204);
buttonRemoveStorage.Name = "buttonRemoveStorage";
buttonRemoveStorage.Size = new Size(206, 29);
buttonRemoveStorage.TabIndex = 3;
buttonRemoveStorage.Text = "Удалить набор";
buttonRemoveStorage.UseVisualStyleBackColor = true;
buttonRemoveStorage.Click += buttonDelStorage_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(6, 94);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(206, 104);
listBoxStorages.TabIndex = 2;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// buttonAddStorage
//
buttonAddStorage.Location = new Point(6, 59);
buttonAddStorage.Name = "buttonAddStorage";
buttonAddStorage.Size = new Size(206, 29);
buttonAddStorage.TabIndex = 1;
buttonAddStorage.Text = "Добавить набор";
buttonAddStorage.UseVisualStyleBackColor = true;
buttonAddStorage.Click += buttonAddStorage_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(6, 26);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(206, 27);
textBoxStorageName.TabIndex = 0;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(6, 404);
maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(218, 27);
maskedTextBoxNumber.TabIndex = 4;
maskedTextBoxNumber.TextAlign = HorizontalAlignment.Center;
maskedTextBoxNumber.ValidatingType = typeof(int);
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(6, 497);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(218, 29);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// buttonRemovePlane
//
buttonRemovePlane.Location = new Point(6, 437);
buttonRemovePlane.Name = "buttonRemovePlane";
buttonRemovePlane.Size = new Size(218, 29);
buttonRemovePlane.TabIndex = 2;
buttonRemovePlane.Text = "Удалить самолет";
buttonRemovePlane.UseVisualStyleBackColor = true;
buttonRemovePlane.Click += buttonRemovePlane_Click;
//
// buttonAddPlane
//
buttonAddPlane.Location = new Point(6, 349);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(218, 29);
buttonAddPlane.TabIndex = 0;
buttonAddPlane.Text = "Добавить самолет";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += buttonAddPlane_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 28);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(787, 510);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1017, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { сохранитьToolStripMenuItem, загрузитьToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// сохранитьToolStripMenuItem
//
сохранитьToolStripMenuItem.Name = "сохранитьToolStripMenuItem";
сохранитьToolStripMenuItem.Size = new Size(166, 26);
сохранитьToolStripMenuItem.Text = "Сохранить";
сохранитьToolStripMenuItem.Click += saveToFileToolStripMenuItem_Click;
//
// загрузитьToolStripMenuItem
//
загрузитьToolStripMenuItem.Name = агрузитьToolStripMenuItem";
загрузитьToolStripMenuItem.Size = new Size(166, 26);
загрузитьToolStripMenuItem.Text = "Загрузить";
загрузитьToolStripMenuItem.Click += loadFromFileToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1017, 538);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormPlaneCollection";
Text = "Набор самолетов";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
groupBoxStorages.ResumeLayout(false);
groupBoxStorages.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private Button buttonRefreshCollection;
private Button buttonRemovePlane;
private Button buttonAddPlane;
private MaskedTextBox maskedTextBoxNumber;
private PictureBox pictureBoxCollection;
private GroupBox groupBoxStorages;
private Button buttonRemoveStorage;
private ListBox listBoxStorages;
private Button buttonAddStorage;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранитьToolStripMenuItem;
private ToolStripMenuItem загрузитьToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,250 @@
using ProjectStormtrooper.Properties;
using Microsoft.Extensions.Logging;
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;
using System.Xml.Linq;
namespace ProjectStormtrooper
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningPlane
/// </summary>
public partial class FormPlaneCollection : Form
{
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Набор объектов
/// </summary>
private readonly PlanesGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
{
InitializeComponent();
_storage = new PlanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddStorage_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Неудачная попытка добавить хранилище: не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
ReloadObjects();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowPlanes();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelStorage_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
string? name = listBoxStorages.SelectedItem.ToString();
_storage.DelSet(name ?? string.Empty);
_logger.LogInformation($"Удален набор: {name}");
ReloadObjects();
}
_logger.LogWarning("Отмена удаления набора");
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddPlane_Click(object sender, EventArgs e)
{
var formPlaneConfig = new FormPlaneConfig();
formPlaneConfig.AddEvent(AddPlaneListener);
formPlaneConfig.Show();
}
public void AddPlaneListener(DrawingPlane plane)
{
plane._pictureWidth = pictureBoxCollection.Width;
plane._pictureHeight = pictureBoxCollection.Height;
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
try
{
if (obj + plane > -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {plane}");
pictureBoxCollection.Image = obj.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning("Ошибка добавления: " + ex.Message);
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemovePlane_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var removedObj = obj - pos;
if (removedObj != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект {removedObj} с позиции {pos}");
pictureBoxCollection.Image = obj.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
catch (PlaneNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning("Ошибка удаления: " + ex.Message);
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
RefreshCollection();
}
private void RefreshCollection()
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowPlanes();
}
private void saveToFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные сохранены в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
private void loadFromFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
RefreshCollection();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
}
}

View File

@ -0,0 +1,129 @@
<?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>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>152, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>319, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,358 @@
namespace ProjectStormtrooper
{
partial class FormPlaneConfig
{
/// <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()
{
groupBoxParams = new GroupBox();
groupBoxColors = new GroupBox();
panelColorPink = new Panel();
panelColorPurple = new Panel();
panelColorBlue = new Panel();
panelColorBrown = new Panel();
panelColorGreen = new Panel();
panelColorLightBlue = new Panel();
panelColorYellow = new Panel();
panelColorRed = new Panel();
labelStormtrooper = new Label();
labelPlane = new Label();
checkBoxRockets = new CheckBox();
checkBoxBombs = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
buttonCancel = new Button();
buttonApply = new Button();
pictureBoxObject = new PictureBox();
labelAddColor = new Label();
labelColor = new Label();
panelControl = new Panel();
groupBoxParams.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelControl.SuspendLayout();
SuspendLayout();
//
// groupBoxParams
//
groupBoxParams.Controls.Add(groupBoxColors);
groupBoxParams.Controls.Add(labelStormtrooper);
groupBoxParams.Controls.Add(labelPlane);
groupBoxParams.Controls.Add(checkBoxRockets);
groupBoxParams.Controls.Add(checkBoxBombs);
groupBoxParams.Controls.Add(numericUpDownWeight);
groupBoxParams.Controls.Add(numericUpDownSpeed);
groupBoxParams.Controls.Add(labelWeight);
groupBoxParams.Controls.Add(labelSpeed);
groupBoxParams.Location = new Point(2, 7);
groupBoxParams.Name = "groupBoxParams";
groupBoxParams.Size = new Size(497, 261);
groupBoxParams.TabIndex = 0;
groupBoxParams.TabStop = false;
groupBoxParams.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelColorPink);
groupBoxColors.Controls.Add(panelColorPurple);
groupBoxColors.Controls.Add(panelColorBlue);
groupBoxColors.Controls.Add(panelColorBrown);
groupBoxColors.Controls.Add(panelColorGreen);
groupBoxColors.Controls.Add(panelColorLightBlue);
groupBoxColors.Controls.Add(panelColorYellow);
groupBoxColors.Controls.Add(panelColorRed);
groupBoxColors.Location = new Point(176, 26);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(308, 156);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelColorPink
//
panelColorPink.BackColor = Color.PeachPuff;
panelColorPink.Location = new Point(241, 89);
panelColorPink.Name = "panelColorPink";
panelColorPink.Size = new Size(50, 50);
panelColorPink.TabIndex = 1;
//
// panelColorPurple
//
panelColorPurple.BackColor = Color.Fuchsia;
panelColorPurple.Location = new Point(164, 89);
panelColorPurple.Name = "panelColorPurple";
panelColorPurple.Size = new Size(50, 50);
panelColorPurple.TabIndex = 1;
//
// panelColorBlue
//
panelColorBlue.BackColor = Color.Blue;
panelColorBlue.Location = new Point(87, 89);
panelColorBlue.Name = "panelColorBlue";
panelColorBlue.Size = new Size(50, 50);
panelColorBlue.TabIndex = 1;
//
// panelColorBrown
//
panelColorBrown.BackColor = Color.DarkRed;
panelColorBrown.Location = new Point(17, 89);
panelColorBrown.Name = "panelColorBrown";
panelColorBrown.Size = new Size(50, 50);
panelColorBrown.TabIndex = 3;
//
// panelColorGreen
//
panelColorGreen.BackColor = Color.Lime;
panelColorGreen.Location = new Point(241, 26);
panelColorGreen.Name = "panelColorGreen";
panelColorGreen.Size = new Size(50, 50);
panelColorGreen.TabIndex = 1;
//
// panelColorLightBlue
//
panelColorLightBlue.BackColor = Color.Cyan;
panelColorLightBlue.Location = new Point(164, 26);
panelColorLightBlue.Name = "panelColorLightBlue";
panelColorLightBlue.Size = new Size(50, 50);
panelColorLightBlue.TabIndex = 2;
//
// panelColorYellow
//
panelColorYellow.BackColor = Color.Yellow;
panelColorYellow.Location = new Point(87, 26);
panelColorYellow.Name = "panelColorYellow";
panelColorYellow.Size = new Size(50, 50);
panelColorYellow.TabIndex = 1;
//
// panelColorRed
//
panelColorRed.BackColor = Color.Red;
panelColorRed.Location = new Point(17, 26);
panelColorRed.Name = "panelColorRed";
panelColorRed.Size = new Size(50, 50);
panelColorRed.TabIndex = 0;
//
// labelStormtrooper
//
labelStormtrooper.BorderStyle = BorderStyle.FixedSingle;
labelStormtrooper.Location = new Point(340, 203);
labelStormtrooper.Name = "labelStormtrooper";
labelStormtrooper.Padding = new Padding(10);
labelStormtrooper.Size = new Size(127, 42);
labelStormtrooper.TabIndex = 7;
labelStormtrooper.Text = "Продвинутый";
labelStormtrooper.TextAlign = ContentAlignment.MiddleCenter;
labelStormtrooper.MouseDown += labelObject_MouseDown;
//
// labelPlane
//
labelPlane.BorderStyle = BorderStyle.FixedSingle;
labelPlane.Location = new Point(193, 203);
labelPlane.Name = "labelPlane";
labelPlane.Padding = new Padding(10);
labelPlane.Size = new Size(120, 42);
labelPlane.TabIndex = 6;
labelPlane.Text = "Простой";
labelPlane.TextAlign = ContentAlignment.MiddleCenter;
labelPlane.MouseDown += labelObject_MouseDown;
//
// checkBoxRockets
//
checkBoxRockets.AutoSize = true;
checkBoxRockets.Location = new Point(6, 145);
checkBoxRockets.Name = "checkBoxRockets";
checkBoxRockets.Size = new Size(79, 24);
checkBoxRockets.TabIndex = 5;
checkBoxRockets.Text = "Ракеты";
checkBoxRockets.UseVisualStyleBackColor = true;
//
// checkBoxBombs
//
checkBoxBombs.AutoSize = true;
checkBoxBombs.Location = new Point(6, 115);
checkBoxBombs.Name = "checkBoxBombs";
checkBoxBombs.Size = new Size(80, 24);
checkBoxBombs.TabIndex = 4;
checkBoxBombs.Text = "Бомбы";
checkBoxBombs.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(88, 73);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(82, 27);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(88, 29);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(82, 27);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(6, 75);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(6, 31);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// buttonCancel
//
buttonCancel.Location = new Point(178, 220);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 4;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// buttonApply
//
buttonApply.Location = new Point(21, 220);
buttonApply.Name = "buttonApply";
buttonApply.Size = new Size(94, 29);
buttonApply.TabIndex = 3;
buttonApply.Text = "Добавить";
buttonApply.UseVisualStyleBackColor = true;
buttonApply.Click += buttonApply_Click;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(21, 68);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(251, 146);
pictureBoxObject.TabIndex = 2;
pictureBoxObject.TabStop = false;
//
// labelAddColor
//
labelAddColor.AllowDrop = true;
labelAddColor.BorderStyle = BorderStyle.FixedSingle;
labelAddColor.Location = new Point(172, 16);
labelAddColor.Name = "labelAddColor";
labelAddColor.Size = new Size(100, 40);
labelAddColor.TabIndex = 1;
labelAddColor.Text = "Доп. цвет";
labelAddColor.TextAlign = ContentAlignment.MiddleCenter;
labelAddColor.DragDrop += labelAddColor_DragDrop;
labelAddColor.DragEnter += labelColor_DragEnter;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(21, 16);
labelColor.Name = "labelColor";
labelColor.Size = new Size(100, 40);
labelColor.TabIndex = 0;
labelColor.Text = "Цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += labelColor_DragDrop;
labelColor.DragEnter += labelColor_DragEnter;
//
// panelControl
//
panelControl.AllowDrop = true;
panelControl.Controls.Add(labelColor);
panelControl.Controls.Add(buttonCancel);
panelControl.Controls.Add(buttonApply);
panelControl.Controls.Add(pictureBoxObject);
panelControl.Controls.Add(labelAddColor);
panelControl.Location = new Point(505, 12);
panelControl.Name = "panelControl";
panelControl.Size = new Size(298, 256);
panelControl.TabIndex = 5;
panelControl.DragDrop += panelControlObject_DragDrop;
panelControl.DragEnter += panelControlObject_DragEnter;
//
// FormPlaneConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(809, 275);
Controls.Add(panelControl);
Controls.Add(groupBoxParams);
Name = "FormPlaneConfig";
Text = "Создание объекта";
groupBoxParams.ResumeLayout(false);
groupBoxParams.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelControl.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParams;
private GroupBox groupBoxColors;
private Label labelStormtrooper;
private Label labelPlane;
private CheckBox checkBoxRockets;
private CheckBox checkBoxBombs;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Panel panelColorRed;
private Panel panelColorPink;
private Panel panelColorPurple;
private Panel panelColorBlue;
private Panel panelColorBrown;
private Panel panelColorGreen;
private Panel panelColorLightBlue;
private Panel panelColorYellow;
private Button buttonCancel;
private Button buttonApply;
private PictureBox pictureBoxObject;
private Label labelAddColor;
private Label labelColor;
private Panel panelControl;
}
}

View File

@ -0,0 +1,127 @@
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 ProjectStormtrooper
{
public partial class FormPlaneConfig : Form
{
/// <summary>
/// Переменная-выбранный самолет
/// </summary>
DrawingPlane? _plane = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingPlane>? EventAddPlane;
public FormPlaneConfig()
{
InitializeComponent();
panelColorRed.MouseDown += panelColor_MouseDown;
panelColorYellow.MouseDown += panelColor_MouseDown;
panelColorLightBlue.MouseDown += panelColor_MouseDown;
panelColorGreen.MouseDown += panelColor_MouseDown;
panelColorBrown.MouseDown += panelColor_MouseDown;
panelColorBlue.MouseDown += panelColor_MouseDown;
panelColorPurple.MouseDown += panelColor_MouseDown;
panelColorPink.MouseDown += panelColor_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawingPlane> ev)
{
if (EventAddPlane == null)
{
EventAddPlane = ev;
}
else
{
EventAddPlane += ev;
}
}
/// <summary>
/// Отрисовать машину
/// </summary>
private void DrawPlane()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_plane?.SetPosition((int)((pictureBoxObject.Width - _plane?.GetWidth) / 2), (int)((pictureBoxObject.Height - _plane?.GetHeight) / 2));
_plane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void buttonApply_Click(object sender, EventArgs e)
{
EventAddPlane?.Invoke(_plane);
Close();
}
private void panelControlObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void panelControlObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelPlane":
_plane = new DrawingPlane((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelStormtrooper":
_plane = new DrawingStormtrooper((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxRockets.Checked, checkBoxBombs.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
DrawPlane();
}
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
private void panelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_plane == null)
return;
_plane.EntityPlane.SetColor((Color)e.Data.GetData(typeof(Color).ToString()));
DrawPlane();
}
private void labelAddColor_DragDrop(object sender, DragEventArgs e)
{
if (_plane == null || _plane is not DrawingStormtrooper)
return;
(_plane.EntityPlane as EntityStormtrooper).SetAdditionalColor((Color)e.Data.GetData(typeof(Color).ToString()));
DrawPlane();
}
}
}

View File

@ -1,24 +1,24 @@
<?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
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="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>
@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,192 @@
namespace ProjectStormtrooper
{
partial class FormStormtrooper
{
/// <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()
{
pictureBoxStormtrooper = new PictureBox();
buttonCreateStormtrooper = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonRight = new Button();
buttonCreatePlane = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonSelectPlane = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit();
SuspendLayout();
//
// pictureBoxStormtrooper
//
pictureBoxStormtrooper.Dock = DockStyle.Fill;
pictureBoxStormtrooper.Location = new Point(0, 0);
pictureBoxStormtrooper.Name = "pictureBoxStormtrooper";
pictureBoxStormtrooper.Size = new Size(948, 546);
pictureBoxStormtrooper.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxStormtrooper.TabIndex = 0;
pictureBoxStormtrooper.TabStop = false;
//
// buttonCreateStormtrooper
//
buttonCreateStormtrooper.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateStormtrooper.Location = new Point(12, 505);
buttonCreateStormtrooper.Name = "buttonCreateStormtrooper";
buttonCreateStormtrooper.Size = new Size(201, 29);
buttonCreateStormtrooper.TabIndex = 1;
buttonCreateStormtrooper.Text = "Создать штурмовик";
buttonCreateStormtrooper.UseVisualStyleBackColor = true;
buttonCreateStormtrooper.Click += buttonCreateStormtrooper_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUP;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(870, 468);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 2;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDOWN;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(870, 504);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLEFT;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(834, 504);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRIGHT;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(906, 504);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonCreatePlane
//
buttonCreatePlane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreatePlane.Location = new Point(219, 505);
buttonCreatePlane.Name = "buttonCreatePlane";
buttonCreatePlane.Size = new Size(201, 29);
buttonCreatePlane.TabIndex = 6;
buttonCreatePlane.Text = "Создать самолет";
buttonCreatePlane.UseVisualStyleBackColor = true;
buttonCreatePlane.Click += buttonCreatePlane_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToRightBottom" });
comboBoxStrategy.Location = new Point(785, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(842, 46);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(94, 29);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonSelectPlane
//
buttonSelectPlane.Location = new Point(426, 505);
buttonSelectPlane.Name = "buttonSelectPlane";
buttonSelectPlane.Size = new Size(137, 29);
buttonSelectPlane.TabIndex = 9;
buttonSelectPlane.Text = "Выбрать";
buttonSelectPlane.UseVisualStyleBackColor = true;
buttonSelectPlane.Click += ButtonSelectPlane_Click;
//
// FormStormtrooper
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(948, 546);
Controls.Add(buttonSelectPlane);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreatePlane);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonCreateStormtrooper);
Controls.Add(pictureBoxStormtrooper);
Name = "FormStormtrooper";
StartPosition = FormStartPosition.CenterScreen;
Text = "Штурмовик";
((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxStormtrooper;
private Button buttonCreateStormtrooper;
private Button buttonUp;
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private Button buttonCreatePlane;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectPlane;
}
}

View File

@ -0,0 +1,178 @@
namespace ProjectStormtrooper
{
/// <summary>
/// Ôîðìà äëÿ ðàáîòû ñ îáúåêòîì "Øòóðìîâèê"
/// </summary>
public partial class FormStormtrooper : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingPlane? _drawingPlane;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Âûáðàííûé àâòîìîáèëü
/// </summary>
public DrawingPlane? SelectedPlane { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormStormtrooper()
{
InitializeComponent();
_strategy = null;
SelectedPlane = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè îáúåêòà
/// </summary>
private void Draw()
{
if (_drawingPlane == null)
{
return;
}
Bitmap bmp = new(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
Graphics g = Graphics.FromImage(bmp);
_drawingPlane.DrawTransport(g);
pictureBoxStormtrooper.Image = bmp;
}
/// <summary>
/// Îáðàáîò÷èê íàæàòèÿ êíîïêè "Ñîçäàòü øòóðìîâèê"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateStormtrooper_Click(object sender, EventArgs e)
{
Random random = new();
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;
}
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
dopColor = dialog.Color;
}
_drawingPlane = new DrawingStormtrooper(
random.Next(100, 300),
random.Next(1000, 3000),
color,
dopColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxStormtrooper.Width,
pictureBoxStormtrooper.Height
);
_drawingPlane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîò÷èê íàæàòèÿ êíîïêè "Ñîçäàòü ñàìîëåò"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreatePlane_Click(object sender, EventArgs e)
{
Random random = new();
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;
}
_drawingPlane = new DrawingPlane(
random.Next(100, 300),
random.Next(1000, 3000),
color,
pictureBoxStormtrooper.Width,
pictureBoxStormtrooper.Height
);
_drawingPlane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîò÷èê íàæàòèÿ êíîïîê ïåðåìåùåíèÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingPlane == null)
{
return;
}
string buttonName = ((Button)sender)?.Name ?? string.Empty;
switch (buttonName)
{
case "buttonUp":
_drawingPlane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingPlane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingPlane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingPlane.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingPlane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToRightBottom(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new DrawingObjectPlane(_drawingPlane), pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
/// <summary>
/// Âûáîð ñàìîëåòà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectPlane_Click(object sender, EventArgs e)
{
SelectedPlane = _drawingPlane;
DialogResult = DialogResult.OK;
}
}
}

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

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления перемещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
public class MoveToRightBottom : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder >= FieldWidth - GetStep() && objParams.DownBorder >= FieldHeight - GetStep();
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
if (objParams.RightBorder < FieldWidth - GetStep())
{
MoveRight();
}
if (objParams.TopBorder < FieldHeight - GetStep())
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningPlane
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class PlanesGenericCollection<T, U>
where T : DrawingPlane
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 160;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 120;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public PlanesGenericCollection(int picWidth, int picHeight)
{
int horizontalObjectsCount = picWidth / _placeSizeWidth;
int verticalObjectsCount = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(horizontalObjectsCount * verticalObjectsCount);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(PlanesGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
}
return collect?._collection.Insert(obj) ?? -1;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(PlanesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowPlanes()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
// Линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int placesColumnCount = _pictureHeight / _placeSizeHeight;
int placesRowCount = _pictureWidth / _placeSizeWidth;
int i = 0;
foreach (var plane in _collection.GetPlanes())
{
if (plane != null)
{
// установка позиции
plane.SetPosition(
(int)((placesRowCount - 1) * _placeSizeWidth - (i % placesColumnCount * _placeSizeWidth) + (_placeSizeWidth - plane.GetWidth) / 2),
(int)(i / placesColumnCount * _placeSizeHeight + (_placeSizeHeight - plane.GetHeight) / 2)
);
// прорисовка объекта
plane.DrawTransport(g);
}
i++;
}
}
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetPlanes => _collection.GetPlanes();
}
}

View File

@ -0,0 +1,162 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
internal class PlanesGenericStorage
{
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>> _planeStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _planeStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public PlanesGenericStorage(int pictureWidth, int pictureHeight)
{
_planeStorages = new Dictionary<string, PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_planeStorages.Add(name, new PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_planeStorages.ContainsKey(name))
_planeStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>? this[string ind]
{
get
{
if (_planeStorages.ContainsKey(ind))
return _planeStorages[ind];
return null;
}
}
/// <summary>
/// Сохранение информации в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = File.CreateText(filename))
{
sw.WriteLine($"PlaneStorage");
string storageString;
foreach (var storage in _planeStorages)
{
storageString = "";
foreach (var plane in storage.Value.GetPlanes)
{
storageString += $"{plane?.GetDataForSave(_separatorForObject)}{_separatorRecords}";
}
if (storageString == "")
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
sw.WriteLine($"{storage.Key}{_separatorForKeyValue}{storageString}");
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Ошибка открытия файла");
}
using (StreamReader sr = new StreamReader(filename))
{
string? currentLine = sr.ReadLine();
if (currentLine == null)
{
throw new IOException("Нет данных для загрузки");
}
if (!currentLine.Contains("PlaneStorage"))
{
throw new FileFormatException("Неверный формат данных");
}
_planeStorages.Clear();
currentLine = sr.ReadLine();
while (currentLine != null)
{
string[] record = currentLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
PlanesGenericCollection<DrawingPlane, DrawingObjectPlane> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingPlane? plane = elem?.CreateDrawingPlane(_separatorForObject, _pictureWidth, _pictureHeight);
if (plane != null)
{
if (collection + plane == -1)
{
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_planeStorages.Add(record[0], collection);
currentLine = sr.ReadLine();
}
}
}
}
}

View File

@ -1,9 +1,14 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectStormtrooper
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
@ -11,7 +16,30 @@ namespace ProjectStormtrooper
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormPlaneCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormPlaneCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appSettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -8,4 +8,39 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="appSettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appSettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper.Properties
{
[Serializable]
internal class PlaneNotFoundException : ApplicationException
{
public PlaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public PlaneNotFoundException() : base() { }
public PlaneNotFoundException(string message) : base(message) { }
public PlaneNotFoundException(string message, Exception exception) : base(message, exception) { }
protected PlaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectStormtrooper.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectStormtrooper.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowDOWN {
get {
object obj = ResourceManager.GetObject("arrowDOWN", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowLEFT {
get {
object obj = ResourceManager.GetObject("arrowLEFT", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowRIGHT {
get {
object obj = ResourceManager.GetObject("arrowRIGHT", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowUP {
get {
object obj = ResourceManager.GetObject("arrowUP", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,133 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="arrowLEFT" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowLEFT.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowDOWN" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowDOWN.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowRIGHT" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowRIGHT.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowUP" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowUP.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper.Properties
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,131 @@
using ProjectStormtrooper.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
internal class SetGeneric<T> where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавления объекта в набор
/// </summary>
/// <param name="plane"></param>
/// <returns></returns>
public int Insert(T plane)
{
return Insert(plane, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="plane"></param>
/// <param name="position"></param>
/// <returns></returns>
public int Insert(T plane, int position)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
// Проверка позиции
if (position < 0 || position >= _maxCount)
{
return -1;
}
// Вставка по позиции
_places.Insert(position, plane);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Remove(int position)
{
// Проверка позиции
if (position < 0 || position >= _maxCount)
{
return null;
}
if (position >= Count && position < _maxCount)
{
throw new PlaneNotFoundException(position);
}
// Удаление объекта из массива, присвоив элементу массива значение null
T? plane = _places[position];
_places.RemoveAt(position);
return plane;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
// Проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
set
{
// Проверка позиции
// Проверка свободных мест в списке
if (position < 0 || position >= _maxCount || Count == _maxCount)
{
return;
}
// Вставка в список по позиции
_places.Insert(position, value);
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetPlanes(int? maxPlanes = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxPlanes.HasValue && i == maxPlanes.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Planes"
}
}
}