Compare commits

...

17 Commits
main ... Lab7

Author SHA1 Message Date
zum
8ac0e1f7e4 сноваа массив 2024-05-07 16:17:24 +04:00
zum
f577eb1198 исправил небольшой съезд 2024-05-07 16:03:48 +04:00
zum
96cd694efd lab7 2024-04-30 18:38:51 +04:00
zum
1c65dd299d lab6 Succes 2024-04-15 13:51:34 +04:00
zum
34bc9b98b9 some fix 2024-04-15 12:38:53 +04:00
zum
55c68c2d70 lab6 2024-04-13 17:35:43 +04:00
zum
44c56936ff lab6 2024-04-07 00:10:10 +04:00
zum
596a483a90 удалены TODO 2024-04-01 14:15:50 +04:00
zum
65a980276a lab5Succes 2024-04-01 12:43:18 +04:00
zum
56a45d4ae1 Merge branch 'Lab3' into Lab4 2024-03-21 19:13:46 +04:00
zum
8ae53d9903 изменил вставку 2024-03-21 19:09:59 +04:00
zum
9514ca7432 убрал все TODO комментарии 2024-03-18 13:33:28 +04:00
zum
0050c862a5 lab4Commit 2024-03-18 12:54:38 +04:00
zum
e5df4eb3e6 lab3 commit 2024-03-18 12:30:33 +04:00
zum
b10755b6bb изменил свойство кнопок в формах 2024-03-12 22:29:45 +04:00
zum
b9691cc763 lab2 commit 2024-03-04 18:15:31 +04:00
zum
ef4e357f91 first commit lab 1 2024-02-19 12:34:19 +04:00
44 changed files with 3971 additions and 83 deletions

View File

@ -0,0 +1,134 @@
using ProjectStormTrooper.Drawnings;
using ProjectStormTrooper.Exceptions;
namespace ProjectStormTrooper.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
/// </summary>
public abstract class AbstractCompany
{
// Размер пробела
protected readonly int ColsSpace = 30;
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 150;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 100;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция автомобилей
/// </summary>
protected ICollectionGenericObjects<DrawningWarPlane>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (int)Math.Floor((double)(_pictureWidth * _pictureHeight / ((_placeSizeWidth+ColsSpace) * _placeSizeHeight ))*1.1);
/// <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;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="plane">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningWarPlane plane)
{
if (company._collection.Insert(plane))
{
return 1;
}
return 0;
}
/// <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);
}
/// <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)
{
try
{
DrawningWarPlane obj = _collection.Get(i);
obj.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
}
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,22 @@
namespace ProjectStormTrooper.CollectionGenericObjects;
/// <summary>
/// Тип коллекции
/// </summary>
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// Список
/// </summary>
List = 2
}

View File

@ -0,0 +1,68 @@
using ProjectStormTrooper.Drawnings;
using ProjectStormTrooper.Exceptions;
namespace ProjectStormTrooper.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - каршеринг
/// </summary>
public class Hangar : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public Hangar(int picWidth, int picHeight, ICollectionGenericObjects<DrawningWarPlane> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black, 3);
int posX = 0;
for (int i = 0; i < _pictureWidth/_placeSizeWidth; i++)
{
int posY = 0;
g.DrawLine(pen, posX, posY, posX, posY + _placeSizeHeight*(_pictureHeight/ _placeSizeHeight));
for(int j = 0; j <= _pictureHeight/_placeSizeHeight; j++)
{
g.DrawLine(pen, posX, posY, posX + _placeSizeWidth-ColsSpace, posY);
posY += _placeSizeHeight;
}
posX += _placeSizeWidth;
}
}
protected override void SetObjectsPosition()
{
int posX = _pictureWidth / _placeSizeWidth-1;
int posY = 0;
for (int i = 0; i < _collection?.Count; i++)
{
try
{
_collection?.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i).SetPosition(posX * _placeSizeWidth, posY * _placeSizeHeight);
}
catch (ObjectNotFoundException)
{
break;
}
if(posX > 0)
{
posX--;
}
else
{
posX = _pictureWidth / _placeSizeWidth-1;
posY++;
}
if(posY >= _placeSizeHeight) { return; }
}
}
}

View File

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

View File

@ -0,0 +1,101 @@
using NLog.LayoutRenderers;
using ProjectStormTrooper.CollectionGenericObjects;
using ProjectStormTrooper.Exceptions;
/// <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 MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public int Count => _collection.Count;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
if(position > _collection.Count || position < 0)
{
throw new PositionOutOfCollectionException();
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException();
}
return _collection[position];
}
public bool Insert(T obj)
{
if (Count + 1 > MaxCount)
{
throw new CollectionOverflowException();
}
_collection.Add(obj);
return true;
}
public bool Insert(T obj, int position)
{
if (_collection.Count + 1 < _maxCount)
{
throw new CollectionOverflowException();
}
if (position > _collection.Count || position < 0)
{
throw new PositionOutOfCollectionException();
}
_collection.Insert(position, obj);
return true;
}
public T Remove(int position)
{
if (position > _collection.Count || position < 0)
{
throw new PositionOutOfCollectionException();
}
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];
}
}
}

View File

@ -0,0 +1,128 @@

using ProjectStormTrooper.Exceptions;
namespace ProjectStormTrooper.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 > _collection.Length - 1)
{
throw new PositionOutOfCollectionException();
}
if(_collection[position] == null)
{
throw new ObjectNotFoundException();
}
return _collection[position];
}
public bool Insert(T obj)
{
int index = Array.IndexOf(_collection, null);
if(index >= 0)
{
_collection[index] = obj;
return true;
}
throw new CollectionOverflowException();
}
public bool Insert(T obj, int position)
{
if(position < 0 || position > _collection.Length -1)
{
throw new PositionOutOfCollectionException();
}
for(int i = position; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
for (int i = position; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
return false;
}
public T Remove(int position)
{
if (position < 0 || position > _collection.Length - 1)
{
throw new PositionOutOfCollectionException();
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException();
}
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];
}
}
}

View File

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

View File

@ -0,0 +1,31 @@
namespace ProjectStormTrooper.Drawnings;
/// <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,112 @@
using System.DirectoryServices;
using ProjectStormTrooper.Drawnings;
using ProjectStormTrooper.Entities;
namespace ProjectStormTrooper.Drawnings;
public class DrawningStormTrooper : DrawningWarPlane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rockets">Признак наличия ракет</param>
/// <param name="bombs">Признак наличия бомб</param>
public DrawningStormTrooper(int speed, double weight, Color bodyColor, Color colorOfHead, Color additionalColor, bool bombs, bool rockets)
{
EntityWarPlane = new EntityStormTrooper(speed, weight, bodyColor, colorOfHead, additionalColor, bombs, rockets);
}
/// <summary>
/// Конструктор принимающий объект Entity
/// </summary>
public DrawningStormTrooper(EntityWarPlane? entityWarPlane)
{
if (entityWarPlane != null)
{
EntityWarPlane = entityWarPlane;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityWarPlane == null || EntityWarPlane is not EntityStormTrooper stormTrooper|| !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(stormTrooper.AdditionalColor);
Brush mainBrush = new SolidBrush(EntityWarPlane.BodyColor);
Brush headBrush = new SolidBrush(EntityWarPlane.ColorOfHead);
Rectangle bodyOfFighter = new Rectangle(_startPosX.Value, _startPosY.Value + 40, 120, 20);
int middleOfBody = (bodyOfFighter.X + bodyOfFighter.Right) / 2;
base.DrawTransport(g);
// ракеты
if (stormTrooper.Rockets)
{
//верхняя ракета
int middleOfWingX = (2*middleOfBody + 30 ) /2;
int middleOfTopWingY = (2 * bodyOfFighter.Top - 50) / 2;
Point topLeftTopRocket = new Point(middleOfWingX - 1, middleOfTopWingY + 3);
Point bottomLeftTopRocket = new Point(middleOfWingX + 6, middleOfTopWingY + 12);
Point edgeOfTopRocket = new Point(middleOfWingX + 12, middleOfTopWingY + 6);
Point[] headOfTopRocket = new Point[] { topLeftTopRocket, bottomLeftTopRocket, edgeOfTopRocket };
g.DrawPolygon(pen, headOfTopRocket);
g.FillPolygon(additionalBrush, headOfTopRocket);
//нижняя ракета
int middleOfBottomWingY = (2*bodyOfFighter.Top + 50) / 2;
Point topLeftBottomRocket = new Point(middleOfWingX + 8, middleOfBottomWingY + 2);
Point bottomLeftBottomRocket = new Point(middleOfWingX + 4, middleOfBottomWingY + 12);
Point edgeOfBottomRocket = new Point(middleOfWingX + 16, middleOfBottomWingY + 6);
Point[] headOfBottomRocket = new Point[] { topLeftBottomRocket, bottomLeftBottomRocket, edgeOfBottomRocket };
g.DrawPolygon(pen, headOfBottomRocket);
g.FillPolygon(additionalBrush, headOfBottomRocket);
}
// бомбы
if (stormTrooper.Bombs)
{
Rectangle topBombBody = new Rectangle(middleOfBody + 40, bodyOfFighter.Top - 10, 10, 10);
Rectangle bottomBombBody = new Rectangle(middleOfBody + 40, bodyOfFighter.Bottom, 10, 10);
//голова верхней бомбы
Point topTopBomb = new Point(topBombBody.Right + 1, topBombBody.Top);
Point bottomTopBomb = new Point(topBombBody.Right + 1, topBombBody.Bottom);
Point edgeTopBomb = new Point(topBombBody.Right + 10, (topBombBody.Top + topBombBody.Bottom) / 2);
Point[] headOfTopBomb = new Point[] { topTopBomb, bottomTopBomb, edgeTopBomb };
g.DrawPolygon(pen, headOfTopBomb);
g.FillPolygon(additionalBrush, headOfTopBomb);
Point topBottomBomb = new Point(bottomBombBody.Right + 1, bottomBombBody.Top);
Point bottomBottomBomb = new Point(bottomBombBody.Right + 1, bottomBombBody.Bottom);
Point edgeBottomBomb = new Point(bottomBombBody.Right + 10, (bottomBombBody.Top + bottomBombBody.Bottom) / 2);
Point[] headOfBottomBomb = new Point[] { topBottomBomb, bottomBottomBomb, edgeBottomBomb };
g.DrawPolygon(pen, headOfBottomBomb);
g.FillPolygon(additionalBrush, headOfBottomBomb);
g.DrawRectangle(pen, topBombBody);
g.DrawRectangle(pen, bottomBombBody);
g.FillRectangle(additionalBrush, topBombBody);
g.FillRectangle(additionalBrush, bottomBombBody);
}
}
}

View File

@ -0,0 +1,270 @@
using ProjectStormTrooper.Entities;
using ProjectStormTrooper.Drawnings;
namespace ProjectStormTrooper.Drawnings
{
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 = 140;
/// <summary>
/// Высота прорисовки самолета
/// </summary>
private readonly int _drawningWarPlaneHeight = 95;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningWarPlaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningWarPlaneHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
public DrawningWarPlane()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
public DrawningWarPlane(int speed, double weight, Color bodyColor, Color colorOfHead)
{
EntityWarPlane = new EntityWarPlane(speed, weight, bodyColor, colorOfHead);
}
/// <summary>
/// Конструктор принимающий объект Entity
/// </summary>
public DrawningWarPlane(EntityWarPlane? entityWarPlane)
{
if(entityWarPlane != null)
{
EntityWarPlane = entityWarPlane;
}
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
if (width <= _drawningWarPlaneWidth || height <= _drawningWarPlaneHeight)
{
return false;
};
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningWarPlaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth.Value - _drawningWarPlaneWidth;
}
if (_startPosY + _drawningWarPlaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight.Value - _drawningWarPlaneHeight;
}
}
return true;
}
/// <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;
}
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
_startPosX = x;
_startPosY = y;
if (_drawningWarPlaneHeight + y > _pictureHeight || y < 0)
{
_startPosY = 0;
}
if (_drawningWarPlaneWidth + x > _pictureWidth || x < 0)
{
_startPosX = 0;
}
return;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public 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.Right:
if (_startPosX.Value + EntityWarPlane.Step + _drawningWarPlaneWidth < _pictureWidth)
{
_startPosX += (int)EntityWarPlane.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityWarPlane.Step + _drawningWarPlaneHeight < _pictureHeight)
{
_startPosY += (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);
Brush mainBrush = new SolidBrush(EntityWarPlane.BodyColor);
Brush headBrush = new SolidBrush(EntityWarPlane.ColorOfHead);
// флюзеляж
Rectangle bodyOfFighter = new Rectangle(_startPosX.Value, _startPosY.Value + 40, 120, 20);
g.DrawRectangle(pen, bodyOfFighter);
g.FillRectangle(mainBrush, bodyOfFighter);
Point topOfNose = new Point(bodyOfFighter.Right, bodyOfFighter.Top);
Point bottomOfNose = new Point(bodyOfFighter.Right, bodyOfFighter.Bottom);
Point edgeOfNose = new Point(bodyOfFighter.Right + 20, (bodyOfFighter.Top + bodyOfFighter.Bottom) / 2);
Point[] nose = new Point[] { topOfNose, bottomOfNose, edgeOfNose };
g.DrawPolygon(pen, nose);
g.FillPolygon(headBrush, nose);
// крылья штурмовика
int middleOfBody = (bodyOfFighter.X + bodyOfFighter.Right) / 2;
// верхнее крыло
Point topWingRightBottom = new Point(middleOfBody + 30, bodyOfFighter.Top);
Point topWingRightTop = new Point(middleOfBody, bodyOfFighter.Top - 40);
Point topWingLeftTop = new Point(middleOfBody - 10, bodyOfFighter.Top - 40);
Point topWingLeftBottom = new Point(middleOfBody - 10, bodyOfFighter.Top);
Point[] topWing = new Point[] { topWingRightBottom, topWingRightTop, topWingLeftTop, topWingLeftBottom };
g.DrawPolygon(pen, topWing);
g.FillPolygon(mainBrush, topWing);
//нижнее крыло
Point bottomWingRightTop = new Point(middleOfBody + 30, bodyOfFighter.Bottom);
Point bottomWingRightBottom = new Point(middleOfBody, bodyOfFighter.Bottom + 40);
Point bottomWingLeftBottom = new Point(middleOfBody - 10, bodyOfFighter.Bottom + 40);
Point bottomWingLeftTop = new Point(middleOfBody - 10, bodyOfFighter.Bottom);
Point[] bottomWing = new Point[] { bottomWingRightTop, bottomWingRightBottom, bottomWingLeftBottom, bottomWingLeftTop };
g.DrawPolygon(pen, bottomWing);
g.FillPolygon(mainBrush, bottomWing);
//задние стабилизаторы
//верхний
Point topStabRightBottom = new Point(bodyOfFighter.X + 30, bodyOfFighter.Top);
Point topStabRightTop = new Point(bodyOfFighter.X + 10, bodyOfFighter.Top - 20);
Point topStabLeftTop = new Point(bodyOfFighter.X, bodyOfFighter.Top - 20);
Point topStabLeftBottom = new Point(bodyOfFighter.X, bodyOfFighter.Top);
Point[] topStable = new Point[] { topStabRightBottom, topStabRightTop, topStabLeftTop, topStabLeftBottom };
g.DrawPolygon(pen, topStable);
g.FillPolygon(mainBrush, topStable);
//нижний
Point bottomStabRightBottom = new Point(bodyOfFighter.X + 30, bodyOfFighter.Bottom);
Point bottomStabRightTop = new Point(bodyOfFighter.X + 10, bodyOfFighter.Bottom + 20);
Point bottomStabLeftTop = new Point(bodyOfFighter.X, bodyOfFighter.Bottom + 20);
Point bottomStabLeftBottom = new Point(bodyOfFighter.X, bodyOfFighter.Bottom);
Point[] bottomStable = new Point[] { bottomStabRightBottom, bottomStabRightTop, bottomStabLeftTop, bottomStabLeftBottom };
g.DrawPolygon(pen, bottomStable);
g.FillPolygon(mainBrush, bottomStable);
}
}
}

View File

@ -0,0 +1,54 @@
using ProjectStormTrooper.Entities;
namespace ProjectStormTrooper.Drawnings;
/// <summary>
/// Расширение для класса EntityWarPlane
/// </summary>
public static class ExtentionDrawningWarPlane
{
/// <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 = EntityStormTrooper.CreateEntityStormTrooper(strs);
if (warPlane != null)
{
return new DrawningStormTrooper(warPlane);
}
warPlane = EntityWarPlane.CreateEntityCar(strs);
if (warPlane != null)
{
return new DrawningWarPlane(warPlane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</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,72 @@
namespace ProjectStormTrooper.Entities;
public class EntityStormTrooper : EntityWarPlane
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
/// <summary>
/// Признак (опция) наличия ракет
/// </summary>
public bool Rockets { get; private set; }
public void SetAdditionalColor(Color additionalColor)
{
AdditionalColor = additionalColor;
}
/// <summary>
/// Инициализация полей объекта-класса штурмовика
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес штурмовика</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="rockets">Признак наличия ракет</param>
public EntityStormTrooper(int speed, double weight, Color bodyColor, Color colorOfHead, Color additionalColor, bool bombs, bool rockets) : base(speed, weight, bodyColor, colorOfHead)
{
AdditionalColor = additionalColor;
Bombs = bombs;
Rockets = rockets;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityStormTrooper), Speed.ToString(), Weight.ToString(), BodyColor.Name,
ColorOfHead.Name, AdditionalColor.Name,Bombs.ToString(), Rockets.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityStormTrooper? CreateEntityStormTrooper(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityStormTrooper))
{
return null;
}
return new EntityStormTrooper(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
Color.FromName(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
}

View File

@ -0,0 +1,73 @@

namespace ProjectStormTrooper.Entities
{
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 Color ColorOfHead { get; private set; }
public void SetBodyColor(Color bodyColor)
{
BodyColor = bodyColor;
}
public void SetColorOfHead(Color colorOfHead)
{
ColorOfHead = colorOfHead;
}
/// <summary>
/// Шаг перемещения штурмовика
/// </summary>
public double Step => Speed * 200 / Weight;
public EntityWarPlane(int speed, double weight, Color bodyColor, Color colorOfHead) {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
ColorOfHead = colorOfHead;
}
//TODO Прописать метод
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityWarPlane), Speed.ToString(), Weight.ToString(), BodyColor.Name, ColorOfHead.Name};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityWarPlane? CreateEntityCar(string[] strs)
{
if (strs.Length != 5 || strs[0] != nameof(EntityWarPlane))
{
return null;
}
return new EntityWarPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]));
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectStormTrooper.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,39 +0,0 @@
namespace ProjectStormTrooper
{
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()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

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

View File

@ -0,0 +1,155 @@
namespace ProjectStormTrooper
{
partial class FormStormTrooper
{
/// <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()
{
pictureBoxStormTrooper = new PictureBox();
buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonStrategyStep = new Button();
comboBoxStrategy = new ComboBox();
((System.ComponentModel.ISupportInitialize)pictureBoxStormTrooper).BeginInit();
SuspendLayout();
//
// pictureBoxStormTrooper
//
pictureBoxStormTrooper.BackColor = SystemColors.Window;
pictureBoxStormTrooper.Dock = DockStyle.Fill;
pictureBoxStormTrooper.Location = new Point(0, 0);
pictureBoxStormTrooper.Margin = new Padding(3, 4, 3, 4);
pictureBoxStormTrooper.Name = "pictureBoxStormTrooper";
pictureBoxStormTrooper.Size = new Size(950, 540);
pictureBoxStormTrooper.TabIndex = 0;
pictureBoxStormTrooper.TabStop = false;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(794, 477);
buttonLeft.Margin = new Padding(3, 4, 3, 4);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(40, 47);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(841, 423);
buttonUp.Margin = new Padding(3, 4, 3, 4);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(40, 47);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(841, 477);
buttonDown.Margin = new Padding(3, 4, 3, 4);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(40, 47);
buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(888, 477);
buttonRight.Margin = new Padding(3, 4, 3, 4);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(40, 47);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(851, 63);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(87, 29);
buttonStrategyStep.TabIndex = 7;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(820, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(125, 28);
comboBoxStrategy.TabIndex = 8;
//
// FormStormTrooper
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(950, 540);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStrategyStep);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxStormTrooper);
Margin = new Padding(3, 4, 3, 4);
Name = "FormStormTrooper";
Text = "Штурмовик";
((System.ComponentModel.ISupportInitialize)pictureBoxStormTrooper).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxStormTrooper;
private Button buttonLeft;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private Button buttonStrategyStep;
private ComboBox comboBoxStrategy;
}
}

View File

@ -0,0 +1,141 @@

using ProjectStormTrooper.Drawnings;
using ProjectStormTrooper.MovementStrategy;
namespace ProjectStormTrooper;
public partial class FormStormTrooper : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningWarPlane? _drawningWarPlane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawningWarPlane SetWarPlane
{
set
{
_drawningWarPlane = value;
_drawningWarPlane.SetPictureSize(pictureBoxStormTrooper.Width, pictureBoxStormTrooper.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// Инициализация формы
/// </summary>
public FormStormTrooper()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки машины
/// </summary>
private void Draw()
{
if (_drawningWarPlane == null)
{
return;
}
Bitmap bmp = new(pictureBoxStormTrooper.Width, pictureBoxStormTrooper.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningWarPlane.DrawTransport(gr);
pictureBoxStormTrooper.Image = bmp;
}
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();
}
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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.SetData(new MoveableCar(_drawningWarPlane), pictureBoxStormTrooper.Width, pictureBoxStormTrooper.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

View File

@ -1,17 +1,17 @@
<?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
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>
@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,341 @@
namespace ProjectStormTrooper
{
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();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
buttonCreateCompany = new Button();
panelCompanyTools = new Panel();
buttonGoToCheck = new Button();
buttonRefresh = new Button();
buttonRemoveWarPlane = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddWarPlane = new Button();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBox1.SuspendLayout();
panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(panelStorage);
groupBox1.Controls.Add(buttonCreateCompany);
groupBox1.Controls.Add(panelCompanyTools);
groupBox1.Controls.Add(comboBoxSelectorCompany);
groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(616, 28);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(197, 782);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
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, 23);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(191, 336);
panelStorage.TabIndex = 9;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(5, 294);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(172, 29);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(5, 163);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(170, 104);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(5, 116);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(172, 29);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(93, 84);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(5, 84);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(5, 40);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(172, 27);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(24, 11);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(158, 20);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(8, 441);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(172, 29);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonRemoveWarPlane);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonAddWarPlane);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 521);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(191, 258);
panelCompanyTools.TabIndex = 7;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(5, 185);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(172, 27);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(5, 218);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(172, 29);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonRemoveWarPlane
//
buttonRemoveWarPlane.Location = new Point(5, 128);
buttonRemoveWarPlane.Name = "buttonRemoveWarPlane";
buttonRemoveWarPlane.Size = new Size(172, 51);
buttonRemoveWarPlane.TabIndex = 4;
buttonRemoveWarPlane.Text = "Удалить военный самолет";
buttonRemoveWarPlane.UseVisualStyleBackColor = true;
buttonRemoveWarPlane.Click += ButtonRemoveWarPlane_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(5, 95);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(172, 27);
maskedTextBoxPosition.TabIndex = 3;
//
// buttonAddWarPlane
//
buttonAddWarPlane.Location = new Point(5, 4);
buttonAddWarPlane.Name = "buttonAddWarPlane";
buttonAddWarPlane.Size = new Size(172, 50);
buttonAddWarPlane.TabIndex = 1;
buttonAddWarPlane.Text = "Добавить военный самолет";
buttonAddWarPlane.UseVisualStyleBackColor = true;
buttonAddWarPlane.Click += ButtonAddWarPlane_Click;
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Ангар" });
comboBoxSelectorCompany.Location = new Point(8, 396);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(172, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(616, 782);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(813, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
SaveToolStripMenuItem.Size = new Size(227, 26);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
LoadToolStripMenuItem.Size = new Size(227, 26);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormWarPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(813, 810);
Controls.Add(pictureBox);
Controls.Add(groupBox1);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormWarPlaneCollection";
Text = "Коллекция военных самолетов";
groupBox1.ResumeLayout(false);
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBox1;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddWarPlane;
private Button buttonRefresh;
private Button buttonRemoveWarPlane;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonGoToCheck;
private Panel panelStorage;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private RadioButton radioButtonList;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,327 @@
using ProjectStormTrooper.CollectionGenericObjects;
using ProjectStormTrooper.Drawnings;
using Microsoft.Extensions.Logging;
using ProjectStormTrooper.Exceptions;
using System.Xml.Linq;
namespace ProjectStormTrooper
{
public partial class FormWarPlaneCollection : Form
{
private AbstractCompany? _company = null;
private readonly StorageCollection<DrawningWarPlane> _storageCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
public FormWarPlaneCollection(ILogger<FormWarPlaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление обычного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddWarPlane_Click(object sender, EventArgs e)
{
FormWarPlaneConfig form = new FormWarPlaneConfig();
form.AddEvent(SetWarPlane);
form.Show();
}
/// <summary>
/// Добавление автомобиля в коллекцию
/// </summary>
/// <param name="warPlane"></param>
private void SetWarPlane(DrawningWarPlane? warPlane)
{
if (_company == null || warPlane == null)
{
return;
}
try
{
int addingObject = (_company + warPlane);
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {warPlane.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
catch(CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveWarPlane_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
_logger.LogWarning("Удаление объекта из несуществующей коллекции");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
object decrementObject = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален по позиции {pos}");
pictureBox.Image = _company.Show();
}
catch(ObjectNotFoundException ex)
{
MessageBox.Show("Объект не найден");
_logger.LogWarning($"Удаление не найденного объекта в позиции {pos} ");
}
catch(PositionOutOfCollectionException ex)
{
MessageBox.Show("Удаление вне рамках коллекции");
_logger.LogWarning($"Удаление объекта за пределами коллекции {pos} ");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();
}
catch (ObjectNotFoundException)
{
counter--;
if (counter <= 0)
{
break;
}
}
}
if (warPlane == null)
{
return;
}
FormStormTrooper form = new()
{
SetWarPlane = warPlane
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
/// <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);
_logger.LogWarning("Не заполненная коллекция");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RerfreshListBoxItems();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Удаление невыбранной коллекции");
return;
}
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция: {name}");
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <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("Коллекция не выбрана");
_logger.LogWarning("Создание компании невыбранной коллекции");
return;
}
ICollectionGenericObjects<DrawningWarPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не удалось инициализировать коллекцию");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Ангар":
_company = new Hangar(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RerfreshListBoxItems();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}
}

View File

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

View File

@ -0,0 +1,381 @@
namespace ProjectStormTrooper
{
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()
{
buttonCancel = new Button();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelRed = new Panel();
panelYellow = new Panel();
panelGreen = new Panel();
panelBlack = new Panel();
panelWhite = new Panel();
panelGray = new Panel();
panelBlue = new Panel();
labelAdditionalColor = new Label();
labelHeadColor = new Label();
labelBodyColor = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
panelObject = new Panel();
checkBoxRockets = new CheckBox();
checkBoxBombs = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
labelWeight = new Label();
labelSpeed = new Label();
groupBoxConfig = new GroupBox();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
groupBoxConfig.SuspendLayout();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(723, 248);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Location = new Point(308, 54);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(255, 150);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(201, 86);
panelPurple.Margin = new Padding(3, 4, 3, 4);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(39, 45);
panelPurple.TabIndex = 14;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(17, 27);
panelRed.Margin = new Padding(3, 4, 3, 4);
panelRed.Name = "panelRed";
panelRed.Size = new Size(39, 45);
panelRed.TabIndex = 9;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(201, 27);
panelYellow.Margin = new Padding(3, 4, 3, 4);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(39, 45);
panelYellow.TabIndex = 10;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(77, 27);
panelGreen.Margin = new Padding(3, 4, 3, 4);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(39, 45);
panelGreen.TabIndex = 12;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(137, 86);
panelBlack.Margin = new Padding(3, 4, 3, 4);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(39, 45);
panelBlack.TabIndex = 15;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(17, 86);
panelWhite.Margin = new Padding(3, 4, 3, 4);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(39, 45);
panelWhite.TabIndex = 13;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(77, 86);
panelGray.Margin = new Padding(3, 4, 3, 4);
panelGray.Name = "panelGray";
panelGray.Size = new Size(39, 45);
panelGray.TabIndex = 16;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(137, 27);
panelBlue.Margin = new Padding(3, 4, 3, 4);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(39, 45);
panelBlue.TabIndex = 11;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(173, 7);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(77, 37);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelColors_DragDrop;
labelAdditionalColor.DragEnter += LabelColors_DragEnter;
//
// labelHeadColor
//
labelHeadColor.AllowDrop = true;
labelHeadColor.BorderStyle = BorderStyle.FixedSingle;
labelHeadColor.Location = new Point(88, 7);
labelHeadColor.Name = "labelHeadColor";
labelHeadColor.Size = new Size(81, 37);
labelHeadColor.TabIndex = 2;
labelHeadColor.Text = "Цвет носа";
labelHeadColor.TextAlign = ContentAlignment.MiddleCenter;
labelHeadColor.DragDrop += LabelColors_DragDrop;
labelHeadColor.DragEnter += LabelColors_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(13, 7);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(70, 37);
labelBodyColor.TabIndex = 1;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelColors_DragDrop;
labelBodyColor.DragEnter += LabelColors_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(23, 50);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(227, 150);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(597, 248);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelHeadColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(582, 12);
panelObject.Name = "panelObject";
panelObject.Size = new Size(263, 222);
panelObject.TabIndex = 5;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// checkBoxRockets
//
checkBoxRockets.AutoSize = true;
checkBoxRockets.Location = new Point(25, 154);
checkBoxRockets.Name = "checkBoxRockets";
checkBoxRockets.Size = new Size(196, 24);
checkBoxRockets.TabIndex = 7;
checkBoxRockets.Text = "Признак наличия ракет";
checkBoxRockets.UseVisualStyleBackColor = true;
//
// checkBoxBombs
//
checkBoxBombs.AutoSize = true;
checkBoxBombs.Location = new Point(25, 123);
checkBoxBombs.Name = "checkBoxBombs";
checkBoxBombs.Size = new Size(200, 24);
checkBoxBombs.TabIndex = 6;
checkBoxBombs.Text = " Признак наличия бомб\n";
checkBoxBombs.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(94, 68);
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(150, 27);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(94, 36);
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(150, 27);
numericUpDownSpeed.TabIndex = 4;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(444, 219);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(109, 39);
labelModifiedObject.TabIndex = 3;
labelModifiedObject.Text = "Продвинутый ";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(325, 219);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(99, 39);
labelSimpleObject.TabIndex = 2;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 68);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 36);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxRockets);
groupBoxConfig.Controls.Add(checkBoxBombs);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(576, 279);
groupBoxConfig.TabIndex = 4;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// FormWarPlaneConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(848, 279);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxConfig);
Name = "FormWarPlaneConfig";
Text = "Создание объекта";
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
ResumeLayout(false);
}
#endregion
private Button buttonCancel;
private GroupBox groupBoxColors;
private Label labelAdditionalColor;
private Label labelHeadColor;
private Label labelBodyColor;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Panel panelObject;
private CheckBox checkBoxRockets;
private CheckBox checkBoxBombs;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Label labelWeight;
private Label labelSpeed;
private GroupBox groupBoxConfig;
private Panel panelPurple;
private Panel panelRed;
private Panel panelYellow;
private Panel panelGreen;
private Panel panelBlack;
private Panel panelWhite;
private Panel panelGray;
private Panel panelBlue;
}
}

View File

@ -0,0 +1,153 @@
using ProjectStormTrooper.Drawnings;
using ProjectStormTrooper.Entities;
namespace ProjectStormTrooper
{
/// <summary>
/// форма конфигурации объекта
/// </summary>
public partial class FormWarPlaneConfig : Form
{
private DrawningWarPlane? warPlane;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawningWarPlane> _warPlaneDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormWarPlaneConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="carDelegate"></param>
public void AddEvent(Action<DrawningWarPlane> warPlaneDelegate)
{
_warPlaneDelegate += warPlaneDelegate;
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
warPlane?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
warPlane?.SetPosition(15, 15);
warPlane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>labelSimpleObjectlabelSimpleObject
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, Color.Black);
break;
case "labelModifiedObject":
warPlane = new DrawningStormTrooper((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, Color.Black, checkBoxBombs.Checked, checkBoxRockets.Checked);
break;
}
DrawObject();
}
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelColors_DragEnter(object? sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
private void LabelColors_DragDrop(object? sender, DragEventArgs e)
{
if(warPlane == null)
{
return;
}
Label label = (Label)sender;
Color newColor = (Color) e.Data.GetData(typeof(Color).ToString());
switch (label.Name)
{
case "labelBodyColor":
warPlane.EntityWarPlane.SetBodyColor(newColor);
DrawObject();
break;
case "labelHeadColor":
warPlane.EntityWarPlane.SetColorOfHead(newColor);
DrawObject();
break;
case "labelAdditionalColor":
if(warPlane is DrawningStormTrooper)
{
(warPlane.EntityWarPlane as EntityStormTrooper).SetAdditionalColor(newColor);
DrawObject();
}
break;
}
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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,139 @@
namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
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; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
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,25 @@
namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,54 @@

using System.Runtime.Remoting;
namespace ProjectStormTrooper.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.DownBorder + GetStep() >= FieldHeight && objParams.RightBorder + GetStep() >= FieldWidth;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,56 @@

namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
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,65 @@

using ProjectStormTrooper.Drawnings;
namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningCar
/// </summary>
public class MoveableCar : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// </summary>
private readonly DrawningWarPlane? _warPlane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="warPlane">Объект класса DrawningWarPlane</param>
public MoveableCar(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.GetWidth, _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,27 @@
namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,72 @@
namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
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,22 @@
namespace ProjectStormTrooper.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@ -1,17 +1,49 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace ProjectStormTrooper
{
internal static class Program
{
internal static class Program
{
[STAThread]
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider =
services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormWarPlaneCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
services.AddSingleton<FormWarPlaneCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}
}

View File

@ -2,10 +2,43 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<TargetFramework>net7.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.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>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectStormTrooper.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[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>
/// Returns the cached ResourceManager instance used by this class.
/// </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("ProjectStormTrooper.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowDown {
get {
object obj = ResourceManager.GetObject("arrowDown", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowLeft {
get {
object obj = ResourceManager.GetObject("arrowLeft", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowRight {
get {
object obj = ResourceManager.GetObject("arrowRight", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowUp {
get {
object obj = ResourceManager.GetObject("arrowUp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,133 @@
<?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="arrowDown" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowDown.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowLeft" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowLeft.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowRight" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowRight.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowUp" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowUp.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: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "StormTrooper"
}
}
}