13 Commits

Author SHA1 Message Date
3ed0fd1ce0 7 лабораторная работа 2024-05-16 09:19:52 +04:00
7fd93c6c32 правильное 2024-05-16 03:51:54 +04:00
696f879bad 7 лабораторная работа 2024-05-13 17:08:23 +04:00
bacf66aad8 шаг первый 2024-05-12 02:46:08 +04:00
40bc918983 во избежание конфликтов 2024-05-12 00:06:51 +04:00
76285d7e5b 5 лаба 2024-05-02 09:48:22 +04:00
922e66830c доработка по требованиям 2024-05-02 09:26:44 +04:00
433975003c пара изменений 2024-04-18 09:50:55 +04:00
e946dbbd54 5 лабораторная работа 2024-04-07 22:58:03 +04:00
ec4709d52f 4 лабораторная работа 2024-04-07 21:39:34 +04:00
18aaa18c04 изменено название 2024-04-07 18:20:57 +04:00
85ac980f74 3 лабораторная работа 2024-04-07 18:12:35 +04:00
2ceb123bf2 добавлен интерфейс 2024-04-06 01:12:15 +04:00
30 changed files with 2520 additions and 165 deletions

View File

@@ -0,0 +1,126 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию военных самолётов
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 100;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 105;
/// <summary>
/// Ширина окна2
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция военных самолётов
/// </summary>
protected ICollectionGenericObjects<DrawningMilitaryAircraft>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция военных самолётов</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningMilitaryAircraft> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="militaryAircraft">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningMilitaryAircraft militaryAircraft)
{
return company._collection.Insert(militaryAircraft);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningMilitaryAircraft operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningMilitaryAircraft? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
DrawningMilitaryAircraft? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
catch (CollectionOverflowException e)
{ }
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@@ -0,0 +1,67 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - ангар
/// </summary>
public class Angar : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public Angar(int picWidth, int picHeight, ICollectionGenericObjects<DrawningMilitaryAircraft> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 2);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth + 5, j * _placeSizeHeight, i * _placeSizeWidth + 5 + _placeSizeWidth - 30, j * _placeSizeHeight);
g.DrawLine(pen, i * _placeSizeWidth + 5, j * _placeSizeHeight, i * _placeSizeWidth + 5, j * _placeSizeHeight - _placeSizeHeight);
}
}
}
protected override void SetObjectsPosition()
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1;
int curHeight = height - 1;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth > 0)
curWidth--;
else
{
curWidth = width - 1;
curHeight--;
}
if (curHeight >= height)
{
return;
}
}
}
}

View File

@@ -0,0 +1,22 @@
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Тип коллекции
/// </summary>
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// Список
/// </summary>
List = 2
}

View File

@@ -0,0 +1,61 @@
using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
}

View File

@@ -0,0 +1,85 @@
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -0,0 +1,128 @@
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
{
for (int i = 0; i < Count - 3; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
// вставка
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
if (position >= Count - 3 || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -0,0 +1,235 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
using System.Text;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningMilitaryAircraft
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name)) { return; }
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
return;
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
}
}
/// <summary>
/// Сохранение информации по военным самолётам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по военным самолётам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new FormatException("В файле неверные данные");
}
if (!str.StartsWith(_collectionKey))
{
throw new FormatException("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningMilitaryAircraft() is T militaryAircraft)
{
try
{
if (collection.Insert(militaryAircraft) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
///
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -5,7 +5,7 @@ namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirFighter : DrawningFighter
public class DrawningAirFighter : DrawningMilitaryAircraft
{
/// <summary>
@@ -17,14 +17,30 @@ public class DrawningAirFighter : DrawningFighter
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="wings">Признак наличия доп крыльев</param>
/// <param name="rockets">Признак наличия ракет</param>
public DrawningAirFighter (int speed, double weight, Color bodyColor, Color additionalColor, bool wings, bool rockets) : base (70, 70)
public DrawningAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool wings, bool rockets) : base(70, 70)
{
EntityFighter = new EntityAirFighter(speed, weight, bodyColor, additionalColor, wings, rockets);
EntityMilitaryAircraft = new EntityAirFighter(speed, weight, bodyColor, additionalColor, wings, rockets);
}
/// <summary>
/// Конструктор
/// </summary>
public DrawningAirFighter(EntityAirFighter militaryAircraft) : base(110, 60)
{
EntityMilitaryAircraft = new EntityAirFighter(militaryAircraft.Speed, militaryAircraft.Weight, militaryAircraft.BodyColor, militaryAircraft.AdditionalColor, militaryAircraft.Wings, militaryAircraft.Rockets);
}
//public DrawningAirFighter(EntityMilitaryAircraft entityMilitaryAircraft) : base(110, 60)
//{
// if (entityMilitaryAircraft != null)
// {
// EntityMilitaryAircraft = entityMilitaryAircraft;
// }
//}
public override void DrawTransport(Graphics g)
{
if (EntityFighter == null || EntityFighter is not EntityAirFighter airFighter || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityMilitaryAircraft == null || EntityMilitaryAircraft is not EntityAirFighter airFighter || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}

View File

@@ -5,12 +5,12 @@ namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
/// </summary>
public class DrawningFighter
public class DrawningMilitaryAircraft
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityFighter? EntityFighter { get; protected set; }
public EntityMilitaryAircraft? EntityMilitaryAircraft { get; protected set; }
/// <summary>
/// Ширина окна
@@ -23,24 +23,24 @@ public class DrawningFighter
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки самолёта
/// Левая координата прорисовки самолёта
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки самолёта
/// Верхняя кооридната прорисовки военного самолёта
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки самолёта
/// Ширина прорисовки военного самолёта
/// </summary>
private readonly int _drawningFighterWidth = 70;
private readonly int _drawningMilitaryAircraftWidth = 70;
/// <summary>
/// Высота прорисовки самолёта
/// Высота прорисовки военного самолёта
/// </summary>
private readonly int _drawningFighterHeight = 70;
private readonly int _drawningMilitaryAircraftHeight = 70;
/// <summary>
/// Координата X объекта
@@ -55,17 +55,17 @@ public class DrawningFighter
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningFighterWidth;
public int GetWidth => _drawningMilitaryAircraftWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningFighterHeight;
public int GetHeight => _drawningMilitaryAircraftHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningFighter()
private DrawningMilitaryAircraft()
{
_pictureWidth = null;
_pictureHeight = null;
@@ -79,25 +79,34 @@ public class DrawningFighter
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningFighter (int speed, double weight, Color bodyColor) : this()
public DrawningMilitaryAircraft(int speed, double weight, Color bodyColor) : this()
{
EntityFighter = new EntityFighter(speed, weight, bodyColor);
EntityMilitaryAircraft = new EntityMilitaryAircraft(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="militaryAircraft">Класс-сущность</param>
public DrawningMilitaryAircraft(EntityMilitaryAircraft militaryAircraft) : this()
{
EntityMilitaryAircraft = militaryAircraft;
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningCarWidth">Ширина прорисовки самолёта</param>
/// <param name="drawningCarHeight">Высота прорисовки самолёта</param>
protected DrawningFighter(int drawningFighterWidth, int drawningFighterHeight) : this()
/// <param name="drawningCarWidth">Ширина прорисовки военного самолёта</param>
/// <param name="drawningCarHeight">Высота прорисовки военного самолёта</param>
protected DrawningMilitaryAircraft(int drawningMilitaryAircraftWidth, int drawningMilitaryAircraftHeight) : this()
{
_drawningFighterWidth = drawningFighterWidth;
_drawningFighterHeight = drawningFighterHeight;
_drawningMilitaryAircraftWidth = drawningMilitaryAircraftWidth;
_drawningMilitaryAircraftHeight = drawningMilitaryAircraftHeight;
}
public bool SetPictureSize(int width, int height)
{
if (_drawningFighterWidth < width && _drawningFighterHeight < height)
if (_drawningMilitaryAircraftWidth < width && _drawningMilitaryAircraftHeight < height)
{
_pictureWidth = width;
_pictureHeight = height;
@@ -118,9 +127,9 @@ public class DrawningFighter
return;
}
if (x + _drawningFighterWidth > _pictureWidth)
if (x + _drawningMilitaryAircraftWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningFighterWidth;
_startPosX = _pictureWidth - _drawningMilitaryAircraftWidth;
}
else if (x < 0)
{
@@ -130,9 +139,9 @@ public class DrawningFighter
{
_startPosX = x;
}
if (y + _drawningFighterHeight > _pictureHeight)
if (y + _drawningMilitaryAircraftHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningFighterHeight;
_startPosY = _pictureHeight - _drawningMilitaryAircraftHeight;
}
else if (y < 0)
{
@@ -146,7 +155,7 @@ public class DrawningFighter
public bool MoveTransport(DirectionType direction)
{
if (EntityFighter == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityMilitaryAircraft == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
@@ -154,27 +163,27 @@ public class DrawningFighter
switch (direction)
{
case DirectionType.Left:
if (_startPosX.Value - EntityFighter.Step > 0)
if (_startPosX.Value - EntityMilitaryAircraft.Step > 0)
{
_startPosX -= (int)EntityFighter.Step;
_startPosX -= (int)EntityMilitaryAircraft.Step;
}
return true;
case DirectionType.Up:
if (_startPosY.Value - EntityFighter.Step > 0)
if (_startPosY.Value - EntityMilitaryAircraft.Step > 0)
{
_startPosY -= (int)EntityFighter.Step;
_startPosY -= (int)EntityMilitaryAircraft.Step;
}
return true;
case DirectionType.Right:
if (_startPosX.Value + _drawningFighterWidth + EntityFighter.Step < _pictureWidth)
if (_startPosX.Value + _drawningMilitaryAircraftWidth + EntityMilitaryAircraft.Step < _pictureWidth)
{
_startPosX += (int)EntityFighter.Step;
_startPosX += (int)EntityMilitaryAircraft.Step;
}
return true;
case DirectionType.Down:
if (_startPosY.Value + _drawningFighterHeight + EntityFighter.Step < _pictureHeight)
if (_startPosY.Value + _drawningMilitaryAircraftHeight + EntityMilitaryAircraft.Step < _pictureHeight)
{
_startPosY += (int)EntityFighter.Step;
_startPosY += (int)EntityMilitaryAircraft.Step;
}
return true;
default:
@@ -184,13 +193,13 @@ public class DrawningFighter
public virtual void DrawTransport(Graphics g)
{
if (EntityFighter == null || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityMilitaryAircraft == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush br = new SolidBrush(EntityFighter.BodyColor);
Brush br = new SolidBrush(EntityMilitaryAircraft.BodyColor);
g.FillRectangle(br, _startPosX.Value + 10, _startPosY.Value + 30, 60, 10);
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 30, 60, 10);

View File

@@ -0,0 +1,54 @@
using ProjectAirFighter.Entities;
namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtentionDrawningMilitaryAircraft
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningMilitaryAircraft? CreateDrawningMilitaryAircraft(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityMilitaryAircraft? militaryAircraft = EntityAirFighter.CreateEntityAirFighter(strs);
if (militaryAircraft != null)
{
return new DrawningAirFighter((EntityAirFighter)militaryAircraft);
}
militaryAircraft = EntityMilitaryAircraft.CreateEntityMilitaryAircraft(strs);
if (militaryAircraft != null)
{
return new DrawningMilitaryAircraft(militaryAircraft);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningMilitaryAircraft drawningMilitaryAircraft)
{
string[]? array = drawningMilitaryAircraft?.EntityMilitaryAircraft?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -3,18 +3,43 @@
/// <summary>
/// Класс-сущность "Истребитель"
/// </summary>
public class EntityAirFighter : EntityFighter
public class EntityAirFighter : EntityMilitaryAircraft
{
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color additionalColor)
{
AdditionalColor = additionalColor;
}
public bool Wings { get; private set; }
public bool Rockets { get; private set; }
public EntityAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool wings, bool rockets) : base(5, 45, Color.Black)
public EntityAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool wings, bool rockets) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Rockets = rockets;
Wings = wings;
}
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirFighter), Speed.ToString(), Weight.ToString(), BodyColor.Name, Wings.ToString(), Rockets.ToString(), AdditionalColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAirFighter? CreateEntityAirFighter(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityAirFighter))
{
return null;
}
return new EntityAirFighter(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@@ -1,29 +0,0 @@
namespace ProjectAirFighter.Entities;
/// <summary>
/// Класс-сущность "Истребитель"
/// </summary>
public class EntityFighter
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityFighter (int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@@ -0,0 +1,58 @@
namespace ProjectAirFighter.Entities;
/// <summary>
/// Класс-сущность "Военный самолёт"
/// </summary>
public class EntityMilitaryAircraft
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public void SetBodyColor(Color bodyColor)
{
BodyColor = bodyColor;
}
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityMilitaryAircraft(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityMilitaryAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityMilitaryAircraft? CreateEntityMilitaryAircraft(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityMilitaryAircraft))
{
return null;
}
return new EntityMilitaryAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -22,12 +22,10 @@
private void InitializeComponent()
{
pictureBoxAirFighter = new PictureBox();
buttonCreateAirFighter = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonLeft = new Button();
buttonUp = new Button();
buttonCreateFighter = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirFighter).BeginInit();
@@ -42,17 +40,6 @@
pictureBoxAirFighter.TabIndex = 0;
pictureBoxAirFighter.TabStop = false;
//
// buttonCreateAirFighter
//
buttonCreateAirFighter.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAirFighter.Location = new Point(12, 409);
buttonCreateAirFighter.Name = "buttonCreateAirFighter";
buttonCreateAirFighter.Size = new Size(169, 29);
buttonCreateAirFighter.TabIndex = 1;
buttonCreateAirFighter.Text = "Создать истребитель";
buttonCreateAirFighter.UseVisualStyleBackColor = true;
buttonCreateAirFighter.Click += buttonCreateAirFighter_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
@@ -101,17 +88,6 @@
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonCreateFighter
//
buttonCreateFighter.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateFighter.Location = new Point(196, 409);
buttonCreateFighter.Name = "buttonCreateFighter";
buttonCreateFighter.Size = new Size(169, 29);
buttonCreateFighter.TabIndex = 6;
buttonCreateFighter.Text = "Создать самолёт";
buttonCreateFighter.UseVisualStyleBackColor = true;
buttonCreateFighter.Click += buttonCreateAir_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
@@ -139,12 +115,10 @@
ClientSize = new Size(800, 450);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateFighter);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonCreateAirFighter);
Controls.Add(pictureBoxAirFighter);
Name = "FormAirFighter";
Text = "Истребитель";
@@ -155,12 +129,10 @@
#endregion
private PictureBox pictureBoxAirFighter;
private Button buttonCreateAirFighter;
private Button buttonDown;
private Button buttonRight;
private Button buttonLeft;
private Button buttonUp;
private Button buttonCreateFighter;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}

View File

@@ -5,7 +5,7 @@ namespace ProjectAirFighter;
public partial class FormAirFighter : Form
{
private DrawningFighter? _drawningFighter;
private DrawningMilitaryAircraft? _drawningMilitaryAircraft;
private AbstractStrategy? _strategy;
@@ -15,52 +15,34 @@ public partial class FormAirFighter : Form
_strategy = null;
}
public DrawningMilitaryAircraft SetAir
{
set
{
_drawningMilitaryAircraft = value;
_drawningMilitaryAircraft.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
private void Draw()
{
if (_drawningFighter == null)
if (_drawningMilitaryAircraft == null)
{
return;
}
Bitmap bmp = new(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningFighter.DrawTransport(gr);
_drawningMilitaryAircraft.DrawTransport(gr);
pictureBoxAirFighter.Image = bmp;
}
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningFighter):
_drawningFighter = new DrawningFighter(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningAirFighter):
_drawningFighter = new DrawningAirFighter(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)));
break;
default:
return;
}
_drawningFighter.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
_drawningFighter.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
private void buttonCreateAirFighter_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirFighter));
private void buttonCreateAir_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningFighter));
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningFighter == null)
if (_drawningMilitaryAircraft == null)
{
return;
}
@@ -70,16 +52,16 @@ public partial class FormAirFighter : Form
switch (name)
{
case "buttonUp":
result = _drawningFighter.MoveTransport(DirectionType.Up);
result = _drawningMilitaryAircraft.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningFighter.MoveTransport(DirectionType.Down);
result = _drawningMilitaryAircraft.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningFighter.MoveTransport(DirectionType.Left);
result = _drawningMilitaryAircraft.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningFighter.MoveTransport(DirectionType.Right);
result = _drawningMilitaryAircraft.MoveTransport(DirectionType.Right);
break;
}
@@ -91,7 +73,7 @@ public partial class FormAirFighter : Form
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningFighter == null)
if (_drawningMilitaryAircraft == null)
{
return;
}
@@ -108,7 +90,7 @@ public partial class FormAirFighter : Form
{
return;
}
_strategy.SetData(new MoveableAir(_drawningFighter), pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
_strategy.SetData(new MoveableMilitaryAircraft(_drawningMilitaryAircraft), pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
}
if (_strategy == null)

View File

@@ -0,0 +1,348 @@
namespace ProjectAirFighter
{
partial class FormMilitaryAircraftCollection
{
/// <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()
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonRemoveMilitaryAircraft = new Button();
buttonAddMilitaryAircraft = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
textBoxCollectionName = new TextBox();
radioButtonMassive = new RadioButton();
radioButtonList = new RadioButton();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(744, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(206, 639);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveMilitaryAircraft);
panelCompanyTools.Controls.Add(buttonAddMilitaryAircraft);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 357);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(200, 279);
panelCompanyTools.TabIndex = 10;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 227);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(192, 49);
buttonRefresh.TabIndex = 7;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 178);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(192, 49);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonRemoveMilitaryAircraft
//
buttonRemoveMilitaryAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMilitaryAircraft.Location = new Point(4, 129);
buttonRemoveMilitaryAircraft.Name = "buttonRemoveMilitaryAircraft";
buttonRemoveMilitaryAircraft.Size = new Size(191, 49);
buttonRemoveMilitaryAircraft.TabIndex = 5;
buttonRemoveMilitaryAircraft.Text = "Удаление военного самолёта";
buttonRemoveMilitaryAircraft.UseVisualStyleBackColor = true;
buttonRemoveMilitaryAircraft.Click += buttonRemoveMilitaryAircraft_Click;
//
// buttonAddMilitaryAircraft
//
buttonAddMilitaryAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddMilitaryAircraft.Location = new Point(4, 3);
buttonAddMilitaryAircraft.Name = "buttonAddMilitaryAircraft";
buttonAddMilitaryAircraft.Size = new Size(191, 49);
buttonAddMilitaryAircraft.TabIndex = 1;
buttonAddMilitaryAircraft.Text = "Добавление военного самолёта";
buttonAddMilitaryAircraft.UseVisualStyleBackColor = true;
buttonAddMilitaryAircraft.Click += buttonAddMilitaryAircraft_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(3, 96);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(192, 27);
maskedTextBoxPosition.TabIndex = 4;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(7, 322);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(191, 29);
buttonCreateCompany.TabIndex = 9;
buttonCreateCompany.Text = "Создание компании";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 23);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(200, 256);
panelStorage.TabIndex = 8;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(6, 224);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(189, 29);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удаление коллекции";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += buttonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(6, 131);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(189, 84);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(6, 96);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(189, 29);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += buttonCollectionAdd_Click;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(6, 33);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(189, 27);
textBoxCollectionName.TabIndex = 3;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(6, 66);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(115, 66);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 1;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(17, 10);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(158, 20);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(7, 285);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(193, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(744, 639);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(950, 28);
menuStrip.TabIndex = 4;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormMilitaryAircraftCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(950, 667);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMilitaryAircraftCollection";
Text = "Коллекция военных самолётов";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddMilitaryAircraft;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Button buttonRemoveMilitaryAircraft;
private Panel panelStorage;
private TextBox textBoxCollectionName;
private RadioButton radioButtonMassive;
private RadioButton radioButtonList;
private Label labelCollectionName;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@@ -0,0 +1,294 @@
using Microsoft.Extensions.Logging;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter;
public partial class FormMilitaryAircraftCollection : Form
{
/// <summary>
/// Хранилише коллекций
/// </summary>
private readonly StorageCollection<DrawningMilitaryAircraft> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMilitaryAircraftCollection(ILogger<FormMilitaryAircraftCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление военного самолёта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddMilitaryAircraft_Click(object sender, EventArgs e)
{
FormMilitaryAircraftConfig form = new();
form.Show();
form.AddEvent(SetMilitaryAircraft);
}
// <summary>
/// Добавление военного самолёта в коллекцию
/// </summary>
/// <param name="militaryAircraft"></param>
private void SetMilitaryAircraft(DrawningMilitaryAircraft? militaryAircraft)
{
if (_company == null || militaryAircraft == null)
{
return;
}
try
{
var res = _company + militaryAircraft;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemoveMilitaryAircraft_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningMilitaryAircraft? militaryAircraft = null;
int counter = 100;
while (militaryAircraft == null)
{
militaryAircraft = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (militaryAircraft == null)
{
return;
}
FormAirFighter form = new()
{
SetAir = militaryAircraft
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningMilitaryAircraft>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Angar(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

View File

@@ -0,0 +1,129 @@
<?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="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 17</value>
</metadata>
</root>

View File

@@ -0,0 +1,357 @@
namespace ProjectAirFighter
{
partial class FormMilitaryAircraftConfig
{
/// <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()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelBlueViolet = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxRockets = new CheckBox();
checkBoxWings = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxRockets);
groupBoxConfig.Controls.Add(checkBoxWings);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(604, 207);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelBlueViolet);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(347, 12);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(250, 125);
groupBoxColors.TabIndex = 1;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelBlueViolet
//
panelBlueViolet.BackColor = Color.BlueViolet;
panelBlueViolet.Location = new Point(196, 83);
panelBlueViolet.Name = "panelBlueViolet";
panelBlueViolet.Size = new Size(36, 36);
panelBlueViolet.TabIndex = 9;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(136, 83);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(36, 36);
panelBlack.TabIndex = 11;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(77, 83);
panelGray.Name = "panelGray";
panelGray.Size = new Size(36, 36);
panelGray.TabIndex = 10;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(15, 83);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(36, 36);
panelWhite.TabIndex = 9;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(196, 26);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(36, 36);
panelYellow.TabIndex = 9;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(136, 26);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(36, 36);
panelBlue.TabIndex = 9;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(77, 26);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(36, 36);
panelGreen.TabIndex = 9;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(15, 26);
panelRed.Name = "panelRed";
panelRed.Size = new Size(36, 36);
panelRed.TabIndex = 8;
//
// checkBoxRockets
//
checkBoxRockets.AutoSize = true;
checkBoxRockets.Location = new Point(6, 154);
checkBoxRockets.Name = "checkBoxRockets";
checkBoxRockets.Size = new Size(339, 24);
checkBoxRockets.TabIndex = 7;
checkBoxRockets.Text = "Признак наличия дополнительных крыльев";
checkBoxRockets.UseVisualStyleBackColor = true;
//
// checkBoxWings
//
checkBoxWings.AutoSize = true;
checkBoxWings.Location = new Point(6, 124);
checkBoxWings.Name = "checkBoxWings";
checkBoxWings.Size = new Size(318, 24);
checkBoxWings.TabIndex = 6;
checkBoxWings.Text = "Признак наличия дополнительных ракет";
checkBoxWings.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(102, 75);
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(126, 27);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 75);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(102, 32);
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(126, 27);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 34);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(466, 154);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(113, 36);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(347, 154);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(113, 36);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(3, 49);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(185, 99);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(610, 166);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(85, 29);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(716, 166);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(85, 29);
buttonCancel.TabIndex = 2;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(610, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(191, 160);
panelObject.TabIndex = 3;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(100, 9);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(88, 36);
labelAdditionalColor.TabIndex = 2;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelColors_DragDrop;
labelAdditionalColor.DragEnter += LabelColors_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(3, 9);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(88, 36);
labelBodyColor.TabIndex = 1;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelColors_DragDrop;
labelBodyColor.DragEnter += LabelColors_DragEnter;
//
// FormMilitaryAircraftConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 207);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormMilitaryAircraftConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxRockets;
private CheckBox checkBoxWings;
private GroupBox groupBoxColors;
private Panel panelRed;
private Panel panelBlueViolet;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,169 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Entities;
namespace ProjectAirFighter;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormMilitaryAircraftConfig : Form
{
/// <summary>
/// Объект - прорисовка автомобиля
/// </summary>
private DrawningMilitaryAircraft? _militaryAircraft;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawningMilitaryAircraft>? MilitaryAircraftDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormMilitaryAircraftConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelBlueViolet.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="militaryAircraftDelegate"></param>
public void AddEvent(Action<DrawningMilitaryAircraft> militaryAircraftDelegate)
{
if (MilitaryAircraftDelegate != null)
{
MilitaryAircraftDelegate = militaryAircraftDelegate;
}
else
{
MilitaryAircraftDelegate += militaryAircraftDelegate;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_militaryAircraft.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_militaryAircraft?.SetPosition(15, 15);
_militaryAircraft?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <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 ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_militaryAircraft = new DrawningMilitaryAircraft((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.Black);
break;
case "labelModifiedObject":
_militaryAircraft = new DrawningAirFighter((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxRockets.Checked, checkBoxWings.Checked);
break;
}
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>2
private void Panel_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColors_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColors_DragDrop(object sender, DragEventArgs e)
{
if (_militaryAircraft == null)
{
return;
}
Label label = (Label)sender;
Color newColor = (Color)e.Data.GetData(typeof(Color).ToString());
switch (label.Name)
{
case "labelBodyColor":
_militaryAircraft.EntityMilitaryAircraft.SetBodyColor(newColor);
DrawObject();
break;
case "labelAdditionalColor":
if (_militaryAircraft is DrawningAirFighter)
{
(_militaryAircraft.EntityMilitaryAircraft as EntityAirFighter).SetAdditionalColor(newColor);
DrawObject();
}
break;
}
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_militaryAircraft != null)
{
MilitaryAircraftDelegate?.Invoke(_militaryAircraft);
Close();
}
}
}

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

@@ -10,8 +10,10 @@ public class MoveToBorder : AbstractStrategy
return false;
}
return objParams.RightBorder <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight && objParams.DownBorder + GetStep() >= FieldHeight;
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()

View File

@@ -13,8 +13,10 @@ public class MoveToCenter : AbstractStrategy
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()

View File

@@ -3,46 +3,46 @@
namespace ProjectAirFighter.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningCar
/// Класс-реализация IMoveableObject с использованием DrawningMilitaryAircraft
/// </summary>
public class MoveableAir : IMoveableObject
public class MoveableMilitaryAircraft : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// Поле-объект класса DrawningMilitaryAircraft или его наследника
/// </summary>
private readonly DrawningFighter? _air = null;
private readonly DrawningMilitaryAircraft? _militaryAircraft = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="car">Объект класса DrawningCar</param>
public MoveableAir(DrawningFighter air)
/// <param name="militaryAircraft">Объект класса DrawningMilitaryAircraft</param>
public MoveableMilitaryAircraft(DrawningMilitaryAircraft militaryAircraft)
{
_air = air;
_militaryAircraft = militaryAircraft;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_air == null || _air.EntityFighter == null || !_air.GetPosX.HasValue || !_air.GetPosY.HasValue)
if (_militaryAircraft == null || _militaryAircraft.EntityMilitaryAircraft == null || !_militaryAircraft.GetPosX.HasValue || !_militaryAircraft.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_air.GetPosX.Value, _air.GetPosY.Value, _air.GetWidth, _air.GetHeight);
return new ObjectParameters(_militaryAircraft.GetPosX.Value, _militaryAircraft.GetPosY.Value, _militaryAircraft.GetWidth, _militaryAircraft.GetHeight);
}
}
public int GetStep => (int)(_air?.EntityFighter?.Step ?? 0);
public int GetStep => (int)(_militaryAircraft?.EntityMilitaryAircraft?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_air == null || _air.EntityFighter == null)
if (_militaryAircraft == null || _militaryAircraft.EntityMilitaryAircraft == null)
{
return false;
}
return _air.MoveTransport(GetDirectionType(direction));
return _militaryAircraft.MoveTransport(GetDirectionType(direction));
}
/// <summary>

View File

@@ -1,17 +1,50 @@
namespace ProjectAirFighter
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirFighter;
internal static class Program
{
internal static class Program
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService <FormMilitaryAircraftCollection>());
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMilitaryAircraftCollection>().AddLogging(option =>
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAirFighter());
}
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}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}

View File

@@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

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": "AirFighter"
}
}
}