Compare commits

..

64 Commits
master ... Lab7

Author SHA1 Message Date
2ffd010a15 Merge pull request 'Agliullov D. A. Lab Work 8 Advanced' (#9) from Lab8 into Lab7
Reviewed-on: http://student.git.athene.tech/d.agliullov/ISEbd-21_Agliullov.D.A._AirBomber.Advanced/pulls/9
2022-11-07 11:34:01 +04:00
Данияр Аглиуллов
75695fec70 Отформатированы условия 2022-11-02 23:32:34 +04:00
Данияр Аглиуллов
ae8305225f Merge branch 'PrevLab8' into Lab8 2022-11-02 23:29:07 +04:00
Данияр Аглиуллов
59e97ac59e Решение конфликта слияния 2022-11-02 23:28:08 +04:00
d.agil
44b8fefd9e Исправлена загрузка карты 2022-11-02 23:22:28 +04:00
d.agil
31b12793cd Исправлена загрузка карты 2022-11-02 23:21:37 +04:00
d.agil
844514fc0d fix 2022-11-02 23:13:51 +04:00
Данияр Аглиуллов
fb360824dc fix 2022-11-02 23:11:53 +04:00
d.agil
00c78f3e32 Исправлена загрузка карты 2022-11-02 23:06:24 +04:00
d.agil
d25097873c fix 2022-11-02 13:12:01 +04:00
Данияр Аглиуллов
0f9caec5c3 Реализован интерфейс итераторов для Airplane и AirBomber 2022-11-02 00:56:09 +04:00
Данияр Аглиуллов
8c6ce67917 Реализовано сравнение хранилища 2022-11-01 22:07:42 +04:00
Данияр Аглиуллов
5e1f609741 В проверке на эквивалентность самолетов, добавлены проверки на тип и количество двигателей 2022-11-01 21:30:26 +04:00
Данияр Аглиуллов
9da6b57bd9 Добавлены изменения из базовой части 2022-11-01 21:29:35 +04:00
Данияр Аглиуллов
7019af70fd Изменен уровень логгирования при некорректном добавлении / удалении самолета 2022-10-30 04:59:42 +04:00
Данияр Аглиуллов
b5e2869633 Исправлено удаление самолета 2022-10-30 04:27:11 +04:00
Данияр Аглиуллов
b570c25680 Добавлена логгирование всех непредвиденных ошибок 2022-10-30 04:17:42 +04:00
Данияр Аглиуллов
25e6f2df67 Добавлены фильтры для логгирования в разные файлы 2022-10-30 04:17:17 +04:00
Данияр Аглиуллов
2fca625262 Изменения из базовой части 2022-10-30 02:14:28 +04:00
Данияр Аглиуллов
0d29e1742b Лаба 6 2022-10-28 02:18:13 +04:00
Данияр Аглиуллов
c33afe18fd Изменения из базовой части 6 лабы 2022-10-28 00:53:37 +04:00
Данияр Аглиуллов
a5f607c8c0 Изменен способ установки значения свойств самолетов 2022-10-19 18:39:26 +04:00
Данияр Аглиуллов
67dde9fb10 Изменена отправка данных по DragAndDrop 2022-10-19 17:21:13 +04:00
Данияр Аглиуллов
0a5d9819bc Релизована логика изменения типов двигателей у самолета 2022-10-18 04:51:49 +04:00
Данияр Аглиуллов
639df36fd9 Реализован интерфейс для типов двигателей 2022-10-18 03:58:43 +04:00
Данияр Аглиуллов
a9a8cd78f2 Изменения из базовой части 2022-10-18 03:10:31 +04:00
Данияр Аглиуллов
85c57c4fbf сделаны размеры самолета как в базовой части 2022-10-18 03:07:47 +04:00
Данияр Аглиуллов
d1ee0249c1 Решены конфликты между 3 и 4 лабой 2022-10-13 16:01:02 +04:00
Данияр Аглиуллов
c65c4d2d62 Решены конфликты между 3 и 4 лабой 2022-10-13 15:41:27 +04:00
Данияр Аглиуллов
daa66a3e1f Решены конфликты между 3 и 4 лабой 2022-10-13 15:21:46 +04:00
Данияр Аглиуллов
396cc84c61 Merge branch 'Lab3' into Lab3.0 2022-10-13 15:18:30 +04:00
Данияр Аглиуллов
d29860efb1 изменена отрисовка участков карты 2022-10-13 15:16:15 +04:00
Данияр Аглиуллов
59f128aa16 Переименование метода 2022-10-13 15:15:13 +04:00
Данияр Аглиуллов
453c7c79c4 Изменен тип возвращаемого значения 2022-10-13 15:10:07 +04:00
Данияр Аглиуллов
a20390f707 Исправлена ошибка с добавлением / удалением самолетов 2022-10-13 15:00:02 +04:00
Данияр Аглиуллов
ca0967fdce Измененен тип возвращаемого значения 2022-10-13 14:57:11 +04:00
Данияр Аглиуллов
d13c74aec0 изменена отрисовка участков карты 2022-10-05 01:20:21 +04:00
Данияр Аглиуллов
3a5fa25ce4 изменена отрисовка участков карты 2022-10-05 01:19:54 +04:00
Данияр Аглиуллов
75f994437e Теперь самолет отрисовывается сразу при создании формы 2022-10-01 06:05:00 +04:00
Данияр Аглиуллов
ff9b1a050f Исправлена ошибка при удалении самолета 2022-10-01 05:59:12 +04:00
Данияр Аглиуллов
1e4bdd4812 Переименован метод 2022-10-01 05:53:56 +04:00
Данияр Аглиуллов
552cc1f93f Переименован метод 2022-10-01 05:53:37 +04:00
Данияр Аглиуллов
750fe21582 Добавлена возможность устанавливать самолет в констуктор форм 2022-10-01 05:52:54 +04:00
Данияр Аглиуллов
e0dedff290 Переименование метода 2022-10-01 05:39:32 +04:00
Данияр Аглиуллов
a9ba63977f Переименование метода 2022-10-01 05:39:18 +04:00
Данияр Аглиуллов
8cb71ce5ed Добавление удаленного объекта в форму 2022-10-01 05:26:27 +04:00
Данияр Аглиуллов
86bafe4f71 Удаляемые объекты добавляются в связный список 2022-10-01 04:35:31 +04:00
Данияр Аглиуллов
67fcdb8118 Реализация индексатора по картам и объектам карты 2022-10-01 04:30:10 +04:00
Данияр Аглиуллов
d35ac5bb0a Реализовано добавление карт в форме 2022-10-01 04:23:58 +04:00
Данияр Аглиуллов
c02d68fd6f Исправлена ошибка с перемещением 2022-10-01 03:23:47 +04:00
Данияр Аглиуллов
5aa2c32f02 Удалена ненужная карта 2022-10-01 03:22:42 +04:00
Данияр Аглиуллов
9619209384 Изменения из 3 базовой части 2022-10-01 03:20:21 +04:00
Данияр Аглиуллов
e46d5da591 Переименована форма 2022-10-01 03:08:40 +04:00
Данияр Аглиуллов
6a090aee45 Добавлены ангары, и возможность добавлять к ним самолеты 2022-10-01 02:59:35 +04:00
Данияр Аглиуллов
52c040d55b Добавлена возможность добавлять различные типы двигателя для генерации 2022-09-30 23:31:09 +04:00
Данияр Аглиуллов
7259d846ed Реализована форма генерации самолетов 2022-09-30 23:23:02 +04:00
Данияр Аглиуллов
3d0fd13bec Добавлен класс - генератор самолетов 2022-09-30 21:16:33 +04:00
Данияр Аглиуллов
45dcef4cf9 Изменения из 3 базовой части 2022-09-30 20:20:18 +04:00
Данияр Аглиуллов
f91c1d48c6 Замена комментариев в коде 2022-09-23 12:22:40 +04:00
Данияр Аглиуллов
d5d6d4ecb2 Замена в комментариях автомобиля на самолет 2022-09-23 12:14:29 +04:00
Данияр Аглиуллов
a02a602dce Реализован способ инициализации разных типов двигателей 2022-09-22 07:50:53 +04:00
Данияр Аглиуллов
006cea0aca Добавлены три реализации разных форм двигателя 2022-09-22 07:02:39 +04:00
Данияр Аглиуллов
8d19ef6890 Добавлен интерфейс для класса DrawningAirplaneEngines 2022-09-22 06:08:48 +04:00
Данияр Аглиуллов
cb68550a45 Измения из базовой части 2022-09-22 05:29:34 +04:00
34 changed files with 3602 additions and 50 deletions

View File

@ -0,0 +1,203 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal abstract class AbstractMap : IEquatable<AbstractMap>
{
private IDrawningObject _drawningObject = null;
private Bitmap? _staticBitMap;
protected int[,] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected readonly Random _random = new();
protected readonly int _freeRoad = 0;
protected readonly int _barrier = 1;
public Bitmap CreateMap(int width, int height, IDrawningObject drawningObject)
{
_staticBitMap = null;
_width = width;
_height = height;
_drawningObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
/// <summary>Проверяет наличие непроходимых участков в заданной области</summary>
/// <param name="area">Заданная область</param>
/// <param name="iBarrier">i-ый индекс первого барьера, который был найден в области</param>
/// <param name="jBarrier">j-ый индекс первого барьера, который был найден в области</param>
/// <returns>Есть ли барьеры</returns>
protected bool BarriersInArea(RectangleF area, ref int iBarrier, ref int jBarrier)
{
if (!(0 < area.Left && area.Right < _width && 0 < area.Top && area.Bottom < _height))
{
return true; // Если область попала за карту, считаем что она столкнулась с барьером
}
int rightArea = (int)Math.Ceiling(area.Right / _size_x);
int bottomArea = (int)Math.Ceiling(area.Bottom / _size_y);
for (int i = (int)(area.Left / _size_x); i < rightArea; i++)
{
for (int j = (int)(area.Top / _size_y); j < bottomArea; j++)
{
if (_map[i, j] == _barrier)
{
iBarrier = i;
jBarrier = j;
return true;
}
}
}
return false;
}
/// <summary>Проверяет наличие непроходимых участков в заданной области</summary>
/// <param name="area">Заданная область</param>
/// <returns>Есть ли барьеры</returns>
protected bool BarriersInArea(RectangleF area)
{
int a = 0, b = 0;
return BarriersInArea(area, ref a, ref b);
}
public Bitmap MoveObject(Direction direction)
{
var rect = _drawningObject.GetCurrentPosition();
var step = _drawningObject.Step;
// Вычисляем области смещения объекта
RectangleF? area = null;
if (direction == Direction.Left)
area = new(rect.Left - step, rect.Top, step, rect.Height);
else if (direction == Direction.Right)
area = new(rect.Right, rect.Top, step, rect.Height);
else if (direction == Direction.Up)
area = new(rect.Left, rect.Top - step, rect.Width, step);
else if (direction == Direction.Down)
area = new(rect.Left, rect.Bottom, rect.Width, step);
if (area.HasValue && !BarriersInArea(area.Value))
{
_drawningObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private bool SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.Next(0, 10);
int y = _random.Next(0, 10);
_drawningObject.SetObject(x, y, _width, _height);
// Если натыкаемся на барьер помещаем левый верхний угол чуть ниже этого барьера
// если при этом выходим за карту, пермещаем правый нижный угол чуть выше этого барьера
// если объект выходит за карту, генирируем новые координаты рандомно
int currI = 0, currJ = 0;
var areaObject = _drawningObject.GetCurrentPosition();
int cntOut = 10000; // Количество итераций до выхода из цикла
while (BarriersInArea(areaObject, ref currI, ref currJ) && --cntOut >= 0)
{
if ((currJ + 1) * _size_y + areaObject.Height <= _height)
{
areaObject.Location = new PointF((currI + 1) * _size_x, (currJ + 1) * _size_y);
}
else if ((currI - 1) * _size_x - areaObject.Width >= 0)
{
areaObject = new((currI - 1) * _size_x - areaObject.Width, (currJ - 1) * _size_y - areaObject.Height, areaObject.Width, areaObject.Height);
}
else
{
areaObject.Location = new PointF(_random.Next(0, _width - (int)areaObject.Width),
_random.Next(0, _height - (int)areaObject.Height));
}
}
_drawningObject.SetObject((int)areaObject.X, (int)areaObject.Y, _width, _height);
return cntOut >= 0;
}
/// <summary>
/// Заполняет BitMap для отрисовки статичных объектов. Выполняется один раз при создании карты
/// </summary>
private void DrawMap()
{
if (_staticBitMap != null) return;
_staticBitMap = new(_width, _height);
Graphics gr = Graphics.FromImage(_staticBitMap);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
if (_map[i, j] == _freeRoad)
{
DrawRoadPart(gr, i, j);
}
else if (_map[i, j] == _barrier)
{
DrawBarrierPart(gr, i, j);
}
}
}
}
private Bitmap DrawMapWithObject()
{
Bitmap bmp = new(_width, _height);
if (_drawningObject == null || _map == null)
{
return bmp;
}
Graphics gr = Graphics.FromImage(bmp);
if (_staticBitMap == null)
DrawMap();
if (_staticBitMap != null)
gr.DrawImage(_staticBitMap, 0, 0);
_drawningObject.DrawObject(gr);
return bmp;
}
/// <summary>
/// Генерация карты. При перегрузки определить поля _map, _size_x, _size_y
/// </summary>
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics g, int i, int j);
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
public bool Equals(AbstractMap? other)
{
if (other == null ||
_map != other._map ||
_width != other._width ||
_size_x != other._size_x ||
_size_y != other._size_y ||
_height != other._height ||
GetType() != other.GetType() ||
_map.GetLength(0) != other._map.GetLength(0) ||
_map.GetLength(1) != other._map.GetLength(1))
{
return false;
}
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i, j] != other._map[i, j])
{
return false;
}
}
}
return true;
}
}
}

View File

@ -8,4 +8,29 @@
<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="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.2" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Expressions" Version="3.4.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Filters.Expressions" Version="2.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Settings.Delegates" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class AirplaneArrowEngines : DrawningAirplaneEngines
{
protected override void DrawEngine(Graphics g, Color colorAirplane, RectangleF rectAroundEngine)
{
var x = rectAroundEngine.X + rectAroundEngine.Width / 4;
g.FillPolygon(new SolidBrush(colorAirplane), new PointF[]
{
new PointF(rectAroundEngine.Left, rectAroundEngine.Top + rectAroundEngine.Height / 2),
new PointF(x, rectAroundEngine.Top),
new PointF(x, rectAroundEngine.Bottom),
});
int margin = 2;
g.FillRectangle(new SolidBrush(colorAirplane),
x , rectAroundEngine.Top + margin,
rectAroundEngine.Right - x, rectAroundEngine.Height - margin * 2);
}
}
}

View File

@ -0,0 +1,33 @@
namespace AirBomber
{
internal class AirplaneCompareByColor : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
var xAirplane = (DrawningAirplane?)(x as DrawningObject);
var yAirplane = (DrawningAirplane?)(y as DrawningObject);
if (xAirplane == yAirplane)
{
return 0;
}
if (xAirplane == null)
{
return 1;
}
if (yAirplane == null)
{
return -1;
}
var xEntity = xAirplane.Airplane;
var yEntity = yAirplane.Airplane;
var colorWeight = xEntity.BodyColor.ToArgb().CompareTo(yEntity.BodyColor.ToArgb());
if (colorWeight != 0 ||
xEntity is not EntityAirBomber xEntityAirBomber ||
yEntity is not EntityAirBomber yEntityAirBomber)
{
return colorWeight;
}
return xEntityAirBomber.DopColor.ToArgb().CompareTo(yEntityAirBomber.DopColor.ToArgb());
}
}
}

View File

@ -0,0 +1,37 @@
namespace AirBomber
{
internal class AirplaneCompareByType : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
var xAirplane = (DrawningAirplane?)(x as DrawningObject);
var yAirplane = (DrawningAirplane?)(y as DrawningObject);
if (xAirplane == yAirplane)
{
return 0;
}
if (xAirplane == null)
{
return 1;
}
if (yAirplane == null)
{
return -1;
}
if (xAirplane.GetType().Name != yAirplane.GetType().Name)
{
if (xAirplane.Airplane.GetType() == typeof(DrawningAirplane))
{
return -1;
}
return 1;
}
var speedCompare = xAirplane.Airplane.Speed.CompareTo(yAirplane.Airplane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xAirplane.Airplane.Weight.CompareTo(yAirplane.Airplane.Weight);
}
}
}

View File

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

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class AirplaneRectEngines : DrawningAirplaneEngines
{
protected override void DrawEngine(Graphics g, Color colorAirplane, RectangleF rectAroundEngine)
{
g.FillRectangle(new SolidBrush(colorAirplane), rectAroundEngine);
g.FillRectangle(new SolidBrush(Color.Black),
rectAroundEngine.Left, rectAroundEngine.Top, rectAroundEngine.Width / 4, rectAroundEngine.Height);
}
}
}

View File

@ -3,8 +3,9 @@
/// <summary>
/// Направление перемещения
/// </summary>
internal enum Direction
public enum Direction
{
None = 0,
Up = 1,
Down = 2,
Left = 3,

View File

@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class DrawningAirBomber : DrawningAirplane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет обшивки</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="hasBombs">Признак наличия бомб</param>
/// <param name="hasFuelTanks">Признак наличия топливных баков</param>
/// <param name="typeAirplaneEngines">Какой будет двигатель самолета. null - двигатели отсутствуют</param>
public DrawningAirBomber(int speed, float weight, Color bodyColor, Color dopColor, bool hasBombs, bool hasFuelTanks, IAirplaneEngines? typeAirplaneEngines = null)
: base(speed, weight, bodyColor, 95, 110, typeAirplaneEngines)
{
Airplane = new EntityAirBomber(speed, weight, bodyColor, dopColor, hasBombs, hasFuelTanks);
}
/// <summary>
/// Получения копии текущего объекта. Для перемены свойств изменить необязательные аргументы нужным значением
/// </summary>
/// <param name="speed">The speed.</param>
/// <param name="weight">The weight.</param>
/// <param name="bodyColor">Color of the body.</param>
/// <returns>Копию или Измененную копию текущего объекта</returns>
public DrawningAirBomber Copy(int? speed = null, float? weight = null, Color? bodyColor = null,
Color? dopColor = null, bool? hasBombs = null, bool? hasFuelTanks = null, IAirplaneEngines? typeAirplaneEngines = null)
{
var e = (EntityAirBomber)Airplane;
var res = new DrawningAirBomber(speed ?? e.Speed, weight ?? e.Weight, bodyColor ?? e.BodyColor, dopColor ?? e.DopColor, hasBombs ?? e.HasBombs, hasFuelTanks ?? e.HasFuelTanks);
res.DrawningEngines = typeAirplaneEngines ?? DrawningEngines;
return res;
}
public override void DrawTransport(Graphics g)
{
if (Airplane is not EntityAirBomber airBomber)
{
return;
}
var x = _startPosX;
var y = _startPosY;
var w = _airplaneWidth;
var h = _airplaneHeight;
Brush brush = new SolidBrush(airBomber.DopColor);
if (airBomber.HasBombs) // Бомбы снизу рисуются сначала
{
DrawBomb(g, airBomber.DopColor, new RectangleF(x + w / 2 - 15, y + h / 2 - 19, 23, 10));
DrawBomb(g, airBomber.DopColor, new RectangleF(x + w / 2 - 15, y + h / 2 + 9, 23, 10));
}
base.DrawTransport(g);
if (airBomber.HasFuelTanks)
{
g.FillEllipse(brush, new RectangleF(x + w / 4, y + h / 2 - 6, w / 2.5f, 12));
}
}
private void DrawBomb(Graphics g, Color colorBomb, RectangleF r)
{
Pen pen = new(colorBomb);
pen.Width = r.Height / 3;
var widthTail = r.Width / 6;
g.FillEllipse(new SolidBrush(colorBomb), r.X, r.Y, r.Width - widthTail, r.Height); // Основание бомбы
// Хвост бомбы
var baseTail = new PointF(r.Right - widthTail, r.Y + r.Height / 2);
g.DrawLine(pen, baseTail, new PointF(r.Right, r.Top));
g.DrawLine(pen, baseTail, new PointF(r.Right, r.Bottom));
}
/// <summary>
/// Возвращает итератор со свойствами самолета в порядке:
/// Скорость -> Вес -> Цвет корпуса -> Тип двигателя, либо null если их нет -> Количество двигателей -> Дополнительный цвет -> Наличие бомб -> Наличие топливных баков
/// </summary>
public override IEnumerator<object> GetEnumerator()
{
IEnumerator<object> enumBase = base.GetEnumerator();
while (enumBase.MoveNext())
{
yield return enumBase.Current;
}
var entity = (EntityAirBomber)Airplane;
yield return entity.DopColor;
yield return entity.HasBombs;
yield return entity.HasFuelTanks;
yield break;
}
}
}

View File

@ -1,52 +1,94 @@
namespace AirBomber
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections;
namespace AirBomber
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
internal class DrawningAirplane
public class DrawningAirplane : IEnumerator<object>, IEnumerable<object>
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirplane Airplane { get; private set; }
public EntityAirplane Airplane { get; protected set; }
public IAirplaneEngines? DrawningEngines { get; protected set; }
private IEnumerator<object>? _machineStateEnum = null;
public object Current => _machineStateEnum?.Current;
public DrawningAirplaneEngines DrawningEngines { get; private set; }
/// <summary>
/// Левая координата отрисовки самолета
/// </summary>
private float _startPosX;
protected float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки самолета
/// </summary>
private float _startPosY;
protected float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private int? _pictureWidth = null;
protected int? _pictureWidth = null;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private int? _pictureHeight = null;
protected int? _pictureHeight = null;
/// <summary>
/// Ширина отрисовки самолета
/// </summary>
private readonly int _airplaneWidth = 110;
protected readonly int _airplaneWidth = 80;
/// <summary>
/// Высота отрисовки самолета
/// </summary>
private readonly int _airplaneHeight = 140;
protected readonly int _airplaneHeight = 90;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет обшивки</param>
public void Init(int speed, float weight, Color bodyColor)
/// <param name="typeAirplaneEngines">Какой будет двигатель самолета. null - двигатели отсутствуют</param>
public DrawningAirplane(int speed, float weight, Color bodyColor, IAirplaneEngines? typeAirplaneEngines = null)
{
Airplane = new EntityAirplane();
Airplane.Init(speed, weight, bodyColor);
DrawningEngines = new();
DrawningEngines.CountEngines = 6;
Airplane = new EntityAirplane(speed, weight, bodyColor);
DrawningEngines = typeAirplaneEngines;
}
public DrawningAirplane(EntityAirplane entityAirplane, IAirplaneEngines? typeAirplaneEngines = null)
{
Airplane = entityAirplane;
DrawningEngines = typeAirplaneEngines;
}
/// <summary>
/// Получения копии текущего объекта. Для перемены свойств изменить необязательные аргументы нужным значением
/// </summary>
/// <param name="speed">The speed.</param>
/// <param name="weight">The weight.</param>
/// <param name="bodyColor">Color of the body.</param>
/// <returns>Копию или Измененную копию текущего объекта</returns>
public DrawningAirplane Copy(int? speed = null, float? weight = null, Color? bodyColor = null, IAirplaneEngines? typeAirplaneEngines = null)
{
var res = new DrawningAirplane(speed ?? Airplane.Speed, weight ?? Airplane.Weight, bodyColor ?? Airplane.BodyColor);
res.DrawningEngines = typeAirplaneEngines ?? DrawningEngines;
return res;
}
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет обшивки</param>
/// <param name="airplaneWidth">Ширина отрисовки самолета</param>
/// <param name="airplaneHeight">Высота отрисовки самолета</param>
/// <param name="typeAirplaneEngines">Какой будет двигатель самолета. null - двигатели отсутствуют</param>
protected DrawningAirplane(int speed, float weight, Color bodyColor, int airplaneWidth, int airplaneHeight, IAirplaneEngines? typeAirplaneEngines) :
this(speed, weight, bodyColor, typeAirplaneEngines)
{
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
}
/// <summary>
/// Установка позиции самолета
@ -63,7 +105,7 @@
_pictureHeight = height;
// Проверка на нахождение предмета полностью в границах окна
if (width <= _airplaneWidth || height <= _airplaneHeight
|| _startPosX < 0 || _startPosX + _airplaneWidth > width ||
|| _startPosX < 0 || _startPosX + _airplaneWidth > width ||
_startPosY < 0 || _startPosY + _airplaneHeight > height)
{
_pictureWidth = null;
@ -116,7 +158,7 @@
/// Отрисовка самолета
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0
|| !_pictureHeight.HasValue || !_pictureWidth.HasValue)
@ -129,14 +171,14 @@
var h = _airplaneHeight;
SolidBrush BodyColorBrush = new(Airplane.BodyColor);
// Треугольник самолета
g.FillPolygon(BodyColorBrush, new PointF[] {
g.FillPolygon(BodyColorBrush, new PointF[] {
new PointF(x , y + h / 2),
new PointF(x + 15, y + h / 2 - 7),
new PointF(x + 15, y + h / 2 + 8),
});
// Тело самолета
g.FillRectangle(BodyColorBrush, x + 15, y + h / 2 - 7, w - 35, 15);
DrawWing(g, BodyColorBrush, new PointF(x + w / 2 - 20, y + h / 2 - 7), new PointF(x + w / 2, y + h / 2 - 7), true , h / 2 - 7);
DrawWing(g, BodyColorBrush, new PointF(x + w / 2 - 20, y + h / 2 - 7), new PointF(x + w / 2, y + h / 2 - 7), true, h / 2 - 7);
DrawWing(g, BodyColorBrush, new PointF(x + w / 2 - 20, y + h / 2 + 7), new PointF(x + w / 2, y + h / 2 + 7), false, h / 2 - 7);
// Линия примыкающая к хвосту слева
@ -156,7 +198,7 @@
// Конец хвоста
g.FillRectangle(BodyColorBrush, x + w - 5, y + 15, 5, h - 30);
// Двигатели
DrawningEngines.DrawEngines(g, Airplane.BodyColor, x + w / 2 - 20, y + h, y, 15);
DrawningEngines?.DrawEngines(g, Airplane.BodyColor, x + w / 2 - 20, y + h, y, 15);
}
@ -198,5 +240,43 @@
_startPosY = _pictureHeight.Value - _airplaneHeight;
}
}
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public RectangleF GetCurrentPosition()
{
return new(_startPosX, _startPosY, _airplaneWidth, _airplaneHeight);
}
public bool MoveNext()
{
if (_machineStateEnum == null)
{
_machineStateEnum = GetEnumerator();
}
return _machineStateEnum.MoveNext();
}
public void Reset() => throw new NotSupportedException();
public void Dispose() => GC.SuppressFinalize(this);
/// <summary>
/// Возвращает итератор со свойствами самолета в порядке:
/// Скорость -> Вес -> Цвет корпуса -> Тип двигателя, либо null если их нет -> Количество двигателей
/// </summary>
virtual public IEnumerator<object> GetEnumerator()
{
yield return Airplane.Speed;
yield return Airplane.Weight;
yield return Airplane.BodyColor;
yield return DrawningEngines;
yield return DrawningEngines?.CountEngines ?? 0;
yield break;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}

View File

@ -9,13 +9,11 @@ namespace AirBomber
/// <summary>
/// Класс-дополнение к самолету отвечающий за число двигателей и их отрисовку
/// </summary>
internal class DrawningAirplaneEngines
internal class DrawningAirplaneEngines : IAirplaneEngines
{
/// <summary>Приватное поле содержащие текущее количество двигателей самолета</summary>
private CountEngines _countEngines;
/// <summary>Получение действительного количества двигателей или установка поддерживаемого числа двигателей</summary>
/// <value>The count engines.</value>
public int CountEngines
{
get => (int)_countEngines;
@ -27,14 +25,6 @@ namespace AirBomber
}
}
/// <summary>Отрисовывает все двигатели на обеих крыльях</summary>
/// <param name="g">The g.</param>
/// <param name="colorEngine">Цвет двигателей.</param>
/// <param name="wingPosX">Позиция крыльев по x. В этой координате будут центры двигателей</param>
/// <param name="leftWingY">Крайняя левая позиция левого крыла по y</param>
/// <param name="rightWingY">Крайняя правая позиция правого крыла по y</param>
/// <param name="widthBodyAirplane">Ширина тела самолета, или расстояние между крыльями.</param>
public void DrawEngines(Graphics g, Color colorEngine, float wingPosX, float leftWingY, float rightWingY, int widthBodyAirplane)
{
float distanceBetweenEngines = (leftWingY - rightWingY - widthBodyAirplane) / 8.0f;
@ -47,7 +37,7 @@ namespace AirBomber
}
}
private void DrawEngine(Graphics g, Color colorAirplane, RectangleF rectAroundEngine)
protected virtual void DrawEngine(Graphics g, Color colorAirplane, RectangleF rectAroundEngine)
{
g.FillEllipse(new SolidBrush(colorAirplane), rectAroundEngine);
g.FillEllipse(new SolidBrush(Color.Black),

View File

@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
public class DrawningObject : IDrawningObject
{
private DrawningAirplane _airplane;
public DrawningObject(DrawningAirplane airplane)
{
_airplane = airplane;
}
public float Step => _airplane?.Airplane?.Step ?? 0;
public RectangleF GetCurrentPosition()
{
return _airplane.GetCurrentPosition();
}
public void MoveObject(Direction direction)
{
_airplane?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_airplane?.SetPosition(x, y, width, height);
}
public void DrawObject(Graphics g)
{
_airplane.DrawTransport(g);
}
/// <summary>
/// Получения самолета из объекта отрисовки
/// </summary>
/// <param name="drawningObject">The drawning object.</param>
/// <returns></returns>
public static explicit operator DrawningAirplane?(DrawningObject? drawningObject) => drawningObject?._airplane ?? null;
public string GetInfo() => _airplane?.GetDataForSave() ?? string.Empty;
public static IDrawningObject Create(string data) => new DrawningObject(data.CreateDrawningAirplane());
public bool Equals(IDrawningObject? other)
{
if (other is not DrawningObject otherAirplane ||
_airplane.DrawningEngines?.GetType() != otherAirplane._airplane.DrawningEngines?.GetType() ||
_airplane.DrawningEngines?.CountEngines != otherAirplane._airplane.DrawningEngines?.CountEngines)
{
return false;
}
var entity = _airplane.Airplane;
var otherEntity = otherAirplane._airplane.Airplane;
if (entity.GetType() != otherEntity.GetType() ||
entity.Speed != otherEntity.Speed ||
entity.Weight != otherEntity.Weight ||
entity.BodyColor != otherEntity.BodyColor)
{
return false;
}
if (entity is EntityAirBomber entityAirBomber &&
otherEntity is EntityAirBomber otherEntityAirBomber && (
entityAirBomber.HasBombs != otherEntityAirBomber.HasBombs ||
entityAirBomber.DopColor != otherEntityAirBomber.DopColor ||
entityAirBomber.HasFuelTanks != otherEntityAirBomber.HasFuelTanks))
{
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
public class EntityAirBomber : EntityAirplane
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; private set; }
/// <summary>
/// Признак наличия бомб
/// </summary>
public bool HasBombs { get; private set; }
/// <summary>
/// Признак наличия топливных баков
/// </summary>
public bool HasFuelTanks { get; private set; }
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет обшивки</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="hasBombs">Признак наличия бомб</param>
/// <param name="hasFuelTanks">Признак наличия топливных баков</param>
public EntityAirBomber(int speed, float weight, Color bodyColor, Color dopColor, bool hasBombs, bool hasFuelTanks) :
base(speed, weight, bodyColor)
{
DopColor = dopColor;
HasBombs = hasBombs;
HasFuelTanks = hasFuelTanks;
}
}
}

View File

@ -3,7 +3,7 @@
/// <summary>
/// Класс-сущность "Самолет"
/// </summary>
internal class EntityAirplane
public class EntityAirplane
{
/// <summary>
/// Скорость
@ -28,7 +28,7 @@
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <returns></returns>
public void Init(int speed, float weight, Color bodyColor)
public EntityAirplane(int speed, float weight, Color bodyColor)
{
Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;

View File

@ -0,0 +1,66 @@
namespace AirBomber
{
/// <summary>
/// Расширение для класса DrawningAirplane
/// </summary>
internal static class ExtentionAirplane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Получение цвета из строки 16-ричных чисел, либо из его имени
/// </summary>
/// <param name="hexOrName"></param>
/// <returns></returns>
private static Color GetColor(string hexOrName)
{
try
{
return Color.FromArgb(Convert.ToInt32(hexOrName, 16));
}
catch (Exception)
{
return Color.FromName(hexOrName);
}
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningAirplane CreateDrawningAirplane(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningAirplane(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), GetColor(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningAirBomber(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), GetColor(strs[2]),
GetColor(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirplane"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningAirplane drawningAirplane)
{
var Airplane = drawningAirplane.Airplane;
var str = $"{Airplane.Speed}{_separatorForObject}{Airplane.Weight}{_separatorForObject}{Airplane.BodyColor.Name}";
if (Airplane is not EntityAirBomber AirBomber)
{
return str;
}
return $"{str}{_separatorForObject}{AirBomber.DopColor.Name}{_separatorForObject}{AirBomber.HasBombs}{_separatorForObject}{AirBomber.HasFuelTanks}";
}
}
}

View File

@ -33,6 +33,7 @@
this.toolStripStatusLabelSpeed = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelWeight = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelBodyColor = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusCountEngines = new System.Windows.Forms.ToolStripStatusLabel();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
@ -40,7 +41,8 @@
this.buttonDown = new System.Windows.Forms.Button();
this.countEngineBox = new System.Windows.Forms.NumericUpDown();
this.labelInformCountEngines = new System.Windows.Forms.Label();
this.toolStripStatusCountEngines = new System.Windows.Forms.ToolStripStatusLabel();
this.comboTypeEngines = new System.Windows.Forms.ComboBox();
this.buttonSelectAirplane = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCar)).BeginInit();
this.statusStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.countEngineBox)).BeginInit();
@ -87,10 +89,16 @@
this.toolStripStatusLabelBodyColor.Size = new System.Drawing.Size(36, 17);
this.toolStripStatusLabelBodyColor.Text = "Цвет:";
//
// toolStripStatusCountEngines
//
this.toolStripStatusCountEngines.Name = "toolStripStatusCountEngines";
this.toolStripStatusCountEngines.Size = new System.Drawing.Size(139, 17);
this.toolStripStatusCountEngines.Text = "Количество двигателей:";
//
// buttonCreate
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(244, 390);
this.buttonCreate.Location = new System.Drawing.Point(372, 390);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(75, 23);
this.buttonCreate.TabIndex = 2;
@ -149,37 +157,57 @@
// countEngineBox
//
this.countEngineBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.countEngineBox.Location = new System.Drawing.Point(142, 390);
this.countEngineBox.Location = new System.Drawing.Point(306, 390);
this.countEngineBox.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.countEngineBox.Name = "countEngineBox";
this.countEngineBox.Size = new System.Drawing.Size(96, 23);
this.countEngineBox.Size = new System.Drawing.Size(60, 23);
this.countEngineBox.TabIndex = 7;
//
// labelInformCountEngines
//
this.labelInformCountEngines.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.labelInformCountEngines.AutoSize = true;
this.labelInformCountEngines.Location = new System.Drawing.Point(0, 394);
this.labelInformCountEngines.Location = new System.Drawing.Point(161, 394);
this.labelInformCountEngines.Name = "labelInformCountEngines";
this.labelInformCountEngines.Size = new System.Drawing.Size(139, 15);
this.labelInformCountEngines.TabIndex = 8;
this.labelInformCountEngines.Text = "Количество двигателей:";
//
// toolStripStatusCountEngines
// comboTypeEngines
//
this.toolStripStatusCountEngines.Name = "toolStripStatusCountEngines";
this.toolStripStatusCountEngines.Size = new System.Drawing.Size(139, 17);
this.toolStripStatusCountEngines.Text = "Количество двигателей:";
this.comboTypeEngines.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.comboTypeEngines.FormattingEnabled = true;
this.comboTypeEngines.Items.AddRange(new object[] {
"Закругленный",
"Квадратный",
"Стрелка"});
this.comboTypeEngines.Location = new System.Drawing.Point(12, 390);
this.comboTypeEngines.Name = "comboTypeEngines";
this.comboTypeEngines.Size = new System.Drawing.Size(143, 23);
this.comboTypeEngines.TabIndex = 9;
//
// buttonSelectAirplane
//
this.buttonSelectAirplane.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonSelectAirplane.Location = new System.Drawing.Point(593, 390);
this.buttonSelectAirplane.Name = "buttonSelectAirplane";
this.buttonSelectAirplane.Size = new System.Drawing.Size(75, 23);
this.buttonSelectAirplane.TabIndex = 10;
this.buttonSelectAirplane.Text = "Выбрать";
this.buttonSelectAirplane.UseVisualStyleBackColor = true;
this.buttonSelectAirplane.Click += new System.EventHandler(this.buttonSelectAirplane_Click);
//
// FormAirBomber
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonSelectAirplane);
this.Controls.Add(this.comboTypeEngines);
this.Controls.Add(this.labelInformCountEngines);
this.Controls.Add(this.countEngineBox);
this.Controls.Add(this.buttonDown);
@ -215,5 +243,7 @@
private NumericUpDown countEngineBox;
private Label labelInformCountEngines;
private ToolStripStatusLabel toolStripStatusCountEngines;
private ComboBox comboTypeEngines;
private Button buttonSelectAirplane;
}
}

View File

@ -2,11 +2,19 @@ namespace AirBomber
{
public partial class FormAirBomber : Form
{
private DrawningAirplane _airplane;
public FormAirBomber()
private DrawningAirplane _airplane;
/// <summary>
/// Âûáðàííûé ñàìîëåò
/// </summary>
public DrawningObject SelectedAirplane { get; private set; }
public FormAirBomber(DrawningAirplane? airplane = null)
{
_airplane = airplane;
InitializeComponent();
Draw();
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû
@ -16,6 +24,7 @@ namespace AirBomber
Bitmap bmp = new(pictureBoxCar.Width, pictureBoxCar.Height);
Graphics gr = Graphics.FromImage(bmp);
_airplane?.DrawTransport(gr);
pictureBoxCar.Image = bmp;
}
/// <summary>
@ -25,9 +34,27 @@ namespace AirBomber
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
{
IAirplaneEngines? typeAirplaneEngines = null;
switch (comboTypeEngines.Text)
{
case "Êâàäðàòíûé":
typeAirplaneEngines = new AirplaneRectEngines();
break;
case "Ñòðåëêà":
typeAirplaneEngines = new AirplaneArrowEngines();
break;
default:
typeAirplaneEngines = new DrawningAirplaneEngines();
break;
}
Random rnd = new();
_airplane = new DrawningAirplane();
_airplane.Init(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_airplane = new DrawningAirplane(rnd.Next(100, 300), rnd.Next(1000, 2000), color, typeAirplaneEngines);
_airplane.DrawningEngines.CountEngines = (int)countEngineBox.Value;
_airplane.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxCar.Width, pictureBoxCar.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_airplane.Airplane.Speed}";
@ -72,5 +99,11 @@ namespace AirBomber
_airplane?.ChangeBorders(pictureBoxCar.Width, pictureBoxCar.Height);
Draw();
}
private void buttonSelectAirplane_Click(object sender, EventArgs e)
{
SelectedAirplane = new(_airplane);
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,488 @@
namespace AirBomber
{
partial class FormAirplaneConfig
{
/// <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.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.TypesOfEngines = new System.Windows.Forms.GroupBox();
this.labelRoundedEngines = new System.Windows.Forms.Label();
this.labelRectEngines = new System.Windows.Forms.Label();
this.labelArrowEngines = new System.Windows.Forms.Label();
this.numericUpDownCountEngines = new System.Windows.Forms.NumericUpDown();
this.labelCountEngines = new System.Windows.Forms.Label();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxHasFuelTanks = new System.Windows.Forms.CheckBox();
this.checkBoxHasBombs = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelSpeed = new System.Windows.Forms.Label();
this.panelObject = new System.Windows.Forms.Panel();
this.labelTypesOfEngines = new System.Windows.Forms.Label();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOk = new System.Windows.Forms.Button();
this.groupBoxConfig.SuspendLayout();
this.TypesOfEngines.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCountEngines)).BeginInit();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.TypesOfEngines);
this.groupBoxConfig.Controls.Add(this.numericUpDownCountEngines);
this.groupBoxConfig.Controls.Add(this.labelCountEngines);
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxHasFuelTanks);
this.groupBoxConfig.Controls.Add(this.checkBoxHasBombs);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.labelWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.labelSpeed);
this.groupBoxConfig.Location = new System.Drawing.Point(12, 12);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(700, 253);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// TypesOfEngines
//
this.TypesOfEngines.Controls.Add(this.labelRoundedEngines);
this.TypesOfEngines.Controls.Add(this.labelRectEngines);
this.TypesOfEngines.Controls.Add(this.labelArrowEngines);
this.TypesOfEngines.Location = new System.Drawing.Point(514, 22);
this.TypesOfEngines.Name = "TypesOfEngines";
this.TypesOfEngines.Size = new System.Drawing.Size(180, 225);
this.TypesOfEngines.TabIndex = 19;
this.TypesOfEngines.TabStop = false;
this.TypesOfEngines.Text = "Типы двигателей";
//
// labelRoundedEngines
//
this.labelRoundedEngines.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelRoundedEngines.Location = new System.Drawing.Point(6, 23);
this.labelRoundedEngines.Name = "labelRoundedEngines";
this.labelRoundedEngines.Size = new System.Drawing.Size(168, 52);
this.labelRoundedEngines.TabIndex = 24;
this.labelRoundedEngines.Text = "Закругленный";
this.labelRoundedEngines.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelRoundedEngines.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelsTypeOfEngines_MouseDown);
//
// labelRectEngines
//
this.labelRectEngines.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelRectEngines.Location = new System.Drawing.Point(6, 96);
this.labelRectEngines.Name = "labelRectEngines";
this.labelRectEngines.Size = new System.Drawing.Size(168, 52);
this.labelRectEngines.TabIndex = 23;
this.labelRectEngines.Text = "Квадратный";
this.labelRectEngines.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelRectEngines.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelsTypeOfEngines_MouseDown);
//
// labelArrowEngines
//
this.labelArrowEngines.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelArrowEngines.Location = new System.Drawing.Point(6, 165);
this.labelArrowEngines.Name = "labelArrowEngines";
this.labelArrowEngines.Size = new System.Drawing.Size(168, 52);
this.labelArrowEngines.TabIndex = 22;
this.labelArrowEngines.Text = "Стрелка";
this.labelArrowEngines.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelArrowEngines.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelsTypeOfEngines_MouseDown);
//
// numericUpDownCountEngines
//
this.numericUpDownCountEngines.Location = new System.Drawing.Point(151, 118);
this.numericUpDownCountEngines.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.numericUpDownCountEngines.Name = "numericUpDownCountEngines";
this.numericUpDownCountEngines.Size = new System.Drawing.Size(79, 23);
this.numericUpDownCountEngines.TabIndex = 18;
this.numericUpDownCountEngines.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// labelCountEngines
//
this.labelCountEngines.AutoSize = true;
this.labelCountEngines.Location = new System.Drawing.Point(6, 120);
this.labelCountEngines.Name = "labelCountEngines";
this.labelCountEngines.Size = new System.Drawing.Size(139, 15);
this.labelCountEngines.TabIndex = 17;
this.labelCountEngines.Text = "Количество двигателей:";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(279, 201);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(212, 38);
this.labelModifiedObject.TabIndex = 16;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(279, 151);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(212, 38);
this.labelSimpleObject.TabIndex = 15;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(267, 22);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(241, 127);
this.groupBoxColors.TabIndex = 14;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(184, 73);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(40, 40);
this.panelPurple.TabIndex = 3;
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(184, 22);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(40, 40);
this.panelYellow.TabIndex = 1;
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(127, 73);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 4;
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(127, 22);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(40, 40);
this.panelBlue.TabIndex = 1;
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(72, 73);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(40, 40);
this.panelGray.TabIndex = 5;
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(72, 22);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
this.panelGreen.TabIndex = 1;
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(15, 73);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(40, 40);
this.panelWhite.TabIndex = 2;
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(15, 22);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 0;
//
// checkBoxHasFuelTanks
//
this.checkBoxHasFuelTanks.AutoSize = true;
this.checkBoxHasFuelTanks.Location = new System.Drawing.Point(22, 201);
this.checkBoxHasFuelTanks.Name = "checkBoxHasFuelTanks";
this.checkBoxHasFuelTanks.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.checkBoxHasFuelTanks.Size = new System.Drawing.Size(222, 19);
this.checkBoxHasFuelTanks.TabIndex = 12;
this.checkBoxHasFuelTanks.Text = "Признак наличия топливных баков";
this.checkBoxHasFuelTanks.UseVisualStyleBackColor = true;
//
// checkBoxHasBombs
//
this.checkBoxHasBombs.AutoSize = true;
this.checkBoxHasBombs.Location = new System.Drawing.Point(22, 162);
this.checkBoxHasBombs.Name = "checkBoxHasBombs";
this.checkBoxHasBombs.Size = new System.Drawing.Size(156, 19);
this.checkBoxHasBombs.TabIndex = 11;
this.checkBoxHasBombs.Text = "Признак наличия бомб";
this.checkBoxHasBombs.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(151, 74);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(79, 23);
this.numericUpDownWeight.TabIndex = 10;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(6, 76);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(29, 15);
this.labelWeight.TabIndex = 9;
this.labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(151, 32);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(79, 23);
this.numericUpDownSpeed.TabIndex = 8;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(6, 34);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(62, 15);
this.labelSpeed.TabIndex = 7;
this.labelSpeed.Text = "Скорость:";
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelTypesOfEngines);
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(718, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(262, 220);
this.panelObject.TabIndex = 2;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelTypesOfEngines
//
this.labelTypesOfEngines.AllowDrop = true;
this.labelTypesOfEngines.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelTypesOfEngines.Location = new System.Drawing.Point(20, 52);
this.labelTypesOfEngines.Name = "labelTypesOfEngines";
this.labelTypesOfEngines.Size = new System.Drawing.Size(225, 32);
this.labelTypesOfEngines.TabIndex = 3;
this.labelTypesOfEngines.Text = "Тип двигателей";
this.labelTypesOfEngines.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelTypesOfEngines.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelTypesOfEngines_DragDrop);
this.labelTypesOfEngines.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelTypesOfEngines_DragEnter);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(141, 9);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(104, 32);
this.labelDopColor.TabIndex = 2;
this.labelDopColor.Text = "Доп. цвет";
this.labelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDopColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
this.labelDopColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(20, 9);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(104, 32);
this.labelBaseColor.TabIndex = 1;
this.labelBaseColor.Text = "Цвет";
this.labelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragDrop);
this.labelBaseColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(20, 89);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(225, 125);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(859, 235);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(104, 30);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(738, 235);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(104, 30);
this.buttonOk.TabIndex = 4;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// FormAirplaneConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(987, 277);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormAirplaneConfig";
this.Text = "Создание объекта";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.TypesOfEngines.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCountEngines)).EndInit();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private CheckBox checkBoxHasFuelTanks;
private CheckBox checkBoxHasBombs;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private Panel panelObject;
private Label labelDopColor;
private Label labelBaseColor;
private PictureBox pictureBoxObject;
private Button buttonCancel;
private Button buttonOk;
private NumericUpDown numericUpDownCountEngines;
private Label labelCountEngines;
private GroupBox TypesOfEngines;
private Label labelTypesOfEngines;
private Label labelRoundedEngines;
private Label labelRectEngines;
private Label labelArrowEngines;
}
}

View File

@ -0,0 +1,228 @@
using System.Drawing;
using System.Xml.Linq;
namespace AirBomber
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormAirplaneConfig : Form
{
/// <summary>
/// Переменная-выбранная самолет
/// </summary>
DrawningAirplane _airplane = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningAirplane> EventAddAirplane;
/// <summary>
/// Конструктор
/// </summary>
public FormAirplaneConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать самолет
/// </summary>
private void DrawAirplane()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_airplane?.SetPosition(5, 5, pictureBoxObject.Width, pictureBoxObject.Height);
_airplane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev"></param>
public void AddEvent(Action<DrawningAirplane> ev)
{
if (EventAddAirplane == null)
{
EventAddAirplane = new(ev);
}
else
{
EventAddAirplane += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_airplane = new DrawningAirplane((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White,
new DrawningAirplaneEngines());
break;
case "labelModifiedObject":
_airplane = new DrawningAirBomber((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxHasBombs.Checked, checkBoxHasFuelTanks.Checked, new DrawningAirplaneEngines());
break;
}
_airplane.DrawningEngines.CountEngines = (int)numericUpDownCountEngines.Value;
DrawAirplane();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Установливает статус перемещаемых данных
/// </summary>
/// <param name="e"></param>
/// <param name="needTypeData">Тип которого должны соответствовать перемещаемые данные</param>
/// <param name="condition">условие на возможность копирования данных</param>
private void setDragEffect(DragEventArgs e, Type needTypeData, bool condition)
{
if (e.Data.GetDataPresent(needTypeData) && condition)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragEnter(object sender, DragEventArgs e) => setDragEffect(e, typeof(Color), _airplane != null);
private void LabelDopColor_DragEnter(object sender, DragEventArgs e) => setDragEffect(e, typeof(Color), _airplane != null && _airplane is DrawningAirBomber);
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
if (_airplane is DrawningAirBomber)
{
_airplane = ((DrawningAirBomber)_airplane).Copy(bodyColor: color);
}
else if (_airplane is DrawningAirplane)
{
_airplane = _airplane.Copy(bodyColor: color);
}
DrawAirplane();
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
var airplane = _airplane as DrawningAirBomber;
if (airplane != null)
{
_airplane = airplane.Copy(dopColor: color);
}
DrawAirplane();
}
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddAirplane?.Invoke(_airplane);
Close();
}
/// <summary>
/// Создание DragAndDrop перемещения по нажатию мыши
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelsTypeOfEngines_MouseDown(object sender, MouseEventArgs e)
{
string text = ((Label)sender)?.Text ?? string.Empty;
IAirplaneEngines typesOfEngines;
switch (text)
{
case "Закругленный":
typesOfEngines = new DrawningAirplaneEngines();
break;
case "Квадратный":
typesOfEngines = new AirplaneRectEngines();
break;
case "Стрелка":
typesOfEngines = new AirplaneArrowEngines();
break;
default:
return;
}
(sender as Label).DoDragDrop(Tuple.Create(typesOfEngines.GetType(), typesOfEngines), DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelTypesOfEngines_DragDrop(object sender, DragEventArgs e)
{
var data = (Tuple<Type, IAirplaneEngines>)e.Data.GetData(typeof(Tuple<Type, IAirplaneEngines>));
var engines = data.Item2;
engines.CountEngines = _airplane.DrawningEngines.CountEngines;
if (_airplane is DrawningAirBomber)
{
_airplane = ((DrawningAirBomber)_airplane).Copy(typeAirplaneEngines: engines);
}
else if (_airplane is DrawningAirplane)
{
_airplane = _airplane.Copy(typeAirplaneEngines: engines);
}
DrawAirplane();
}
private void labelTypesOfEngines_DragEnter(object sender, DragEventArgs e) => setDragEffect(e, typeof(Tuple<Type, IAirplaneEngines>), _airplane != null);
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,529 @@
namespace AirBomber
{
partial class FormMapWithSetAirplanes
{
/// <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.comboTypeEngines = new System.Windows.Forms.ComboBox();
this.groupBoxTools = new System.Windows.Forms.GroupBox();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.buttonSortByType = new System.Windows.Forms.Button();
this.btnAddDeletedObject = new System.Windows.Forms.Button();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.buttonAddMap = new System.Windows.Forms.Button();
this.buttonDeleteMap = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonRemoveAirplane = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonAddAirplane = new System.Windows.Forms.Button();
this.groupBoxGenerate = new System.Windows.Forms.GroupBox();
this.btnAddTypeOfEngines = new System.Windows.Forms.Button();
this.labelSpeed = new System.Windows.Forms.Label();
this.numericSpeed = new System.Windows.Forms.NumericUpDown();
this.buttonAddTypeOfEntity = new System.Windows.Forms.Button();
this.labelWeight = new System.Windows.Forms.Label();
this.numericUpDownEngines = new System.Windows.Forms.NumericUpDown();
this.numericWeight = new System.Windows.Forms.NumericUpDown();
this.labelCountEngines = new System.Windows.Forms.Label();
this.btnGenerateAirplane = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
this.groupBoxGenerate.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownEngines)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// comboTypeEngines
//
this.comboTypeEngines.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.comboTypeEngines.FormattingEnabled = true;
this.comboTypeEngines.Items.AddRange(new object[] {
"Закругленный",
"Квадратный",
"Стрелка"});
this.comboTypeEngines.Location = new System.Drawing.Point(19, 116);
this.comboTypeEngines.Name = "comboTypeEngines";
this.comboTypeEngines.Size = new System.Drawing.Size(175, 23);
this.comboTypeEngines.TabIndex = 9;
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.buttonSortByColor);
this.groupBoxTools.Controls.Add(this.buttonSortByType);
this.groupBoxTools.Controls.Add(this.btnAddDeletedObject);
this.groupBoxTools.Controls.Add(this.groupBoxMaps);
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonRemoveAirplane);
this.groupBoxTools.Controls.Add(this.buttonShowStorage);
this.groupBoxTools.Controls.Add(this.buttonShowOnMap);
this.groupBoxTools.Controls.Add(this.buttonAddAirplane);
this.groupBoxTools.Controls.Add(this.groupBoxGenerate);
this.groupBoxTools.Controls.Add(this.buttonDown);
this.groupBoxTools.Controls.Add(this.buttonRight);
this.groupBoxTools.Controls.Add(this.buttonLeft);
this.groupBoxTools.Controls.Add(this.buttonUp);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(840, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(409, 522);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(223, 413);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(175, 35);
this.buttonSortByColor.TabIndex = 12;
this.buttonSortByColor.Text = "Отсортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(223, 372);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(175, 35);
this.buttonSortByType.TabIndex = 28;
this.buttonSortByType.Text = "Отсортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// btnAddDeletedObject
//
this.btnAddDeletedObject.Location = new System.Drawing.Point(25, 317);
this.btnAddDeletedObject.Name = "btnAddDeletedObject";
this.btnAddDeletedObject.Size = new System.Drawing.Size(175, 45);
this.btnAddDeletedObject.TabIndex = 27;
this.btnAddDeletedObject.Text = "Добавить удаленный самолет";
this.btnAddDeletedObject.UseVisualStyleBackColor = true;
this.btnAddDeletedObject.Click += new System.EventHandler(this.btnAddDeletedObject_Click);
//
// groupBoxMaps
//
this.groupBoxMaps.Controls.Add(this.buttonAddMap);
this.groupBoxMaps.Controls.Add(this.buttonDeleteMap);
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(212, 14);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Size = new System.Drawing.Size(192, 253);
this.groupBoxMaps.TabIndex = 26;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(11, 80);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(175, 47);
this.buttonAddMap.TabIndex = 2;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(11, 218);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(175, 29);
this.buttonDeleteMap.TabIndex = 4;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 15;
this.listBoxMaps.Location = new System.Drawing.Point(11, 133);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(175, 79);
this.listBoxMaps.TabIndex = 3;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(11, 22);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(175, 23);
this.textBoxNewMapName.TabIndex = 0;
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Карта со стенами"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(11, 51);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(175, 23);
this.comboBoxSelectorMap.TabIndex = 0;
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(25, 379);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(175, 23);
this.maskedTextBoxPosition.TabIndex = 22;
this.maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonRemoveAirplane
//
this.buttonRemoveAirplane.Location = new System.Drawing.Point(25, 413);
this.buttonRemoveAirplane.Name = "buttonRemoveAirplane";
this.buttonRemoveAirplane.Size = new System.Drawing.Size(175, 35);
this.buttonRemoveAirplane.TabIndex = 23;
this.buttonRemoveAirplane.Text = "Удалить самолет";
this.buttonRemoveAirplane.UseVisualStyleBackColor = true;
this.buttonRemoveAirplane.Click += new System.EventHandler(this.ButtonRemoveAirplane_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(223, 273);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(175, 35);
this.buttonShowStorage.TabIndex = 24;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(223, 317);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(175, 45);
this.buttonShowOnMap.TabIndex = 25;
this.buttonShowOnMap.Text = "Посмотреть карту";
this.buttonShowOnMap.UseVisualStyleBackColor = true;
this.buttonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonAddAirplane
//
this.buttonAddAirplane.Location = new System.Drawing.Point(23, 273);
this.buttonAddAirplane.Name = "buttonAddAirplane";
this.buttonAddAirplane.Size = new System.Drawing.Size(175, 35);
this.buttonAddAirplane.TabIndex = 21;
this.buttonAddAirplane.Text = "Добавить самолет вручную";
this.buttonAddAirplane.UseVisualStyleBackColor = true;
this.buttonAddAirplane.Click += new System.EventHandler(this.ButtonAddAirplane_Click);
//
// groupBoxGenerate
//
this.groupBoxGenerate.Controls.Add(this.comboTypeEngines);
this.groupBoxGenerate.Controls.Add(this.btnAddTypeOfEngines);
this.groupBoxGenerate.Controls.Add(this.labelSpeed);
this.groupBoxGenerate.Controls.Add(this.numericSpeed);
this.groupBoxGenerate.Controls.Add(this.buttonAddTypeOfEntity);
this.groupBoxGenerate.Controls.Add(this.labelWeight);
this.groupBoxGenerate.Controls.Add(this.numericUpDownEngines);
this.groupBoxGenerate.Controls.Add(this.numericWeight);
this.groupBoxGenerate.Controls.Add(this.labelCountEngines);
this.groupBoxGenerate.Controls.Add(this.btnGenerateAirplane);
this.groupBoxGenerate.Location = new System.Drawing.Point(6, 14);
this.groupBoxGenerate.Name = "groupBoxGenerate";
this.groupBoxGenerate.Size = new System.Drawing.Size(200, 253);
this.groupBoxGenerate.TabIndex = 20;
this.groupBoxGenerate.TabStop = false;
this.groupBoxGenerate.Text = "Генерация";
//
// btnAddTypeOfEngines
//
this.btnAddTypeOfEngines.Location = new System.Drawing.Point(17, 175);
this.btnAddTypeOfEngines.Name = "btnAddTypeOfEngines";
this.btnAddTypeOfEngines.Size = new System.Drawing.Size(175, 43);
this.btnAddTypeOfEngines.TabIndex = 12;
this.btnAddTypeOfEngines.Text = "Добавить тип двигателя и их кол-во для генерации";
this.btnAddTypeOfEngines.UseVisualStyleBackColor = true;
this.btnAddTypeOfEngines.Click += new System.EventHandler(this.btnAddTypeOfEngines_Click);
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(17, 19);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(117, 15);
this.labelSpeed.TabIndex = 19;
this.labelSpeed.Text = "Скорость самолета:";
//
// numericSpeed
//
this.numericSpeed.Location = new System.Drawing.Point(136, 17);
this.numericSpeed.Name = "numericSpeed";
this.numericSpeed.Size = new System.Drawing.Size(56, 23);
this.numericSpeed.TabIndex = 18;
//
// buttonAddTypeOfEntity
//
this.buttonAddTypeOfEntity.Location = new System.Drawing.Point(17, 71);
this.buttonAddTypeOfEntity.Name = "buttonAddTypeOfEntity";
this.buttonAddTypeOfEntity.Size = new System.Drawing.Size(175, 39);
this.buttonAddTypeOfEntity.TabIndex = 11;
this.buttonAddTypeOfEntity.Text = "Добавить свойства для генерации";
this.buttonAddTypeOfEntity.UseVisualStyleBackColor = true;
this.buttonAddTypeOfEntity.Click += new System.EventHandler(this.buttonAddTypeOfEntity_Click);
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(17, 44);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(100, 15);
this.labelWeight.TabIndex = 17;
this.labelWeight.Text = "Масса самолета:";
//
// numericUpDownEngines
//
this.numericUpDownEngines.Location = new System.Drawing.Point(136, 146);
this.numericUpDownEngines.Name = "numericUpDownEngines";
this.numericUpDownEngines.Size = new System.Drawing.Size(56, 23);
this.numericUpDownEngines.TabIndex = 13;
//
// numericWeight
//
this.numericWeight.Location = new System.Drawing.Point(136, 42);
this.numericWeight.Name = "numericWeight";
this.numericWeight.Size = new System.Drawing.Size(56, 23);
this.numericWeight.TabIndex = 16;
//
// labelCountEngines
//
this.labelCountEngines.AutoSize = true;
this.labelCountEngines.Location = new System.Drawing.Point(17, 148);
this.labelCountEngines.Name = "labelCountEngines";
this.labelCountEngines.Size = new System.Drawing.Size(113, 15);
this.labelCountEngines.TabIndex = 14;
this.labelCountEngines.Text = "Кол-во двигателей:";
//
// btnGenerateAirplane
//
this.btnGenerateAirplane.Location = new System.Drawing.Point(17, 224);
this.btnGenerateAirplane.Name = "btnGenerateAirplane";
this.btnGenerateAirplane.Size = new System.Drawing.Size(175, 23);
this.btnGenerateAirplane.TabIndex = 15;
this.btnGenerateAirplane.Text = "Сгенерировать самолет";
this.btnGenerateAirplane.UseVisualStyleBackColor = true;
this.btnGenerateAirplane.Click += new System.EventHandler(this.btnGenerateAirplane_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AirBomber.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(57, 486);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 10;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AirBomber.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(93, 486);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 9;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AirBomber.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(21, 486);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 8;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AirBomber.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(57, 450);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 7;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(840, 522);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1249, 24);
this.menuStrip.TabIndex = 2;
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.SaveMapToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(280, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// SaveMapToolStripMenuItem
//
this.SaveMapToolStripMenuItem.Name = "SaveMapToolStripMenuItem";
this.SaveMapToolStripMenuItem.Size = new System.Drawing.Size(280, 22);
this.SaveMapToolStripMenuItem.Text = "Сохранение Выбранного хранилища";
this.SaveMapToolStripMenuItem.Click += new System.EventHandler(this.SaveMapToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(280, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetAirplanes
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1249, 546);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetAirplanes";
this.Text = "Генератор самолетов";
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
this.groupBoxGenerate.ResumeLayout(false);
this.groupBoxGenerate.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownEngines)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComboBox comboTypeEngines;
private GroupBox groupBoxTools;
private PictureBox pictureBox;
private ComboBox comboBoxSelectorMap;
private Button buttonDown;
private Button buttonRight;
private Button buttonLeft;
private Button buttonUp;
private Button btnAddTypeOfEngines;
private Button buttonAddTypeOfEntity;
private Label labelCountEngines;
private NumericUpDown numericUpDownEngines;
private Button btnGenerateAirplane;
private Label labelSpeed;
private NumericUpDown numericSpeed;
private Label labelWeight;
private NumericUpDown numericWeight;
private GroupBox groupBoxGenerate;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonRemoveAirplane;
private Button buttonShowStorage;
private Button buttonShowOnMap;
private Button buttonAddAirplane;
private GroupBox groupBoxMaps;
private Button buttonAddMap;
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private TextBox textBoxNewMapName;
private Button btnAddDeletedObject;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private ToolStripMenuItem SaveMapToolStripMenuItem;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -0,0 +1,428 @@
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace AirBomber
{
public partial class FormMapWithSetAirplanes : Form
{
/// <summary>
/// Словарь для выпадающего списка
/// </summary>
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Карта со стенами", new WallMap() },
};
/// <summary>
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
private GeneratorAirplane<EntityAirplane, IAirplaneEngines> _generatorAirplane;
/// <summary>
/// Все объекты удаленные с каких либо карт
/// </summary>
private LinkedList<IDrawningObject> _deletedObjects;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetAirplanes(ILogger<FormMapWithSetAirplanes> logger)
{
InitializeComponent();
_generatorAirplane = new(100, 100);
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
_logger = logger;
_deletedObjects = new();
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
private string NameMap => listBoxMaps.SelectedItem?.ToString() ?? string.Empty;
/// <summary>
/// Заполнение listBoxMaps
/// </summary>
private void ReloadMaps()
{
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for (int i = 0; i < _mapsCollection.Keys.Count; i++)
{
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
}
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{
listBoxMaps.SelectedIndex = 0;
}
else if (listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
listBoxMaps.SelectedIndex = index;
}
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[NameMap].ShowSet();
_logger.LogInformation("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(NameMap);
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
/// <summary>Добавление самолета на карту</summary>
/// <param name="airplane">Самолет</param>
/// <param name="text">Текст MessageBox если самолета нет</param>
/// <param name="caption">Заголовок MessageBox если самолета нет</param>
private void AddAirplaneInMap(DrawningObject? airplane, string? text = null, string? caption = null)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
}
else if (airplane == null)
{
MessageBox.Show(text, caption);
}
else if ((_mapsCollection[NameMap] + airplane) == -1)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
else
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[NameMap].ShowSet();
_logger.LogInformation("Добавлен объект {@Airplane}", (DrawningAirplane?)airplane);
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException ex)
{
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Airplane}", ex.Message, (DrawningAirplane?)airplane);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
{
case "buttonUp":
dir = Direction.Up;
break;
case "buttonDown":
dir = Direction.Down;
break;
case "buttonLeft":
dir = Direction.Left;
break;
case "buttonRight":
dir = Direction.Right;
break;
}
pictureBox.Image = _mapsCollection[NameMap].MoveObject(dir);
}
/// <summary>
/// Добавления типа двигателя и его количество в генератор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddTypeOfEntity_Click(object sender, EventArgs e)
{
Random rnd = new();
Color colorBody = Color.FromArgb(rnd.Next() % 256, rnd.Next() % 256, rnd.Next() % 256);
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
colorBody = dialog.Color;
}
var entity = new EntityAirplane((int)numericSpeed.Value, (int)numericWeight.Value, colorBody);
_generatorAirplane.AddTypeOfEntity(entity);
MessageBox.Show($"Добавлены свойства самолета:\n" +
$"Вес: {entity.Weight}\n" +
$"Скорость: {entity.Speed}\n" +
$"Цвет: {colorBody.Name}",
"Успешно добавлены свойства");
}
/// <summary>
/// Генерация самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGenerateAirplane_Click(object sender, EventArgs e)
{
AddAirplaneInMap(_generatorAirplane.Generate(),
"Не удалось сгенерировать самолет. Добавьте хотя бы по одному количество двигателей и свойств для генерации",
"Генерация самолета"
);
}
/// <summary>
/// Добавления сущности в генератор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAddTypeOfEngines_Click(object sender, EventArgs e)
{
IAirplaneEngines? typeAirplaneEngines = null;
switch (comboTypeEngines.Text)
{
case "Квадратный":
typeAirplaneEngines = new AirplaneRectEngines();
break;
case "Стрелка":
typeAirplaneEngines = new AirplaneArrowEngines();
break;
default:
typeAirplaneEngines = new DrawningAirplaneEngines();
break;
}
typeAirplaneEngines.CountEngines = (int)numericUpDownEngines.Value;
_generatorAirplane.AddTypeOfEngines(typeAirplaneEngines);
}
/// <summary>
/// Вызов формы для создания самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAirplane_Click(object sender, EventArgs e)
{
FormAirplaneConfig formAirplane = new();
formAirplane.AddEvent(new(AddAirplane));
formAirplane.Show();
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="airplane"></param>
private void AddAirplane(DrawningAirplane airplane)
{
AddAirplaneInMap(new(airplane));
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirplane_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1 || string.IsNullOrEmpty(maskedTextBoxPosition.Text)
|| MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
var deletedObject = _mapsCollection[NameMap] - pos;
if (deletedObject != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удален объект {@Airplane}", deletedObject);
_deletedObjects.AddLast(deletedObject);
pictureBox.Image = _mapsCollection[NameMap].ShowSet();
}
else
{
_logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (AirplaneNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapsCollection[NameMap].ShowSet();
}
/// <summary>
/// Вывод карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapsCollection[NameMap].ShowOnMap();
}
private void btnAddDeletedObject_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (_deletedObjects.Count == 0)
{
MessageBox.Show("Нет удаленных объектов", "Добавление удаленного объекта");
return;
}
FormAirBomber form = new((DrawningAirplane)_deletedObjects.First());
_deletedObjects.RemoveFirst();
if (form.ShowDialog() == DialogResult.OK)
{
AddAirplaneInMap(form.SelectedAirplane);
}
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
catch (Exception ex)
{
_logger.LogError("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
MessageBox.Show("Не удалось открыть", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void SaveMapToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog.FileName = NameMap;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName);
ReloadMaps();
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}
private void maskedTextBoxPosition_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void SortBy(IComparer<IDrawningObject> comparer)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(comparer);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonSortByType_Click (object sender, EventArgs e) => SortBy(new AirplaneCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => SortBy(new AirplaneCompareByColor());
}
}

View File

@ -0,0 +1,69 @@
<root>
<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>125, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>258, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
/// <summary>
/// Класс, который генирирует самолет из разнообразного количества сущностей и типа двигателей
/// </summary>
/// <typeparam name="T">Класс Сущность самолет</typeparam>
/// <typeparam name="U">Класс двигателя самолета</typeparam>
internal class GeneratorAirplane<T, U>
where T : EntityAirplane
where U : class, IAirplaneEngines
{
private readonly T[] typesOfEntity;
private readonly U[] typesOfEngines;
public int NumTypesOfEntity { get; private set; }
public int NumTypesOfEngines { get; private set; }
public GeneratorAirplane(int countTypesOfEntity, int countTypesOfEngines)
{
typesOfEntity = new T[countTypesOfEntity];
typesOfEngines = new U[countTypesOfEngines];
}
/// <summary>
/// Добавляет возможный тип сущности при генерации самолета
/// </summary>
/// <param name="type">тип</param>
/// <returns>Успешно ли проведена операция</returns>
public virtual bool AddTypeOfEntity(T type)
{
if (NumTypesOfEntity >= typesOfEntity.Length)
{
return false;
}
typesOfEntity[NumTypesOfEntity++] = type;
return true;
}
/// <summary>
/// Добавляет возможный тип двигателей при генерации самолета
/// </summary>
/// <param name="type">тип</param>
/// <returns>Успешно ли проведена операция</returns>
public virtual bool AddTypeOfEngines(U type)
{
if (NumTypesOfEngines >= typesOfEngines.Length)
{
return false;
}
typesOfEngines[NumTypesOfEngines++] = type;
return true;
}
/// <summary>
/// Генерирует объект отрисовки
/// </summary>
/// <returns>Возвращает объект отрисовки, либо null, если не были добавлены типы для выборки</returns>
public DrawningObject? Generate()
{
if (NumTypesOfEngines == 0 || NumTypesOfEntity == 0)
{
return null;
}
var rnd = new Random();
var airplane = new DrawningAirplane(typesOfEntity[rnd.Next() % NumTypesOfEntity], typesOfEngines[rnd.Next() % NumTypesOfEngines]);
return new DrawningObject(airplane);
}
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
public interface IAirplaneEngines
{
/// <summary>Получение действительного количества двигателей или установка поддерживаемого числа двигателей</summary>
/// <value>The count engines.</value>
int CountEngines { get; set; }
/// <summary>Отрисовывает все двигатели на обеих крыльях</summary>
/// <param name="g">The g.</param>
/// <param name="colorEngine">Цвет двигателей.</param>
/// <param name="wingPosX">Позиция крыльев по x. В этой координате будут центры двигателей</param>
/// <param name="leftWingY">Крайняя левая позиция левого крыла по y</param>
/// <param name="rightWingY">Крайняя правая позиция правого крыла по y</param>
/// <param name="widthBodyAirplane">Ширина тела самолета, или расстояние между крыльями.</param>
void DrawEngines(Graphics g, Color colorEngine, float wingPosX, float leftWingY, float rightWingY, int widthBodyAirplane);
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
public interface IDrawningObject : IEquatable<IDrawningObject>
{
/// <summary>
/// Шаг перемещения объекта
/// </summary>
public float Step { get; }
/// <summary>
/// Установка позиции объекта
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина полотна</param>
/// <param name="height">Высота полотна</param>
void SetObject(int x, int y, int width, int height);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
void MoveObject(Direction direction);
/// <summary>
/// Отрисовка объекта
/// </summary>
/// <param name="g"></param>
void DrawObject(Graphics g);
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
RectangleF GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@ -0,0 +1,236 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class MapWithSetAirplanesGeneric<T, U> : IComparable<MapWithSetAirplanesGeneric<T, U>>
where T : class, IEquatable<T>, IDrawningObject
where U : AbstractMap
{
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 190;
/// <summary>
/// Набор объектов
/// </summary>
public SetAirplanesGeneric<T> SetAirplanes { get; private set; }
/// <summary>
/// Карта
/// </summary>
private readonly U _map;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="map"></param>
public MapWithSetAirplanesGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
SetAirplanes = new SetAirplanesGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="airplane"></param>
/// <returns>Возвращает позицию вставленого объекта либо -1, если не получилось его добавить</returns>
public static int operator +(MapWithSetAirplanesGeneric<T, U> map, T airplane)
{
return map.SetAirplanes.Insert(airplane);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="map"></param>
/// <param name="position"></param>
/// <returns>Возвращает удаленный объект, либо null если его не удалось удалить</returns>
public static T operator -(MapWithSetAirplanesGeneric<T, U> map, int position)
{
return map.SetAirplanes.Remove(position);
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawAirplanes(gr);
return bmp;
}
/// <summary>
/// Просмотр объекта на карте
/// </summary>
/// <returns></returns>
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < SetAirplanes.Count; i++)
{
var airplane = SetAirplanes[i];
if (airplane != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, airplane);
}
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Перемещение объекта по крате
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()
{
int j = SetAirplanes.Count - 1;
for (int i = 0; i < SetAirplanes.Count; i++)
{
if (SetAirplanes[i] == null)
{
for (; j > i; j--)
{
var airplane = SetAirplanes[j];
if (airplane != null)
{
SetAirplanes.Insert(airplane, i);
SetAirplanes.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
/// <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++)
{
DrawHangar(g, pen, new RectangleF(i * _placeSizeWidth, j * _placeSizeHeight, _placeSizeWidth / 1.8F, _placeSizeHeight / 1.6F));
}
}
}
private void DrawHangar(Graphics g, Pen pen, RectangleF rect)
{
g.DrawLine(pen, rect.Left , rect.Top , rect.Right, rect.Top );
g.DrawLine(pen, rect.Right, rect.Top , rect.Right, rect.Bottom);
g.DrawLine(pen, rect.Right, rect.Bottom, rect.Left , rect.Bottom);
// Края ворот ангара
g.DrawLine(pen, rect.Left, rect.Top , rect.Left, rect.Top + rect.Height / 10);
g.DrawLine(pen, rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 10);
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawAirplanes(Graphics g)
{
int countInLine = _pictureWidth / _placeSizeWidth;
int maxLeft = (countInLine - 1) * _placeSizeWidth;
for (int i = 0; i < SetAirplanes.Count; i++)
{
var airplane = SetAirplanes[i];
airplane?.SetObject(maxLeft - i % countInLine * _placeSizeWidth, i / countInLine * _placeSizeHeight + 3, _pictureWidth, _pictureHeight);
airplane?.DrawObject(g);
}
}
public void Clear()
{
SetAirplanes.Clear();
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var airplane in SetAirplanes.GetAirplanes())
{
data += $"{airplane.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
SetAirplanes.Insert(DrawningObject.Create(rec) as T);
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
SetAirplanes.SortSet(comparer);
}
public int CompareTo(MapWithSetAirplanesGeneric<T, U>? other)
{
if (other == null)
{
return 1;
}
if (this == other)
{
return 0;
}
return SetAirplanes.Count.CompareTo(other.SetAirplanes.Count);
}
}
}

View File

@ -0,0 +1,189 @@
using AirBomber;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
/// <summary>
/// Класс для хранения коллекции карт
/// </summary>
internal class MapsCollection
{
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetAirplanesGeneric<IDrawningObject,
AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
public List<string> Keys => _mapStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string,
MapWithSetAirplanesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="name">Название карты</param>
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
_mapStorages.Add(name, new(_pictureWidth, _pictureHeight, map));
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="name">Название карты</param>
public void DelMap(string name)
{
_mapStorages.Remove(name);
}
/// <summary>
/// Доступ к аэродрому
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetAirplanesGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
_mapStorages.TryGetValue(ind, out var mapWithSetAirplanesGeneric);
return mapWithSetAirplanesGeneric;
}
}
public IDrawningObject this[string ind, int indDrawningObject]
{
get
{
_mapStorages.TryGetValue(ind, out var mapWithSetAirplanesGeneric);
return mapWithSetAirplanesGeneric?.SetAirplanes[indDrawningObject];
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new(filename))
{
fs.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
}
public bool SaveMap(string filename, string nameMap)
{
if (!_mapStorages.ContainsKey(nameMap))
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new(filename))
{
fs.Write($"Map{Environment.NewLine}");
fs.Write($"Name: {nameMap}{Environment.NewLine}");
fs.Write(_mapStorages[nameMap].GetData(separatorDict, separatorData));
}
return true;
}
private void LoadMap(string nameMapStorage, string nameMap, string lineData)
{
AbstractMap map = null;
switch (nameMap)
{
case "SimpleMap":
map = new SimpleMap();
break;
case "WallMap":
map = new WallMap();
break;
}
if (_mapStorages.ContainsKey(nameMapStorage))
{
_mapStorages[nameMapStorage].Clear();
}
else
{
_mapStorages[nameMapStorage] = new(_pictureWidth, _pictureHeight, map);
}
_mapStorages[nameMapStorage].LoadData(lineData.Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
/// <summary>
/// Загрузка информации по самолетам в ангарах из файла
/// </summary>
/// <param name="filename"></param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader fs = new(filename))
{
var formatData = fs.ReadLine() ?? string.Empty;
bool isNotMapsCollection = !formatData.Contains("MapsCollection");
if (formatData.Contains("Map") && isNotMapsCollection)
{
var nameMap = fs.ReadLine().Replace("Name: ", "");
var elem = fs.ReadLine().Split(separatorDict);
LoadMap(nameMap, elem[0], elem[1]);
}
if (isNotMapsCollection)
{
//если нет такой записи, то это не те данные
throw new FileFormatException("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
while (!fs.EndOfStream)
{
var elem = fs.ReadLine().Split(separatorDict);
LoadMap(elem[0], elem[1], elem[2]);
}
}
}
}
}

View File

@ -1,3 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
using System;
namespace AirBomber
{
internal static class Program
@ -11,7 +18,42 @@ namespace AirBomber
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAirBomber());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
try
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetAirplanes>());
}
catch (Exception ex)
{
GetLogger().Fatal(ex, "Íåïðåäâèäåííàÿ îøèáêà.");
}
}
}
private static Serilog.ILogger GetLogger()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
return logger;
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetAirplanes>()
.AddLogging(option =>
{
var logger = GetLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetAirplanesGeneric<T>
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
private readonly int _maxcount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetAirplanesGeneric(int count)
{
_maxcount = count;
_places = new List<T>();
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="airplane">Добавляемый самолет</param>
/// <returns>Возвращает позицию вставленого объекта либо -1, если не получилось его добавить</returns>
public int Insert(T airplane)
{
return Insert(airplane, 0);
}
private bool isCorrectPosition(int position)
{
return 0 <= position && position < _maxcount;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="airplane">Добавляемый самолет</param>
/// <param name="position">Позиция</param>
/// <exception cref="ArgumentException"> Исключения генерируется при попытке добавить дубликат в набор</exception>
/// <exception cref="StorageOverflowException"> </exception>
/// <returns>Возвращает позицию вставленого объекта либо -1, если не получилось его добавить</returns>
public int Insert(T airplane, int position)
{
if (_places.Contains(airplane))
throw new ArgumentException($"Объект {airplane} уже есть в наборе");
if (Count == _maxcount)
throw new StorageOverflowException(_maxcount);
if (!isCorrectPosition(position))
{
return -1;
}
_places.Insert(position, airplane);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns>Возвращает удаленный объект, либо null если его не удалось удалить</returns>
public T Remove(int position)
{
if (!isCorrectPosition(position))
return null;
var result = this[position];
if (result == null)
throw new AirplaneNotFoundException(position);
_places.RemoveAt(position);
return result;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T this[int position]
{
get
{
return isCorrectPosition(position) && position < Count ? _places[position] : null;
}
set
{
Insert(value, position);
}
}
/// <summary>
/// Проход по набору до первого пустого
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetAirplanes()
{
foreach (var airplane in _places)
{
if (airplane != null)
{
yield return airplane;
}
else
{
yield break;
}
}
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
public void Clear()
{
_places.Clear();
}
public void Clear()
{
_places.Clear();
}
}
}

View File

@ -0,0 +1,50 @@
namespace AirBomber
{
/// <summary>
/// Простая реализация абсрактного класса AbstractMap
/// </summary>
internal class SimpleMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Black);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.Gray);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
while (counter < 50)
{
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace AirBomber
{
[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) { }
}
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class WallMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Brown);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.LightPink);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillPolygon(barrierColor, new PointF[]
{
new PointF(i * _size_x, j * _size_y),
new PointF((i + 1) * _size_x, j * _size_y),
new PointF((i + 1) * _size_x - _size_x / 4, (j + 1) * _size_y - _size_y / 2),
new PointF((i + 1) * _size_x, (j + 1) * _size_y),
new PointF(i * _size_x, (j + 1) * _size_y),
new PointF(i * _size_x + _size_x / 4, (j + 1) * _size_y - _size_y / 2),
});
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void GenerateMap()
{
_map = new int[120, 120];
var minSize = Math.Min(_map.GetLength(0), _map.GetLength(1));
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
for (var i = 0; i < 10; i++)
{
var lengthWall = _random.Next(3, minSize / 2);
var incX = _random.Next(0, 2);
var incY = 1 - incX;
var left = _random.Next(0, _map.GetLength(0) - lengthWall);
var top = _random.Next(0, _map.GetLength(1) - lengthWall);
for (var j = 0; j < lengthWall; j++)
{
_map[left + incX * j, top + incY * j] = _barrier;
}
}
}
}
}

View File

@ -0,0 +1,90 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Filters.Expressions" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "(@Level = 'Information')"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/actions_user_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
]
}
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "(@Level = 'Warning' or @Level = 'Error' or @Level = 'Fatal')"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/errors_.log",
"rollingInterval": "Day",
"outputTemplate": "{Message:lj} ({Timestamp:dd.MM.yyyy}){NewLine}{Exception}"
}
}
]
}
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Destructure": [
{
"Name": "ByTransforming",
"Args": {
"returnType": "AirBomber.EntityAirplane",
"transformation": "r => new { BodyColor = r.BodyColor.Name, r.Speed, r.Weight }"
}
},
{
"Name": "ByTransforming",
"Args": {
"returnType": "AirBomber.EntityAirBomber",
"transformation": "r => new { BodyColor = r.BodyColor.Name, DopColor = r.DopColor.Name, r.HasBombs, r.HasFuelTanks, r.Speed, r.Weight }"
}
},
{
"Name": "ToMaximumDepth",
"Args": { "maximumDestructuringDepth": 4 }
},
{
"Name": "ToMaximumStringLength",
"Args": { "maximumStringLength": 100 }
},
{
"Name": "ToMaximumCollectionCount",
"Args": { "maximumCollectionCount": 10 }
}
],
"Properties": {
"Application": "AirBomber"
}
}
}