Compare commits

...

15 Commits

27 changed files with 2484 additions and 46 deletions

View File

@ -0,0 +1,121 @@
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal abstract class 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 HasCollisionBarrier(float x, float y, float right, float bottom)
{
if (x < 0 || y < 0 || right > _width || bottom > _height)
{
return false;
}
for (float i = x / _size_x; i < right / _size_x; i++)
{
for (float j = y / _size_y; j < bottom / _size_y; j++)
{
if (_map[(int)i, (int)j] == _barrier)
{
return true;
}
}
}
return false;
}
public Bitmap MoveObject(Direction direction)
{
(float left, float top, float right, float bottom) = _drawningObject.GetCurrentPosition();
float width = right - left, height = bottom - top;
if (direction == Direction.Up)
{
top -= _drawningObject.Step;
}
if (direction == Direction.Down)
{
top += _drawningObject.Step;
}
if (direction == Direction.Left)
{
left -= _drawningObject.Step;
}
if (direction == Direction.Right)
{
left += _drawningObject.Step;
}
if (!HasCollisionBarrier(left, top, left+width, top+height))
{
_drawningObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private bool SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
_drawningObject.SetObject(x, y, _width, _height);
(float left, float top, float right, float bottom) = _drawningObject.GetCurrentPosition();
return !HasCollisionBarrier(x, y, right, bottom);
}
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);
}
}

View File

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

View File

@ -8,6 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.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.Settings.Delegates" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +37,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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

View File

@ -4,20 +4,20 @@ namespace AirplaneWithRadar
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
internal class DrawningAirplane
public class DrawningAirplane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirplane Airplane { private set; get; }
public EntityAirplane Airplane { protected set; get; }
/// <summary>
/// Левая координата отрисовки самолёта
/// </summary>
private float _startPosX;
protected float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки самолёта
/// </summary>
private float _startPosY;
protected float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -33,18 +33,34 @@ namespace AirplaneWithRadar
/// <summary>
/// Высота отрисовки самолёта
/// </summary>
private readonly int _airplaneHeight = 10;
private readonly int _airplaneHeight = 20;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет</param>
public void Init(int speed, float weight, Color bodyColor)
public DrawningAirplane(int speed, float weight, Color bodyColor)
{
Airplane = new EntityAirplane();
Airplane.Init(speed, weight, bodyColor);
Airplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолёта</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="airplaneWidth">Ширина отрисовки самолёта</param>
/// <param name="airplaneHeight">Высота отрисовки самолёта</param>
protected DrawningAirplane(int speed, float weight, Color bodyColor, int
airplaneWidth, int airplaneHeight) :
this(speed, weight, bodyColor)
{
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
}
/// <summary>
/// Установка позиции
/// </summary>
@ -52,6 +68,7 @@ namespace AirplaneWithRadar
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void SetPosition(int x, int y, int width, int height)
{
_startPosX = x;
@ -111,7 +128,7 @@ namespace AirplaneWithRadar
/// Отрисовка самолёта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0
|| !_pictureHeight.HasValue || !_pictureWidth.HasValue)
@ -120,38 +137,39 @@ namespace AirplaneWithRadar
}
Pen pen = new(Color.Black);
Brush brush = new SolidBrush(Airplane.BodyColor);
int h = 10;
_startPosY += 4;
//корпус
g.DrawRectangle(pen, _startPosX, _startPosY + _airplaneHeight-7,
_airplaneWidth-5, _airplaneHeight);
g.DrawRectangle(pen, _startPosX, _startPosY + h-7, _airplaneWidth-15, h);
//нос
PointF[] point = new PointF[3];
point[0] = new PointF(_startPosX + _airplaneWidth-5, _startPosY + _airplaneHeight / 3);
point[1] = new PointF(_startPosX + _airplaneWidth+10 , _startPosY + _airplaneHeight-3);
point[2] = new PointF(_startPosX + _airplaneWidth-5, _startPosY + _airplaneHeight + (_airplaneHeight / 3));
point[0] = new PointF(_startPosX + _airplaneWidth-15, _startPosY + h / 3);
point[1] = new PointF(_startPosX + _airplaneWidth , _startPosY + h-3);
point[2] = new PointF(_startPosX + _airplaneWidth-15, _startPosY + h + (h / 3));
g.FillPolygon(brush, point);
//хвост
point = new PointF[3];
point[0] = new PointF(_startPosX, _startPosY-10);
point[1] = new PointF(_startPosX, _startPosY + _airplaneHeight / 3);
point[2] = new PointF(_startPosX + 15, _startPosY + _airplaneHeight / 3);
point[1] = new PointF(_startPosX, _startPosY + h / 3);
point[2] = new PointF(_startPosX + 15, _startPosY + h / 3);
g.FillPolygon(brush, point);
//крылья
g.DrawLine(pen, _startPosX + 20, _startPosY + _airplaneHeight - 3, _startPosX + 60, _startPosY + _airplaneHeight - 3);
g.DrawLine(pen, _startPosX + 20, _startPosY + _airplaneHeight - 2, _startPosX + 60, _startPosY + _airplaneHeight - 2);
g.DrawLine(pen, _startPosX + 20, _startPosY + h - 3, _startPosX + 60, _startPosY + h - 3);
g.DrawLine(pen, _startPosX + 20, _startPosY + h - 2, _startPosX + 60, _startPosY + h - 2);
g.DrawLine(pen, _startPosX-1, _startPosY + _airplaneHeight / 3, _startPosX + 15, _startPosY + _airplaneHeight / 3);
g.DrawLine(pen, _startPosX-1, _startPosY + _airplaneHeight / 3 + 1, _startPosX + 15, _startPosY + _airplaneHeight / 3 + 1);
g.DrawLine(pen, _startPosX-1, _startPosY + _airplaneHeight / 3 + 2, _startPosX + 15, _startPosY + _airplaneHeight / 3 + 2);
g.DrawLine(pen, _startPosX-1, _startPosY + h / 3, _startPosX + 15, _startPosY + h / 3);
g.DrawLine(pen, _startPosX-1, _startPosY + h / 3 + 1, _startPosX + 15, _startPosY + h / 3 + 1);
g.DrawLine(pen, _startPosX-1, _startPosY + h / 3 + 2, _startPosX + 15, _startPosY + h / 3 + 2);
//колёса
g.DrawRectangle(pen, _startPosX + 20, _startPosY + _airplaneHeight + (_airplaneHeight / 3), 2, 2);
g.DrawRectangle(pen, _startPosX + 24, _startPosY + _airplaneHeight + (_airplaneHeight / 3), 2, 2);
g.DrawRectangle(pen, _startPosX + _airplaneWidth-20, _startPosY + _airplaneHeight + (_airplaneHeight / 3), 2, 2);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + h + (h / 3), 2, 2);
g.DrawRectangle(pen, _startPosX + 24, _startPosY + h + (h / 3), 2, 2);
g.DrawRectangle(pen, _startPosX + _airplaneWidth-20, _startPosY + h + (h / 3), 2, 2);
_startPosY -= 4;
}
/// <summary>
/// Смена границ формы отрисовки
@ -177,6 +195,17 @@ namespace AirplaneWithRadar
_startPosY = _pictureHeight.Value - _airplaneHeight;
}
}
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public (float Left, float Top, float Right, float Bottom)
GetCurrentPosition()
{
return (_startPosX, _startPosY, _startPosX + _airplaneWidth, _startPosY +
_airplaneHeight);
}
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace AirplaneWithRadar
{
internal class DrawningAirplaneWithRadar : DrawningAirplane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="fuelTanks">Признак наличия дополнительных топливных баков</param>
public DrawningAirplaneWithRadar(int speed, float weight, Color bodyColor, Color
dopColor, bool radar, bool fuelTanks) :
base(speed, weight, bodyColor, 100, 20)
{
Airplane = new EntityAirplaneWithRadar(speed, weight, bodyColor, dopColor, radar, fuelTanks);
}
public override void DrawTransport(Graphics g)
{
if (Airplane is not EntityAirplaneWithRadar airplaneWithRadar)
{
return;
}
Pen pen = new(Color.Black);
Brush dopBrush = new SolidBrush(airplaneWithRadar.DopColor);
if (airplaneWithRadar.Radar)
{
g.FillEllipse(dopBrush, _startPosX + 30, _startPosY, 20, 5);
g.DrawLine(pen, _startPosX + 33, _startPosY + 4, _startPosX + 33, _startPosY + 7);
g.DrawLine(pen, _startPosX + 47, _startPosY + 4, _startPosX + 47, _startPosY + 7);
}
base.DrawTransport(g);
if (airplaneWithRadar.FuelTanks)
{
g.FillEllipse(dopBrush, _startPosX + 25, _startPosY + 12, 30, 5);
}
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class DrawningObjectAirplane : IDrawningObject
{
private DrawningAirplane _airplane = null;
public DrawningObjectAirplane(DrawningAirplane airplane)
{
_airplane = airplane;
}
public float Step => _airplane?.Airplane?.Step ?? 0;
public (float Left, float Top, float Right, float Bottom)
GetCurrentPosition()
{
return _airplane?.GetCurrentPosition() ?? default;
}
public void MoveObject(Direction direction)
{
_airplane?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_airplane.SetPosition(x, y, width, height);
}
public void DrawningObject(Graphics g)
{
_airplane.DrawTransport(g);
}
public string GetInfo() => _airplane?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectAirplane(data.CreateDrawningAirplane());
}
}

View File

@ -4,7 +4,7 @@ namespace AirplaneWithRadar
/// <summary>
/// Класс-сущность "Самолёт"
/// </summary>
internal class EntityAirplane
public class EntityAirplane
{
/// <summary>
/// Скорость
@ -17,7 +17,7 @@ namespace AirplaneWithRadar
/// <summary>
/// Цвет кузова
/// </summary>
public Color BodyColor { get; private set; }
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения самолёта
/// </summary>
@ -29,7 +29,7 @@ namespace AirplaneWithRadar
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <returns></returns>
public void Init(int speed, float weight, Color bodyColor)
public EntityAirplane(int speed, float weight, Color bodyColor)
{
Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class EntityAirplaneWithRadar : EntityAirplane
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; set; }
/// <summary>
/// Признак наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Признак наличия дополнительного топливного бака
/// </summary>
public bool FuelTanks { get; private set; }
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолёта</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="fuelTanks">Признак наличия дополнительных топливных баков</param>
public EntityAirplaneWithRadar(int speed, float weight, Color bodyColor, Color
dopColor, bool radar, bool fuelTanks) :
base(speed, weight, bodyColor)
{
DopColor = dopColor;
Radar = radar;
FuelTanks = fuelTanks;
}
}
}

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal static class ExtentionAirplane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningAirplane CreateDrawningAirplane(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningAirplane(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningAirplaneWithRadar(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirplane"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningAirplane drawningAirplane)
{
var airplane = drawningAirplane.Airplane;
var str = $"{airplane.Speed}{_separatorForObject}{airplane.Weight}{_separatorForObject}{airplane.BodyColor.Name}";
if (airplane is not EntityAirplaneWithRadar airplaneWithRadar)
{
return str;
}
return $"{str}{_separatorForObject}{airplaneWithRadar.DopColor.Name}{_separatorForObject}{airplaneWithRadar.Radar}{_separatorForObject}{airplaneWithRadar.FuelTanks}";
}
}
}

View File

@ -38,6 +38,8 @@
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonCreateModif = new System.Windows.Forms.Button();
this.buttonSelectAirplane = new System.Windows.Forms.Button();
this.statusStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirplane)).BeginInit();
this.SuspendLayout();
@ -81,7 +83,6 @@
this.pictureBoxAirplane.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxAirplane.TabIndex = 1;
this.pictureBoxAirplane.TabStop = false;
this.pictureBoxAirplane.Click += new System.EventHandler(this.pictureBoxAirplane_Click);
this.pictureBoxAirplane.Resize += new System.EventHandler(this.PictureBoxAirplane_Resize);
//
// buttonCreate
@ -89,11 +90,11 @@
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(12, 395);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(75, 23);
this.buttonCreate.Size = new System.Drawing.Size(96, 23);
this.buttonCreate.TabIndex = 2;
this.buttonCreate.Text = "Создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
this.buttonCreate.Click += new System.EventHandler(this.ButtonCreate_Click);
//
// buttonUp
//
@ -143,11 +144,33 @@
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonCreateModif
//
this.buttonCreateModif.Location = new System.Drawing.Point(12, 366);
this.buttonCreateModif.Name = "buttonCreateModif";
this.buttonCreateModif.Size = new System.Drawing.Size(96, 23);
this.buttonCreateModif.TabIndex = 7;
this.buttonCreateModif.Text = "Модификация";
this.buttonCreateModif.UseVisualStyleBackColor = true;
this.buttonCreateModif.Click += new System.EventHandler(this.ButtonCreateModif_Click);
//
// buttonSelectAirplane
//
this.buttonSelectAirplane.Location = new System.Drawing.Point(582, 402);
this.buttonSelectAirplane.Name = "buttonSelectAirplane";
this.buttonSelectAirplane.Size = new System.Drawing.Size(75, 23);
this.buttonSelectAirplane.TabIndex = 8;
this.buttonSelectAirplane.Text = "Выбрать";
this.buttonSelectAirplane.UseVisualStyleBackColor = true;
this.buttonSelectAirplane.Click += new System.EventHandler(this.ButtonSelectAirplane_Click);
//
// FormAirplane
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonSelectAirplane);
this.Controls.Add(this.buttonCreateModif);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
@ -177,5 +200,7 @@
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateModif;
private Button buttonSelectAirplane;
}
}

View File

@ -3,6 +3,10 @@ namespace AirplaneWithRadar
public partial class FormAirplane : Form
{
private DrawningAirplane _airplane;
/// <summary>
/// Âűáđŕííűé îáúĺęň
/// </summary>
public DrawningAirplane SelectedAirplane { get; private set; }
public FormAirplane()
{
@ -12,11 +16,6 @@ namespace AirplaneWithRadar
/// <summary>
/// Ìåòîä ïðîðèñîâêè ñàìîë¸òà
/// </summary>
private void pictureBoxAirplane_Click(object sender, EventArgs e)
{
}
private void Draw()
{
Bitmap bmp = new(pictureBoxAirplane.Width, pictureBoxAirplane.Height);
@ -24,22 +23,36 @@ namespace AirplaneWithRadar
_airplane?.DrawTransport(gr);
pictureBoxAirplane.Image = bmp;
}
/// <summary>
/// Ěĺňîä óńňŕíîâęč äŕííűő
/// </summary>
private void SetData()
{
Random rnd = new();
_airplane.SetPosition(rnd.Next(20, 100), rnd.Next(20, 100), pictureBoxAirplane.Width, pictureBoxAirplane.Height);
toolStripStatusLabelSpeed.Text = $"Ńęîđîńňü: {_airplane.Airplane.Speed}";
toolStripStatusLabelWeight.Text = $"Âĺń: {_airplane.Airplane.Weight}";
toolStripStatusLabelBodyColor.Text = $"Öâĺň: {_airplane.Airplane.BodyColor.Name}";
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
///
private void buttonCreate_Click(object sender, EventArgs e)
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
_airplane = new DrawningAirplane();
_airplane.Init(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_airplane.SetPosition(rnd.Next(20, 100), rnd.Next(20, 100), pictureBoxAirplane.Width, pictureBoxAirplane.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_airplane.Airplane.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_airplane.Airplane.Weight}";
toolStripStatusLabelBodyColor.Text = $"Öâåò: {_airplane.Airplane.BodyColor.Name}";
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_airplane = new DrawningAirplane(rnd.Next(100, 300), rnd.Next(1000, 2000), color);
SetData();
Draw();
}
@ -79,5 +92,42 @@ namespace AirplaneWithRadar
_airplane?.ChangeBorders(pictureBoxAirplane.Width, pictureBoxAirplane.Height);
Draw();
}
/// <summary>
/// Îáđŕáîňęŕ íŕćŕňč˙ ęíîďęč "Ěîäčôčęŕöč˙"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
_airplane = new DrawningAirplaneWithRadar(rnd.Next(100, 300), rnd.Next(1000, 2000), color, dopColor,
Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
SetData();
Draw();
}
/// <summary>
/// Îáđŕáîňęŕ íŕćŕňč˙ ęíîďęč "Âűáđŕňü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectAirplane_Click(object sender, EventArgs e)
{
SelectedAirplane = _airplane;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,381 @@
namespace AirplaneWithRadar
{
partial class FormAirplaneConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.checkBoxFuelTanks = new System.Windows.Forms.CheckBox();
this.checkBoxHasRadar = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOk = new System.Windows.Forms.Button();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.panelObject = new System.Windows.Forms.Panel();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
this.groupBoxConfig.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.panelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxFuelTanks);
this.groupBoxConfig.Controls.Add(this.checkBoxHasRadar);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.labelWeight);
this.groupBoxConfig.Controls.Add(this.labelSpeed);
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Location = new System.Drawing.Point(12, 12);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(613, 213);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// checkBoxFuelTanks
//
this.checkBoxFuelTanks.AutoSize = true;
this.checkBoxFuelTanks.Location = new System.Drawing.Point(43, 141);
this.checkBoxFuelTanks.Name = "checkBoxFuelTanks";
this.checkBoxFuelTanks.Size = new System.Drawing.Size(222, 19);
this.checkBoxFuelTanks.TabIndex = 5;
this.checkBoxFuelTanks.Text = "Признак наличия топливных баков";
this.checkBoxFuelTanks.UseVisualStyleBackColor = true;
//
// checkBoxHasRadar
//
this.checkBoxHasRadar.AutoSize = true;
this.checkBoxHasRadar.Location = new System.Drawing.Point(43, 116);
this.checkBoxHasRadar.Name = "checkBoxHasRadar";
this.checkBoxHasRadar.Size = new System.Drawing.Size(164, 19);
this.checkBoxHasRadar.TabIndex = 4;
this.checkBoxHasRadar.Text = "Признак наличия радара";
this.checkBoxHasRadar.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(80, 76);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(64, 23);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(113, 47);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(66, 23);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(45, 78);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(29, 15);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес:";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(45, 51);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(62, 15);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость:";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(185, 66);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(40, 40);
this.panelPurple.TabIndex = 22;
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(185, 15);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(40, 40);
this.panelYellow.TabIndex = 18;
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(128, 66);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 23;
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(128, 15);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(40, 40);
this.panelBlue.TabIndex = 19;
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(73, 66);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(40, 40);
this.panelGray.TabIndex = 24;
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(73, 15);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
this.panelGreen.TabIndex = 20;
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(16, 66);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(40, 40);
this.panelWhite.TabIndex = 21;
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(16, 15);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 17;
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(447, 162);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(97, 38);
this.labelModifiedObject.TabIndex = 26;
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(335, 162);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(97, 38);
this.labelSimpleObject.TabIndex = 25;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(319, 29);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(255, 120);
this.groupBoxColors.TabIndex = 27;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(804, 202);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(104, 30);
this.buttonCancel.TabIndex = 8;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(683, 202);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(104, 30);
this.buttonOk.TabIndex = 7;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(20, 44);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(225, 125);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(663, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(262, 184);
this.panelObject.TabIndex = 6;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(141, 9);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(104, 32);
this.labelDopColor.TabIndex = 2;
this.labelDopColor.Text = "Доп. цвет";
this.labelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDopColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
this.labelDopColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(20, 9);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(104, 32);
this.labelBaseColor.TabIndex = 1;
this.labelBaseColor.Text = "Цвет";
this.labelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragDrop);
this.labelBaseColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragEnter);
//
// FormAirplaneConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(974, 242);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormAirplaneConfig";
this.Text = "Создание объекта";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.panelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private CheckBox checkBoxFuelTanks;
private CheckBox checkBoxHasRadar;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColors;
private Button buttonCancel;
private Button buttonOk;
private PictureBox pictureBoxObject;
private Panel panelObject;
private Label labelDopColor;
private Label labelBaseColor;
}
}

View File

@ -0,0 +1,175 @@
namespace AirplaneWithRadar
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormAirplaneConfig : Form
{
/// <summary>
/// Переменная-выбранная самолёт
/// </summary>
DrawningAirplane _airplane = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningAirplane> EventAddAirplane;
/// <summary>
/// Конструктор
/// </summary>
public FormAirplaneConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать самолёт
/// </summary>
private void DrawAirplane()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_airplane?.SetPosition(5, 5, pictureBoxObject.Width,
pictureBoxObject.Height);
_airplane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev"></param>
public void AddEvent(Action<DrawningAirplane> ev)
{
if (EventAddAirplane == null)
{
EventAddAirplane = new (ev);
}
else
{
EventAddAirplane += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_airplane = new DrawningAirplane((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxHasRadar.Checked, checkBoxFuelTanks.Checked);
break;
}
DrawAirplane();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _airplane != null && _airplane is DrawningAirplaneWithRadar)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
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)
{
var color = (Color)e.Data.GetData(typeof(Color));
_airplane.Airplane.BodyColor = color;
DrawAirplane();
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
((EntityAirplaneWithRadar)_airplane.Airplane).DopColor = color;
DrawAirplane();
}
/// <summary>
/// Добавление машины
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddAirplane?.Invoke(_airplane);
Close();
}
}
}

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,337 @@
namespace AirplaneWithRadar
{
partial class FormMapWithSetAirplanes
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxTools = 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.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = 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.buttonRemoveAirplane = new System.Windows.Forms.Button();
this.buttonAddAirplane = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.groupBoxMaps);
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonRight);
this.groupBoxTools.Controls.Add(this.buttonLeft);
this.groupBoxTools.Controls.Add(this.buttonDown);
this.groupBoxTools.Controls.Add(this.buttonUp);
this.groupBoxTools.Controls.Add(this.buttonShowOnMap);
this.groupBoxTools.Controls.Add(this.buttonShowStorage);
this.groupBoxTools.Controls.Add(this.buttonRemoveAirplane);
this.groupBoxTools.Controls.Add(this.buttonAddAirplane);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(801, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(200, 545);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.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, 259);
this.groupBoxMaps.TabIndex = 11;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(7, 221);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(176, 31);
this.buttonDeleteMap.TabIndex = 13;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 15;
this.listBoxMaps.Location = new System.Drawing.Point(7, 121);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(175, 94);
this.listBoxMaps.TabIndex = 12;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(6, 84);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(176, 31);
this.buttonAddMap.TabIndex = 11;
this.buttonAddMap.Text = "Добавить Карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(8, 22);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(174, 23);
this.textBoxNewMapName.TabIndex = 0;
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Моя карта"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(8, 51);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(174, 23);
this.comboBoxSelectorMap.TabIndex = 10;
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(14, 337);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(174, 23);
this.maskedTextBoxPosition.TabIndex = 9;
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AirplaneWithRadar.Properties.Resources.arrRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(121, 509);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 8;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AirplaneWithRadar.Properties.Resources.arrLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(49, 509);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 7;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AirplaneWithRadar.Properties.Resources.arrDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(85, 509);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 6;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AirplaneWithRadar.Properties.Resources.arrUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(85, 473);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 5;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(14, 440);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(174, 34);
this.buttonShowOnMap.TabIndex = 4;
this.buttonShowOnMap.Text = "Посмотреть карту";
this.buttonShowOnMap.UseVisualStyleBackColor = true;
this.buttonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(14, 402);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(174, 32);
this.buttonShowStorage.TabIndex = 3;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// buttonRemoveAirplane
//
this.buttonRemoveAirplane.Location = new System.Drawing.Point(14, 366);
this.buttonRemoveAirplane.Name = "buttonRemoveAirplane";
this.buttonRemoveAirplane.Size = new System.Drawing.Size(174, 30);
this.buttonRemoveAirplane.TabIndex = 2;
this.buttonRemoveAirplane.Text = "Удалить самолёт";
this.buttonRemoveAirplane.UseVisualStyleBackColor = true;
this.buttonRemoveAirplane.Click += new System.EventHandler(this.ButtonRemoveAirplane_Click);
//
// buttonAddAirplane
//
this.buttonAddAirplane.Location = new System.Drawing.Point(14, 298);
this.buttonAddAirplane.Name = "buttonAddAirplane";
this.buttonAddAirplane.Size = new System.Drawing.Size(175, 33);
this.buttonAddAirplane.TabIndex = 1;
this.buttonAddAirplane.Text = "Добавить самолёт";
this.buttonAddAirplane.UseVisualStyleBackColor = true;
this.buttonAddAirplane.Click += new System.EventHandler(this.ButtonAddAirplane_Click);
//
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(801, 545);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1001, 24);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetAirplanes
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1001, 569);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetAirplanes";
this.Text = "FormMapWithSetAirplanes";
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonRight;
private Button buttonLeft;
private Button buttonDown;
private Button buttonUp;
private Button buttonShowOnMap;
private Button buttonShowStorage;
private Button buttonRemoveAirplane;
private Button buttonAddAirplane;
private PictureBox pictureBox;
private ComboBox comboBoxSelectorMap;
private GroupBox groupBoxMaps;
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -0,0 +1,300 @@
using Microsoft.Extensions.Logging;
namespace AirplaneWithRadar
{
public partial class FormMapWithSetAirplanes : Form
{
/// <summary>
/// Словарь для выпадающего списка
/// </summary>
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Моя карта", new MyMap() },
};
/// <summary>
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Конструктор
/// </summary>
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetAirplanes(ILogger<FormMapWithSetAirplanes> logger)
{
InitializeComponent();
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
_logger = logger;
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(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[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(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAirplane_Click(object sender, EventArgs e)
{
FormAirplaneConfig formAirplane = new();
formAirplane.AddEvent(new(AddAirplane));
formAirplane.Show();
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="airplane"></param>
private void AddAirplane(DrawningAirplane airplane)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
}
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectAirplane(airplane) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Airplane}", airplane);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirplane_Click(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
{
var deletedAirplane = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedAirplane != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удален объект {@Airplane}", deletedAirplane);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (AirplaneNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Вывод карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
{
case "buttonUp":
dir = Direction.Up;
break;
case "buttonDown":
dir = Direction.Down;
break;
case "buttonLeft":
dir = Direction.Left;
break;
case "buttonRight":
dir = Direction.Right;
break;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName);
ReloadMaps();
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>125, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal interface IDrawningObject
{
/// <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();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@ -0,0 +1,205 @@
namespace AirplaneWithRadar
{
/// <summary>
/// Карта с набром объектов под нее
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetAirplanesGeneric<T, U>
where T : class, IDrawningObject
where U : AbstractMap
{
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetAirplanesGeneric<T> _setAirplanes;
/// <summary>
/// Карта
/// </summary>
private readonly U _map;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="map"></param>
public MapWithSetAirplanesGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setAirplanes = new SetAirplanesGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="airplane"></param>
/// <returns></returns>
public static int operator +(MapWithSetAirplanesGeneric<T, U> map, T airplane)
{
return map._setAirplanes.Insert(airplane);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="map"></param>
/// <param name="position"></param>
/// <returns></returns>
public static T operator -(MapWithSetAirplanesGeneric<T, U> map, int position)
{
return map._setAirplanes.Remove(position);
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawAirplanes(gr);
return bmp;
}
/// <summary>
/// Просмотр объекта на карте
/// </summary>
/// <returns></returns>
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setAirplanes.Count; i++)
{
var airplane = _setAirplanes[i];
if (airplane != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, airplane);
}
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Перемещение объекта по крате
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var car in _setAirplanes.GetAirplanes())
{
data += $"{car.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setAirplanes.Insert(DrawningObjectAirplane.Create(rec) as T);
}
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()
{
int j = _setAirplanes.Count - 1;
for (int i = 0; i < _setAirplanes.Count; i++)
{
if (_setAirplanes[i] == null)
{
for (; j > i; j--)
{
var airplane = _setAirplanes[j];
if (airplane != null)
{
_setAirplanes.Insert(airplane, i);
_setAirplanes.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
private void DrawHangar(Graphics g, int x, int y, int width, int height)
{
Pen pen = new(Color.Black, 3);
g.DrawLine(pen, x, y, x + width, y);
g.DrawLine(pen, x, y, x, y + height);
g.DrawLine(pen, x, y + height, x + width, y + height);
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
DrawHangar(g, i * _placeSizeWidth, j * _placeSizeHeight , _placeSizeWidth * 3 / 4, _placeSizeHeight - 55);
}
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawAirplanes(Graphics g)
{
int countInLine = _pictureWidth / _placeSizeWidth;
int maxLeft = (countInLine - 1) * _placeSizeWidth;
for (int i = 0; i < _setAirplanes.Count; i++)
{
var airplane = _setAirplanes[i];
airplane?.SetObject(maxLeft - i % countInLine * _placeSizeWidth + 5, i / countInLine * _placeSizeHeight + 15 , _pictureWidth, _pictureHeight);
airplane?.DrawningObject(g);
}
}
}
}

View File

@ -0,0 +1,146 @@
using System.Text;
namespace AirplaneWithRadar
{
internal class MapsCollection
{
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetAirplanesGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
public List<string> Keys => _mapStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetAirplanesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="name">Название карты</param>
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
_mapStorages.TryGetValue(name, out var buffer);
if (buffer == null)
{
_mapStorages.Add(name, new(_pictureWidth, _pictureHeight, map));
}
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="name">Название карты</param>
public void DelMap(string name)
{
_mapStorages.Remove(name);
}
/// <summary>
/// Доступ к парковке
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetAirplanesGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
_mapStorages.TryGetValue(ind, out var mapWithSetAirplanesGeneric);
return mapWithSetAirplanesGeneric;
}
}
/// <summary>
/// Метод записи информации в файл
/// </summary>
/// <param name="text">Строка, которую следует записать</param>
/// <param name="stream">Поток для записи</param>
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new(filename))
{
fs.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
}
/// <summary>
/// Загрузка нформации по автомобилям на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader fs = new(filename))
{
if (!fs.ReadLine().Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
throw new FileFormatException("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
while (!fs.EndOfStream)
{
var elem = fs.ReadLine().Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "MyMap":
map = new MyMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetAirplanesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
{
internal class MyMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Brown);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.BlueViolet);
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 < 20)
{
int x = _random.Next(0, _map.GetLength(0));
int y = _random.Next(0, _map.GetLength(1));
int len = _random.Next(3, 10);
for (int i = x; i < _map.GetLength(0) && i < len + x; i++)
{
_map[i, y] = _barrier;
}
counter++;
}
}
}
}

View File

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

View File

@ -0,0 +1,108 @@
namespace AirplaneWithRadar
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetAirplanesGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T> _places;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetAirplanesGeneric(int count)
{
_maxCount = count;
_places = new List<T>();
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="airplane">Добавляемый самолёт</param>
/// <returns></returns>
public int Insert(T airplane)
{
return Insert(airplane, 0);
}
private bool isCorrectPosition(int position)
{
return 0 <= position && position < _maxCount;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="airplane">Добавляемый самолет</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T airplane, int position)
{
if (Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!isCorrectPosition(position))
{
return -1;
}
_places.Insert(position, airplane);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Remove(int position)
{
if (!isCorrectPosition(position))
return null;
var result = this[position];
if (result == null)
throw new AirplaneNotFoundException(position);
_places.RemoveAt(position);
return result;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T this[int position]
{
get
{
return isCorrectPosition(position) && position < Count ? _places[position] : null;
}
set
{
Insert(value, position);
}
}
public IEnumerable<T> GetAirplanes()
{
foreach (var airplane in _places)
{
if (airplane != null)
{
yield return airplane;
}
else
{
yield break;
}
}
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
]
}
}