Compare commits

...

7 Commits

Author SHA1 Message Date
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
21 changed files with 1645 additions and 109 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

@ -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; private 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>
/// <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 bool operator +(AirplanesGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return false;
}
return (bool)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];
if (obj != null)
{
collect._collection.Remove(pos);
}
return false;
}
/// <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,82 @@
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>
/// Класс для хранения коллекции
/// </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>
/// <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))
return;
_airplaneStorages[name] = new AirplanesGenericCollection<DrawningAirplane,
DrawningObjectAirplane>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_airplaneStorages.ContainsKey(name))
return;
_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;
}
}
}
}

View File

@ -4,17 +4,24 @@ 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>
@ -26,44 +33,60 @@ namespace AirplaneWithRadar
/// <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)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
{
return false;
return;
}
EntityAirplaneWithRadar = new EntityAirplaneWithRadar();
EntityAirplaneWithRadar.Init(speed, weight, bodyColor, additionalColor, radar, tank, pin);
return true;
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)
{
_pictureWidth = width;
_pictureHeight = height;
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight)
{
return;
}
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,13 @@ 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) });
}
}
}
}

View File

@ -0,0 +1,70 @@
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);
}
base.DrawTransport(g);
// Штырь
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) });
}
}
}
}

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,44 @@
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; private 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,22 +4,13 @@ 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>
@ -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,200 @@
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();
pictureBoxCollection = new PictureBox();
groupBoxInstruments.SuspendLayout();
groupBoxSets.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.Dock = DockStyle.Right;
groupBoxInstruments.Location = new Point(707, 0);
groupBoxInstruments.Margin = new Padding(2);
groupBoxInstruments.Name = "groupBoxInstruments";
groupBoxInstruments.Padding = new Padding(2);
groupBoxInstruments.Size = new Size(214, 570);
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(14, 33);
groupBoxSets.Name = "groupBoxSets";
groupBoxSets.Size = new Size(182, 313);
groupBoxSets.TabIndex = 6;
groupBoxSets.TabStop = false;
groupBoxSets.Text = "Наборы";
//
// buttonDeleteSet
//
buttonDeleteSet.Location = new Point(9, 223);
buttonDeleteSet.Margin = new Padding(2);
buttonDeleteSet.Name = "buttonDeleteSet";
buttonDeleteSet.Size = new Size(166, 30);
buttonDeleteSet.TabIndex = 9;
buttonDeleteSet.Text = "Удалить набор";
buttonDeleteSet.UseVisualStyleBackColor = true;
buttonDeleteSet.Click += buttonDeleteSet_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(14, 111);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(152, 84);
listBoxStorages.TabIndex = 8;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// buttonAddInSet
//
buttonAddInSet.Location = new Point(9, 65);
buttonAddInSet.Margin = new Padding(2);
buttonAddInSet.Name = "buttonAddInSet";
buttonAddInSet.Size = new Size(166, 30);
buttonAddInSet.TabIndex = 7;
buttonAddInSet.Text = "Добавить в набор";
buttonAddInSet.UseVisualStyleBackColor = true;
buttonAddInSet.Click += buttonAddInSet_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(9, 33);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(162, 27);
textBoxStorageName.TabIndex = 0;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(51, 425);
maskedTextBoxNumber.Margin = new Padding(2);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(119, 27);
maskedTextBoxNumber.TabIndex = 5;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(38, 509);
buttonUpdate.Margin = new Padding(2);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(142, 50);
buttonUpdate.TabIndex = 4;
buttonUpdate.Text = "Обновить коллекцию";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += buttonUpdate_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(30, 369);
buttonAdd.Margin = new Padding(2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(166, 30);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить самолет";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(38, 456);
buttonDelete.Margin = new Padding(2);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(142, 30);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить самолет";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += buttonDelete_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Margin = new Padding(2);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(707, 570);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.TabIndex = 6;
pictureBoxCollection.TabStop = false;
//
// FormAirplaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(921, 570);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxInstruments);
Margin = new Padding(2);
Name = "FormAirplaneCollection";
Text = "FormAirplaneCollection";
groupBoxInstruments.ResumeLayout(false);
groupBoxInstruments.PerformLayout();
groupBoxSets.ResumeLayout(false);
groupBoxSets.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;
}
}

View File

@ -0,0 +1,187 @@
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.Generics;
using AirplaneWithRadar.MovementStrategy;
namespace AirplaneWithRadar
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningAirplane
/// </summary>
public partial class FormAirplaneCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly AirplanesGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormAirplaneCollection()
{
InitializeComponent();
_storage = new AirplanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <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();
}
/// <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)
{
return;
}
if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?",
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
AirplaneWithRadarForm form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (obj + form.SelectedAirplane)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowAirplanes();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <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)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowAirplanes();
}
else
{
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,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

@ -11,7 +11,7 @@ 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());
Application.Run(new FormAirplaneCollection());
}
}
}

View File

@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 bool Insert(T airplane)
{
if (_places.Count == _maxCount)
{
return false;
}
Insert(airplane, 0);
return true;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="airplane">Добавляемый самолет</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T airplane, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) return false;
_places.Insert(position, airplane);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= Count) return false;
_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
}
}