Compare commits

...

18 Commits

Author SHA1 Message Date
nezui1
fccfd0c91a Лабораторная работа№8 2024-05-20 21:23:21 +04:00
nezui1
ed278533b7 Лабораторная работа№7 2024-05-06 22:40:56 +04:00
nezui1
9bf206eff5 Лабораторная работа№6 2024-05-06 18:57:29 +04:00
nezui1
5d662983bd Лабораторная работа№6 2024-04-22 18:03:58 +04:00
nezui1
d5fc3fd5ec Лабораторная работа №5 2024-04-20 15:47:54 +04:00
nezui1
2c39c97efa first version 2024-04-20 12:00:32 +03:00
nezui1
6dcc2b89b7 лабораторная работа№4(1) 2024-04-09 09:10:22 +03:00
nezui1
d3ebbc092d изменения.1 2024-04-06 14:06:20 +03:00
nezui1
dd60ab3219 Лабораторная работа №4 2024-04-06 14:58:10 +04:00
nezui1
f74d8a8bd3 Лабораторная работа№3 2024-04-06 13:40:17 +03:00
nezui1
26e0d00ce5 Лабораторная работа№3 2024-03-25 22:51:47 +04:00
nezui1
bf7cfe1f84 Коллекция объектов 2024-03-19 18:02:35 +04:00
nezui1
d215fc5864 Добавление стратегии 2024-03-10 20:06:26 +04:00
nezui1
692f1a21c1 Добавление стратегии 2024-03-10 20:04:31 +04:00
nezui1
2f34b4bdcf Добавление родителей и ввод конструкторов 2024-03-10 18:01:53 +04:00
nezui1
71156a3ec2 Лабораторная работа№1 2024-02-27 13:51:18 +03:00
nezui1
18baaa5880 Лабораторная работа№1 2024-02-26 20:55:25 +04:00
nezui1
4ef5a5cac1 Лабораторная работа№1 2024-02-12 21:13:24 +04:00
55 changed files with 4352 additions and 63 deletions

View File

@ -0,0 +1,118 @@
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Drawning;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.CollectionGenericObjects;
public abstract class AbstractCompany
{
/// <summary>
/// Размер места(ширина)
/// </summary>
public readonly int _placeSizeWidth = 140;
/// <summary>
/// Размер места(высота)
/// </summary>
public readonly int _placeSizeHeight = 160;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция военных самолетов
/// </summary>
protected ICollectionGenericObjects<DrawningWarPlane> _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<DrawningWarPlane> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount - 4;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company"></param>
/// <param name="warPlane"></param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningWarPlane warPlane)
{
return company._collection.Insert(warPlane, new DrawningWarPlaneEqtubles());
}
/// <summary>
/// Перегрузка оператора удаление для класса
/// </summary>
/// <param name="company"></param>
/// <param name="position"></param>
/// <returns></returns>
public static DrawningWarPlane operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
public void Sort(IComparer<DrawningWarPlane?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningWarPlane? 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)
{
DrawningWarPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
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,91 @@
using ProjectAirFighter.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
///
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
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

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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,70 @@
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawning;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.CollectionGenericObject;
/// <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, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемы объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась</returns>
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <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();
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -0,0 +1,131 @@
using Microsoft.VisualBasic.Devices;
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Exceptions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 CollectionType GetCollectionType => CollectionType.List;
public int MaxCount {
get
{
return _maxCount;
}
set
{
if (value > 0)
{
_maxCount = value ;
}
}
}
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
//проверка позиции
if (position >= Count || position < 0)
throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj,IEqualityComparer<T?>? comparer = null)
{
//проверка, что не превышено максимальное количество элементов
if(Count + 1 > _maxCount)
throw new CollectionOverflowException(Count);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new EqualException(obj);
}
}
//вставка в конец набора
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count + 1 > _maxCount)
throw new CollectionOverflowException(Count);
//проверка позиции
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new EqualException(obj);
}
}
//вставка по позиции
_collection.Insert(position,obj);
return 1;
}
public T? Remove(int position)
{
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
T? temp = _collection[position];
_collection.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for(int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -0,0 +1,168 @@
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawning;
using ProjectAirFighter.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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)
throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length && _collection[position] == null)
throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new EqualException(i);
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position > Count)
throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new EqualException(i);
}
}
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int temp = position + 1;
while (temp < Count)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
temp++;
}
temp = position - 1;
while (temp > 0)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
temp--;
}
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position < 0 || position > Count)
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for(int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -0,0 +1,224 @@
using Microsoft.AspNetCore.Http;
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Drawning;
using ProjectAirFighter.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningWarPlane
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
private Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
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))
{
return;
}
if (collectionType == CollectionType.None) return;
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(CollectionInfo collectionInfo)
{
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
{
get
{
//логика получения объекта
if(_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new(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.GetCollectionType);
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 FileNotFoundException($"{filename} не существует");
}
using (StreamReader reader = File.OpenText(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
throw new IOException("Файл не подходит");
}
if (!line.Equals(_collectionKey))
{
throw new IOException("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = reader.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo =
CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningWarPlane() is T warPlane)
{
try
{
collection.Insert(warPlane);
}
catch (Exception ex)
{
throw new 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

@ -0,0 +1,62 @@
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Drawning;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.CollectionGenericObjects;
public class WarPlaneBase : AbstractCompany
{
public WarPlaneBase(int picWidth, int picHeight, ICollectionGenericObjects<DrawningWarPlane> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; j++)
{
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth - 20, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _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++)
{
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 5);
}
if (curWidth > 0)
curWidth--;
else
{
curHeight--;
curWidth = width - 1;
}
if (curHeight < 0)
{
return;
}
}
}
}

View File

@ -0,0 +1,30 @@
namespace ProjectAirFighter.Drawning;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное напрвление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,88 @@
using System.Net.NetworkInformation;
using System.Net.Sockets;
using ProjectAirFighter.Entities;
namespace ProjectAirFighter.Drawning;
/// <summary>
/// класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirFighter : DrawningWarPlane
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия корпуса</param>
/// <param name="rocket">Признак наличия рокет</param>
/// <param name="additionalWing">Признак наличия дополнительных крыльев</param>
//public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool rocket, bool additionalWing)
public DrawningAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool rocket, bool additionalWing) : base(120,140)
{
EntityWarPlane = new EntityAirFighter(speed, weight, bodyColor, additionalColor, rocket, additionalWing);
}
/// <summary>
/// Конструктор для метода создания объекта из строки (ExtentionDrawningWarPlane)
/// </summary>
/// <param name="warPlane"></param>
public DrawningAirFighter(EntityWarPlane? warPlane) : base(warPlane)
{
if (warPlane != null)
EntityWarPlane = warPlane;
}
public override void DrawTransport(Graphics g)
{
if (EntityWarPlane == null || EntityWarPlane is not EntityAirFighter warPlane||!_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black, 3);
Pen pen_rocket = new(Color.Black);
Brush brAdd = new SolidBrush(warPlane.AdditionalColor);
//ракеты
if (warPlane.Rocket)
{
Point[] FirstRocket = { new Point(_startPosX.Value + 55, _startPosY.Value + 110), new Point(_startPosX.Value + 95, _startPosY.Value + 110),
new Point(_startPosX.Value + 105, _startPosY.Value + 115),new Point(_startPosX.Value + 95, _startPosY.Value + 120),
new Point(_startPosX.Value + 55, _startPosY.Value + 120) };
g.DrawPolygon(pen_rocket, FirstRocket);
Point[] SecondRocket = { new Point(_startPosX.Value + 55, _startPosY.Value + 30), new Point(_startPosX.Value + 95, _startPosY.Value + 30),
new Point(_startPosX.Value + 105, _startPosY.Value + 35),new Point(_startPosX.Value + 95, _startPosY.Value + 40),
new Point(_startPosX.Value + 55, _startPosY.Value + 40) };
g.DrawPolygon(pen_rocket, SecondRocket);
g.FillPolygon(brAdd, FirstRocket);
g.FillPolygon(brAdd, SecondRocket);
}
base.DrawTransport(g);
if (warPlane.AdditionalWing)
{
Point[] AddWingLower = { new Point(_startPosX.Value + 60, _startPosY.Value + 80),
new Point(_startPosX.Value + 60, _startPosY.Value + 140), new Point(_startPosX.Value + 50, _startPosY.Value + 140),
new Point(_startPosX.Value + 40, _startPosY.Value + 80) };
g.DrawPolygon(pen, AddWingLower);
Point[] AddWingUpper = { new Point(_startPosX.Value + 60, _startPosY.Value + 60), new Point(_startPosX.Value + 60, _startPosY.Value),
new Point(_startPosX.Value + 50, _startPosY.Value), new Point(_startPosX.Value + 40, _startPosY.Value + 60) };
g.DrawPolygon(pen, AddWingUpper);
g.FillPolygon(brAdd, AddWingUpper);
g.FillPolygon(brAdd, AddWingLower);
}
}
}

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public class DrawningCompareByColor : IComparer<DrawningWarPlane?>
{
public int Compare(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityWarPlane == null)
{
return 1;
}
if (y == null || y.EntityWarPlane == null)
{
return -1;
}
if (ToHex(x.EntityWarPlane.BodyColor) != ToHex(y.EntityWarPlane.BodyColor))
{
return String.Compare(ToHex(x.EntityWarPlane.BodyColor), ToHex(y.EntityWarPlane.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityWarPlane.Speed.CompareTo(y.EntityWarPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarPlane.Weight.CompareTo(y.EntityWarPlane.Weight);
}
static String ToHex(Color c)
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public class DrawningCompareByType : IComparer<DrawningWarPlane?>
{
public int Compare(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (x == null || x.EntityWarPlane == null)
{
return -1;
}
if (y == null || y.EntityWarPlane == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityWarPlane.Speed.CompareTo(y.EntityWarPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarPlane.Weight.CompareTo(y.EntityWarPlane.Weight);
}
}

View File

@ -0,0 +1,278 @@
using ProjectAirFighter.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public class DrawningWarPlane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityWarPlane? EntityWarPlane { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки самолета
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки самолета
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки самолета
/// </summary>
private readonly int _drawningWarPlaneWidth = 120;
/// <summary>
/// Высота прорисовки самолета
/// </summary>
private readonly int _drawningWarPlaneHeight = 140;
/// <summary>
/// Координаты X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координаты Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningWarPlaneHeight;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWigdth => _drawningWarPlaneWidth;
private DrawningWarPlane()
{
_pictureHeight = null;
_pictureWidth = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningWarPlane(int speed, double weight, Color bodyColor) : this()
{
EntityWarPlane = new EntityWarPlane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наслдеников
/// </summary>
/// <param name="drawningWarPlaneHeight">Высота прорисовки самолета</param>
/// <param name="drawningWarPlaneWidth">Ширина прорисовки самолета</param>
public DrawningWarPlane(int drawningWarPlaneWidth, int drawningWarPlaneHeight) : this()
{
_drawningWarPlaneWidth = drawningWarPlaneWidth;
_drawningWarPlaneHeight = drawningWarPlaneHeight;
}
/// <summary>
/// Конструктор для метода создания объекта из строки (ExtentionDrawningWarPlane)
/// </summary>
/// <param name="warPlane"></param>
public DrawningWarPlane(EntityWarPlane? warPlane) : this()
{
EntityWarPlane = warPlane;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns></returns>
public bool SetPictureSize(int width, int height)
{
if (width > _drawningWarPlaneWidth && height > _drawningWarPlaneHeight)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null && _startPosY != null)
{
if (_startPosX.Value < 0)
{
_startPosX = 0;
}
if (_startPosY.Value < 0)
{
_startPosY = 0;
}
if (_startPosX.Value + _drawningWarPlaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningWarPlaneWidth;
}
if (_startPosY.Value + _drawningWarPlaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningWarPlaneHeight;
}
}
return true;
}
return false;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
else
{
_startPosX = x;
_startPosY = y;
if (_startPosX.Value < 0)
{
_startPosX = 0;
}
if (_startPosY.Value < 0)
{
_startPosY = 0;
}
if (_startPosX + _drawningWarPlaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningWarPlaneWidth;
}
if (_startPosY + _drawningWarPlaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningWarPlaneHeight;
}
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещение выполнено, false - перемещение невозможно </returns>
public virtual bool MoveTransport(DirectionType direction)
{
if (EntityWarPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityWarPlane.Step > 0)
{
_startPosX -= (int)EntityWarPlane.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityWarPlane.Step > 0)
{
_startPosY -= (int)EntityWarPlane.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityWarPlane.Step + _drawningWarPlaneWidth < _pictureHeight)
{
_startPosY += (int)EntityWarPlane.Step;
}
return true;
//вправо
case DirectionType.Right:
if (_startPosX.Value + EntityWarPlane.Step + _drawningWarPlaneWidth < _pictureWidth)
{
_startPosX += (int)EntityWarPlane.Step;
}
return true;
default:
return false;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityWarPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black, 3);
Pen pen_rocket = new(Color.Black);
//корпус
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 60, 100, 20);
Point[] body = { new Point(_startPosX.Value + 100, _startPosY.Value + 80),
new Point(_startPosX.Value + 120, _startPosY.Value + 70), new Point(_startPosX.Value + 100, _startPosY.Value + 60) };
g.DrawPolygon(pen, body);
//нижнее крыло
Point[] wingUpper = { new Point(_startPosX.Value + 80, _startPosY.Value + 80),
new Point(_startPosX.Value + 80, _startPosY.Value + 140), new Point(_startPosX.Value + 70, _startPosY.Value + 140),
new Point(_startPosX.Value + 60, _startPosY.Value + 80) };
g.DrawPolygon(pen, wingUpper);
//верхнее крыло
Point[] wingLower = { new Point(_startPosX.Value + 80, _startPosY.Value + 60), new Point(_startPosX.Value + 80, _startPosY.Value),
new Point(_startPosX.Value + 70, _startPosY.Value), new Point(_startPosX.Value + 60, _startPosY.Value + 60) };
g.DrawPolygon(pen, wingLower);
//задние крылья
//верхнее
Point[] rearWingUpper = { new Point(_startPosX.Value, _startPosY.Value + 60), new Point(_startPosX.Value, _startPosY.Value + 30),
new Point(_startPosX.Value + 25, _startPosY.Value + 50), new Point(_startPosX.Value + 25, _startPosY.Value + 60)};
g.DrawPolygon(pen, rearWingUpper);
//нижнее
Point[] rearWingLower = { new Point(_startPosX.Value, _startPosY.Value + 80),
new Point(_startPosX.Value, _startPosY.Value + 110),new Point(_startPosX.Value + 25, _startPosY.Value + 90),
new Point(_startPosX.Value + 25, _startPosY.Value + 80) };
g.DrawPolygon(pen, rearWingLower);
//залив носа
Brush brBlack = new SolidBrush(Color.Black);
g.FillPolygon(brBlack, body);
//залив корпуса
Brush br = new SolidBrush(EntityWarPlane.BodyColor);
g.FillRectangle(br, _startPosX.Value, _startPosY.Value + 60, 100, 20);
g.FillPolygon(br, wingLower);
g.FillPolygon(br, wingUpper);
g.FillPolygon(br, rearWingUpper);
g.FillPolygon(br, rearWingLower);
}
}

View File

@ -0,0 +1,65 @@
using ProjectAirFighter.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public class DrawningWarPlaneEqtubles : IEqualityComparer<DrawningWarPlane?>
{
public bool Equals(DrawningWarPlane? x, DrawningWarPlane? y)
{
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarPlane != null && y.EntityWarPlane != null && x.EntityWarPlane.Speed != y.EntityWarPlane.Speed)
{
return false;
}
if (x.EntityWarPlane.Weight != y.EntityWarPlane.Weight)
{
return false;
}
if (x.EntityWarPlane.BodyColor != y.EntityWarPlane.BodyColor)
{
return false;
}
if (x is DrawningAirFighter && y is DrawningAirFighter)
{
if (((EntityAirFighter)x.EntityWarPlane).AdditionalColor !=
((EntityAirFighter)y.EntityWarPlane).AdditionalColor)
{
return false;
}
if (((EntityAirFighter)x.EntityWarPlane).Rocket !=
((EntityAirFighter)y.EntityWarPlane).Rocket)
{
return false;
}
if (((EntityAirFighter)x.EntityWarPlane).AdditionalWing !=
((EntityAirFighter)y.EntityWarPlane).AdditionalWing)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningWarPlane? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,60 @@
using ProjectAirFighter.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public static class ExtetntionDrawningWarPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningWarPlane? CreateDrawningWarPlane(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityWarPlane? warPlane = EntityAirFighter.CreateEntityAirFighter(strs);
if (warPlane != null)
{
return new DrawningAirFighter(warPlane);
}
warPlane = EntityWarPlane.CreateEntityWarPlane(strs);
if (warPlane != null)
{
return new DrawningWarPlane(warPlane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningWarPlane">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningWarPlane drawningWarPlane)
{
string[]? array = drawningWarPlane?.EntityWarPlane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -0,0 +1,80 @@
namespace ProjectAirFighter.Entities;
/// <summary>
/// Класс-сущность "Истребитель"
/// </summary>
public class EntityAirFighter : EntityWarPlane
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия ракет
/// </summary>
public bool Rocket { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительных крыльев
/// </summary>
public bool AdditionalWing { get; private set; }
/// <summary>
/// Шаг
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Иницифлизация полей объекта-класса истребителя
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rocket">Признак наличия рокет</param>
/// <param name="additionalWing">Признак наличия дополнительных крыльев</param>
public void SetAdditionalColor(Color addirionalColor)
{
AdditionalColor = addirionalColor;
}
public EntityAirFighter(int speed, double weight, Color bodyColor, Color additionalColor, bool rocket, bool additionalWing) :base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Rocket = rocket;
AdditionalWing = additionalWing;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirFighter), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
Rocket.ToString(), AdditionalWing.ToString()};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAirFighter? CreateEntityAirFighter(string[] strs)
{
if (strs.Length != 7 || 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

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

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку преполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: count " + 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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Exceptions;
internal class EqualException : ApplicationException
{
public EqualException(object i) : base("В коллекции уже есть такой элемент " + i) { }
public EqualException() : base() { }
public EqualException(string message) : base(message) { }
public EqualException(string message, Exception exception) : base(message, exception)
{ }
protected EqualException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
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,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
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

@ -1,45 +0,0 @@
namespace ProjectAirFighter
{
partial class Form1
{
/// <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()
{
SuspendLayout();
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(407, 301);
Name = "Form1";
Text = "Form1";
ResumeLayout(false);
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace ProjectAirFighter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,151 @@
namespace ProjectAirFighter
{
partial class FormAirFighter
{
/// <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()
{
pictureBoxAirFighter = new PictureBox();
buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirFighter).BeginInit();
SuspendLayout();
//
// pictureBoxAirFighter
//
pictureBoxAirFighter.Dock = DockStyle.Fill;
pictureBoxAirFighter.Location = new Point(0, 0);
pictureBoxAirFighter.Name = "pictureBoxAirFighter";
pictureBoxAirFighter.Size = new Size(924, 557);
pictureBoxAirFighter.TabIndex = 0;
pictureBoxAirFighter.TabStop = false;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.left;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(785, 510);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.ClientSizeChanged += FormAirFighter_SizeChanged;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.up;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(828, 469);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.ClientSizeChanged += FormAirFighter_SizeChanged;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.down;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(828, 510);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.ClientSizeChanged += FormAirFighter_SizeChanged;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.right;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(869, 510);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.ClientSizeChanged += FormAirFighter_SizeChanged;
buttonRight.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(791, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(829, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormAirFighter
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(924, 557);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxAirFighter);
Name = "FormAirFighter";
Text = "Истребитель";
SizeChanged += FormAirFighter_SizeChanged;
((System.ComponentModel.ISupportInitialize)pictureBoxAirFighter).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxAirFighter;
private Button buttonLeft;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectAirFighter.Drawning;
using ProjectAirFighter.Entities;
using ProjectAirFighter.MovementStrategy;
namespace ProjectAirFighter
{
public partial class FormAirFighter : Form
{
private DrawningWarPlane? _drawningWarPlane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public DrawningWarPlane SetWarPlane{
set
{
_drawningWarPlane = value;
_drawningWarPlane.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
public FormAirFighter()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки
/// </summary>
private void Draw()
{
if (_drawningWarPlane == null) return;
Bitmap bmp = new(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningWarPlane.DrawTransport(gr);
pictureBoxAirFighter.Image = bmp;
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningWarPlane == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningWarPlane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningWarPlane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningWarPlane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningWarPlane.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
private void FormAirFighter_SizeChanged(object sender, EventArgs e)
{
if (_drawningWarPlane == null) return;
_drawningWarPlane.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
if (_drawningWarPlane.SetPictureSize(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height))
{
Draw();
}
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningWarPlane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetDate(new MoveableWarPlane(_drawningWarPlane), pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

View File

@ -0,0 +1,367 @@
namespace ProjectAirFighter
{
partial class FormWarPlaneCollection
{
/// <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()
{
groupBox1 = new GroupBox();
panelCompanyTools = new Panel();
buttonRemove = new Button();
buttonAddWarPlane = new Button();
button1 = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonGoToCheck = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionRemove = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
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();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBox1.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(buttonSortByType);
groupBox1.Controls.Add(buttonSortByColor);
groupBox1.Controls.Add(panelCompanyTools);
groupBox1.Controls.Add(buttonCreateCompany);
groupBox1.Controls.Add(panelStorage);
groupBox1.Controls.Add(comboBoxSelectorCompany);
groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(659, 24);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(174, 739);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonRemove);
panelCompanyTools.Controls.Add(buttonAddWarPlane);
panelCompanyTools.Controls.Add(button1);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 373);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(174, 262);
panelCompanyTools.TabIndex = 9;
//
// buttonRemove
//
buttonRemove.Location = new Point(6, 121);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(162, 48);
buttonRemove.TabIndex = 4;
buttonRemove.Text = "Удалить самолет";
buttonRemove.UseVisualStyleBackColor = true;
buttonRemove.Click += ButtonRemove_Click;
//
// buttonAddWarPlane
//
buttonAddWarPlane.Location = new Point(6, 3);
buttonAddWarPlane.Name = "buttonAddWarPlane";
buttonAddWarPlane.Size = new Size(162, 56);
buttonAddWarPlane.TabIndex = 1;
buttonAddWarPlane.Text = "Добавление военного самолета";
buttonAddWarPlane.UseVisualStyleBackColor = true;
buttonAddWarPlane.Click += ButtonAddWarPlane_Click;
//
// button1
//
button1.Location = new Point(6, 221);
button1.Name = "button1";
button1.Size = new Size(162, 34);
button1.TabIndex = 6;
button1.Text = "Обновить";
button1.UseVisualStyleBackColor = true;
button1.Click += ButtonRefresh_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(8, 87);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(162, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(6, 171);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(162, 48);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тест";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 344);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(162, 23);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionRemove);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(168, 271);
panelStorage.TabIndex = 7;
//
// buttonCollectionRemove
//
buttonCollectionRemove.Location = new Point(3, 210);
buttonCollectionRemove.Name = "buttonCollectionRemove";
buttonCollectionRemove.Size = new Size(162, 23);
buttonCollectionRemove.TabIndex = 6;
buttonCollectionRemove.Text = "Удалить коллекцию";
buttonCollectionRemove.UseVisualStyleBackColor = true;
buttonCollectionRemove.Click += ButtonCollectionRemove_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 110);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(162, 94);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 81);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(162, 23);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(92, 56);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(3, 56);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 27);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(162, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(21, 9);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
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(6, 312);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(162, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(659, 739);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(833, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click_1;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(8, 644);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(162, 35);
buttonSortByType.TabIndex = 10;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(8, 685);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(160, 42);
buttonSortByColor.TabIndex = 11;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormWarPlaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(833, 763);
Controls.Add(pictureBox);
Controls.Add(groupBox1);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormWarPlaneCollection";
Text = "Коллекция военных самолетов";
groupBox1.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 groupBox1;
private ComboBox comboBoxSelectorCompany;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonAddWarPlane;
private PictureBox pictureBox;
private Button buttonRemove;
private Button buttonGoToCheck;
private Button button1;
private Panel panelStorage;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Button buttonCreateCompany;
private Button buttonCollectionRemove;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@ -0,0 +1,376 @@
using Microsoft.Extensions.Logging;
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawning;
using ProjectAirFighter.Exceptions;
using System.Runtime.Intrinsics.Arm;
namespace ProjectAirFighter;
public partial class FormWarPlaneCollection : Form
{
/// <summary>
/// Хранилище коолекций
/// </summary>
private readonly StorageCollection<DrawningWarPlane> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormWarPlaneCollection(ILogger<FormWarPlaneCollection> 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;
}
private void ButtonAddWarPlane_Click(object sender, EventArgs e)
{
FormWarPlaneConfig form = new();
form.Show();
form.AddEvent(SetWarPlane);
}
private void SetWarPlane(DrawningWarPlane warPlane)
{
if (_company == null || warPlane == null)
{
return;
}
try
{
if (_company + warPlane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен: " + warPlane.GetDataForSave());
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
catch (CollectionOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonRemove_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален на позиции: " + pos);
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningWarPlane? warPlane = null;
int counter = 100;
while (warPlane == null)
{
try
{
warPlane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
if (warPlane == null)
{
return;
}
FormAirFighter form = new()
{
SetWarPlane = warPlane
};
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
/// <summary>
/// Добавление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Massege}", ex.Message);
}
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
CollectionInfo? colName = _storageCollection.Keys?[i];
if (!colName!.IsEmpty())
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <summary>
/// Удалиние коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionRemove_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
_storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Создать компанию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningWarPlane>? collection = _storageCollection[
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "")];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
try
{
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new WarPlaneBase(pictureBox.Width, pictureBox.Height, collection);
break;
}
}
catch (ObjectNotFoundException)
{
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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("Сохранение в файл: {filname}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filname}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareWarPlanes(new DrawningCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareWarPlanes(new DrawningCompareByColor());
}
private void CompareWarPlanes(IComparer<DrawningWarPlane?> comparer)
{
if(_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

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

View File

@ -0,0 +1,380 @@
namespace ProjectAirFighter
{
partial class FormWarPlaneConfig
{
/// <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();
groupBoxColor = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelGrey = new Panel();
panelBlue = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxAdditionalWing = new CheckBox();
checkBoxRocket = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWheight = 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();
groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
PanelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColor);
groupBoxConfig.Controls.Add(checkBoxAdditionalWing);
groupBoxConfig.Controls.Add(checkBoxRocket);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWheight);
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.Margin = new Padding(3, 2, 3, 2);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Padding = new Padding(3, 2, 3, 2);
groupBoxConfig.Size = new Size(498, 264);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColor
//
groupBoxColor.Controls.Add(panelPurple);
groupBoxColor.Controls.Add(panelYellow);
groupBoxColor.Controls.Add(panelBlack);
groupBoxColor.Controls.Add(panelGrey);
groupBoxColor.Controls.Add(panelBlue);
groupBoxColor.Controls.Add(panelWhite);
groupBoxColor.Controls.Add(panelGreen);
groupBoxColor.Controls.Add(panelRed);
groupBoxColor.Location = new Point(192, 9);
groupBoxColor.Margin = new Padding(3, 2, 3, 2);
groupBoxColor.Name = "groupBoxColor";
groupBoxColor.Padding = new Padding(3, 2, 3, 2);
groupBoxColor.Size = new Size(293, 123);
groupBoxColor.TabIndex = 8;
groupBoxColor.TabStop = false;
groupBoxColor.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(237, 74);
panelPurple.Margin = new Padding(3, 2, 3, 2);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(51, 39);
panelPurple.TabIndex = 7;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(237, 20);
panelYellow.Margin = new Padding(3, 2, 3, 2);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(51, 39);
panelYellow.TabIndex = 3;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(154, 74);
panelBlack.Margin = new Padding(3, 2, 3, 2);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(51, 39);
panelBlack.TabIndex = 6;
//
// panelGrey
//
panelGrey.BackColor = Color.Gray;
panelGrey.Location = new Point(78, 74);
panelGrey.Margin = new Padding(3, 2, 3, 2);
panelGrey.Name = "panelGrey";
panelGrey.Size = new Size(51, 39);
panelGrey.TabIndex = 5;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(154, 20);
panelBlue.Margin = new Padding(3, 2, 3, 2);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(51, 39);
panelBlue.TabIndex = 2;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(5, 74);
panelWhite.Margin = new Padding(3, 2, 3, 2);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(51, 39);
panelWhite.TabIndex = 4;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(78, 20);
panelGreen.Margin = new Padding(3, 2, 3, 2);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(51, 39);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(5, 20);
panelRed.Margin = new Padding(3, 2, 3, 2);
panelRed.Name = "panelRed";
panelRed.Size = new Size(51, 39);
panelRed.TabIndex = 0;
//
// checkBoxAdditionalWing
//
checkBoxAdditionalWing.AutoSize = true;
checkBoxAdditionalWing.Location = new Point(6, 234);
checkBoxAdditionalWing.Margin = new Padding(3, 2, 3, 2);
checkBoxAdditionalWing.Name = "checkBoxAdditionalWing";
checkBoxAdditionalWing.Size = new Size(270, 19);
checkBoxAdditionalWing.TabIndex = 7;
checkBoxAdditionalWing.Text = "Признак наличия дополнительных крыльев";
checkBoxAdditionalWing.UseVisualStyleBackColor = true;
//
// checkBoxRocket
//
checkBoxRocket.AutoSize = true;
checkBoxRocket.Location = new Point(6, 195);
checkBoxRocket.Margin = new Padding(3, 2, 3, 2);
checkBoxRocket.Name = "checkBoxRocket";
checkBoxRocket.Size = new Size(156, 19);
checkBoxRocket.TabIndex = 6;
checkBoxRocket.Text = "Признак наличия ракет";
checkBoxRocket.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(84, 47);
numericUpDownWeight.Margin = new Padding(3, 2, 3, 2);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(74, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWheight
//
labelWheight.AutoSize = true;
labelWheight.Location = new Point(15, 53);
labelWheight.Name = "labelWheight";
labelWheight.Size = new Size(26, 15);
labelWheight.TabIndex = 4;
labelWheight.Text = "Вес";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(84, 20);
numericUpDownSpeed.Margin = new Padding(3, 2, 3, 2);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(74, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(15, 18);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(59, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(399, 233);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(93, 18);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(304, 233);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(84, 18);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(12, 38);
pictureBoxObject.Margin = new Padding(3, 2, 3, 2);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(176, 149);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
pictureBoxObject.DragDrop += PanelObject_DragDrop;
pictureBoxObject.DragEnter += PanelObject_DragEnter;
//
// buttonAdd
//
buttonAdd.Location = new Point(517, 236);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(82, 22);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(623, 236);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 3;
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(517, 9);
PanelObject.Margin = new Padding(3, 2, 3, 2);
PanelObject.Name = "PanelObject";
PanelObject.Size = new Size(197, 205);
PanelObject.TabIndex = 4;
PanelObject.DragDrop += PanelObject_DragDrop;
PanelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(100, 6);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(88, 18);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(12, 6);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(77, 18);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// FormWarPlaneConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(717, 264);
Controls.Add(PanelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Margin = new Padding(3, 2, 3, 2);
Name = "FormWarPlaneConfig";
Text = "98";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColor.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 labelSimpleObject;
private Label labelModifiedObject;
private Label labelSpeed;
private NumericUpDown numericUpDownSpeed;
private Label labelWheight;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxRocket;
private CheckBox checkBoxAdditionalWing;
private GroupBox groupBoxColor;
private Panel panelRed;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGrey;
private Panel panelWhite;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel PanelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@ -0,0 +1,177 @@
using ProjectAirFighter.Drawning;
using ProjectAirFighter.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectAirFighter;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormWarPlaneConfig : Form
{
/// <summary>
/// Объект - прорисовка военного самолета
/// </summary>
private DrawningWarPlane _warPlane = null;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawningWarPlane>? WarPlaneDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormWarPlaneConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelGrey.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
//TODO привязать анонимный метод через lamda с закрытием формы
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="warPlaneDelegate"></param>
public void AddEvent(Action<DrawningWarPlane> warPlaneDelegate)
{
if (WarPlaneDelegate == null)
{
WarPlaneDelegate = warPlaneDelegate;
}
else
{
WarPlaneDelegate += warPlaneDelegate;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_warPlane?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_warPlane?.SetPosition(5, 5);
_warPlane?.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":
_warPlane = new DrawningWarPlane((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_warPlane = new DrawningAirFighter((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxRocket.Checked, checkBoxAdditionalWing.Checked);
break;
}
DrawObject();
}
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
//TODO
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor!, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_warPlane == null) return;
_warPlane.EntityWarPlane?.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_warPlane?.EntityWarPlane is EntityAirFighter _airFighter)
{
_airFighter?.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_warPlane?.EntityWarPlane is EntityAirFighter _airFighter) {
if (e.Data.GetDataPresent(typeof(Color)))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_warPlane != null)
{
WarPlaneDelegate?.Invoke(_warPlane);
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

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

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.MovementStrategy;
public interface IMoveableObject
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.LeftBorder - GetStep() <= 0 || objParams.RightBorder + GetStep() >= FieldWidth ||
objParams.TopBorder - GetStep() <= 0 || objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int x = objParams.RightBorder;
if (x + GetStep() < FieldWidth) MoveRight();
int y = objParams.DownBorder;
if (y + GetStep() < FieldHeight) MoveDown();
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.MovementStrategy;
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
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()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,67 @@
using ProjectAirFighter.Drawning;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.MovementStrategy;
/// <summary>
/// класс реализация IMoveableObject с исользованием DrawningWarPlane
/// </summary>
public class MoveableWarPlane: IMoveableObject
{
/// <summary>
/// Полк объекта DrawningWarPlane или его наследника
/// </summary>
private readonly DrawningWarPlane? _warPlane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="warPlane">Объект класса DrawningWarPlane</param>
public MoveableWarPlane(DrawningWarPlane warPlane)
{
_warPlane = warPlane;
}
public ObjectParameters? GetObjectPosition {
get
{
if (_warPlane == null || _warPlane.EntityWarPlane == null || !_warPlane.GetPosX.HasValue || !_warPlane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_warPlane.GetPosX.Value, _warPlane.GetPosY.Value, _warPlane.GetWigdth, _warPlane.GetHeight);
}
}
public int GetStep => (int)(_warPlane?.EntityWarPlane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_warPlane == null || _warPlane.EntityWarPlane == null)
{
return false;
}
return _warPlane.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

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

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@ -1,17 +1,42 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirFighter namespace ProjectAirFighter
{ {
internal static class Program internal static class Program
{ {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new Form1()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormWarPlaneCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormWarPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(pathNeed)
.AddJsonFile("serilog.json")
.Build())
.CreateLogger());
});
} }
} }
} }

View File

@ -2,10 +2,34 @@
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework> <TargetFramework>net8.0-windows7.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,113 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectAirFighter.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectAirFighter.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap down {
get {
object obj = ResourceManager.GetObject("down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap left {
get {
object obj = ResourceManager.GetObject("left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap png_clipart_arrow_computer_icons_red_arrow_down_blue_triangle {
get {
object obj = ResourceManager.GetObject("png-clipart-arrow-computer-icons-red-arrow-down-blue-triangle", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right {
get {
object obj = ResourceManager.GetObject("right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap up {
get {
object obj = ResourceManager.GetObject("up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,136 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="left" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\left.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="right" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\right.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="down" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\down.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="png-clipart-arrow-computer-icons-red-arrow-down-blue-triangle" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\png-clipart-arrow-computer-icons-red-arrow-down-blue-triangle.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="up" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\up.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View File

@ -0,0 +1,6 @@
using ProjectAirFighter.Drawning;
namespace ProjectAirFighter;
public delegate void WarPlaneDelegate(DrawningWarPlane warPlane);

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}

BIN
down.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
left.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
right.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
up.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB