Compare commits

..

33 Commits

Author SHA1 Message Date
ArtemEmelyanov
4b2b4e4d2c готово 2022-12-14 13:01:37 +04:00
ArtemEmelyanov
2f7700a12e Сделанная лаба 2022-12-09 12:39:15 +04:00
ArtemEmelyanov
7aab615e91 Сортировка 2022-12-09 12:31:38 +04:00
ArtemEmelyanov
13591af122 Сравнение объектов 2022-12-09 12:17:27 +04:00
ArtemEmelyanov
644ea73342 complete 2022-12-09 11:59:35 +04:00
ArtemEmelyanov
5fa1c4cdc3 Сданная лаба 2022-11-30 10:08:55 +04:00
ArtemEmelyanov
39f7f8c79b вроде как доделанная лаба 2022-11-26 21:00:21 +04:00
ArtemEmelyanov
70543c40c7 Логирование. Собранная лаба 2022-11-25 16:18:49 +04:00
ArtemEmelyanov
aceb46ebe1 Генерация ошибок 2022-11-25 15:57:08 +04:00
ArtemEmelyanov
6f3123432f Сданная 6 лаба 2022-11-16 12:51:22 +04:00
ArtemEmelyanov
e55dbeb7a1 qwe 2022-11-16 12:43:59 +04:00
ArtemEmelyanov
bb01e3ae47 облажался 2022-11-16 12:42:55 +04:00
ArtemEmelyanov
e38935887b Сданная лаба 2022-11-16 12:29:30 +04:00
ArtemEmelyanov
f186addd69 Еще изменения 2022-11-10 21:40:24 +04:00
ArtemEmelyanov
f8259e6949 Внесены некоторые изменения 2022-11-10 21:28:52 +04:00
ArtemEmelyanov
5309551aa3 Собранная лаба 2022-11-10 19:23:10 +04:00
ArtemEmelyanov
080173f97f Сданная лаба 2022-11-04 17:53:34 +04:00
ArtemEmelyanov
75a36c4019 Вроде как доделанная лаба 2022-10-29 15:28:55 +04:00
ArtemEmelyanov
bc84a238c4 Этап 3 2022-10-29 14:59:03 +04:00
ArtemEmelyanov
71e7819cfd Этап 2 2022-10-29 14:12:01 +04:00
ArtemEmelyanov
81a407cc63 Этап 1. Смена массива на списки. 2022-10-29 14:07:33 +04:00
ArtemEmelyanov
378ba86d6c Сданная лаба 2022-10-19 10:00:42 +04:00
ArtemEmelyanov
2d38dcf373 Переделаны методы, готовая лаба 2022-10-18 16:51:12 +04:00
ArtemEmelyanov
9a7af194fe Вроде как доделанная лаба 2022-10-16 19:48:03 +04:00
ArtemEmelyanov
6c938430b0 Дополненная форма FormPlane 2022-10-16 13:34:08 +04:00
ArtemEmelyanov
80f867986d changes forms 2022-10-16 13:14:33 +04:00
ArtemEmelyanov
96b1b664a7 generic classes 2022-10-16 12:44:39 +04:00
ArtemEmelyanov
ed7cfe6354 Абстрактный класс 2022-10-15 23:39:05 +04:00
ArtemEmelyanov
477c7c1500 Добавление интерфейса 2022-10-15 22:54:57 +04:00
ArtemEmelyanov
5ac86cbb43 Продвинутый объект 2022-10-15 22:40:19 +04:00
ArtemEmelyanov
928fa3a1df Переходы на конструкторы 2022-10-15 22:17:30 +04:00
ArtemEmelyanov
dd086e5c0b LabWork01 2022-10-15 18:37:59 +04:00
ArtemEmelyanov
f81a857f68 FirstLab 2022-10-15 17:04:02 +04:00
31 changed files with 2956 additions and 260 deletions

View File

@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
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();
}
private bool CheckBarriers(float topOffset, float rightOffset, float leftOffset, float bottomOffset)
{
int top = Convert.ToInt32((_drawningObject.GetCurrentPosition().Top + topOffset) / _size_y);
int right = Convert.ToInt32((_drawningObject.GetCurrentPosition().Right + rightOffset) / _size_x);
int left = Convert.ToInt32((_drawningObject.GetCurrentPosition().Left + leftOffset) / _size_x);
int bottom = Convert.ToInt32((_drawningObject.GetCurrentPosition().Bottom + bottomOffset) / _size_y);
if (top < 0 || left < 0 || right >= _map.GetLength(1) || bottom >= _map.GetLength(0)) return false;
for (int i = top; i <= bottom; i++)
{
for (int j = left; j <= right; j++)
{
if (_map[j, i] == _barrier) return false;
}
}
return true;
}
public Bitmap MoveObject(Direction direction)
{
// TODO проверка, что объект может переместится в требуемом направлении
if (_drawningObject == null) return DrawMapWithObject();
bool isTrue = true;
switch (direction)
{
case Direction.Left:
if (!CheckBarriers(0, -1 * _drawningObject.Step, -1 * _drawningObject.Step, 0)) isTrue = false;
break;
case Direction.Right:
if (!CheckBarriers(0, _drawningObject.Step, _drawningObject.Step, 0)) isTrue = false;
break;
case Direction.Up:
if (!CheckBarriers(-1 * _drawningObject.Step, 0, 0, -1 * _drawningObject.Step)) isTrue = false;
break;
case Direction.Down:
if (!CheckBarriers(_drawningObject.Step, 0, 0, _drawningObject.Step)) isTrue = false;
break;
}
if (isTrue)
{
_drawningObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private bool SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.Next(0, 10);
int y = _random.Next(0, 10);
_drawningObject.SetObject(x, y, _width, _height);
// TODO првоерка, что объект не "накладывается" на закрытые участки
if (!CheckBarriers(0, 0, 0, 0)) return false;
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 ||
_map != other._map ||
_width != other._width ||
_size_x != other._size_x ||
_size_y != other._size_y ||
_height != other._height ||
GetType() != other.GetType() ||
_map.GetLength(0) != other._map.GetLength(0) ||
_map.GetLength(1) != other._map.GetLength(1))
{
return false;
}
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i, j] != other._map[i, j])
{
return false;
}
}
}
return true;
}
}
}

View File

@ -8,6 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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="NLog.Extensions.Logging" Version="5.1.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -6,8 +6,9 @@ using System.Threading.Tasks;
namespace Airbus namespace Airbus
{ {
internal enum Direction public enum Direction
{ {
None = 0,
Up = 1, Up = 1,
Down = 2, Down = 2,
Left = 3, Left = 3,

View File

@ -6,171 +6,71 @@ using System.Threading.Tasks;
namespace Airbus namespace Airbus
{ {
internal class DrawningAirbus internal class DrawningAirbus : DrawningPlane
{ {
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirbus Airbus { get; private set; }
/// <summary>
/// Левая координата отрисовки самолета
/// </summary>
private float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки самолета
/// </summary>
private float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private int? _pictureWidth = null;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private int? _pictureHeight = null;
/// <summary>
/// Ширина отрисовки самолета
/// </summary>
private readonly int _AirbusWidth = 130;
/// <summary>
/// Высота отрисовки самолета
/// </summary>
private readonly int _AirbusHeight = 70;
/// <summary> /// <summary>
/// Инициализация свойств /// Инициализация свойств
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param> /// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Цвет кузова</param> /// <param name="bodyColor">Цвет кузова</param>
public void Init(EntityAirbus Airbus) /// <param name="dopColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="wing">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
public DrawningAirbus(int speed, float weight, Color bodyColor, Color
dopColor, bool bodyKit, bool wing, bool sportLine) :
base(speed, weight, bodyColor, 140, 70)
{ {
this.Airbus = Airbus; Plane = new EntityAirbus(speed, weight, bodyColor, dopColor, bodyKit, wing, sportLine);
}
/// <summary>
/// Установка позиции самолета
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void SetPosition(int x, int y, int width, int height)
{
if (x >= 0 && x + _AirbusWidth <= width && y >= 0 && y + _AirbusHeight <= height)
{
_startPosX = x;
_startPosY = y;
_pictureWidth = width;
_pictureHeight = height;
} }
} public override void DrawTransport(Graphics g)
/// <summary>
/// Изменение направления пермещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{ {
if (!_pictureWidth.HasValue || !_pictureHeight.HasValue) if (Plane is not EntityAirbus Airbus)
{
return;
}
switch (direction)
{
// вправо
case Direction.Right:
if (_startPosX + _AirbusWidth + Airbus.Step < _pictureWidth)
{
_startPosX += Airbus.Step;
}
break;
//влево
case Direction.Left:
if (_startPosX - Airbus.Step > 0)
{
_startPosX -= Airbus.Step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - Airbus.Step > 0)
{
_startPosY -= Airbus.Step;
}
break;
//вниз
case Direction.Down:
if (_startPosY + _AirbusHeight + Airbus.Step < _pictureHeight)
{
_startPosY += Airbus.Step;
}
break;
}
}
/// <summary>
/// Отрисовка самолета
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0
|| !_pictureHeight.HasValue || !_pictureWidth.HasValue)
{ {
return; return;
} }
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
//границы самолета Brush dopBrush = new SolidBrush(Airbus.DopColor);
g.DrawEllipse(pen, _startPosX, _startPosY + 30, 20, 20); Brush fireBrush = new SolidBrush(Color.Red);
g.DrawRectangle(pen, _startPosX + 10, _startPosY + 30, 100, 20); Brush WindowBrush = new SolidBrush(Color.Blue);
g.DrawLine(pen, _startPosX + 110, _startPosY + 30, _startPosX + 130, _startPosY+40); _startPosX += 10;
g.DrawLine(pen, _startPosX + 110, _startPosY+50, _startPosX + 130, _startPosY+40); _startPosY += 5;
base.DrawTransport(g);
_startPosX -= 10;
_startPosY -= 5;
if (Airbus.BodyKit)
{
//1 реактор
g.DrawRectangle(pen, _startPosX + 70, _startPosY + 50, 22, 16);
g.FillRectangle(dopBrush, _startPosX + 70, _startPosY + 50, 22, 16);
g.FillEllipse(dopBrush, _startPosX + 84, _startPosY + 50, 16, 16);
g.DrawLine(pen, _startPosX, _startPosY, _startPosX, _startPosY+40); g.DrawEllipse(pen, _startPosX + 62, _startPosY + 50, 16, 16);
g.DrawLine(pen, _startPosX, _startPosY, _startPosX + 30, _startPosY+30); g.FillEllipse(fireBrush, _startPosX + 62, _startPosY + 50, 16, 16);
//2 реактор
g.DrawLine(pen, _startPosX + 40, _startPosY + 50, _startPosX + 40, _startPosY+55); g.DrawRectangle(pen, _startPosX + 8, _startPosY + 18, 22, 16);
g.DrawLine(pen, _startPosX + 100, _startPosY + 50, _startPosX + 100, _startPosY+55); g.FillRectangle(dopBrush, _startPosX + 8, _startPosY + 18, 22, 16);
g.DrawEllipse(pen, _startPosX + 95, _startPosY + 55, 10, 10); g.FillEllipse(dopBrush, _startPosX + 24, _startPosY + 18, 16, 16);
g.DrawEllipse(pen, _startPosX + 29, _startPosY + 55, 10, 10);
g.DrawEllipse(pen, _startPosX + 41, _startPosY + 55, 10, 10);
Brush br = new SolidBrush(Airbus?.BodyColor ?? Color.Black); g.DrawEllipse(pen, _startPosX, _startPosY + 18, 16, 16);
g.FillEllipse(br, _startPosX, _startPosY + 31, 20, 19); g.FillEllipse(fireBrush, _startPosX, _startPosY + 18, 16, 16);
g.FillRectangle(br, _startPosX + 10, _startPosY + 31, 100, 19);
//илюминатор
Brush brBlack = new SolidBrush(Color.Black);
g.FillEllipse(brBlack, _startPosX + 40, _startPosY + 35, 60, 5);
g.FillEllipse(brBlack, _startPosX - 5, _startPosY + 25, 30, 10);
} }
/// <summary> if (Airbus.Wing)
/// Смена границ формы отрисовки
/// </summary>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void ChangeBorders(int width, int height)
{ {
_pictureWidth = width; g.DrawLine(pen, _startPosX + 70, _startPosY + 20, _startPosX + 70, _startPosY + 35);
_pictureHeight = height; g.DrawLine(pen, _startPosX + 70, _startPosY + 20, _startPosX + 90, _startPosY + 35);
if (_pictureWidth <= _AirbusWidth || _pictureHeight <= _AirbusHeight)
{
_pictureWidth = null;
_pictureHeight = null;
return;
} }
if (_startPosX + _AirbusWidth > _pictureWidth) if (Airbus.SportLine)
{ {
_startPosX = _pictureWidth.Value - _AirbusWidth; g.DrawEllipse(pen, _startPosX + 110, _startPosY + 40, 9, 9);
} g.FillEllipse(WindowBrush, _startPosX + 110, _startPosY + 40, 9, 9);
if (_startPosY + _AirbusHeight > _pictureHeight)
{
_startPosY = _pictureHeight.Value - _AirbusHeight;
} }
} }
} }

View File

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
internal class DrawningObjectPlane : IDrawningObject
{
private DrawningPlane _plane = null;
public DrawningObjectPlane(DrawningPlane plane)
{
_plane = plane;
}
public float Step => _plane?.Plane?.Step ?? 0;
public DrawningPlane GetPlane => _plane;
public (float Left, float Top, float Right, float Bottom)
GetCurrentPosition()
{
return _plane?.GetCurrentPosition() ?? default;
}
public void MoveObject(Direction direction)
{
_plane?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_plane.SetPosition(x, y, width, height);
}
public void DrawningObject(Graphics g)
{
_plane.DrawTransport(g);
}
public string GetInfo() => _plane?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectPlane(data.CreateDrawningPlane());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otherPlane = other as DrawningObjectPlane;
if (otherPlane == null)
{
return false;
}
var plane = _plane.Plane;
var otherPlanePlane = otherPlane._plane.Plane;
if (plane.Speed != otherPlanePlane.Speed)
{
return false;
}
if (plane.Weight != otherPlanePlane.Weight)
{
return false;
}
if (plane.BodyColor != otherPlanePlane.BodyColor)
{
return false;
}
if ((plane is EntityAirbus) && !(otherPlanePlane is EntityAirbus)
|| !(plane is EntityAirbus) && (otherPlanePlane is EntityAirbus))
{
return false;
}
if (plane is EntityAirbus airbus && otherPlanePlane is EntityAirbus otherAirbus)
{
if (airbus.DopColor != otherAirbus.DopColor)
{
return false;
}
if (airbus.BodyKit != otherAirbus.BodyKit)
{
return false;
}
if (airbus.Wing != otherAirbus.BodyKit)
{
return false;
}
if (airbus.SportLine != otherAirbus.SportLine)
{
return false;
}
}
return true;
}
}
}

View File

@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
public class DrawningPlane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityPlane Plane { get; protected set; }
/// <summary>
/// Левая координата отрисовки самолета
/// </summary>
protected float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки самолета
/// </summary>
protected float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private int? _pictureWidth = null;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private int? _pictureHeight = null;
/// <summary>
/// Ширина отрисовки самолета
/// </summary>
private readonly int _PlaneWidth = 130;
/// <summary>
/// Высота отрисовки самолета
/// </summary>
private readonly int _PlaneHeight = 70;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет кузова</param>
public DrawningPlane(int speed, float weight, Color bodyColor)
{
Plane = new EntityPlane(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции самолета
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void SetPosition(int x, int y, int width, int height)
{
if (x >= 0 && x + _PlaneWidth <= width && y >= 0 && y + _PlaneHeight <= height)
{
_startPosX = x;
_startPosY = y;
_pictureWidth = width;
_pictureHeight = height;
}
}
/// <summary>
/// Изменение направления пермещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{
if (!_pictureWidth.HasValue || !_pictureHeight.HasValue)
{
return;
}
switch (direction)
{
// вправо
case Direction.Right:
if (_startPosX + _PlaneWidth + Plane.Step < _pictureWidth)
{
_startPosX += Plane.Step;
}
break;
//влево
case Direction.Left:
if (_startPosX - Plane.Step > 0)
{
_startPosX -= Plane.Step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - Plane.Step > 0)
{
_startPosY -= Plane.Step;
}
break;
//вниз
case Direction.Down:
if (_startPosY + _PlaneHeight + Plane.Step < _pictureHeight)
{
_startPosY += Plane.Step;
}
break;
}
}
/// <summary>
/// Отрисовка самолета
/// </summary>
/// <param name="g"></param>
///
protected DrawningPlane(int speed, float weight, Color bodyColor, int planeWidth, int planeHeight) : this(speed, weight, bodyColor)
{
_PlaneWidth = planeWidth;
_PlaneHeight = planeHeight;
}
public virtual void DrawTransport(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0
|| !_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
Pen pen = new(Color.Black);
//границы самолета
g.DrawEllipse(pen, _startPosX, _startPosY + 30, 20, 20);
g.DrawRectangle(pen, _startPosX + 10, _startPosY + 30, 100, 20);
g.DrawLine(pen, _startPosX + 110, _startPosY + 30, _startPosX + 130, _startPosY+40);
g.DrawLine(pen, _startPosX + 110, _startPosY+50, _startPosX + 130, _startPosY+40);
g.DrawLine(pen, _startPosX, _startPosY, _startPosX, _startPosY+40);
g.DrawLine(pen, _startPosX, _startPosY, _startPosX + 30, _startPosY+30);
g.DrawLine(pen, _startPosX + 40, _startPosY + 50, _startPosX + 40, _startPosY+55);
g.DrawLine(pen, _startPosX + 100, _startPosY + 50, _startPosX + 100, _startPosY+55);
g.DrawEllipse(pen, _startPosX + 95, _startPosY + 55, 10, 10);
g.DrawEllipse(pen, _startPosX + 29, _startPosY + 55, 10, 10);
g.DrawEllipse(pen, _startPosX + 41, _startPosY + 55, 10, 10);
Brush br = new SolidBrush(Plane?.BodyColor ?? Color.Black);
g.FillEllipse(br, _startPosX, _startPosY + 31, 20, 19);
g.FillRectangle(br, _startPosX + 10, _startPosY + 31, 100, 19);
//илюминатор
Brush brBlack = new SolidBrush(Color.Black);
g.FillEllipse(brBlack, _startPosX + 40, _startPosY + 35, 60, 5);
g.FillEllipse(brBlack, _startPosX - 5, _startPosY + 25, 30, 10);
}
/// <summary>
/// Смена границ формы отрисовки
/// </summary>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void ChangeBorders(int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth <= _PlaneWidth || _pictureHeight <= _PlaneHeight)
{
_pictureWidth = null;
_pictureHeight = null;
return;
}
if (_startPosX + _PlaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth.Value - _PlaneWidth;
}
if (_startPosY + _PlaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight.Value - _PlaneHeight;
}
}
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return (_startPosX, _startPosY, _startPosX + _PlaneWidth, _startPosY + _PlaneHeight);
}
}
}

View File

@ -6,39 +6,41 @@ using System.Threading.Tasks;
namespace Airbus namespace Airbus
{ {
internal class EntityAirbus internal class EntityAirbus : EntityPlane
{ {
/// <summary> /// <summary>
/// Скорость /// Дополнительный цвет
/// </summary> /// </summary>
public int Speed { get; private set; } public Color DopColor { get; set; }
/// <summary> /// <summary>
/// Вес /// Признак наличия обвеса
/// </summary> /// </summary>
public float Weight { get; private set; } public bool BodyKit { get; private set; }
/// <summary> /// <summary>
/// Цвет кузова /// Признак наличия антикрыла
/// </summary> /// </summary>
public Color BodyColor { get; private set; } public bool Wing { get; private set; }
/// <summary> /// <summary>
/// Шаг перемещения автомобиля /// Признак наличия гоночной полосы
/// </summary> /// </summary>
public float Step => Speed * 100 / Weight; public bool SportLine { get; private set; }
/// <summary> /// <summary>
/// Инициализация полей объекта-класса автомобиля /// Инициализация свойств
/// </summary> /// </summary>
/// <param name="speed"></param> /// <param name="speed">Скорость</param>
/// <param name="weight"></param> /// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor"></param> /// <param name="bodyColor">Цвет кузова</param>
/// <returns></returns> /// <param name="dopColor">Дополнительный цвет</param>
public void Init(int speed, float weight, Color bodyColor) /// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="wing">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
public EntityAirbus(int speed, float weight, Color bodyColor, Color dopColor, bool bodyKit, bool wing, bool sportLine) : base(speed, weight, bodyColor)
{ {
Random rnd = new(); DopColor = dopColor;
Speed = speed <= 0 ? rnd.Next(50, 150) : speed; BodyKit = bodyKit;
Weight = weight <= 0 ? rnd.Next(40, 70) : weight; Wing = wing;
BodyColor = bodyColor; SportLine = sportLine;
} }
} }
} }

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
public class EntityPlane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public float Weight { get; private set; }
/// <summary>
/// Цвет кузова
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public float Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса автомобиля
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <returns></returns>
public EntityPlane(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,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
internal static class ExtentionPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningPlane CreateDrawningPlane(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningPlane(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawningAirbus(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="drawningPlane"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningPlane drawningPlane)
{
var plane = drawningPlane.Plane;
var str = $"{plane.Speed}{_separatorForObject}{plane.Weight}{_separatorForObject}{plane.BodyColor. Name}";
if (plane is not EntityAirbus airbus)
{
return str;
}
return
$"{str}{_separatorForObject}{airbus.DopColor.Name}{_separatorForObject}{airbus.BodyKit}{_separatorForObject}{airbus.Wing}{_separatorForObject}{airbus.SportLine}";
}
}
}

View File

@ -1,89 +0,0 @@
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 Airbus
{
public partial class FormAirbus : Form
{
private DrawningAirbus _airbus;
public FormAirbus()
{
InitializeComponent();
}
/// <summary>
/// Метод прорисовки самолета
/// </summary>
private void Draw()
{
Bitmap bmp = new(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
Graphics gr = Graphics.FromImage(bmp);
_airbus?.DrawTransport(gr);
pictureBoxAirbus.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
_airbus = new DrawningAirbus();
EntityAirbus Airbus = new EntityAirbus();
Airbus.Init(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_airbus.Init(Airbus);
_airbus.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxAirbus.Width, pictureBoxAirbus.Height);
toolStripStatusLabelSpeed.Text = $"Скорость: {_airbus.Airbus.Speed}";
toolStripStatusLabelWeight.Text = $"Вес: {_airbus.Airbus.Weight}";
toolStripStatusLabelBodyColor.Text = $"Цвет: {_airbus.Airbus.BodyColor.Name}";
Draw();
}
/// <summary>
/// Изменение размеров формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_airbus?.MoveTransport(Direction.Up);
break;
case "buttonDown":
_airbus?.MoveTransport(Direction.Down);
break;
case "buttonLeft":
_airbus?.MoveTransport(Direction.Left);
break;
case "buttonRight":
_airbus?.MoveTransport(Direction.Right);
break;
}
Draw();
}
/// <summary>
/// Изменение размеров формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PictureBoxAirbus_Resize(object sender, EventArgs e)
{
_airbus?.ChangeBorders(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
Draw();
}
}
}

View File

@ -0,0 +1,360 @@
namespace Airbus
{
partial class FormMapWithSetPlanes
{
/// <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.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBoxMaps = 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.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = 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.buttonRemovePlane = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddPlane = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip1 = 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.buttonSortByType = new System.Windows.Forms.Button();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.buttonSortByColor);
this.groupBox1.Controls.Add(this.buttonSortByType);
this.groupBox1.Controls.Add(this.groupBoxMaps);
this.groupBox1.Controls.Add(this.buttonLeft);
this.groupBox1.Controls.Add(this.buttonRight);
this.groupBox1.Controls.Add(this.buttonDown);
this.groupBox1.Controls.Add(this.buttonUp);
this.groupBox1.Controls.Add(this.buttonShowOnMap);
this.groupBox1.Controls.Add(this.buttonShowStorage);
this.groupBox1.Controls.Add(this.buttonRemovePlane);
this.groupBox1.Controls.Add(this.maskedTextBoxPosition);
this.groupBox1.Controls.Add(this.buttonAddPlane);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox1.Location = new System.Drawing.Point(657, 24);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 674);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
//
// groupBoxMaps
//
this.groupBoxMaps.Controls.Add(this.buttonDeleteMap);
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
this.groupBoxMaps.Controls.Add(this.buttonAddMap);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(6, 22);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Size = new System.Drawing.Size(188, 263);
this.groupBoxMaps.TabIndex = 10;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(11, 218);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(171, 34);
this.buttonDeleteMap.TabIndex = 4;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.buttonDeleteMap_Click_1);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 15;
this.listBoxMaps.Location = new System.Drawing.Point(11, 118);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(171, 94);
this.listBoxMaps.TabIndex = 3;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.listBoxMaps_SelectedIndexChanged_1);
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(11, 80);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(171, 32);
this.buttonAddMap.TabIndex = 2;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.buttonAddMap_Click_1);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(11, 22);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(171, 23);
this.textBoxNewMapName.TabIndex = 0;
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Вторая карта"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(11, 51);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(171, 23);
this.comboBoxSelectorMap.TabIndex = 0;
//
// buttonLeft
//
this.buttonLeft.BackgroundImage = global::Airbus.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(56, 634);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 9;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.BackgroundImage = global::Airbus.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(128, 634);
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);
//
// buttonDown
//
this.buttonDown.BackgroundImage = global::Airbus.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(92, 634);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 7;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonUp
//
this.buttonUp.BackgroundImage = global::Airbus.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(92, 598);
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.Location = new System.Drawing.Point(17, 561);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(171, 31);
this.buttonShowOnMap.TabIndex = 5;
this.buttonShowOnMap.Text = "Посмотреть карту";
this.buttonShowOnMap.UseVisualStyleBackColor = true;
this.buttonShowOnMap.Click += new System.EventHandler(this.buttonShowOnMap_Click_1);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(17, 521);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(171, 34);
this.buttonShowStorage.TabIndex = 4;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.buttonShowStorage_Click_1);
//
// buttonRemovePlane
//
this.buttonRemovePlane.Location = new System.Drawing.Point(17, 462);
this.buttonRemovePlane.Name = "buttonRemovePlane";
this.buttonRemovePlane.Size = new System.Drawing.Size(171, 31);
this.buttonRemovePlane.TabIndex = 3;
this.buttonRemovePlane.Text = "Удалить самолёт";
this.buttonRemovePlane.UseVisualStyleBackColor = true;
this.buttonRemovePlane.Click += new System.EventHandler(this.buttonRemovePlane_Click_1);
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(17, 433);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(171, 23);
this.maskedTextBoxPosition.TabIndex = 2;
//
// buttonAddPlane
//
this.buttonAddPlane.Location = new System.Drawing.Point(17, 377);
this.buttonAddPlane.Name = "buttonAddPlane";
this.buttonAddPlane.Size = new System.Drawing.Size(171, 31);
this.buttonAddPlane.TabIndex = 1;
this.buttonAddPlane.Text = "Добавить самолёт";
this.buttonAddPlane.UseVisualStyleBackColor = true;
this.buttonAddPlane.Click += new System.EventHandler(this.buttonAddPlane_Click_1);
//
// 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(657, 674);
this.pictureBox.TabIndex = 0;
this.pictureBox.TabStop = false;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(857, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.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.Filter = "«txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "«txt file | *.txt";
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(17, 291);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(171, 26);
this.buttonSortByType.TabIndex = 11;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(17, 323);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(171, 26);
this.buttonSortByColor.TabIndex = 12;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click);
//
// FormMapWithSetPlanes
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(857, 698);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMapWithSetPlanes";
this.Text = "Карта с набором объектов";
this.Click += new System.EventHandler(this.ButtonMove_Click);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private GroupBox groupBox1;
private Button buttonLeft;
private Button buttonRight;
private Button buttonDown;
private Button buttonUp;
private Button buttonShowOnMap;
private Button buttonShowStorage;
private Button buttonRemovePlane;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonAddPlane;
private ComboBox comboBoxSelectorMap;
private PictureBox pictureBox;
private GroupBox groupBoxMaps;
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -0,0 +1,319 @@
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 Airbus
{
public partial class FormMapWithSetPlanes : Form
{
/// <summary>
/// Словарь для выпадающего списка
/// </summary>
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Вторая карта", new MyMap() }
};
/// <summary>
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Конструктор
/// </summary>
private readonly ILogger _logger;
public FormMapWithSetPlanes(ILogger<FormMapWithSetPlanes> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
/// <summary>
/// Заполнение listBoxMaps
/// </summary>
private void ReloadMaps()
{
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for (int i = 0; i < _mapsCollection.Keys.Count; i++)
{
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
}
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{
listBoxMaps.SelectedIndex = 0;
}
else if (listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
listBoxMaps.SelectedIndex = index;
}
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddMap_Click_1(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Отсутствует карта с типом {0}", comboBoxSelectorMap.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxMaps_SelectedIndexChanged_1(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDeleteMap_Click_1(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddPlane_Click_1(object sender, EventArgs e)
{
var formPlaneConfig = new FormPlaneConfig();
formPlaneConfig.AddEvent(AddPlane);
formPlaneConfig.Show();
}
private void AddPlane(DrawningPlane plane)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
}
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Plane}", plane);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemovePlane_Click_1(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (PlaneNotFoundException 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_1(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_1(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 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)
{
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
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($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new PlaneCompareByType());
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new PlaneCompareByColor());
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="menuStrip1.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>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>272, 17</value>
</metadata>
</root>

View File

@ -1,6 +1,6 @@
namespace Airbus namespace Airbus
{ {
partial class FormAirbus partial class FormPlane
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
@ -38,6 +38,8 @@
this.buttonLeft = new System.Windows.Forms.Button(); this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button(); this.buttonUp = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button(); this.buttonDown = new System.Windows.Forms.Button();
this.buttonCreateModif = new System.Windows.Forms.Button();
this.buttonSelectPlane = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirbus)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirbus)).BeginInit();
this.statusStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
@ -149,11 +151,33 @@
this.buttonDown.UseVisualStyleBackColor = true; this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click); this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
// //
// FormAirbus // buttonCreateModif
//
this.buttonCreateModif.Location = new System.Drawing.Point(98, 285);
this.buttonCreateModif.Name = "buttonCreateModif";
this.buttonCreateModif.Size = new System.Drawing.Size(99, 23);
this.buttonCreateModif.TabIndex = 7;
this.buttonCreateModif.Text = "Модификация";
this.buttonCreateModif.UseVisualStyleBackColor = true;
this.buttonCreateModif.Click += new System.EventHandler(this.buttonCreateModif_Click);
//
// buttonSelectPlane
//
this.buttonSelectPlane.Location = new System.Drawing.Point(514, 285);
this.buttonSelectPlane.Name = "buttonSelectPlane";
this.buttonSelectPlane.Size = new System.Drawing.Size(75, 23);
this.buttonSelectPlane.TabIndex = 8;
this.buttonSelectPlane.Text = "Выбрать";
this.buttonSelectPlane.UseVisualStyleBackColor = true;
this.buttonSelectPlane.Click += new System.EventHandler(this.buttonSelectPlane_Click);
//
// FormPlane
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(700, 338); this.ClientSize = new System.Drawing.Size(700, 338);
this.Controls.Add(this.buttonSelectPlane);
this.Controls.Add(this.buttonCreateModif);
this.Controls.Add(this.buttonDown); this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonUp); this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonLeft); this.Controls.Add(this.buttonLeft);
@ -162,7 +186,7 @@
this.Controls.Add(this.statusStrip1); this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.pictureBoxAirbus); this.Controls.Add(this.pictureBoxAirbus);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormAirbus"; this.Name = "FormPlane";
this.Text = "Самолет"; this.Text = "Самолет";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirbus)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirbus)).EndInit();
this.statusStrip1.ResumeLayout(false); this.statusStrip1.ResumeLayout(false);
@ -184,5 +208,7 @@
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonCreateModif;
private Button buttonSelectPlane;
} }
} }

125
Airbus/Airbus/FormPlane.cs Normal file
View File

@ -0,0 +1,125 @@
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 Airbus
{
public partial class FormPlane : Form
{
private DrawningPlane _plane;
public DrawningPlane SelectedPlane { get; private set; }
public FormPlane()
{
InitializeComponent();
}
/// <summary>
/// Метод прорисовки самолета
/// </summary>
private void Draw()
{
Bitmap bmp = new(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
Graphics gr = Graphics.FromImage(bmp);
_plane?.DrawTransport(gr);
pictureBoxAirbus.Image = bmp;
}
private void SetData()
{
Random rnd = new();
_plane.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxAirbus.Width, pictureBoxAirbus.Height);
toolStripStatusLabelSpeed.Text = $"Скорость: {_plane.Plane.Speed}";
toolStripStatusLabelWeight.Text = $"Вес: {_plane.Plane.Weight}";
toolStripStatusLabelBodyColor.Text = $"Цвет: {_plane.Plane.BodyColor.Name}";
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_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;
}
_plane = new DrawningPlane(rnd.Next(100, 300), rnd.Next(1000, 2000),color);
SetData();
Draw();
}
/// <summary>
/// Изменение размеров формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_plane?.MoveTransport(Direction.Up);
break;
case "buttonDown":
_plane?.MoveTransport(Direction.Down);
break;
case "buttonLeft":
_plane?.MoveTransport(Direction.Left);
break;
case "buttonRight":
_plane?.MoveTransport(Direction.Right);
break;
}
Draw();
}
/// <summary>
/// Изменение размеров формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PictureBoxAirbus_Resize(object sender, EventArgs e)
{
_plane?.ChangeBorders(pictureBoxAirbus.Width, pictureBoxAirbus.Height);
Draw();
}
private void buttonCreateModif_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;
}
_plane = new DrawningAirbus(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 buttonSelectPlane_Click(object sender, EventArgs e)
{
SelectedPlane = _plane;
DialogResult = DialogResult.OK;
}
}
}

372
Airbus/Airbus/FormPlaneConfig.Designer.cs generated Normal file
View File

@ -0,0 +1,372 @@
namespace Airbus
{
partial class FormPlaneConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelPink = new System.Windows.Forms.Panel();
this.panelGol = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelOrange = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxSportLine = new System.Windows.Forms.CheckBox();
this.checkBoxWing = new System.Windows.Forms.CheckBox();
this.checkBoxBodyKit = 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.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.panelObject = new System.Windows.Forms.Panel();
this.labelBaseColor = new System.Windows.Forms.Label();
this.labelDopColor = new System.Windows.Forms.Label();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.panelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColor);
this.groupBoxConfig.Controls.Add(this.checkBoxSportLine);
this.groupBoxConfig.Controls.Add(this.checkBoxWing);
this.groupBoxConfig.Controls.Add(this.checkBoxBodyKit);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.labelWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.labelSpeed);
this.groupBoxConfig.Location = new System.Drawing.Point(12, 12);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(498, 175);
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(396, 130);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(96, 35);
this.labelModifiedObject.TabIndex = 7;
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(298, 130);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(92, 35);
this.labelSimpleObject.TabIndex = 1;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColor
//
this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelPink);
this.groupBoxColor.Controls.Add(this.panelGol);
this.groupBoxColor.Controls.Add(this.panelBlue);
this.groupBoxColor.Controls.Add(this.panelOrange);
this.groupBoxColor.Controls.Add(this.panelYellow);
this.groupBoxColor.Controls.Add(this.panelGreen);
this.groupBoxColor.Controls.Add(this.panelRed);
this.groupBoxColor.Location = new System.Drawing.Point(298, 15);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Size = new System.Drawing.Size(194, 112);
this.groupBoxColor.TabIndex = 1;
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(144, 68);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 1;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelPink
//
this.panelPink.BackColor = System.Drawing.Color.Fuchsia;
this.panelPink.Location = new System.Drawing.Point(98, 68);
this.panelPink.Name = "panelPink";
this.panelPink.Size = new System.Drawing.Size(40, 40);
this.panelPink.TabIndex = 1;
this.panelPink.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGol
//
this.panelGol.BackColor = System.Drawing.Color.Cyan;
this.panelGol.Location = new System.Drawing.Point(52, 68);
this.panelGol.Name = "panelGol";
this.panelGol.Size = new System.Drawing.Size(40, 40);
this.panelGol.TabIndex = 1;
this.panelGol.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
this.panelBlue.Location = new System.Drawing.Point(6, 68);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(40, 40);
this.panelBlue.TabIndex = 2;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelOrange
//
this.panelOrange.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
this.panelOrange.Location = new System.Drawing.Point(144, 22);
this.panelOrange.Name = "panelOrange";
this.panelOrange.Size = new System.Drawing.Size(40, 40);
this.panelOrange.TabIndex = 1;
this.panelOrange.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(98, 22);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(40, 40);
this.panelYellow.TabIndex = 1;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Lime;
this.panelGreen.Location = new System.Drawing.Point(52, 22);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
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(6, 22);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 0;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxSportLine
//
this.checkBoxSportLine.AutoSize = true;
this.checkBoxSportLine.Location = new System.Drawing.Point(17, 146);
this.checkBoxSportLine.Name = "checkBoxSportLine";
this.checkBoxSportLine.Size = new System.Drawing.Size(254, 19);
this.checkBoxSportLine.TabIndex = 6;
this.checkBoxSportLine.Text = "Признак наличия отсека для пассажиров";
this.checkBoxSportLine.UseVisualStyleBackColor = true;
//
// checkBoxWing
//
this.checkBoxWing.AutoSize = true;
this.checkBoxWing.Location = new System.Drawing.Point(17, 121);
this.checkBoxWing.Name = "checkBoxWing";
this.checkBoxWing.Size = new System.Drawing.Size(186, 19);
this.checkBoxWing.TabIndex = 5;
this.checkBoxWing.Text = "Признак наличия антикрыла";
this.checkBoxWing.UseVisualStyleBackColor = true;
//
// checkBoxBodyKit
//
this.checkBoxBodyKit.AutoSize = true;
this.checkBoxBodyKit.Location = new System.Drawing.Point(17, 96);
this.checkBoxBodyKit.Name = "checkBoxBodyKit";
this.checkBoxBodyKit.Size = new System.Drawing.Size(210, 19);
this.checkBoxBodyKit.TabIndex = 4;
this.checkBoxBodyKit.Text = "Признак наличия доп.двигателей";
this.checkBoxBodyKit.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(82, 67);
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(97, 23);
this.numericUpDownWeight.TabIndex = 3;
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(17, 69);
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(82, 28);
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(97, 23);
this.numericUpDownSpeed.TabIndex = 1;
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(17, 30);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(62, 15);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость:";
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(16, 52);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(219, 88);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(522, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(251, 150);
this.panelObject.TabIndex = 1;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(16, 10);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(96, 35);
this.labelBaseColor.TabIndex = 9;
this.labelBaseColor.Text = "Цвет";
this.labelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragDrop);
this.labelBaseColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragEnter);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(139, 10);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(96, 35);
this.labelDopColor.TabIndex = 8;
this.labelDopColor.Text = "Доп. цвет";
this.labelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDopColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
this.labelDopColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragEnter);
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(522, 168);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(100, 23);
this.buttonOk.TabIndex = 2;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(677, 168);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(96, 23);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormPlaneConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(785, 193);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormPlaneConfig";
this.Text = "Создание объекта";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.panelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private CheckBox checkBoxSportLine;
private CheckBox checkBoxWing;
private CheckBox checkBoxBodyKit;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColor;
private Panel panelBlack;
private Panel panelPink;
private Panel panelGol;
private Panel panelBlue;
private Panel panelOrange;
private Panel panelYellow;
private Panel panelGreen;
private Panel panelRed;
private PictureBox pictureBoxObject;
private Panel panelObject;
private Label labelDopColor;
private Button buttonOk;
private Button buttonCancel;
private Label labelBaseColor;
}
}

View File

@ -0,0 +1,177 @@
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 Airbus
{
public partial class FormPlaneConfig : Form
{
/// <summary>
/// Переменная-выбранная машина
/// </summary>
DrawningPlane _plane = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningPlane> EventAddPlane;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPink.MouseDown += PanelColor_MouseDown;
panelOrange.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelGol.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
// TODO buttonCancel.Click with lambda
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать машину
/// </summary>
private void DrawPlane()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_plane?.SetPosition(5, 5, pictureBoxObject.Width, pictureBoxObject.Height);
_plane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev"></param>
public void AddEvent(Action<DrawningPlane> ev)
{
if (EventAddPlane == null)
{
EventAddPlane = new Action<DrawningPlane>(ev);
}
else
{
EventAddPlane += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_plane = new DrawningPlane((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_plane = new DrawningAirbus((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxBodyKit.Checked, checkBoxWing.Checked,
checkBoxSportLine.Checked);
break;
}
DrawPlane();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
// TODO Call method from object _car and set color
if (_plane == null)
{
return;
}
_plane.Plane.BodyColor = (Color)e.Data.GetData(typeof(Color));
DrawPlane();
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if (_plane == null || _plane.Plane is not EntityAirbus airbus)
{
return;
}
airbus.DopColor = (Color)e.Data.GetData(typeof(Color));
DrawPlane();
}
/// <summary>
/// Добавление машины
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonOk_Click(object sender, EventArgs e)
{
EventAddPlane?.Invoke(_plane);
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,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
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>
void MoveObject(Direction direction);
/// <summary>
/// Отрисовка объекта
/// </summary>
/// <param name="g"></param>
void DrawningObject(Graphics g);
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
(float Left, float Top, float Right, float Bottom)
GetCurrentPosition();
string GetInfo();
}
}

View File

@ -0,0 +1,220 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
internal class MapWithSetPlanesGeneric<T, U>
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetPlanesGeneric<T> _setPlanes;
/// <summary>
/// Карта
/// </summary>
private readonly U _map;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="map"></param>
public MapWithSetPlanesGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setPlanes = new SetPlanesGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="planes"></param>
/// <returns></returns>
public static int operator +(MapWithSetPlanesGeneric<T, U> map, T planes)
{
return map._setPlanes.Insert(planes);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="map"></param>
/// <param name="position"></param>
/// <returns></returns>
public static T operator -(MapWithSetPlanesGeneric<T, U> map, int position)
{
return map._setPlanes.Remove(position);
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawPlanes(gr);
return bmp;
}
/// <summary>
/// Просмотр объекта на карте
/// </summary>
/// <returns></returns>
public Bitmap ShowOnMap()
{
Shaking();
foreach (var plane in _setPlanes.GetPlanes())
{
return _map.CreateMap(_pictureWidth, _pictureHeight, plane);
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Перемещение объекта по крате
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()
{
int j = _setPlanes.Count - 1;
for (int i = 0; i < _setPlanes.Count; i++)
{
if (_setPlanes[i] == null)
{
for (; j > i; j--)
{
var plane = _setPlanes[j];
if (plane != null)
{
_setPlanes.Insert(plane, i);
_setPlanes.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Brush road = new SolidBrush(Color.Gray);
g.FillRectangle(road, 0, 0, _pictureWidth, _pictureHeight);
Brush lines = new SolidBrush(Color.White);
for (int y = 0; y < _pictureHeight; y+=80)
{
g.FillRectangle(lines, _pictureWidth / 2 - 10, y, 20, 70);
}
int lastLine = 0;
for (int y = 50; y < _pictureHeight; y += _pictureHeight/3 - 50)
{
g.FillRectangle(lines, _pictureWidth / 3 - 10, y, 20, 70);
g.FillRectangle(lines, _pictureWidth - _pictureWidth / 3 - 10, y, 20, 70);
lastLine = y;
}
g.FillRectangle(lines, _pictureWidth / 3 - 40, lastLine, 20, 70);
g.FillRectangle(lines, _pictureWidth - _pictureWidth / 3 + 20, lastLine, 20, 70);
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i *
_placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth,
(_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawPlanes(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int i = 0;
foreach (var plane in _setPlanes.GetPlanes())
{
// TODO установка позиции
plane.SetObject((width - i % width - 1) * _placeSizeWidth, (height - i / width - 1) * _placeSizeHeight, _pictureWidth, _pictureHeight);
plane.DrawningObject(g);
i++;
}
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var plane in _setPlanes.GetPlanes())
{
data += $"{plane.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setPlanes.Insert(DrawningObjectPlane.Create(rec) as T);
}
}
public void Sort(IComparer<T> comparer)
{
_setPlanes.SortSet(comparer);
}
}
}

View File

@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
internal class MapsCollection
{
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetPlanesGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
public List<string> Keys => _mapStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
private readonly char separatorDict = '|';
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetPlanesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="name">Название карты</param>
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
// TODO Прописать логику для добавления
if (_mapStorages.ContainsKey(name))
{
return;
}
_mapStorages.Add(name, new MapWithSetPlanesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="name">Название карты</param>
public void DelMap(string name)
{
// TODO Прописать логику для удаления
_mapStorages.Remove(name);
}
/// <summary>
/// Доступ к парковке
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetPlanesGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
// TODO Продумать логику получения объекта
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 = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
var tempElem = str.Split(separatorDict);
AbstractMap map = null;
switch (tempElem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "MyMap":
map = new MyMap();
break;
}
_mapStorages.Add(tempElem[0], new MapWithSetPlanesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

48
Airbus/Airbus/MyMap.cs Normal file
View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
internal class MyMap : AbstractMap
{
private readonly Brush barrierColor = new SolidBrush(Color.White);
private readonly Brush roadColor = new SolidBrush(Color.SkyBlue);
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 < 25)
{
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,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
internal class PlaneCompareByColor : 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 xPlane = x as DrawningObjectPlane;
var yPlane = y as DrawningObjectPlane;
if (xPlane == null && yPlane == null)
{
return 0;
}
if (xPlane == null && yPlane != null)
{
return 1;
}
if (xPlane != null && yPlane == null)
{
return -1;
}
string xShipColor = xPlane.GetPlane.Plane.BodyColor.Name;
string yShipColor = yPlane.GetPlane.Plane.BodyColor.Name;
if (xShipColor != yShipColor)
{
return xShipColor.CompareTo(yShipColor);
}
if (xPlane.GetPlane.Plane is EntityAirbus xAirbus && yPlane.GetPlane.Plane is EntityAirbus yAirbus)
{
string xShipDopColor = xAirbus.DopColor.Name;
string yShipDopColor = yAirbus.DopColor.Name;
var dopColorCompare = xShipDopColor.CompareTo(yShipDopColor);
if (dopColorCompare != 0)
{
return dopColorCompare;
}
}
var speedCompare = xPlane.GetPlane.Plane.Speed.CompareTo(yPlane.GetPlane.Plane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xPlane.GetPlane.Plane.Weight.CompareTo(yPlane.GetPlane.Plane.Weight);
}
}
}

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
internal class PlaneCompareByType : 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 xPlane = x as DrawningObjectPlane;
var yPlane = y as DrawningObjectPlane;
if (xPlane == null && yPlane == null)
{
return 0;
}
if (xPlane == null && yPlane != null)
{
return 1;
}
if (xPlane != null && yPlane == null)
{
return -1;
}
if (xPlane.GetPlane.GetType().Name != yPlane.GetPlane.GetType().Name)
{
if (xPlane.GetPlane.GetType().Name == "DrawningPlane")
{
return -1;
}
return 1;
}
var speedCompare = xPlane.GetPlane.Plane.Speed.CompareTo(yPlane.GetPlane.Plane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xPlane.GetPlane.Plane.Weight.CompareTo(yPlane.GetPlane.Plane.Weight);
}
}
}

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 Airbus
{
[Serializable]
internal class PlaneNotFoundException : ApplicationException
{
public PlaneNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public PlaneNotFoundException() : base() { }
public PlaneNotFoundException(string message) : base(message) { }
public PlaneNotFoundException(string message, Exception exception) : base(message, exception) { }
protected PlaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Airbus namespace Airbus
{ {
internal static class Program internal static class Program
@ -11,7 +16,29 @@ namespace Airbus
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormAirbus()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetPlanes>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetPlanes>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(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,129 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus
{
internal class SetPlanesGeneric<T>
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T> _places;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetPlanesGeneric(int count)
{
_maxCount = count;
_places = new List<T>();
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="plane">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T plane)
{
if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount);
return Insert(plane, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="plane">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T plane, int position)
{
// TODO проверка позиции
// TODO вставка по позиции
if (_places.Contains(plane))
{
return -1;
}
if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, plane);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присовив элементу массива значение null
if (position >= _maxCount || position >= _places.Count) throw new PlaneNotFoundException(position);
T res = _places[position];
_places.Remove(res);
if (res == null) throw new PlaneNotFoundException(position);
return res;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T this[int position]
{
get
{
// TODO проверка позиции
if (position < 0 || position >= _maxCount)
{
return null;
}
return _places[position];
}
set
{
// TODO проверка позиции
// TODO вставка в список по позиции
if (position < 0 || position >= _maxCount)
{
Insert(value, position);
}
}
}
/// <summary>
/// Проход по набору до первого пустого
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetPlanes()
{
foreach (var plane in _places)
{
if (plane != null)
{
yield return plane;
}
else
{
yield break;
}
}
}
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,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"
}
}
}