Compare commits

...

21 Commits

Author SHA1 Message Date
a.puchkina
925cc7a006 лаба7, готовая, но более уверенная 2023-12-20 02:08:29 +04:00
a.puchkina
d177de49ad лаба 7, я так полагаю, возможно, кто знает, не уверена, готовая лаба 2023-12-19 22:59:17 +04:00
a.puchkina
e016aa1b8e лаба 7, надо подправить позиции 2023-12-06 01:03:31 +04:00
a.puchkina
ef234a35ba лаба 7, в процессе 2023-12-05 20:59:54 +04:00
a.puchkina
62d6124a79 лаба 7, изменения 2023-11-22 08:34:44 +04:00
a.puchkina
542144f95d лаба 7, подключила пакеты 2023-11-21 21:11:31 +04:00
a.puchkina
705355a3ba лаба 7, начала 2023-11-21 20:53:23 +04:00
a.puchkina
7192f69607 подправила цвета 2023-11-19 15:01:25 +04:00
a.puchkina
c8cebea048 лаба 6 2023-11-19 03:33:27 +04:00
a.puchkina
acebbbaff7 цвета поменяла, теперь точно готово 2023-11-19 02:25:50 +04:00
a.puchkina
545ac210cf 5 лаба готова 2023-11-19 02:21:21 +04:00
a.puchkina
329ffa2e48 5 лаба, работает, но надо доделать малясь 2023-11-18 23:36:59 +04:00
a.puchkina
07cc928cb7 в процессе 2023-11-08 11:23:47 +04:00
a.puchkina
c5550d73e2 начала форму 2023-11-08 08:44:15 +04:00
a.puchkina
3e922ab4dd вроде готовая лаба 4 2023-11-06 20:19:29 +04:00
a.puchkina
5ac338e378 убрала доп цвет из базового класса 2023-10-25 14:20:24 +04:00
a.puchkina
feb9260e45 убрала доп цвет из базового класса 2023-10-25 14:20:09 +04:00
a.puchkina
d0e5fcf0a8 Исправила ттипы данных 2023-10-25 09:52:46 +04:00
a.puchkina
e9aede7e6e лаба 3!!!!!!! 2023-10-24 23:36:05 +04:00
a.puchkina
d4c53d0543 лаба 2
создала доп классы, переписала методы, создала класс движения к границе
2023-10-10 21:32:48 +04:00
a.puchkina
a6ecfa293f Entities и DrawningOblects готовы 2023-09-27 11:20:19 +04:00
29 changed files with 2810 additions and 113 deletions

View File

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

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AirplaneWithRadar.Exceptoins
{
[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,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -35,6 +35,10 @@
buttonLeft = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonCreateAirplaneWithRadar = new Button();
buttonStep = new Button();
comboBoxStrategy = new ComboBox();
buttonSelectAirplane = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirplane).BeginInit();
SuspendLayout();
//
@ -42,8 +46,9 @@
//
pictureBoxAirplane.Dock = DockStyle.Fill;
pictureBoxAirplane.Location = new Point(0, 0);
pictureBoxAirplane.Margin = new Padding(4, 4, 4, 4);
pictureBoxAirplane.Name = "pictureBoxAirplane";
pictureBoxAirplane.Size = new Size(882, 453);
pictureBoxAirplane.Size = new Size(1102, 566);
pictureBoxAirplane.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxAirplane.TabIndex = 0;
pictureBoxAirplane.TabStop = false;
@ -51,9 +56,10 @@
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 412);
buttonCreate.Location = new Point(15, 515);
buttonCreate.Margin = new Padding(4, 4, 4, 4);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29);
buttonCreate.Size = new Size(118, 36);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
@ -64,9 +70,10 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.Up;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(798, 375);
buttonUp.Location = new Point(998, 469);
buttonUp.Margin = new Padding(4, 4, 4, 4);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.Size = new Size(38, 38);
buttonUp.TabIndex = 2;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
@ -76,9 +83,10 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(762, 411);
buttonLeft.Location = new Point(952, 514);
buttonLeft.Margin = new Padding(4, 4, 4, 4);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.Size = new Size(38, 38);
buttonLeft.TabIndex = 3;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
@ -88,9 +96,10 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage");
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(834, 411);
buttonRight.Location = new Point(1042, 514);
buttonRight.Margin = new Padding(4, 4, 4, 4);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.Size = new Size(38, 38);
buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
@ -100,24 +109,76 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(798, 411);
buttonDown.Location = new Point(998, 514);
buttonDown.Margin = new Padding(4, 4, 4, 4);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.Size = new Size(38, 38);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonCreateAirplaneWithRadar
//
buttonCreateAirplaneWithRadar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirplaneWithRadar.Location = new Point(140, 514);
buttonCreateAirplaneWithRadar.Margin = new Padding(4, 4, 4, 4);
buttonCreateAirplaneWithRadar.Name = "buttonCreateAirplaneWithRadar";
buttonCreateAirplaneWithRadar.Size = new Size(248, 38);
buttonCreateAirplaneWithRadar.TabIndex = 6;
buttonCreateAirplaneWithRadar.Text = "Создать с дополнениями";
buttonCreateAirplaneWithRadar.UseVisualStyleBackColor = true;
buttonCreateAirplaneWithRadar.Click += buttonCreateAirplaneWithRadar_Click;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(985, 42);
buttonStep.Margin = new Padding(4, 4, 4, 4);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(118, 36);
buttonStep.TabIndex = 7;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "в центр", "к гарнице" });
comboBoxStrategy.Location = new Point(914, 0);
comboBoxStrategy.Margin = new Padding(4, 4, 4, 4);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(188, 33);
comboBoxStrategy.TabIndex = 8;
//
// buttonSelectAirplane
//
buttonSelectAirplane.Location = new Point(483, 515);
buttonSelectAirplane.Name = "buttonSelectAirplane";
buttonSelectAirplane.Size = new Size(222, 34);
buttonSelectAirplane.TabIndex = 9;
buttonSelectAirplane.Text = "Выбрать самолет";
buttonSelectAirplane.UseVisualStyleBackColor = true;
buttonSelectAirplane.Click += buttonSelectAirplane_Click;
//
// AirplaneWithRadarForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
ClientSize = new Size(1102, 566);
Controls.Add(buttonSelectAirplane);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStep);
Controls.Add(buttonCreateAirplaneWithRadar);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonUp);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxAirplane);
Margin = new Padding(4, 4, 4, 4);
Name = "AirplaneWithRadarForm";
StartPosition = FormStartPosition.CenterScreen;
Text = "AirplaneWithRadarForm";
@ -134,5 +195,9 @@
private Button buttonLeft;
private Button buttonRight;
private Button buttonDown;
private Button buttonCreateAirplaneWithRadar;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button buttonSelectAirplane;
}
}

View File

@ -7,6 +7,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.MovementStrategy;
namespace AirplaneWithRadar
{
@ -19,14 +21,24 @@ namespace AirplaneWithRadar
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningAirplane? _drawningAirplane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Выбранный самолет
/// </summary>
public DrawningAirplane? SelectedAirplane { get; set; }
/// <summary>
/// Инициализация формы
/// </summary>
public AirplaneWithRadarForm()
{
InitializeComponent();
_strategy = null;
SelectedAirplane = null;
}
/// <summary>
/// Метод прорисовки самолета
/// </summary>
@ -41,28 +53,56 @@ namespace AirplaneWithRadar
_drawningAirplane.DrawTransport(gr);
pictureBoxAirplane.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать самолет"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAirplane_Click(object sender, EventArgs e)
{
Random random = new();
_drawningAirplane = new DrawningAirplane();
_drawningAirplane.Init(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), pictureBoxAirplane.Width, pictureBoxAirplane.Height);
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new ColorDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
bodyColor = dialog.Color;
}
_drawningAirplane = new DrawningAirplane(random.Next(100, 300), random.Next(1000, 3000),
bodyColor,
pictureBoxAirplane.Width, pictureBoxAirplane.Height);
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void buttonCreateAirplaneWithRadar_Click(object sender, EventArgs e)
{
Random random = new();
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new ColorDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
bodyColor = dialog.Color;
}
Color additionalColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
if (dialog.ShowDialog() == DialogResult.OK)
{
additionalColor = dialog.Color;
}
_drawningAirplane = new DrawningAirplaneWithRadar(random.Next(100, 300),
random.Next(1000, 3000),
bodyColor,
additionalColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxAirplane.Width, pictureBoxAirplane.Height);
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Изменение размеров формы
/// Изменение положения самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
@ -90,5 +130,55 @@ namespace AirplaneWithRadar
}
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningAirplane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(_drawningAirplane.GetMoveableObject, pictureBoxAirplane.Width,
pictureBoxAirplane.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
/// <summary>
/// Выбор самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSelectAirplane_Click(object sender, EventArgs e)
{
SelectedAirplane = _drawningAirplane;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -121,7 +121,7 @@
<data name="buttonLeft.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAA4QAAAOEBAMAAAALYOIIAAAABGdBTUEAALGPC/xhBQAAABJQTFRF5ubm
AQEB////AAAAa2trubm55kNtzgAAAAlwSFlzAAAOvgAADr4B6kKxwAAAFy1JREFUeNrtnV2S6ka2RkFB
AQEB////AAAAa2trubm55kNtzgAAAAlwSFlzAAAOvAAADrwBlbxySQAAFy1JREFUeNrtnV2S6ka2RkFB
v7ese98VCmkA6hwBlzsB4tjzn0qTPxLC5lBCKH++qsVDVy932yf5VmxD1lbmPnT+1R78C5RD4pBH4pBH
4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pBH4pDH6VWFvw6qInHII3HII3HII3HII3HII3HI
I3HII3HII3HII3HII3HII3HII3HII3EIY/hJ700WiUMeiUMeiUMeiUMeiUMeiUMeiUMeiUMeiUMeiUMe
@ -328,7 +328,7 @@
<data name="buttonDown.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAA4QAAAOEBAMAAAALYOIIAAAABGdBTUEAALGPC/xhBQAAABJQTFRF5ubm
AQEB////AAAAa2trubm55kNtzgAAAAlwSFlzAAAOvgAADr4B6kKxwAAAGBNJREFUeNrt3V9y+r7Vx3Fj
AQEB////AAAAa2trubm55kNtzgAAAAlwSFlzAAAOvAAADrwBlbxySQAAGBNJREFUeNrt3V9y+r7Vx3Fj
NoARuTeacB9VYQGPM92A2f9eimTZSb5PSAD/05Hens7QTy/6i/WqjqFHkotwlbq7oosf1fWy3WWq7lo+
WvsW4+B8jRBCmDahglA6oYUQQgghhBBCCCGEEEIIIRwT+V0IIYQQQjg2KgilE1bqJV7C8FmH/zy2WH5c
i5gNI6rCkK4Qq5e6iHSsIIQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGE8K+oIJROaM/xEoaLfuGvka49

View File

@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.MovementStrategy;
namespace AirplaneWithRadar.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningAirplane
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class AirplanesGenericCollection<T, U>
where T : DrawningAirplane
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 220;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 100;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetAirplanes => _collection.GetAirplanes();
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public AirplanesGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(AirplanesGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(AirplanesGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection[pos];
return collect._collection.Remove(pos);
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowAirplanes()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int i = 0;
foreach (var airplane in _collection.GetAirplanes())
{
if (airplane != null)
{
airplane.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (airplane is DrawningAirplaneWithRadar)
(airplane as DrawningAirplaneWithRadar).DrawTransport(g);
else airplane.DrawTransport(g);
airplane.DrawTransport(g);
}
i++;
}
}
}
}

View File

@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.Exceptoins;
using System.Numerics;
namespace AirplaneWithRadar.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class AirplanesGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, AirplanesGenericCollection<DrawningAirplane,
DrawningObjectAirplane>> _airplaneStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _airplaneStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public AirplanesGenericStorage(int pictureWidth, int pictureHeight)
{
_airplaneStorages = new Dictionary<string,
AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (!_airplaneStorages.ContainsKey(name))
_airplaneStorages.Add(name,new AirplanesGenericCollection<DrawningAirplane,
DrawningObjectAirplane>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_airplaneStorages.ContainsKey(name))
_airplaneStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>?
this[string ind]
{
get
{
if (_airplaneStorages.ContainsKey(ind))
return _airplaneStorages[ind];
return null;
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>> record in _airplaneStorages)
{
StringBuilder records = new();
foreach (DrawningAirplane? elem in record.Value.GetAirplanes)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"AirplaneStorage{Environment.NewLine}{data}");
}
}
/// <summary>
/// Загрузка информации по самолетам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException($"Файл {filename} не найден");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new NullReferenceException("Нет данных для загрузки");
}
if (!str.StartsWith("AirplaneStorage"))
{
//если нет такой записи, то это не те данные
throw new FormatException("Неверный формат данных");
}
_airplaneStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
if (strs == null)
{
throw new NullReferenceException("Нет данных для загрузки");
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
AirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if (airplane != null)
{
if (collection + airplane == -1)
{
throw new InvalidOperationException("Ошибка добавления в коллекцию");
}
}
}
_airplaneStorages.Add(record[0], collection);
}
}
}
}
}

View File

@ -0,0 +1,20 @@
{
"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}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "AirplaneWithRadar"
}
}
}

View File

@ -4,66 +4,89 @@ using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.Entities;
using AirplaneWithRadar.MovementStrategy;
namespace AirplaneWithRadar
namespace AirplaneWithRadar.DrawningObjects
{/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirplane
{
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningAirplane
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectAirplane(this);
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirplaneWithRadar? EntityAirplaneWithRadar{ get; private set; }
public EntityAirplane? EntityAirplane { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
public int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
public int _pictureHeight;
/// <summary>
/// /// Левая координата прорисовки самолета
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки самолета
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки самолета
/// </summary>
private readonly int _airplaneWidth = 200;
protected readonly int _airplaneWidth = 200;
/// <summary>
/// Высота прорисовки самолета
/// </summary>
private readonly int _airplaneHeight = 85;
protected readonly int _airplaneHeight = 85;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет фюзеляжа</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="tank">Признак наличия доп.бака</param>
/// <param name="pin">Признак наличия штыря</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool radar, bool tank, bool pin, int width, int height)
public DrawningAirplane(int speed, double weight, Color bodyColor, int width, int height)
{
if (width <= _airplaneWidth || height <= _airplaneHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="airplaneWidth">Ширина прорисовки автомобиля</param>
/// <param name="airplaneHeight">Высота прорисовки автомобиля</param>
protected DrawningAirplane(int speed, double weight, Color bodyColor, int
width, int height, int airplaneWidth, int airplaneHeight)
{
if (width <= _airplaneWidth || height <= _airplaneHeight)
{
return false;
return;
}
EntityAirplaneWithRadar = new EntityAirplaneWithRadar();
EntityAirplaneWithRadar.Init(speed, weight, bodyColor, additionalColor, radar, tank, pin);
return true;
_pictureWidth = width;
_pictureHeight = height;
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
@ -76,12 +99,52 @@ namespace AirplaneWithRadar
_startPosY = Math.Min(y, _pictureHeight - _airplaneHeight);
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объект
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _airplaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _airplaneHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityAirplane == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityAirplane.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityAirplane.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityAirplane.Step < _pictureWidth + _airplaneWidth,
//вниз
DirectionType.Down => _startPosY + EntityAirplane.Step < _pictureHeight + _airplaneHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityAirplaneWithRadar == null)
if (!CanMove(direction) || EntityAirplane == null)
{
return;
}
@ -89,30 +152,30 @@ namespace AirplaneWithRadar
{
//влево
case DirectionType.Left:
if (_startPosX - EntityAirplaneWithRadar.Step > 0)
if (_startPosX - EntityAirplane.Step > 0)
{
_startPosX -= (int)EntityAirplaneWithRadar.Step;
_startPosX -= (int)EntityAirplane.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityAirplaneWithRadar.Step > 0)
if (_startPosY - EntityAirplane.Step > 0)
{
_startPosY -= (int)EntityAirplaneWithRadar.Step;
}
_startPosY -= (int)EntityAirplane.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + EntityAirplaneWithRadar.Step + _airplaneWidth < _pictureWidth)
if (_startPosX + EntityAirplane.Step + _airplaneWidth < _pictureWidth)
{
_startPosX += (int)EntityAirplaneWithRadar.Step;
_startPosX += (int)EntityAirplane.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + EntityAirplaneWithRadar.Step + _airplaneHeight < _pictureHeight)
if (_startPosY + EntityAirplane.Step + _airplaneHeight < _pictureHeight)
{
_startPosY += (int)EntityAirplaneWithRadar.Step;
_startPosY += (int)EntityAirplane.Step;
}
break;
}
@ -121,32 +184,23 @@ namespace AirplaneWithRadar
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityAirplaneWithRadar == null)
if (EntityAirplane == null)
{
return;
}
Pen penBlack = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityAirplaneWithRadar.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityAirplaneWithRadar.BodyColor);
Brush bodyBrush = new SolidBrush(EntityAirplane.BodyColor);
// радар
if (EntityAirplaneWithRadar.Radar)
{
g.FillEllipse(additionalBrush, _startPosX + 65, _startPosY + 25, 50, 10);
g.DrawEllipse(penBlack, _startPosX + 65, _startPosY + 25, 50, 10);
g.FillRectangle(additionalBrush, _startPosX + 85, _startPosY + 35, 10, 5);
g.DrawRectangle(penBlack, _startPosX + 85, _startPosY + 35, 10, 5);
}
//фюзеляж
g.FillRectangle(bodyBrush, _startPosX + 4, _startPosY + 40, 150, 30);
g.DrawRectangle(penBlack, _startPosX + 4, _startPosY + 40, 150, 30);
//киль
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 4, _startPosY + 40), new Point(_startPosX + 4, _startPosY + 0), new Point(_startPosX + 50, _startPosY + 40)});
g.FillPolygon(bodyBrush, new Point[] { new Point(_startPosX + 4, _startPosY + 40), new Point(_startPosX + 4, _startPosY + 0), new Point(_startPosX + 50, _startPosY + 40) });
g.DrawPolygon(penBlack, new Point[] { new Point(_startPosX + 4, _startPosY + 40), new Point(_startPosX + 4, _startPosY + 0), new Point(_startPosX + 50, _startPosY + 40) });
//стабилизатор и крыло
Brush brSilver = new SolidBrush(Color.Silver);
g.FillEllipse(brSilver, _startPosX, _startPosY + 35, 55, 10);
@ -167,27 +221,22 @@ namespace AirplaneWithRadar
//кабина
Brush brLightBlue = new SolidBrush(Color.LightBlue);
Pen penBlue = new Pen(Color.CadetBlue);
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 150, _startPosY + 55), new Point(_startPosX + 190, _startPosY + 55), new Point(_startPosX + 150, _startPosY + 72) });
g.FillPolygon(bodyBrush, new Point[] { new Point(_startPosX + 150, _startPosY + 55), new Point(_startPosX + 190, _startPosY + 55), new Point(_startPosX + 150, _startPosY + 72) });
g.FillPolygon(brLightBlue, new Point[] { new Point(_startPosX + 150, _startPosY + 55), new Point(_startPosX + 150, _startPosY + 38), new Point(_startPosX + 190, _startPosY + 55) });
g.DrawLine(penBlack, new Point(_startPosX + 150, _startPosY + 55), new Point(_startPosX + 150, _startPosY + 38));
g.DrawLine(penBlack, new Point(_startPosX + 150, _startPosY + 38), new Point(_startPosX + 190, _startPosY + 55));
g.DrawLine(penBlue, new Point(_startPosX + 190, _startPosY + 55), new Point(_startPosX + 150, _startPosY + 55));
g.DrawLine(penBlack, new Point(_startPosX + 150, _startPosY + 72), new Point(_startPosX + 150, _startPosY + 55));
g.DrawLine(penBlack, new Point(_startPosX + 150, _startPosY + 72), new Point(_startPosX + 190, _startPosY + 55));
// Штырь
if (EntityAirplaneWithRadar.Pin)
{
g.DrawLine(penGray, new Point(_startPosX + 190, _startPosY + 55), new Point(_startPosX + 200, _startPosY + 55));
}
// бак
if (EntityAirplaneWithRadar.Tank)
{
g.FillRectangle(additionalBrush, _startPosX + 70, _startPosY + 65, 45, 15);
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 70, _startPosY + 65), new Point(_startPosX + 60, _startPosY + 72), new Point(_startPosX + 70, _startPosY + 80) });
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 115, _startPosY + 65), new Point(_startPosX + 125, _startPosY + 72), new Point(_startPosX + 115, _startPosY + 80) });
}
}
public void SetBodyColor(Color color)
{
EntityAirplane.BodyColor = color;
}
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
}
}

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.Entities;
namespace AirplaneWithRadar.DrawningObjects
{
public class DrawningAirplaneWithRadar : DrawningAirplane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет фюзеляжа</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="tank">Признак наличия бака</param>
/// <param name="pin">Признак наличия штыря</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningAirplaneWithRadar(int speed, double weight, Color bodyColor, Color
additionalColor, bool radar, bool tank, bool pin, int width, int height) :
base(speed, weight, bodyColor, width, height, 200, 85)
{
if (EntityAirplane != null)
{
EntityAirplane = new EntityAirplaneWithRadar(speed, weight, bodyColor,
additionalColor, radar, tank, pin);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityAirplane is not EntityAirplaneWithRadar airplaneWithRadar)
{
return;
}
Pen penBlack = new(Color.Black);
Brush additionalBrush = new SolidBrush(airplaneWithRadar.AdditionalColor);
Pen penGray = new Pen(Color.Gray);
// радар
if (airplaneWithRadar.Radar)
{
g.FillEllipse(additionalBrush, _startPosX + 65, _startPosY + 25, 50, 10);
g.DrawEllipse(penBlack, _startPosX + 65, _startPosY + 25, 50, 10);
g.FillRectangle(additionalBrush, _startPosX + 85, _startPosY + 35, 10, 5);
g.DrawRectangle(penBlack, _startPosX + 85, _startPosY + 35, 10, 5);
}
// Штырь
if (airplaneWithRadar.Pin)
{
g.DrawLine(penGray, new Point(_startPosX + 190, _startPosY + 55), new Point(_startPosX + 200, _startPosY + 55));
}
// бак
if (airplaneWithRadar.Tank)
{
g.FillRectangle(additionalBrush, _startPosX + 70, _startPosY + 65, 45, 15);
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 70, _startPosY + 65), new Point(_startPosX + 60, _startPosY + 72), new Point(_startPosX + 70, _startPosY + 80) });
g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 115, _startPosY + 65), new Point(_startPosX + 125, _startPosY + 72), new Point(_startPosX + 115, _startPosY + 80) });
}
base.DrawTransport(g);
}
public void SetAddColor(Color color)
{
(EntityAirplane as EntityAirplaneWithRadar).AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.DrawningObjects;
namespace AirplaneWithRadar.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningCar
/// </summary>
public class DrawningObjectAirplane : IMoveableObject
{
private readonly DrawningAirplane? _drawningAirplane = null;
public DrawningObjectAirplane(DrawningAirplane drawningAirplane)
{
_drawningAirplane = drawningAirplane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningAirplane == null || _drawningAirplane.EntityAirplane ==
null)
{
return null;
}
return new ObjectParameters(_drawningAirplane.GetPosX,
_drawningAirplane.GetPosY, _drawningAirplane.GetWidth, _drawningAirplane.GetHeight);
}
}
public int GetStep => (int)(_drawningAirplane?.EntityAirplane?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawningAirplane?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawningAirplane?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar.Entities
{
/// <summary>
/// Класс-сущность "Самолет"
/// </summary>
public class EntityAirplane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения самолета
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса самолета с радаром
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityAirplane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -4,26 +4,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar
namespace AirplaneWithRadar.Entities
{
public class EntityAirplaneWithRadar
/// <summary>
/// Класс-сущность "Самолет с радаром"
/// </summary>
public class EntityAirplaneWithRadar : EntityAirplane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия радара
/// </summary>
@ -37,10 +28,6 @@ namespace AirplaneWithRadar
/// </summary>
public bool Pin { get; private set; }
/// <summary>
/// Шаг перемещения самолета
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса самолета с радаром
/// </summary>
/// <param name="speed">Скорость</param>
@ -50,17 +37,13 @@ namespace AirplaneWithRadar
/// <param name="radar">Признак наличия радара</param>
/// <param name="tank">Признак наличия доп.бака</param>
/// <param name="pin">Признак наличия штыря</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool radar, bool tank, bool pin)
public EntityAirplaneWithRadar(int speed, double weight, Color bodyColor,
Color additionalColor, bool radar, bool tank, bool pin) : base (speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Radar = radar;
Tank = tank;
Pin = pin;
}
}
}
}

View File

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.Entities;
namespace AirplaneWithRadar.DrawningObjects
{
public static class ExtentionDrawningAirplane
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningAirplane? CreateDrawningAirplane(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningAirplane(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawningAirplaneWithRadar(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
Convert.ToBoolean(strs[6]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirplane">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningAirplane drawningAirplane,
char separatorForObject)
{
var airplane = drawningAirplane.EntityAirplane;
if (airplane == null)
{
return string.Empty;
}
var str =$"{airplane.Speed}{separatorForObject}{airplane.Weight}{separatorForObject}{airplane.BodyColor.Name}";
if (airplane is not EntityAirplaneWithRadar airplaneWithRadar)
{
return str;
}
return $"{str}{separatorForObject}{airplaneWithRadar.AdditionalColor.Name}" +
$"{separatorForObject}{airplaneWithRadar.Radar}{separatorForObject}" +
$"{airplaneWithRadar.Tank}{separatorForObject}{airplaneWithRadar.Pin}";
}
}
}

View File

@ -0,0 +1,260 @@
namespace AirplaneWithRadar
{
partial class FormAirplaneCollection
{
/// <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()
{
groupBoxInstruments = new GroupBox();
groupBoxSets = new GroupBox();
buttonDeleteSet = new Button();
listBoxStorages = new ListBox();
buttonAddInSet = new Button();
textBoxStorageName = new TextBox();
maskedTextBoxNumber = new MaskedTextBox();
buttonUpdate = new Button();
buttonAdd = new Button();
buttonDelete = new Button();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
сохранениеToolStripMenuItem = new ToolStripMenuItem();
загрузкаToolStripMenuItem = new ToolStripMenuItem();
pictureBoxCollection = new PictureBox();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxInstruments.SuspendLayout();
groupBoxSets.SuspendLayout();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// groupBoxInstruments
//
groupBoxInstruments.Controls.Add(groupBoxSets);
groupBoxInstruments.Controls.Add(maskedTextBoxNumber);
groupBoxInstruments.Controls.Add(buttonUpdate);
groupBoxInstruments.Controls.Add(buttonAdd);
groupBoxInstruments.Controls.Add(buttonDelete);
groupBoxInstruments.Controls.Add(menuStrip);
groupBoxInstruments.Dock = DockStyle.Right;
groupBoxInstruments.Location = new Point(619, 0);
groupBoxInstruments.Margin = new Padding(2);
groupBoxInstruments.Name = "groupBoxInstruments";
groupBoxInstruments.Padding = new Padding(2);
groupBoxInstruments.Size = new Size(187, 534);
groupBoxInstruments.TabIndex = 5;
groupBoxInstruments.TabStop = false;
groupBoxInstruments.Text = "Инструменты";
//
// groupBoxSets
//
groupBoxSets.Controls.Add(buttonDeleteSet);
groupBoxSets.Controls.Add(listBoxStorages);
groupBoxSets.Controls.Add(buttonAddInSet);
groupBoxSets.Controls.Add(textBoxStorageName);
groupBoxSets.Location = new Point(17, 118);
groupBoxSets.Margin = new Padding(3, 2, 3, 2);
groupBoxSets.Name = "groupBoxSets";
groupBoxSets.Padding = new Padding(3, 2, 3, 2);
groupBoxSets.Size = new Size(159, 235);
groupBoxSets.TabIndex = 6;
groupBoxSets.TabStop = false;
groupBoxSets.Text = "Наборы";
//
// buttonDeleteSet
//
buttonDeleteSet.Location = new Point(8, 167);
buttonDeleteSet.Margin = new Padding(2);
buttonDeleteSet.Name = "buttonDeleteSet";
buttonDeleteSet.Size = new Size(145, 22);
buttonDeleteSet.TabIndex = 9;
buttonDeleteSet.Text = "Удалить набор";
buttonDeleteSet.UseVisualStyleBackColor = true;
buttonDeleteSet.Click += buttonDeleteSet_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(12, 83);
listBoxStorages.Margin = new Padding(3, 2, 3, 2);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(134, 64);
listBoxStorages.TabIndex = 8;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// buttonAddInSet
//
buttonAddInSet.Location = new Point(8, 49);
buttonAddInSet.Margin = new Padding(2);
buttonAddInSet.Name = "buttonAddInSet";
buttonAddInSet.Size = new Size(145, 22);
buttonAddInSet.TabIndex = 7;
buttonAddInSet.Text = "Добавить в набор";
buttonAddInSet.UseVisualStyleBackColor = true;
buttonAddInSet.Click += buttonAddInSet_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(8, 25);
textBoxStorageName.Margin = new Padding(3, 2, 3, 2);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(142, 23);
textBoxStorageName.TabIndex = 0;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(50, 412);
maskedTextBoxNumber.Margin = new Padding(2);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(105, 23);
maskedTextBoxNumber.TabIndex = 5;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(38, 475);
buttonUpdate.Margin = new Padding(2);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(124, 38);
buttonUpdate.TabIndex = 4;
buttonUpdate.Text = "Обновить коллекцию";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += buttonUpdate_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(31, 370);
buttonAdd.Margin = new Padding(2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(145, 22);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить самолет";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(38, 435);
buttonDelete.Margin = new Padding(2);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(124, 22);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить самолет";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += buttonDelete_Click;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(2, 18);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(183, 24);
menuStrip.TabIndex = 7;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { сохранениеToolStripMenuItem, загрузкаToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// сохранениеToolStripMenuItem
//
сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
сохранениеToolStripMenuItem.Size = new Size(141, 22);
сохранениеToolStripMenuItem.Text = "Сохранение";
сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// загрузкаToolStripMenuItem
//
загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
загрузкаToolStripMenuItem.Size = new Size(141, 22);
загрузкаToolStripMenuItem.Text = "Загрузка";
загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Margin = new Padding(2);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(619, 534);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.TabIndex = 6;
pictureBoxCollection.TabStop = false;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormAirplaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(806, 534);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxInstruments);
MainMenuStrip = menuStrip;
Margin = new Padding(2);
Name = "FormAirplaneCollection";
Text = "FormAirplaneCollection";
groupBoxInstruments.ResumeLayout(false);
groupBoxInstruments.PerformLayout();
groupBoxSets.ResumeLayout(false);
groupBoxSets.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonAdd;
private Button buttonUpdate;
private Button buttonDelete;
private GroupBox groupBoxInstruments;
private PictureBox pictureBoxCollection;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBoxSets;
private Button buttonDeleteSet;
private ListBox listBoxStorages;
private Button buttonAddInSet;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранениеToolStripMenuItem;
private ToolStripMenuItem загрузкаToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,281 @@
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 AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.Generics;
using AirplaneWithRadar.Exceptoins;
using Microsoft.Extensions.Logging;
namespace AirplaneWithRadar
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningAirplane
/// </summary>
public partial class FormAirplaneCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly AirplanesGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormAirplaneCollection(ILogger<FormAirplaneCollection> logger)
{
InitializeComponent();
_storage = new AirplanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранено в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не прошло");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загружено из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не прошла");
}
}
ReloadObjects();
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddInSet_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowAirplanes();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDeleteSet_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Коллекция не выбрана");
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Коллекция не выбрана");
return;
}
var formAirplaneConfig = new FormAirplaneConfig();
formAirplaneConfig.AddEvent(AddAirplane);
formAirplaneConfig.Show();
}
private void AddAirplane(DrawningAirplane airplane)
{
airplane._pictureWidth = pictureBoxCollection.Image.Width;
airplane._pictureHeight = pictureBoxCollection.Image.Height;
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Не удалось добавить объект: набор пуст");
return;
}
try
{
if (obj + airplane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowAirplanes();
_logger.LogInformation($"Объект добавлен {airplane}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelete_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции {pos} из набора {listBoxStorages.SelectedItem.ToString()}");
pictureBoxCollection.Image = obj.ShowAirplanes();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Объект не удален из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (AirplaneNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Самолет не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
catch (FormatException)
{
_logger.LogWarning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonUpdate_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowAirplanes();
}
}
}

View File

@ -0,0 +1,132 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>271, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,399 @@
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()
{
groupBoxParameters = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxPin = new CheckBox();
checkBoxTank = new CheckBox();
checkBoxRadar = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
pictureBoxObject = new PictureBox();
buttonOk = new Button();
buttonCancel = new Button();
groupBoxParameters.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxParameters
//
groupBoxParameters.Controls.Add(labelModifiedObject);
groupBoxParameters.Controls.Add(labelSimpleObject);
groupBoxParameters.Controls.Add(groupBoxColors);
groupBoxParameters.Controls.Add(checkBoxPin);
groupBoxParameters.Controls.Add(checkBoxTank);
groupBoxParameters.Controls.Add(checkBoxRadar);
groupBoxParameters.Controls.Add(numericUpDownWeight);
groupBoxParameters.Controls.Add(numericUpDownSpeed);
groupBoxParameters.Controls.Add(labelWeight);
groupBoxParameters.Controls.Add(labelSpeed);
groupBoxParameters.Location = new Point(10, 9);
groupBoxParameters.Margin = new Padding(3, 2, 3, 2);
groupBoxParameters.Name = "groupBoxParameters";
groupBoxParameters.Padding = new Padding(3, 2, 3, 2);
groupBoxParameters.Size = new Size(437, 190);
groupBoxParameters.TabIndex = 0;
groupBoxParameters.TabStop = false;
groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(318, 144);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(97, 28);
labelModifiedObject.TabIndex = 10;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(231, 144);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(85, 28);
labelSimpleObject.TabIndex = 9;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(217, 32);
groupBoxColors.Margin = new Padding(3, 2, 3, 2);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Padding = new Padding(3, 2, 3, 2);
groupBoxColors.Size = new Size(203, 94);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Plum;
panelPurple.Location = new Point(163, 59);
panelPurple.Margin = new Padding(3, 2, 3, 2);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(35, 30);
panelPurple.TabIndex = 7;
panelPurple.MouseDown += PanelColor_MouseDown;
//
// panelYellow
//
panelYellow.BackColor = Color.LemonChiffon;
panelYellow.Location = new Point(163, 20);
panelYellow.Margin = new Padding(3, 2, 3, 2);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(35, 30);
panelYellow.TabIndex = 3;
panelYellow.MouseDown += PanelColor_MouseDown;
//
// panelBlack
//
panelBlack.BackColor = Color.DimGray;
panelBlack.Location = new Point(113, 59);
panelBlack.Margin = new Padding(3, 2, 3, 2);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(35, 30);
panelBlack.TabIndex = 6;
panelBlack.MouseDown += PanelColor_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.SkyBlue;
panelBlue.Location = new Point(113, 20);
panelBlue.Margin = new Padding(3, 2, 3, 2);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(35, 30);
panelBlue.TabIndex = 2;
panelBlue.MouseDown += PanelColor_MouseDown;
//
// panelGray
//
panelGray.BackColor = Color.Silver;
panelGray.Location = new Point(64, 59);
panelGray.Margin = new Padding(3, 2, 3, 2);
panelGray.Name = "panelGray";
panelGray.Size = new Size(35, 30);
panelGray.TabIndex = 5;
panelGray.MouseDown += PanelColor_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.DarkSeaGreen;
panelGreen.Location = new Point(64, 20);
panelGreen.Margin = new Padding(3, 2, 3, 2);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(35, 30);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += PanelColor_MouseDown;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(14, 59);
panelWhite.Margin = new Padding(3, 2, 3, 2);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(35, 30);
panelWhite.TabIndex = 4;
panelWhite.MouseDown += PanelColor_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Salmon;
panelRed.Location = new Point(14, 20);
panelRed.Margin = new Padding(3, 2, 3, 2);
panelRed.Name = "panelRed";
panelRed.Size = new Size(35, 30);
panelRed.TabIndex = 0;
panelRed.MouseDown += PanelColor_MouseDown;
//
// checkBoxPin
//
checkBoxPin.AutoSize = true;
checkBoxPin.Location = new Point(5, 144);
checkBoxPin.Margin = new Padding(3, 2, 3, 2);
checkBoxPin.Name = "checkBoxPin";
checkBoxPin.Size = new Size(164, 19);
checkBoxPin.TabIndex = 6;
checkBoxPin.Text = "Признак наличия штыря";
checkBoxPin.UseVisualStyleBackColor = true;
//
// checkBoxTank
//
checkBoxTank.AutoSize = true;
checkBoxTank.Location = new Point(5, 122);
checkBoxTank.Margin = new Padding(3, 2, 3, 2);
checkBoxTank.Name = "checkBoxTank";
checkBoxTank.Size = new Size(151, 19);
checkBoxTank.TabIndex = 5;
checkBoxTank.Text = "Признак наличия бака";
checkBoxTank.UseVisualStyleBackColor = true;
//
// checkBoxRadar
//
checkBoxRadar.AutoSize = true;
checkBoxRadar.Location = new Point(5, 99);
checkBoxRadar.Margin = new Padding(3, 2, 3, 2);
checkBoxRadar.Name = "checkBoxRadar";
checkBoxRadar.Size = new Size(164, 19);
checkBoxRadar.TabIndex = 4;
checkBoxRadar.Text = "Признак наличия радара";
checkBoxRadar.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(77, 64);
numericUpDownWeight.Margin = new Padding(3, 2, 3, 2);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(89, 23);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 1000, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(77, 32);
numericUpDownSpeed.Margin = new Padding(3, 2, 3, 2);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(89, 23);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 1000, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(5, 65);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(5, 32);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(452, 9);
panelObject.Margin = new Padding(3, 2, 3, 2);
panelObject.Name = "panelObject";
panelObject.Size = new Size(228, 145);
panelObject.TabIndex = 12;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(117, 4);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(94, 28);
labelAdditionalColor.TabIndex = 13;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(27, 4);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(85, 28);
labelBodyColor.TabIndex = 12;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(3, 34);
pictureBoxObject.Margin = new Padding(3, 2, 3, 2);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(222, 111);
pictureBoxObject.TabIndex = 7;
pictureBoxObject.TabStop = false;
//
// buttonOk
//
buttonOk.Location = new Point(482, 170);
buttonOk.Margin = new Padding(3, 2, 3, 2);
buttonOk.Name = "buttonOk";
buttonOk.Size = new Size(82, 22);
buttonOk.TabIndex = 13;
buttonOk.Text = "Добавить";
buttonOk.UseVisualStyleBackColor = true;
buttonOk.Click += buttonOk_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(570, 170);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 14;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormAirplaneConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(700, 208);
Controls.Add(buttonCancel);
Controls.Add(buttonOk);
Controls.Add(panelObject);
Controls.Add(groupBoxParameters);
Margin = new Padding(3, 2, 3, 2);
Name = "FormAirplaneConfig";
Text = "FormAirplaneConfig";
groupBoxParameters.ResumeLayout(false);
groupBoxParameters.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxRadar;
private CheckBox checkBoxPin;
private CheckBox checkBoxTank;
private GroupBox groupBoxColors;
private Panel panelRed;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
private PictureBox pictureBoxObject;
private Button buttonOk;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,190 @@
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 AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.Entities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AirplaneWithRadar
{
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);
_airplane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawningAirplane>? ev)
{
if (EventAddAirplane == null)
{
EventAddAirplane = 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) ?? false)
{
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)
{
ILogger<FormAirplaneCollection> logger = new NullLogger<FormAirplaneCollection>();
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
labelAdditionalColor.AllowDrop = false;
_airplane = new DrawningAirplane((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelModifiedObject":
labelAdditionalColor.AllowDrop = true;
_airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.DimGray, checkBoxRadar.Checked,
checkBoxTank.Checked, checkBoxPin.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
DrawAirplane();
}
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonOk_Click(object sender, EventArgs e)
{
EventAddAirplane?.Invoke(_airplane);
Close();
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_airplane == null)
return;
var color = e.Data.GetData(typeof(Color));
switch (((Label)sender).Name)
{
case "labelBodyColor":
_airplane.EntityAirplane.BodyColor = (Color)color;
break;
case "labelAdditionalColor":
if (!(_airplane is DrawningAirplaneWithRadar))
return;
(_airplane as DrawningAirplaneWithRadar).EntityAirplane.BodyColor = (Color)color;
break;
}
DrawAirplane();
}
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
var color = e.Data.GetData(typeof(Color));
if (_airplane != null && color != null)
{
_airplane.EntityAirplane.BodyColor = (Color)color;
DrawAirplane();
}
}
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
var color = e.Data.GetData(typeof(Color));
if (_airplane != null && color != null && _airplane.EntityAirplane is EntityAirplaneWithRadar entityAirplaneWithRadar)
{
entityAirplaneWithRadar.AdditionalColor = (Color)color;
DrawAirplane();
}
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

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

View File

@ -0,0 +1,57 @@
using AirplaneWithRadar.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth &&
objParams.ObjectMiddleVertical <= FieldHeight &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,57 @@
using AirplaneWithRadar.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar.MovementStrategy
{
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

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

View File

@ -1,3 +1,14 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using System;
namespace AirplaneWithRadar
{
internal static class Program
@ -11,7 +22,28 @@ 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 AirplaneWithRadarForm());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormAirplaneCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormAirplaneCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}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,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirplaneWithRadar.Exceptoins;
namespace AirplaneWithRadar.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="airplane">Добавляемый самолет</param>
/// <returns></returns>
public int Insert(T airplane)
{
return Insert(airplane, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="airplane">Добавляемый самолет</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T airplane, int position)
{
if (position < 0 || position > Count)
throw new AirplaneNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
_places.Insert(position, airplane);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position >= Count || position < 0)
throw new AirplaneNotFoundException(position);
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (position < 0 || position >= Count) return null;
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount)) return;
_places.Insert(position, value);
return;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetAirplanes(int? maxAirplanes = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxAirplanes.HasValue && i == maxAirplanes.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirplaneWithRadar.MovementStrategy
{
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AirplaneWithRadar.Exceptoins
{
[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) { }
}
}