5 Commits

Author SHA1 Message Date
a18c598b8d убраны комменты 2024-04-04 10:48:41 +04:00
a8591777d9 финал 2024-04-03 16:28:15 +04:00
8c4a09a8b5 Внесены изменения в именах 2024-04-01 00:59:32 +04:00
9654506023 Компания 2024-03-26 00:09:01 +04:00
d39c9e27bc Коллекция объектов 2024-03-15 20:28:52 +04:00
41 changed files with 192 additions and 2228 deletions

View File

@@ -1,5 +1,4 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@@ -49,7 +48,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
@@ -60,8 +59,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningMilitaryAircraft militaryAircraft)
{
return company._collection?.Insert(militaryAircraft, new DrawiningMilitaryAircraftEqutables()) ??
throw new DrawningEquitablesException();
return company._collection.Insert(militaryAircraft);
}
/// <summary>
@@ -97,29 +95,14 @@ public abstract class AbstractCompany
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="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningMilitaryAircraft?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@@ -1,10 +1,9 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - ангар
/// Реализация абстрактной компании - каршеринг
/// </summary>
public class Angar : AbstractCompany
{
@@ -43,13 +42,11 @@ public class Angar : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
if (_collection.Get(i) != null)
{
_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--;
@@ -58,7 +55,7 @@ public class Angar : AbstractCompany
curWidth = width - 1;
curHeight--;
}
if (curHeight >= height)
if (curHeight > height)
{
return;
}

View File

@@ -1,51 +0,0 @@
namespace ProjectAirFighter.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]),
strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public bool IsEmpty()
{
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

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

View File

@@ -1,6 +1,4 @@
using ProjectAirFighter.Drawnings;
namespace ProjectAirFighter.CollectionGenericObjects;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@@ -17,14 +15,14 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
int SetMaxCount { set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@@ -32,7 +30,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@@ -47,21 +45,4 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@@ -1,90 +0,0 @@
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, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
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];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -1,7 +1,4 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -17,12 +14,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int MaxCount
public int SetMaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -39,8 +32,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -51,94 +42,67 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
if (position >= _collection.Length || position < 0)
{ return null; }
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
public int Insert(T obj)
{
if (comparer != null)
int index = 0;
while (index < _collection.Length)
{
foreach (T? item in _collection)
if (_collection[index] == null)
{
if ((comparer as IEqualityComparer<DrawningMilitaryAircraft>).Equals(obj as DrawningMilitaryAircraft, item as DrawningMilitaryAircraft))
throw new CollectionInsertException();
_collection[index] = obj;
return index;
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
index++;
}
throw new CollectionOverflowException(Count);
return -1;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
public int Insert(T obj, int position)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningMilitaryAircraft>).Equals(obj as DrawningMilitaryAircraft, item as DrawningMilitaryAircraft))
throw new CollectionInsertException();
}
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
else
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
for (int i = 1; i < Count; ++i)
if (_collection[index] == null)
{
if (_collection[position + i] == null)
{
_collection[position + i] = obj;
return position + i;
}
for (i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
_collection[position] = obj;
return position;
}
}
throw new CollectionOverflowException(Count);
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
}
public T? Remove(int position)
{
if (position >= Count - 3 || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
if (position >= _collection.Length || position < 0)
{
return null;
}
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];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> value = new List<T?>(_collection);
value.Sort(comparer);
value.CopyTo(_collection, 0);
}
}

View File

@@ -1,226 +0,0 @@
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<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> 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<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo);
else if (collectionType == CollectionType.Massive)
{
_storages[collectionInfo] = new MassiveGenericObjects<T>();
}
else if (collectionType == CollectionType.List)
{
_storages[collectionInfo] = new ListGenericObjects<T>();
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(collectionInfo);
}
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return _storages[collectionInfo];
}
return null;
}
}
/// <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<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
}
}
/// <summary>
/// Загрузка информации по военным самолётам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exceptions.FileNotFoundException(filename);
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (string.IsNullOrEmpty(str))
{
throw new EmptyFileExeption(filename);
}
if (!str.StartsWith(_collectionKey))
{
throw new Exceptions.FileFormatException(filename);
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo =
CollectionInfo.GetCollectionInfo(record[0]) ??
throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningMilitaryAircraft() is T militaryAircraft)
{
try
{
collection.Insert(militaryAircraft);
}
catch (Exception ex)
{
throw new Exceptions.FileFormatException(filename, ex);
}
}
}
_storages.Add(collectionInfo, 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

@@ -1,69 +0,0 @@
using ProjectAirFighter.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningMilitaryAircraftEqutables : IEqualityComparer<DrawningMilitaryAircraft>
{
public bool Equals(DrawningMilitaryAircraft? x, DrawningMilitaryAircraft? y)
{
if (x == null || x.EntityMilitaryAircraft == null)
{
return false;
}
if (y == null || y.EntityMilitaryAircraft == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityMilitaryAircraft.Speed != y.EntityMilitaryAircraft.Speed)
{
return false;
}
if (x.EntityMilitaryAircraft.Weight != y.EntityMilitaryAircraft.Weight)
{
return false;
}
if (x.EntityMilitaryAircraft.BodyColor != y.EntityMilitaryAircraft.BodyColor)
{
return false;
}
if (x is DrawningAirFighter && y is DrawningAirFighter)
{
EntityAirFighter EntityX = (EntityAirFighter)x.EntityMilitaryAircraft;
EntityAirFighter EntityY = (EntityAirFighter)y.EntityMilitaryAircraft;
if (EntityX.Wings != EntityY.Wings)
{
return false;
}
if (EntityX.Rockets != EntityY.Rockets)
{
return false;
}
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningMilitaryAircraft obj)
{
return obj.GetHashCode();
}
}

View File

@@ -17,40 +17,24 @@ public class DrawningAirFighter : DrawningMilitaryAircraft
/// <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)
{
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 (EntityMilitaryAircraft == null || EntityMilitaryAircraft is not EntityAirFighter airFighter || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityMilitaryAircraft == null || EntityMilitaryAircraft is not EntityAirFighter militaryAircraftFighter || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(airFighter.AdditionalColor);
Brush additionalBrush = new SolidBrush(militaryAircraftFighter.AdditionalColor);
base.DrawTransport(g);
if (airFighter.Wings)
if (militaryAircraftFighter.Wings)
{
Point wings1 = new Point(_startPosX.Value + 45, _startPosY.Value + 30);
Point wings2 = new Point(_startPosX.Value + 45, _startPosY.Value + 15);
@@ -69,7 +53,7 @@ public class DrawningAirFighter : DrawningMilitaryAircraft
g.DrawPolygon(pen, DownWing);
}
if (airFighter.Rockets)
if (militaryAircraftFighter.Rockets)
{
Point rocket1 = new Point(_startPosX.Value + 40, _startPosY.Value + 5);
Point rocket2 = new Point(_startPosX.Value + 15, _startPosY.Value + 5);

View File

@@ -23,22 +23,22 @@ public class DrawningMilitaryAircraft
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки самолёта
/// Левая координата прорисовки самолёта
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки военного самолёта
/// Верхняя кооридната прорисовки самолёта
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки военного самолёта
/// Ширина прорисовки самолёта
/// </summary>
private readonly int _drawningMilitaryAircraftWidth = 70;
/// <summary>
/// Высота прорисовки военного самолёта
/// Высота прорисовки самолёта
/// </summary>
private readonly int _drawningMilitaryAircraftHeight = 70;
@@ -79,26 +79,17 @@ public class DrawningMilitaryAircraft
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningMilitaryAircraft(int speed, double weight, Color bodyColor) : this()
public DrawningMilitaryAircraft (int speed, double weight, Color bodyColor) : this()
{
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 DrawningMilitaryAircraft(int drawningMilitaryAircraftWidth, int drawningMilitaryAircraftHeight) : this()
/// <param name="drawningMilitaryAircraftWidth">Ширина прорисовки самолёта</param>
/// <param name="drawningMilitaryAircraftHeight">Высота прорисовки самолёта</param>
protected DrawningMilitaryAircraft(int drawningMilitaryAircraftWidth, int drawningMilitaryAircraftHeight) : this()
{
_drawningMilitaryAircraftWidth = drawningMilitaryAircraftWidth;
_drawningMilitaryAircraftHeight = drawningMilitaryAircraftHeight;

View File

@@ -1,44 +0,0 @@
using ProjectAirFighter.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningMilitaryAircraftCompareByColor : IComparer<DrawningMilitaryAircraft?>
{
public int Compare(DrawningMilitaryAircraft? x, DrawningMilitaryAircraft? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityMilitaryAircraft == null)
{
return 1;
}
if (y == null || y.EntityMilitaryAircraft == null)
{
return -1;
}
if (ToHex(x.EntityMilitaryAircraft.BodyColor) != ToHex(y.EntityMilitaryAircraft.BodyColor))
{
return String.Compare(ToHex(x.EntityMilitaryAircraft.BodyColor), ToHex(y.EntityMilitaryAircraft.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityMilitaryAircraft.Speed.CompareTo(y.EntityMilitaryAircraft.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityMilitaryAircraft.Weight.CompareTo(y.EntityMilitaryAircraft.Weight);
}
private static String ToHex(Color c)
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}

View File

@@ -1,31 +0,0 @@
namespace ProjectAirFighter.Drawnings;
public class DrawningMilitaryAircraftCompareByType : IComparer<DrawningMilitaryAircraft>
{
public int Compare(DrawningMilitaryAircraft? x, DrawningMilitaryAircraft? y)
{
if (x == null || x.EntityMilitaryAircraft == null)
{
return 1;
}
if (y == null || y.EntityMilitaryAircraft == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityMilitaryAircraft.Speed.CompareTo(y.EntityMilitaryAircraft.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityMilitaryAircraft.Weight.CompareTo(y.EntityMilitaryAircraft.Weight);
}
}

View File

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

@@ -7,11 +7,6 @@ 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; }
@@ -22,24 +17,4 @@ public class EntityAirFighter : EntityMilitaryAircraft
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 EntityMilitaryAircraf
{
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 EntityMilitaryAircraf (int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@@ -11,48 +11,19 @@ public class EntityMilitaryAircraft
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="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityMilitaryAircraft(int speed, double weight, Color bodyColor)
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

@@ -1,20 +0,0 @@
using ProjectAirFighter.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception)
{ }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
public class CollectionInfoException : Exception
{
public CollectionInfoException() : base() { }
public CollectionInfoException(string message) : base(message) { }
public CollectionInfoException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionInfoException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
public class CollectionInsertException : Exception
{
public CollectionInsertException(object obj) : base($"Объект {obj} не удволетворяет уникальности") { }
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionInsertException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

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

@@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
public class CollectionTypeException : Exception
{
public CollectionTypeException() : base() { }
public CollectionTypeException(string message) : base(message) { }
public CollectionTypeException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionTypeException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
public class DrawningEquitablesException : Exception
{
public DrawningEquitablesException() : base("Объекты прорисовки одинаковые") { }
public DrawningEquitablesException(string message) : base(message) { }
public DrawningEquitablesException(string message, Exception exception) :
base(message, exception)
{ }
protected DrawningEquitablesException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) :
base(message, exception)
{ }
protected EmptyFileExeption(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -1,15 +0,0 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
public class FileFormatException : Exception
{
public FileFormatException() : base() { }
public FileFormatException(string message) : base(message) { }
public FileFormatException(string name, Exception exception) :
base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception)
{ }
protected FileFormatException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -1,16 +0,0 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
public class FileNotFoundException : Exception
{
public FileNotFoundException(string name) : base($"Файл {name} не существует ") { }
public FileNotFoundException() : base() { }
public FileNotFoundException(string name, string message) : base(message) { }
public FileNotFoundException(string name, string message, Exception exception) :
base(message, exception)
{ }
protected FileNotFoundException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

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

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

@@ -28,7 +28,7 @@
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
name/value pmilitaryAircrafts.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support

View File

@@ -29,74 +29,41 @@
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonRemoveMilitaryAircraft = new Button();
buttonAddMilitaryAircraft = new Button();
buttonRemoveAir = 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();
buttonAddAirFighter = new Button();
buttonAddAir = new Button();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
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(buttonRefresh);
groupBoxTools.Controls.Add(buttonGoToCheck);
groupBoxTools.Controls.Add(buttonRemoveAir);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddAirFighter);
groupBoxTools.Controls.Add(buttonAddAir);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(765, 28);
groupBoxTools.Location = new Point(594, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(206, 714);
groupBoxTools.Size = new Size(206, 450);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(ButtonSortByColor);
panelCompanyTools.Controls.Add(ButtonSortByType);
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, 354);
panelCompanyTools.TabIndex = 10;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 189);
buttonRefresh.Location = new Point(6, 395);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(192, 49);
buttonRefresh.Size = new Size(197, 29);
buttonRefresh.TabIndex = 7;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -105,137 +72,55 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 137);
buttonGoToCheck.Location = new Point(6, 328);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(192, 49);
buttonGoToCheck.Size = new Size(197, 29);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonRemoveMilitaryAircraft
// buttonRemoveAir
//
buttonRemoveMilitaryAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMilitaryAircraft.Location = new Point(3, 82);
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;
buttonRemoveAir.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveAir.Location = new Point(5, 211);
buttonRemoveAir.Name = "buttonRemoveAir";
buttonRemoveAir.Size = new Size(197, 29);
buttonRemoveAir.TabIndex = 5;
buttonRemoveAir.Text = "Удаление самолёта";
buttonRemoveAir.UseVisualStyleBackColor = true;
buttonRemoveAir.Click += buttonRemoveAir_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(4, 58);
maskedTextBoxPosition.Location = new Point(6, 161);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(192, 27);
maskedTextBoxPosition.Size = new Size(194, 27);
maskedTextBoxPosition.TabIndex = 4;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonCreateCompany
// buttonAddAirFighter
//
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;
buttonAddAirFighter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAirFighter.Location = new Point(6, 103);
buttonAddAirFighter.Name = "buttonAddAirFighter";
buttonAddAirFighter.Size = new Size(197, 31);
buttonAddAirFighter.TabIndex = 2;
buttonAddAirFighter.Text = "Добавление истребителя";
buttonAddAirFighter.UseVisualStyleBackColor = true;
buttonAddAirFighter.Click += buttonAddAirFighter_Click;
//
// panelStorage
// buttonAddAir
//
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 = "Название коллекции:";
buttonAddAir.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAir.Location = new Point(6, 68);
buttonAddAir.Name = "buttonAddAir";
buttonAddAir.Size = new Size(197, 29);
buttonAddAir.TabIndex = 1;
buttonAddAir.Text = "Добавление самолёта";
buttonAddAir.UseVisualStyleBackColor = true;
buttonAddAir.Click += buttonAddAir_Click;
//
// comboBoxSelectorCompany
//
@@ -243,134 +128,46 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(7, 285);
comboBoxSelectorCompany.Location = new Point(6, 26);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(193, 28);
comboBoxSelectorCompany.Size = new Size(194, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(765, 714);
pictureBox.Size = new Size(594, 450);
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(971, 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";
//
// ButtonSortByColor
//
ButtonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonSortByColor.Location = new Point(3, 299);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(192, 49);
ButtonSortByColor.TabIndex = 9;
ButtonSortByColor.Text = "Сортировка по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonSortByType.Location = new Point(3, 244);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(192, 49);
ButtonSortByType.TabIndex = 8;
ButtonSortByType.Text = "Сортировка по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// FormMilitaryAircraftCollection
// FormAirCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(971, 742);
ClientSize = new Size(800, 450);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMilitaryAircraftCollection";
Text = "Коллекция военных самолётов";
Name = "FormAirCollection";
Text = "Коллекция самолётов";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
groupBoxTools.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 Button buttonAddAir;
private Button buttonAddAirFighter;
private PictureBox pictureBox;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonRemoveAir;
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;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@@ -1,36 +1,21 @@
using Microsoft.Extensions.Logging;
using ProjectAirFighter.CollectionGenericObjects;
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)
public FormMilitaryAircraftCollection()
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@@ -40,55 +25,86 @@ public partial class FormMilitaryAircraftCollection : Form
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new Angar(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningMilitaryAircraft>());
break;
}
}
/// <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);
}
private void buttonAddAir_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMilitaryAircraft));
// <summary>
/// Добавление военного самолёта в коллекцию
/// <summary>
/// Добавление истребителя
/// </summary>
/// <param name="militaryAircraft"></param>
private void SetMilitaryAircraft(DrawningMilitaryAircraft? militaryAircraft)
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddAirFighter_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAirFighter));
private void CreateObject(string type)
{
if (_company == null || militaryAircraft == null)
if (_company == null)
{
return;
}
try
Random random = new();
DrawningMilitaryAircraft drawningMilitaryAircraft;
switch (type)
{
case nameof(DrawningMilitaryAircraft):
drawningMilitaryAircraft = new DrawningMilitaryAircraft(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningAirFighter):
drawningMilitaryAircraft = new DrawningAirFighter(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningMilitaryAircraft != -1)
{
var res = _company + militaryAircraft;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
else
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemoveMilitaryAircraft_Click(object sender, EventArgs e)
private void buttonRemoveAir_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
@@ -101,18 +117,14 @@ public partial class FormMilitaryAircraftCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
if (_company - pos != null)
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
else
{
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
MessageBox.Show("Не удалось удалить объект");
}
}
@@ -166,153 +178,4 @@ public partial class FormMilitaryAircraftCollection : Form
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].Name;
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);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareMilitaryAircraft(new DrawningMilitaryAircraftCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareMilitaryAircraft(new DrawningMilitaryAircraftCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareMilitaryAircraft(IComparer<DrawningMilitaryAircraft?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@@ -117,13 +117,4 @@
<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

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

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

@@ -1,120 +0,0 @@
<?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,9 +10,9 @@ public class MoveToBorder : AbstractStrategy
return false;
}
return objParams.RightBorder <= FieldWidth &&
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}

View File

@@ -15,7 +15,7 @@ public class MoveToCenter : AbstractStrategy
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}

View File

@@ -1,50 +1,17 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirFighter;
internal static class Program
namespace ProjectAirFighter
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
internal static class Program
{
// 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 =>
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
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);
});
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMilitaryAircraftCollection());
}
}
}

View File

@@ -8,16 +8,6 @@
<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

@@ -28,7 +28,7 @@
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
name/value pmilitaryAircrafts.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support

View File

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