Compare commits

...

25 Commits

Author SHA1 Message Date
e82d5dd28a 8 лаба 2022-12-06 01:47:14 +04:00
5dd9b3f1cb исправление nlog на serilog 2022-12-06 01:02:00 +04:00
3a77f272fc Логирование 2022-11-22 01:04:04 +04:00
58f9a4f809 Генерация ошибок 2022-11-22 00:51:18 +04:00
bdfd25c4cb fix save and load 2022-11-19 19:31:20 +04:00
378cfe47f1 laba06 full 2022-11-05 20:35:02 +04:00
88b129394f Готовая лаб3 2022-11-05 16:51:53 +04:00
9c5aaaf49f Изменения в отрисовке объекта на площадке 2022-10-23 18:00:32 +04:00
fe0017e96c Форма 2022-10-22 17:48:06 +04:00
803cc7bd8d Класс MapsCollection. 2022-10-22 17:01:53 +04:00
35353ac409 Смена массива на список. 2022-10-22 16:53:12 +04:00
d12fbd832b Готовая 3 лабораторная работа. Небольшие изменения в отрисовке объекта 2022-10-07 21:30:29 +04:00
f8b95a402a generic classes 2022-10-07 19:56:39 +04:00
Katerina881
a9903ae47b Небольшие правки карты 2022-10-06 12:51:21 +04:00
Katerina881
76c854f6c2 Изменение названия карты 2022-10-06 12:37:22 +04:00
Katerina881
2308895805 Исправление карты 2022-10-06 12:29:35 +04:00
93af5d6e5a Добавление собственных карт 2022-10-06 03:50:53 +04:00
a091ea799f Добавление проверок, добавление стандарной карты 2022-10-06 03:49:13 +04:00
ee82eb4206 Добавление интерфейса 2022-10-06 02:47:38 +04:00
7196d002ec Продвинутый объект 2022-10-06 02:24:09 +04:00
7e26948aff Переход на конструкторы 2022-10-06 01:34:11 +04:00
f0f0b3a9f9 Изменение имен 2022-10-06 01:18:29 +04:00
09803f8fff Небольшое изменение отрисовки 2022-10-06 01:03:40 +04:00
fccecf9ba0 Изменение цвета и удаление лишних файлов 2022-09-27 09:27:00 +04:00
b23d6866bd Первая лабораторная работа 2022-09-27 09:23:52 +04:00
40 changed files with 3306 additions and 50 deletions

View File

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal abstract class AbstractMap : IEquatable<AbstractMap>
{
private IDrawningObject _drawningObject = null;
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)
{
_width = width;
_height = height;
_drawningObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
public Bitmap MoveObject(Direction direction)
{
(float leftX, float topY, float rightX, float bottomY) = _drawningObject.GetCurrentPosition();
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i, j] == _barrier)
{
switch (direction)
{
case Direction.Up:
if (_size_y * (j + 1) >= topY - _drawningObject.Step && _size_y * (j + 1) < topY && _size_x * (i + 1) > leftX
&& _size_x * (i + 1) <= rightX)
{
return DrawMapWithObject();
}
break;
case Direction.Down:
if (_size_y * j <= bottomY + _drawningObject.Step && _size_y * j > bottomY && _size_x * (i + 1) > leftX
&& _size_x * (i + 1) <= rightX)
{
return DrawMapWithObject();
}
break;
case Direction.Left:
if (_size_x * (i + 1) >= leftX - _drawningObject.Step && _size_x * (i + 1) < leftX && _size_y * (j + 1) < bottomY
&& _size_y * (j + 1) >= topY)
{
return DrawMapWithObject();
}
break;
case Direction.Right:
if (_size_x * i <= rightX + _drawningObject.Step && _size_x * i > leftX && _size_y * (j + 1) < bottomY
&& _size_y * (j + 1) >= topY)
{
return DrawMapWithObject();
}
break;
}
}
}
}
_drawningObject.MoveObject(direction);
return DrawMapWithObject();
}
private bool SetObjectOnMap()
{
(float leftX, float topY, float rightX, float bottomY) = _drawningObject.GetCurrentPosition();
if (_drawningObject == null || _map == null)
{
return false;
}
float airplaneWidth = rightX - leftX;
float airplaneHeight = bottomY - topY;
int x = _random.Next(0, 10);
int y = _random.Next(0, 10);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
if (_map[i, j] == _barrier)
{
if (x + airplaneWidth >= _size_x * i && x <= _size_x * i && y + airplaneHeight > _size_y * j && y <= _size_y * j)
{
return false;
}
}
}
}
_drawningObject.SetObject(x, y, _width, _height);
return true;
}
private Bitmap DrawMapWithObject()
{
Bitmap bmp = new(_width, _height);
if (_drawningObject == null || _map == null)
{
return bmp;
}
Graphics gr = Graphics.FromImage(bmp);
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);
}
}
}
_drawningObject.DrawningObject(gr);
return bmp;
}
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)
{
return false;
}
var otherMap = other as AbstractMap;
if (otherMap == null)
{
return false;
}
if (_width != otherMap._width)
{
return false;
}
if (_height != otherMap._height)
{
return false;
}
if (_size_x != otherMap._size_x)
{
return false;
}
if (_size_y != otherMap._size_y)
{
return false;
}
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i, j] != otherMap._map[i, j])
{
return false;
}
}
}
return true;
}
}
}

View File

@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class AirplaneCompareByColor : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xAirplane = x as DrawningObjectAirplane;
var yAirplane = y as DrawningObjectAirplane;
if (xAirplane == null && yAirplane == null)
{
return 0;
}
if (xAirplane == null && yAirplane != null)
{
return 1;
}
if (xAirplane != null && yAirplane == null)
{
return -1;
}
var xEntityAirplane = xAirplane._airplane.Airplane;
var yEntityAirplane = yAirplane._airplane.Airplane;
var baseColorCompare = xEntityAirplane.BodyColor.ToArgb().CompareTo(yEntityAirplane.BodyColor.ToArgb());
if (baseColorCompare != 0)
{
return baseColorCompare;
}
if (xEntityAirplane is EntityAirplaneWithRadar xAirplaneWithRadar && yEntityAirplane is EntityAirplaneWithRadar yAirplaneWithRadar)
{
var dopColorCompare = xAirplaneWithRadar.DopColor.ToArgb().CompareTo(yAirplaneWithRadar.DopColor.ToArgb());
if (dopColorCompare != 0)
{
return dopColorCompare;
}
}
var speedCompare = xAirplane._airplane.Airplane.Speed.CompareTo(yAirplane._airplane.Airplane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xAirplane._airplane.Airplane.Weight.CompareTo(yAirplane._airplane.Airplane.Weight);
}
}
}

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class AirplaneCompareByType : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xAirplane = x as DrawningObjectAirplane;
var yAirplane = y as DrawningObjectAirplane;
if (xAirplane == null && yAirplane == null)
{
return 0;
}
if (xAirplane == null && yAirplane != null)
{
return 1;
}
if (xAirplane != null && yAirplane == null)
{
return -1;
}
if (xAirplane.GetAirplane.GetType().Name != yAirplane.GetAirplane.GetType().Name)
{
if (xAirplane.GetAirplane.GetType().Name == "DrawningAirplane")
{
return -1;
}
return 1;
}
var speedCompare = xAirplane.GetAirplane.Airplane.Speed.CompareTo(yAirplane.GetAirplane.Airplane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xAirplane.GetAirplane.Airplane.Weight.CompareTo(yAirplane.GetAirplane.Airplane.Weight);
}
}
}

View File

@ -0,0 +1,5 @@
namespace AirplaneWithRadar
{
//делегат для передачи объекта-самолёта
public delegate void AirplaneDelegate(DrawningAirplane airplane);
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
[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 context) : base(info, context) { }
}
}

View File

@ -8,4 +8,36 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Configuration.ConfigurationBuilders.Environment" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.1.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
public enum Direction
{
None = 0,
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
}

View File

@ -0,0 +1,140 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
public class DrawningAirplane
{
public EntityAirplane Airplane { get; protected set; }
protected float _startPosX;
protected float _startPosY;
private int? _pictureWidth = null;
private int? _pictureHeight = null;
private readonly int _airplaneWidth = 50;
private readonly int _airplaneHeight = 27;
public DrawningAirplane(int speed, float weight, Color bodyColor)
{
Airplane = new EntityAirplane(speed, weight, bodyColor);
}
protected DrawningAirplane(int speed, float weight, Color bodyColor, int airplaneWidth, int airplaneHeight) :
this(speed, weight, bodyColor)
{
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
}
public void SetPosition(int x, int y, int width, int height)
{
if (x + _airplaneWidth <= width && y + _airplaneHeight <= height && x >= 0 && y >= 0)
{
_startPosX = x;
_startPosY = y;
_pictureWidth = width;
_pictureHeight = height;
}
}
public void MoveTransport(Direction direction)
{
if (!_pictureWidth.HasValue || !_pictureHeight.HasValue)
{
return;
}
switch (direction)
{
// вправо
case Direction.Right:
if (_startPosX + _airplaneWidth + Airplane.Step < _pictureWidth)
{
_startPosX += Airplane.Step;
}
break;
//влево
case Direction.Left:
if (_startPosX - Airplane.Step > 0)
{
_startPosX -= Airplane.Step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - Airplane.Step > 0)
{
_startPosY -= Airplane.Step;
}
break;
//вниз
case Direction.Down:
if (_startPosY + _airplaneHeight + Airplane.Step + 30 < _pictureHeight)
{
_startPosY += Airplane.Step;
}
break;
}
}
public virtual void DrawTransport(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0 || !_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
Pen pen = new(Color.Black);
// Корпус
g.DrawRectangle(pen, _startPosX, _startPosY + 10, 40, 10);
Brush darkBrush = new SolidBrush(Airplane?.BodyColor ?? Color.Black);
g.FillRectangle(darkBrush, _startPosX + 1, _startPosY + 11, 39, 9);
// Окно
darkBrush = new SolidBrush(Color.Black);
g.FillRectangle(darkBrush, _startPosX + 12, _startPosY + 13, 20, 2);
// Хвост
darkBrush = new SolidBrush(Color.Black);
g.DrawLine(pen, _startPosX, _startPosY + 12, _startPosX, _startPosY);
g.DrawLine(pen, _startPosX, _startPosY, _startPosX + 10, _startPosY + 10);
// Заднее шасси
g.FillRectangle(darkBrush, _startPosX + 10, _startPosY + 21, 2, 2);
g.FillRectangle(darkBrush, _startPosX + 13, _startPosY + 23, 4, 4);
g.FillRectangle(darkBrush, _startPosX + 8, _startPosY + 23, 2, 4);
// Переднее шасси
g.FillRectangle(darkBrush, _startPosX + 35, _startPosY + 21, 2, 2);
g.FillRectangle(darkBrush, _startPosX + 35, _startPosY + 23, 4, 4);
// Нос
g.DrawLine(pen, _startPosX + 40, _startPosY + 10, _startPosX + 47, _startPosY + 15);
g.DrawLine(pen, _startPosX + 40, _startPosY + 20, _startPosX + 50, _startPosY + 15);
}
public void ChangeBorders(int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth <= _airplaneWidth || _pictureHeight <= _airplaneHeight)
{
_pictureWidth = null;
_pictureHeight = null;
return;
}
if (_startPosX + _airplaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth.Value - _airplaneWidth;
}
if (_startPosY + _airplaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight.Value - _airplaneHeight;
}
}
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return (_startPosX, _startPosY, _startPosX + _airplaneWidth, _startPosY + _airplaneHeight);
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class DrawningAirplaneWithRadar : DrawningAirplane
{
public DrawningAirplaneWithRadar(int speed, float weight, Color bodyColor, Color dopColor, bool radar, bool ladder, bool window) :
base(speed, weight, bodyColor, 50, 27)
{
Airplane = new EntityAirplaneWithRadar(speed, weight, bodyColor, dopColor, radar, ladder, window);
}
public override void DrawTransport(Graphics g)
{
if (Airplane is not EntityAirplaneWithRadar airplaneWithRadar)
{
return;
}
Pen pen = new(Color.Black, 2);
Brush dopBrush = new SolidBrush(airplaneWithRadar.DopColor);
base.DrawTransport(g);
if (airplaneWithRadar.Radar)
{
g.DrawEllipse(new Pen(Color.Black), _startPosX + 18, _startPosY + 3, 9, 4);
g.DrawRectangle(new Pen(Color.Black), _startPosX + 20, _startPosY + 6, 5, 4);
}
if (airplaneWithRadar.Window)
{
g.FillEllipse(dopBrush, _startPosX + 40, _startPosY + 13, 5, 5);
}
if (airplaneWithRadar.Ladder)
{
g.DrawLine(new Pen(Color.Black), _startPosX + 3, _startPosY + 18, _startPosX + 3, _startPosY + 12);
g.DrawLine(new Pen(Color.Black), _startPosX + 7, _startPosY + 18, _startPosX + 7, _startPosY + 12);
g.DrawLine(new Pen(Color.Black), _startPosX + 3, _startPosY + 16, _startPosX + 7, _startPosY + 16);
g.DrawLine(new Pen(Color.Black), _startPosX + 3, _startPosY + 13, _startPosX + 7, _startPosY + 13);
}
}
}
}

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class DrawningObjectAirplane : IDrawningObject
{
public DrawningAirplane _airplane { get; private set; }
public DrawningObjectAirplane(DrawningAirplane airplane)
{
_airplane = airplane;
}
public float Step => _airplane?.Airplane?.Step ?? 0;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _airplane?.GetCurrentPosition() ?? default;
}
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);
}
void IDrawningObject.DrawningObject(Graphics g)
{
_airplane.DrawTransport(g);
}
public string GetInfo() => _airplane?.GetDataForSave() ?? string.Empty;
public static IDrawningObject Create(string data) => new DrawningObjectAirplane(data.CreateDrawningAirplane());
public bool Equals(IDrawningObject? other)
{
if (other is not DrawningObjectAirplane otherAirplane)
{
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 EntityAirplaneWithRadar entityAirplaneWithRadar &&
otherEntity is EntityAirplaneWithRadar otherEntityAirplaneWithRadar && (
entityAirplaneWithRadar.Ladder != otherEntityAirplaneWithRadar.Ladder ||
entityAirplaneWithRadar.DopColor != otherEntityAirplaneWithRadar.DopColor ||
entityAirplaneWithRadar.Window != otherEntityAirplaneWithRadar.Window ||
entityAirplaneWithRadar.Radar != otherEntityAirplaneWithRadar.Radar))
{
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
public class EntityAirplane
{
public int Speed { get; private set; }
public float Weight { get; private set; }
public Color BodyColor { get; set; }
public float Step => Speed * 100 / Weight;
public EntityAirplane(int speed, float weight, Color bodyColor)
{
Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;
Weight = weight <= 0 ? rnd.Next(40, 70) : weight;
BodyColor = bodyColor;
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class EntityAirplaneWithRadar : EntityAirplane
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; set; }
/// <summary>
/// Признак наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Признак наличия лестницы
/// </summary>
public bool Ladder { get; private set; }
/// <summary>
/// Признак наличия окон
/// </summary>
public bool Window { get; private set; }
public EntityAirplaneWithRadar(int speed, float weight, Color bodyColor, Color dopColor, bool radar, bool ladder, bool window) :
base(speed, weight, bodyColor)
{
DopColor = dopColor;
Radar = radar;
Ladder = ladder;
Window = window;
}
}
}

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal static class ExtentionAirplane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <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]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawningAirplaneWithRadar(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningLocomotive"></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 EntityAirplaneWithRadar airplaneWithRadar)
{
return str;
}
return $"{str}{_separatorForObject}{airplaneWithRadar.DopColor.Name}{_separatorForObject}{airplaneWithRadar.Radar}{_separatorForObject}{airplaneWithRadar.Ladder}{_separatorForObject}{airplaneWithRadar.Window}";
}
}
}

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class FoggySkyMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Blue);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.DarkGray);
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 < 12)
{
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
if (y + 5 < 100 && x + 3 < 100)
{
_map[x, y] = _barrier;
_map[x + 1, y + 1] = _barrier;
_map[x + 2, y + 2] = _barrier;
_map[x + 1, y + 3] = _barrier;
_map[x + 2, y + 4] = _barrier;
_map[x + 3 , y + 5] = _barrier;
counter++;
}
}
}
}
}
}

View File

@ -1,39 +0,0 @@
namespace AirplaneWithRadar
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

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

View File

@ -0,0 +1,207 @@
namespace AirplaneWithRadar
{
partial class FormAirplane
{
/// <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.pictureBoxAirplane = new System.Windows.Forms.PictureBox();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabelSpeed = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelWeight = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelBodyColor = new System.Windows.Forms.ToolStripStatusLabel();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonCreateModify = new System.Windows.Forms.Button();
this.buttonSelectCar = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirplane)).BeginInit();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxAirplane
//
this.pictureBoxAirplane.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.pictureBoxAirplane.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxAirplane.Location = new System.Drawing.Point(0, 0);
this.pictureBoxAirplane.Name = "pictureBoxAirplane";
this.pictureBoxAirplane.Size = new System.Drawing.Size(800, 451);
this.pictureBoxAirplane.TabIndex = 0;
this.pictureBoxAirplane.TabStop = false;
this.pictureBoxAirplane.Click += new System.EventHandler(this.ButtonMove_Click);
//
// statusStrip1
//
this.statusStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabelSpeed,
this.toolStripStatusLabelWeight,
this.toolStripStatusLabelBodyColor});
this.statusStrip1.Location = new System.Drawing.Point(0, 425);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(800, 26);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabelSpeed
//
this.toolStripStatusLabelSpeed.Name = "toolStripStatusLabelSpeed";
this.toolStripStatusLabelSpeed.Size = new System.Drawing.Size(76, 20);
this.toolStripStatusLabelSpeed.Text = "Скорость:";
//
// toolStripStatusLabelWeight
//
this.toolStripStatusLabelWeight.Name = "toolStripStatusLabelWeight";
this.toolStripStatusLabelWeight.Size = new System.Drawing.Size(36, 20);
this.toolStripStatusLabelWeight.Text = "Вес:";
//
// toolStripStatusLabelBodyColor
//
this.toolStripStatusLabelBodyColor.Name = "toolStripStatusLabelBodyColor";
this.toolStripStatusLabelBodyColor.Size = new System.Drawing.Size(45, 20);
this.toolStripStatusLabelBodyColor.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(11, 391);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(94, 29);
this.buttonCreate.TabIndex = 2;
this.buttonCreate.Text = "Создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.ButtonCreate_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AirplaneWithRadar.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(677, 391);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 29);
this.buttonLeft.TabIndex = 3;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AirplaneWithRadar.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(712, 391);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 29);
this.buttonDown.TabIndex = 4;
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::AirplaneWithRadar.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(747, 392);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 29);
this.buttonRight.TabIndex = 5;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.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::AirplaneWithRadar.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(712, 355);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 29);
this.buttonUp.TabIndex = 6;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonCreateModify
//
this.buttonCreateModify.Location = new System.Drawing.Point(111, 391);
this.buttonCreateModify.Name = "buttonCreateModify";
this.buttonCreateModify.Size = new System.Drawing.Size(133, 29);
this.buttonCreateModify.TabIndex = 7;
this.buttonCreateModify.Text = "Модификация";
this.buttonCreateModify.UseVisualStyleBackColor = true;
this.buttonCreateModify.Click += new System.EventHandler(this.buttonCreateModify_Click);
//
// buttonSelectCar
//
this.buttonSelectCar.Location = new System.Drawing.Point(560, 391);
this.buttonSelectCar.Name = "buttonSelectCar";
this.buttonSelectCar.Size = new System.Drawing.Size(94, 29);
this.buttonSelectCar.TabIndex = 8;
this.buttonSelectCar.Text = "Выбрать";
this.buttonSelectCar.UseVisualStyleBackColor = true;
this.buttonSelectCar.Click += new System.EventHandler(this.buttonSelectCar_Click);
//
// FormAirplane
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 451);
this.Controls.Add(this.buttonSelectCar);
this.Controls.Add(this.buttonCreateModify);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.pictureBoxAirplane);
this.Name = "FormAirplane";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirplane)).EndInit();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private PictureBox pictureBoxAirplane;
private StatusStrip statusStrip1;
private ToolStripStatusLabel toolStripStatusLabelSpeed;
private ToolStripStatusLabel toolStripStatusLabelWeight;
private ToolStripStatusLabel toolStripStatusLabelBodyColor;
private Button buttonCreate;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonUp;
private Button buttonCreateModify;
private Button buttonSelectCar;
}
}

View File

@ -0,0 +1,103 @@
namespace AirplaneWithRadar
{
public partial class FormAirplane : Form
{
private DrawningAirplane _airplane;
/// <summary>
/// Âűáđŕííűé îáúĺęň
/// </summary>
public DrawningAirplane SelectedAirplane { get; private set; }
public FormAirplane()
{
InitializeComponent();
}
private void Draw()
{
Bitmap bmp = new(pictureBoxAirplane.Width, pictureBoxAirplane.Height);
Graphics gr = Graphics.FromImage(bmp);
_airplane?.DrawTransport(gr);
pictureBoxAirplane.Image = bmp;
}
/// <summary>
/// Ěĺňîä óńňŕíîâęč äŕííűő
/// </summary>
private void SetData()
{
Random rnd = new();
_airplane.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxAirplane.Width, pictureBoxAirplane.Height);
toolStripStatusLabelSpeed.Text = $"Ńęîđîńňü: {_airplane.Airplane.Speed}";
toolStripStatusLabelWeight.Text = $"Âĺń: {_airplane.Airplane.Weight}";
toolStripStatusLabelBodyColor.Text = $"Öâĺň: {_airplane.Airplane.BodyColor.Name}";
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random random = new();
Color myColor = new Color();
ColorDialog MyDialog = new ColorDialog();
if (MyDialog.ShowDialog() == DialogResult.OK)
{
myColor = MyDialog.Color;
}
_airplane = new DrawningAirplane(random.Next(30, 50), random.Next(1000, 2000), myColor);
SetData();
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
//ďîëó÷ŕĺě čě˙ ęíîďęč
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_airplane?.MoveTransport(Direction.Up);
break;
case "buttonDown":
_airplane?.MoveTransport(Direction.Down);
break;
case "buttonLeft":
_airplane?.MoveTransport(Direction.Left);
break;
case "buttonRight":
_airplane?.MoveTransport(Direction.Right);
break;
}
Draw();
}
private void PictureBoxAirplane_Resize(object sender, EventArgs e)
{
_airplane?.ChangeBorders(pictureBoxAirplane.Width, pictureBoxAirplane.Height);
Draw();
}
/// <summary>
/// Îáđŕáîňęŕ íŕćŕňč˙ ęíîďęč "Ěîäčôčęŕöč˙"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateModify_Click(object sender, EventArgs e)
{
Random rnd = new();
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;
}
Color dopColor = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialogDop = new();
if (dialogDop.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDop.Color;
}
_airplane = new DrawningAirplaneWithRadar(rnd.Next(100, 300), rnd.Next(1000, 2000), color, dopColor,
Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
SetData();
Draw();
}
private void buttonSelectCar_Click(object sender, EventArgs e)
{
SelectedAirplane = _airplane;
DialogResult = DialogResult.OK;
}
}
}

View File

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

View File

@ -0,0 +1,414 @@
namespace AirplaneWithRadar
{
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.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxAddLadder = new System.Windows.Forms.CheckBox();
this.checkBoxAddWindow = new System.Windows.Forms.CheckBox();
this.checkBoxAddRadar = 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.pictureBox = new System.Windows.Forms.PictureBox();
this.panelObject = new System.Windows.Forms.Panel();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
this.buttonAddObject = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.panelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxAddLadder);
this.groupBoxConfig.Controls.Add(this.checkBoxAddWindow);
this.groupBoxConfig.Controls.Add(this.checkBoxAddRadar);
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(10, 9);
this.groupBoxConfig.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxConfig.Size = new System.Drawing.Size(630, 184);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(521, 116);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(100, 44);
this.labelModifiedObject.TabIndex = 8;
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(412, 116);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(98, 44);
this.labelSimpleObject.TabIndex = 7;
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.panelWhite);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(412, 13);
this.groupBoxColors.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxColors.Size = new System.Drawing.Size(208, 94);
this.groupBoxColors.TabIndex = 6;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(5, 59);
this.panelWhite.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(35, 30);
this.panelWhite.TabIndex = 7;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(59, 59);
this.panelGray.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(35, 30);
this.panelGray.TabIndex = 6;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(114, 59);
this.panelBlack.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(35, 30);
this.panelBlack.TabIndex = 5;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(168, 59);
this.panelPurple.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(35, 30);
this.panelPurple.TabIndex = 4;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(168, 20);
this.panelYellow.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(35, 30);
this.panelYellow.TabIndex = 3;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(114, 20);
this.panelBlue.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(35, 30);
this.panelBlue.TabIndex = 2;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Lime;
this.panelGreen.Location = new System.Drawing.Point(59, 20);
this.panelGreen.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(35, 30);
this.panelGreen.TabIndex = 1;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(5, 20);
this.panelRed.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(35, 30);
this.panelRed.TabIndex = 0;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxAddLadder
//
this.checkBoxAddLadder.AutoSize = true;
this.checkBoxAddLadder.Location = new System.Drawing.Point(17, 154);
this.checkBoxAddLadder.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.checkBoxAddLadder.Name = "checkBoxAddLadder";
this.checkBoxAddLadder.Size = new System.Drawing.Size(276, 19);
this.checkBoxAddLadder.TabIndex = 4;
this.checkBoxAddLadder.Text = "Признак наличия дополнительной лестницы";
this.checkBoxAddLadder.UseVisualStyleBackColor = true;
//
// checkBoxAddWindow
//
this.checkBoxAddWindow.AutoSize = true;
this.checkBoxAddWindow.Location = new System.Drawing.Point(17, 132);
this.checkBoxAddWindow.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.checkBoxAddWindow.Name = "checkBoxAddWindow";
this.checkBoxAddWindow.Size = new System.Drawing.Size(253, 19);
this.checkBoxAddWindow.TabIndex = 5;
this.checkBoxAddWindow.Text = "Признак наличия дополнительного окна";
this.checkBoxAddWindow.UseVisualStyleBackColor = true;
//
// checkBoxAddRadar
//
this.checkBoxAddRadar.AutoSize = true;
this.checkBoxAddRadar.Location = new System.Drawing.Point(17, 110);
this.checkBoxAddRadar.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.checkBoxAddRadar.Name = "checkBoxAddRadar";
this.checkBoxAddRadar.Size = new System.Drawing.Size(265, 19);
this.checkBoxAddRadar.TabIndex = 4;
this.checkBoxAddRadar.Text = "Признак наличия дополнительного радара";
this.checkBoxAddRadar.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(100, 73);
this.numericUpDownWeight.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1500,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(90, 23);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
750,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(17, 74);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(29, 15);
this.labelWeight.TabIndex = 2;
this.labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(100, 28);
this.numericUpDownSpeed.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
2000,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(90, 23);
this.numericUpDownSpeed.TabIndex = 1;
this.numericUpDownSpeed.Value = new decimal(new int[] {
1000,
0,
0,
0});
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(17, 29);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(62, 15);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость:";
//
// pictureBox
//
this.pictureBox.Location = new System.Drawing.Point(14, 38);
this.pictureBox.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(209, 102);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Controls.Add(this.pictureBox);
this.panelObject.Location = new System.Drawing.Point(646, 17);
this.panelObject.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(234, 142);
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);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(123, 4);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(100, 32);
this.labelDopColor.TabIndex = 3;
this.labelDopColor.Text = "Доп. цвет";
this.labelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDopColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelAddColor_DragDrop);
this.labelDopColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(14, 4);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(104, 32);
this.labelBaseColor.TabIndex = 2;
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.LabelColor_DragEnter);
//
// buttonAddObject
//
this.buttonAddObject.Location = new System.Drawing.Point(660, 164);
this.buttonAddObject.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAddObject.Name = "buttonAddObject";
this.buttonAddObject.Size = new System.Drawing.Size(104, 28);
this.buttonAddObject.TabIndex = 3;
this.buttonAddObject.Text = "Добавить";
this.buttonAddObject.UseVisualStyleBackColor = true;
this.buttonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(769, 164);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(100, 28);
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormAirplaneConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(890, 205);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonAddObject);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormAirplaneConfig";
this.Text = "Создание объекта";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.panelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private CheckBox checkBoxAddRadar;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private CheckBox checkBoxAddWindow;
private CheckBox checkBoxAddLadder;
private Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColors;
private Panel panelWhite;
private Panel panelGray;
private Panel panelBlack;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private PictureBox pictureBox;
private Panel panelObject;
private Label labelDopColor;
private Label labelBaseColor;
private Button buttonAddObject;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AirplaneWithRadar
{
public partial class FormAirplaneConfig : Form
{
//переменная-выбранный самолёт
DrawningAirplane _airplane = null;
//событие
private event Action<DrawningAirplane> EventAddAirplane;
//конструктор
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 += (object sender, EventArgs e) => Close();
}
//отрисовка самолёт
private void DrawAirplane()
{
Bitmap bmp = new(pictureBox.Width, pictureBox.Height);
Graphics gr = Graphics.FromImage(bmp);
_airplane?.SetPosition(5, 5, pictureBox.Width, pictureBox.Height);
_airplane?.DrawTransport(gr);
pictureBox.Image = bmp;
}
//добавление события
public void AddEvent(Action<DrawningAirplane> ev)
{
if (EventAddAirplane == null)
{
EventAddAirplane = new Action<DrawningAirplane>(ev);
}
else
{
EventAddAirplane += ev;
}
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name, DragDropEffects.Move | DragDropEffects.Copy);
}
//проверка получаемой информации (ее типа на соответствие требуемому)
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
//действия при приеме перетаскиваемой информации
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, labelBaseColor.BackColor);
break;
case "labelModifiedObject":
_airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, labelBaseColor.BackColor, labelDopColor.BackColor,
checkBoxAddRadar.Checked, checkBoxAddLadder.Checked, checkBoxAddWindow.Checked);
break;
case null:
throw new AirplaneNotFoundException(0);
break;
}
DrawAirplane();
}
//отправляем цвет с панели
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
//проверка получаемой информации (её типа на соответсвие требуемому)
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
//принимаем основной цвет
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
//проверка на пустоту объекта
if (_airplane != null)
{
_airplane.Airplane.BodyColor = (Color)e.Data.GetData(typeof(Color));
DrawAirplane();
}
}
//принимаем дополнительный цвет
private void LabelAddColor_DragDrop(object sender, DragEventArgs e)
{
//проверка на пустоту объекта и правильную сущноть
if (_airplane != null && _airplane.Airplane is EntityAirplaneWithRadar entityAirplane)
{
entityAirplane.DopColor = (Color)e.Data.GetData(typeof(Color));
DrawAirplane();
}
}
//добавление машины
private void ButtonAddObject_Click(object sender, EventArgs e)
{
EventAddAirplane?.Invoke(_airplane);
Close();
}
}
}

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,379 @@
namespace AirplaneWithRadar
{
partial class FormMapWithSetAirplane
{
/// <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.buttonSortByColor = new System.Windows.Forms.Button();
this.buttonSortByType = new System.Windows.Forms.Button();
this.groupBox = new System.Windows.Forms.GroupBox();
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.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonRemoveAirplane = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddAirplane = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.ButtonDeleteMap = new System.Windows.Forms.Button();
this.ListBoxMaps = new System.Windows.Forms.ListBox();
this.ButtonAddMap = new System.Windows.Forms.Button();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
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.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBox.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(19, 279);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(169, 30);
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(19, 243);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(169, 30);
this.buttonSortByType.TabIndex = 11;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBox
//
this.groupBox.Controls.Add(this.buttonSortByColor);
this.groupBox.Controls.Add(this.buttonSortByType);
this.groupBox.Controls.Add(this.buttonDown);
this.groupBox.Controls.Add(this.buttonRight);
this.groupBox.Controls.Add(this.buttonLeft);
this.groupBox.Controls.Add(this.buttonUp);
this.groupBox.Controls.Add(this.buttonShowOnMap);
this.groupBox.Controls.Add(this.buttonShowStorage);
this.groupBox.Controls.Add(this.buttonRemoveAirplane);
this.groupBox.Controls.Add(this.maskedTextBoxPosition);
this.groupBox.Controls.Add(this.buttonAddAirplane);
this.groupBox.Controls.Add(this.groupBox1);
this.groupBox.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox.Location = new System.Drawing.Point(600, 24);
this.groupBox.Name = "groupBox";
this.groupBox.Size = new System.Drawing.Size(200, 590);
this.groupBox.TabIndex = 0;
this.groupBox.TabStop = false;
this.groupBox.Text = "Инструменты";
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AirplaneWithRadar.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(86, 554);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 9;
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::AirplaneWithRadar.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(122, 554);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 8;
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::AirplaneWithRadar.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(50, 554);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 7;
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::AirplaneWithRadar.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(86, 518);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 6;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonShowOnMap
//
this.buttonShowOnMap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonShowOnMap.Location = new System.Drawing.Point(19, 482);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(169, 30);
this.buttonShowOnMap.TabIndex = 5;
this.buttonShowOnMap.Text = "Посмотреть карту";
this.buttonShowOnMap.UseVisualStyleBackColor = true;
this.buttonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonShowStorage.Location = new System.Drawing.Point(19, 446);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(169, 30);
this.buttonShowStorage.TabIndex = 4;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// buttonRemoveAirplane
//
this.buttonRemoveAirplane.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRemoveAirplane.Location = new System.Drawing.Point(19, 410);
this.buttonRemoveAirplane.Name = "buttonRemoveAirplane";
this.buttonRemoveAirplane.Size = new System.Drawing.Size(169, 30);
this.buttonRemoveAirplane.TabIndex = 3;
this.buttonRemoveAirplane.Text = "Удалить самолет";
this.buttonRemoveAirplane.UseVisualStyleBackColor = true;
this.buttonRemoveAirplane.Click += new System.EventHandler(this.ButtonRemoveAirplane_Click);
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 384);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(169, 23);
this.maskedTextBoxPosition.TabIndex = 2;
//
// buttonAddAirplane
//
this.buttonAddAirplane.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonAddAirplane.Location = new System.Drawing.Point(19, 348);
this.buttonAddAirplane.Name = "buttonAddAirplane";
this.buttonAddAirplane.Size = new System.Drawing.Size(169, 30);
this.buttonAddAirplane.TabIndex = 1;
this.buttonAddAirplane.Text = "Добавить самолет";
this.buttonAddAirplane.UseVisualStyleBackColor = true;
this.buttonAddAirplane.Click += new System.EventHandler(this.ButtonAddAirplane_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.ButtonDeleteMap);
this.groupBox1.Controls.Add(this.ListBoxMaps);
this.groupBox1.Controls.Add(this.ButtonAddMap);
this.groupBox1.Controls.Add(this.textBoxNewMapName);
this.groupBox1.Controls.Add(this.comboBoxSelectorMap);
this.groupBox1.Location = new System.Drawing.Point(6, 21);
this.groupBox1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBox1.Size = new System.Drawing.Size(194, 204);
this.groupBox1.TabIndex = 18;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Карты";
//
// ButtonDeleteMap
//
this.ButtonDeleteMap.Location = new System.Drawing.Point(6, 182);
this.ButtonDeleteMap.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ButtonDeleteMap.Name = "ButtonDeleteMap";
this.ButtonDeleteMap.Size = new System.Drawing.Size(182, 22);
this.ButtonDeleteMap.TabIndex = 13;
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(6, 102);
this.ListBoxMaps.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ListBoxMaps.Name = "ListBoxMaps";
this.ListBoxMaps.Size = new System.Drawing.Size(182, 79);
this.ListBoxMaps.TabIndex = 12;
this.ListBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// ButtonAddMap
//
this.ButtonAddMap.Location = new System.Drawing.Point(6, 76);
this.ButtonAddMap.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ButtonAddMap.Name = "ButtonAddMap";
this.ButtonAddMap.Size = new System.Drawing.Size(181, 22);
this.ButtonAddMap.TabIndex = 11;
this.ButtonAddMap.Text = "Добавить карту";
this.ButtonAddMap.UseVisualStyleBackColor = true;
this.ButtonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(6, 20);
this.textBoxNewMapName.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(182, 23);
this.textBoxNewMapName.TabIndex = 10;
//
// 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(6, 49);
this.comboBoxSelectorMap.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(182, 23);
this.comboBoxSelectorMap.TabIndex = 9;
//
// 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(600, 590);
this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
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(800, 24);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
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(141, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file|*.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file|*.txt";
//
// FormMapWithSetAirplane
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 614);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetAirplane";
this.Text = "FormMapWithSetAirplane";
this.groupBox.ResumeLayout(false);
this.groupBox.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button buttonSortByColor;
private Button buttonSortByType;
private GroupBox groupBox;
private Button buttonDown;
private Button buttonRight;
private Button buttonLeft;
private Button buttonUp;
private Button buttonShowOnMap;
private Button buttonShowStorage;
private Button buttonRemoveAirplane;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonAddAirplane;
private ComboBox comboBoxSelectorMap;
private PictureBox pictureBox;
private GroupBox groupBox1;
private Button ButtonDeleteMap;
private ListBox ListBoxMaps;
private Button ButtonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,318 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
namespace AirplaneWithRadar
{
public partial class FormMapWithSetAirplane : Form
{
private readonly Dictionary<string, AbstractMap> _mapDict = new()
{
{"Простая карта", new SimpleMap() },
{"Карта неба с облаками", new SkyMap() },
{"Карта туманного неба с грозой", new FoggySkyMap() }
};
private readonly MapsCollection _mapsCollection;
private ILogger _logger;
public FormMapWithSetAirplane(ILogger<FormMapWithSetAirplane> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
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;
}
}
private void AddAirplane(DrawningAirplane airplane)
{
try
{
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Airplane}", airplane);
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException ex)
{
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, airplane);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAirplane_Click(object sender, EventArgs e)
{
var formAirplaneConfig = new FormAirplaneConfig();
formAirplaneConfig.AddEvent(AddAirplane);
formAirplaneConfig.Show();
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirplane_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
var deletedAirplane = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedAirplane != null)
{
MessageBox.Show("Объект удалён");
_logger.LogInformation("Из текущей карты удалён объект {@Ship}", deletedAirplane);
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (AirplaneNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception 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[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].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[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
//получаем имя кнопки
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[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
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 (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
return;
}
if (textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
{
MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
}
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Осуществлён переход на карту под названием {0}", ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
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(ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation("Удалена карта {0}", ListBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
}
/// <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.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new AirplaneCompareByType());
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new AirplaneCompareByColor());
pictureBox.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

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>265, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal 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 DrawningObject(Graphics g);
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@ -0,0 +1,171 @@
namespace AirplaneWithRadar
{
// Карта с набром объектов под нее
internal class MapWithSetAirplaneGeneric<T, U>
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
// Ширина окна отрисовки
private readonly int _pictureWidth;
// Высота окна отрисовки
private readonly int _pictureHeight;
// Размер занимаемого объектом места (ширина)
private readonly int _placeSizeWidth = 120;
// Размер занимаемого объектом места (высота)
private readonly int _placeSizeHeight = 80;
// Набор объектов
private readonly SetAirplaneGeneric<T> _setAirplane;
// Карта
private readonly U _map;
// Конструктор
public MapWithSetAirplaneGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setAirplane = new SetAirplaneGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
// Перегрузка оператора сложения
public static int operator +(MapWithSetAirplaneGeneric<T, U> map, T airplane)
{
return map._setAirplane.Insert(airplane);
}
// Перегрузка оператора вычитания
public static T operator -(MapWithSetAirplaneGeneric<T, U> map, int position)
{
return map._setAirplane.Remove(position);
}
// Вывод всего набора объектов
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawAirplane(gr);
return bmp;
}
// Просмотр объекта на карте
public Bitmap ShowOnMap()
{
Shaking();
foreach (var ship in _setAirplane.GetAirplane())
{
return _map.CreateMap(_pictureWidth, _pictureHeight, ship);
}
return new(_pictureWidth, _pictureHeight);
}
// Перемещение объекта по карте
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
return new(_pictureWidth, _pictureHeight);
}
/// <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 _setAirplane.GetAirplane())
{
data += $"{airplane.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setAirplane.Insert(DrawningObjectAirplane.Create(rec) as T);
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
_setAirplane.SortSet(comparer);
}
// "Взбалтываем" набор, чтобы все элементы оказались в начале
private void Shaking()
{
int j = _setAirplane.Count - 1;
for (int i = 0; i < _setAirplane.Count; i++)
{
if (_setAirplane[i] == null)
{
for (; j > i; j--)
{
var airplane = _setAirplane[j];
if (airplane != null)
{
_setAirplane.Insert(airplane, i);
_setAirplane.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
// Метод отрисовки фона
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
Brush brush = new SolidBrush(Color.FromArgb(147, 146, 151));
g.FillRectangle(brush, 0, 0, _pictureWidth, _pictureHeight);
for (int i = 0; i <= _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j <= (_pictureHeight / _placeSizeHeight); ++j)
{//линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth, j * _placeSizeHeight);
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight + 10, i * _placeSizeWidth + _placeSizeWidth, j * _placeSizeHeight + 10);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, (_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
// Метод прорисовки объектов
private void DrawAirplane(Graphics g)
{
int widthEl = _pictureWidth / _placeSizeWidth;
int heightEl = _pictureHeight / _placeSizeHeight;
int curWidth = 0;
int curHeight = 0;
foreach (var airplane in _setAirplane.GetAirplane())
{
airplane?.SetObject(_pictureWidth - _placeSizeWidth * curWidth - 80,
curHeight * _placeSizeHeight + 30, _pictureWidth, _pictureHeight);
airplane?.DrawningObject(g);
if (curWidth < widthEl - 1)
curWidth++;
else
{
curWidth = 0;
curHeight++;
}
if (curHeight > heightEl)
{
return;
}
}
}
}
}

View File

@ -0,0 +1,114 @@
using AirplaneWithRadar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetAirplaneGeneric<IDrawningObject, AbstractMap>> _mapStorages;
public List<string> Keys => _mapStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetAirplaneGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddMap(string name, AbstractMap map)
{
if (!_mapStorages.ContainsKey(name))
{
_mapStorages.Add(name, new MapWithSetAirplaneGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
}
public void DelMap(string name)
{
if (_mapStorages.ContainsKey(name)) _mapStorages.Remove(name);
}
public MapWithSetAirplaneGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
if (_mapStorages.ContainsKey(ind))
{
return _mapStorages[ind];
}
return null;
}
}
/// <summary>
/// Сохранение информации по локомотивам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
}
/// <summary>
/// Загрузка информации по локомотивам в депо из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
if (!str.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "SkyMap":
map = new SkyMap();
break;
case "FoggySkyMap":
map = new FoggySkyMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetAirplaneGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirplaneWithRadar
{
internal static class Program
@ -11,7 +17,34 @@ namespace AirplaneWithRadar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetAirplane>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
string path = Directory.GetCurrentDirectory();
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
services.AddSingleton<FormMapWithSetAirplane>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: path + "\\serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

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

View File

@ -117,4 +117,17 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="arrowDown" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowDown.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowLeft" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowLeft.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowRight" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowRight.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowUp" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowUp.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

View File

@ -0,0 +1,100 @@
namespace AirplaneWithRadar
{
// Параметризованный набор объектов
internal class SetAirplaneGeneric<T>
where T : class, IEquatable<T>
{
private readonly List<T> _places;
public int Count => _places.Count;
private readonly int _maxCount;
// Конструктор
public SetAirplaneGeneric(int count)
{
_maxCount = count;
_places = new List<T>();
}
// Добавление объекта в набор
public int Insert(T airplane)
{
if (_places.Count > _maxCount)
{
return -1;
}
// вставка в начало набора
return Insert(airplane, 0);
}
// Добавление объекта в набор на конкретную позицию
public int Insert(T airplane, int position)
{
if (_places.Contains(airplane))
{
throw new ArgumentException($"Объект {airplane} уже присутствует в наборе");
}
if (position < 0 || position > Count || _maxCount == Count)
{
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, airplane);
return position;
}
// Удаление объекта из набора с конкретной позиции
public T Remove(int position)
{
if (position >= Count || position < 0)
{
throw new AirplaneNotFoundException(position);
}
T airplane = _places[position];
_places.RemoveAt(position);
return airplane;
}
// Получение объекта из набора по позиции
public T this[int position]
{
get
{
if (position >= _places.Count || position < 0)
{
return null;
}
return _places[position];
}
set
{
if (position >= _places.Count || position < 0)
{
return;
}
Insert(value, position);
}
}
public IEnumerable<T> GetAirplane()
{
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);
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
/// <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, i * (_size_x + 1), j * (_size_y + 1));
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, i * (_size_x + 1), j * (_size_y + 1));
}
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,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
/// <summary>
/// Простая реализация абсрактного класса AbstractMap
/// </summary>
internal class SkyMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Gray);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.LightBlue);
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 < 10)
{
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
if (x - 2 >=0 && y + 4 < 100 && x + 2 < 100)
{
if (_map[x, y] == _freeRoad && _map[x + 1, y + 1] == _freeRoad && _map[x - 1, y + 1] == _freeRoad && _map[x, y + 2] == _freeRoad && _map[x, y + 1] == _freeRoad
&& _map[x + 2, y + 2] == _freeRoad && _map[x - 2, y + 2] == _freeRoad && _map[x + 1, y + 3] == _freeRoad && _map[x - 1, y + 3] == _freeRoad
&& _map[x, y + 3] == _freeRoad && _map[x, y + 4] == _freeRoad && _map[x + 1, y + 2] == _freeRoad && _map[x - 1, y + 2] == _freeRoad)
{
_map[x, y] = _barrier;
_map[x + 1, y + 1] = _barrier;
_map[x - 1, y + 1] = _barrier;
_map[x + 2, y + 2] = _barrier;
_map[x - 2, y + 2] = _barrier;
_map[x, y + 2] = _barrier;
_map[x, y + 1] = _barrier;
_map[x + 1, y + 3] = _barrier;
_map[x - 1, y + 3] = _barrier;
_map[x, y + 3] = _barrier;
_map[x, y + 4] = _barrier;
_map[x + 1, y + 2] = _barrier;
_map[x - 1, y + 2] = _barrier;
counter++;
}
}
}
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
[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 context) : base(info, context) { }
}
}

View File

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