Compare commits

..

18 Commits

Author SHA1 Message Date
85c0cbdaba Принятая 8 лаба 2024-05-20 14:27:40 +03:00
a3ebc9f2c6 Практиески готово, однако List.Contains не может принимать в себя два аргумента(( 2024-05-20 06:15:43 +03:00
beb7bdf552 Слетевшая 7 лаба готова 2024-05-20 04:55:35 +03:00
72081a1e24 Сохраниние хоть чего-то 2024-05-08 20:05:33 +03:00
63fc8c48c4 Не видит AddLogging, а все остальное сделано!!! 2024-05-03 16:50:15 +03:00
923224c02e Подправил 6 лабу 2024-04-22 13:00:55 +03:00
37a802cde6 С ходу, 6 лаба, без б 2024-04-21 19:30:04 +03:00
26ecf356b8 Допзадание 2024-04-08 14:19:04 +03:00
30131211c3 Готовая 5 лаба, проверенная 2024-04-08 12:53:39 +03:00
a5dec11857 Изменил выбор цвета 2024-04-07 22:31:10 +03:00
9e6472cf47 5 лаба, доволен как слон) 2024-04-07 16:05:09 +03:00
f1b78303ef 4 лаба 2024-03-25 13:43:21 +03:00
e37875f510 LabWork4 2024-03-18 21:37:11 +03:00
3d664c461e LabWork3 2024-03-11 13:38:15 +03:00
be605e1ae1 Коллекция объектов 2024-03-09 21:25:28 +03:00
19cd1a783f Была ошибка, которая создавала дополнительную копию зентной установки 2024-03-09 19:22:05 +03:00
b8787908c3 Это победа! 2 лаба 2024-02-26 14:20:56 +03:00
064b7511c7 Лаборатнорная работа 1 2024-02-12 14:07:08 +03:00
54 changed files with 4014 additions and 75 deletions

View File

@ -8,4 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EntityFramework" Version="6.2.0" />
<PackageReference Include="EntityFramework.ru" Version="6.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<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.File" Version="5.0.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,113 @@
using AntiAircraftGun.Drawnings;
namespace AntiAircraftGun.CollectionGenericObjects;
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 130;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция установок
/// </summary>
protected ICollectionGenericObjects<DrawningGun>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight /
(_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция утановок</param>
public AbstractCompany(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningGun> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="gun">Добавляемый объект</param>
/// <returns></returns>
public static bool operator +(AbstractCompany company, DrawningGun gun)
{
return company._collection.Insert(gun,new DrawningGunEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static bool operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningGun? 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
{
DrawningGun? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}catch(Exception ) { }
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<DrawningGun?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.CollectionGenericObjects;
/// <summary>
///
/// </summary>
public class CollectionInfo:IEquatable<CollectionInfo>
{
/// <summary>
/// Имя
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType,string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs=data.Split(_separator,StringSplitOptions.RemoveEmptyEntries);
if(strs.Length < 1 || strs.Length > 3) return null;
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

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

View File

@ -0,0 +1,66 @@
using AntiAircraftGun.Drawnings;
namespace AntiAircraftGun.CollectionGenericObjects;
/// <summary>
/// Класс, отвечающий за базу
/// </summary>
public class GunSharingService : AbstractCompany
{
public GunSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningGun> collection) : base(picWidth, picHeight, collection)
{
}
private int offsetX = 30;
/// <summary>
/// Отрисовка базы
/// </summary>
/// <param name="g">Графика</param>
protected override void DrawBackgound(Graphics g)
{
Pen pen = new Pen(Color.Black, 4);
int maxCountX = (_pictureWidth / _placeSizeWidth);
int maxCountY = (_pictureHeight / _placeSizeHeight);
for (int i = 0; i < maxCountX; i++)
{
for (int j = 0; j < maxCountY; j++)
{
g.DrawLine(pen, i * offsetX + i * _placeSizeWidth, j * _placeSizeHeight, _placeSizeWidth + i * offsetX + i * _placeSizeWidth, j * _placeSizeHeight);
g.DrawLine(pen, i * offsetX + i * _placeSizeWidth, j * _placeSizeHeight, i * offsetX + i * _placeSizeWidth, _placeSizeHeight + j * _placeSizeHeight);
g.DrawLine(pen, i * offsetX + i * _placeSizeWidth, _placeSizeHeight + j * _placeSizeHeight, _placeSizeWidth + i * offsetX + i * _placeSizeWidth, _placeSizeHeight + j * _placeSizeHeight);
}
}
}
/// <summary>
/// Установка объекта в базу
/// </summary>
protected override void SetObjectsPosition()
{
int maxCountX = _pictureWidth / _placeSizeWidth;
int maxCountY = _pictureHeight / _placeSizeHeight;
int boarderOffsetX = 10;
int boarderOffsetY = 10;
int currentIndex = -1;
try
{
for (int j = 0; j < maxCountY; j++)
{
for (int i = 0; i < maxCountX; i++)
{
currentIndex++;
if (_collection.Get(currentIndex) != null)
{
_collection.Get(currentIndex).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(currentIndex).SetPosition(boarderOffsetX + i * _placeSizeWidth + i * offsetX, boarderOffsetY + j * _placeSizeHeight);
}
}
}
}catch (Exception ) { }
}
}

View File

@ -0,0 +1,61 @@
using AntiAircraftGun.Drawnings;
namespace AntiAircraftGun.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,IEqualityComparer<T?>? comparer=null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position, IEqualityComparer<T?>? comparer=null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
bool 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();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer"></param>
void CollectionSort(IComparer<T?>? comparer);
}

View File

@ -0,0 +1,116 @@
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.Exceptions;
namespace AntiAircraftGun.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return _collection.Count; } }
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
// TODO проверка позиции
// TODO выброс ошибки, если выход за границу
// +-
if (!_collection.Any()) { return null; }
if (_collection.Count <= position || position < 0 || position >= _maxCount) {
throw new PositionOutOfCollectionException(Count);
}
return _collection[position];
}
public bool Insert(T obj, IEqualityComparer<T?> comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
// TODO выброс ошибки, если переполнение
// +-
if (comparer != null)
{
foreach (T? item in _collection)
{
if (item == null) continue;
if ((comparer as IEqualityComparer<DrawningGun>).Equals(obj as DrawningGun, item as DrawningGun))
{
throw new ObjectIsEqualException();
}
}
}
if (_collection.Count>=_maxCount) throw new CollectionOverflowExecption(_maxCount);
_collection.Add(obj);
return true;
}
public bool Insert(T obj, int position, IEqualityComparer<T?> comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
// TODO выброс ошибки, если выход за границу
// TODO выброс ошибки, если переполнение
// +-
if (comparer != null)
{
foreach (T? item in _collection)
{
if (item == null) continue;
if ((comparer as IEqualityComparer<DrawningGun>).Equals(obj as DrawningGun, item as DrawningGun))
{
throw new ObjectIsEqualException();
}
}
}
if (Count>=_maxCount) throw new CollectionOverflowExecption(_maxCount);
if (position >= Count || position < 0) { throw new PositionOutOfCollectionException(position); }
_collection.Insert(position, obj);
return true;
}
public bool Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
// TODO выброс ошибки, если выход за границу массива
// +-
if(position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
return false;
}
_collection.RemoveAt(position);
return true;
}
public CollectionType GetCollectionType => CollectionType.List;
public IEnumerable<T?> GetItems()
{
for(int i=0; i<_collection.Count; i++) yield return _collection[i];
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -0,0 +1,160 @@
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.Exceptions;
using System.Data.Entity.Core;
using System.Diagnostics;
namespace AntiAircraftGun.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int MaxCount
{
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
get
{
return _collection.Length;
}
}
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
// TODO проверка позиции
// TODO выброс ошибки, если переполнение
// TODO выброс ошибки, если пустой
// +-
if (_collection[position] == null)
{
throw new Exceptions.ObjectNotFoundException(position);
}
if (position >= _collection.Length || position<0)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public bool Insert(T obj, IEqualityComparer<T?> comparer = null)
{
// TODO вставка в свободное место набора
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningGun>).Equals(obj as DrawningGun, item as DrawningGun))
throw new ObjectIsEqualException();
}
}
for (int i = 0; i < Count; i++)
{
if (InsertingElementCollection(i, obj)) return true;
}
throw new CollectionOverflowExecption(Count);
}
public bool Insert(T obj, int position, IEqualityComparer<T?> comparer = null)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
// TODO выброс ошибки, если переполнение
// TODO выброс ошибки, если выход за границу массива
// +-
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningGun>).Equals(obj as DrawningGun, item as DrawningGun))
throw new ObjectIsEqualException();
}
}
if (position>=_collection.Length||position<0)
{
throw new PositionOutOfCollectionException(position);
}
if (InsertingElementCollection(position, obj)) return true;
for (int i = position + 1; i < Count; i++)
{
if (InsertingElementCollection(i, obj)) return true;
}
for (int i = position - 1; i >= 0; i--)
{
if (InsertingElementCollection(i, obj)) return true;
}
throw new CollectionOverflowExecption(Count);
}
public bool Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
// TODO выброс ошибки, если выход за границу
// TODO выброс ошибки, если пустой
// +-
if(position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new Exceptions.ObjectNotFoundException(position);
_collection[position] = null;
return true;
}
/// <summary>
/// Если элемент массива пустой, то вставляем новый элемент
/// </summary>
/// <param name="index">Индекс элемента</param>
/// <param name="obj">Элемент</param>
/// <returns>false - элемент массива != null, true - = null</returns>
private bool InsertingElementCollection(int index, T obj)
{
if (_collection[index] != null) return false;
_collection[index] = obj;
return true;
}
public CollectionType GetCollectionType => CollectionType.Massive;
public IEnumerable<T?> GetItems()
{
for (int i=0; i < _collection.Length; i++) yield return _collection[i];
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -0,0 +1,187 @@
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.Exceptions;
using System.Text;
namespace AntiAircraftGun.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningGun
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (!_storages.ContainsKey(collectionInfo)) { return; }
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
// TODO Продумать логику получения объекта
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (!_storages.ContainsKey(collectionInfo)) { return null; }
return _storages[collectionInfo];
}
}
/// <summary>
/// Запись информации в файл
/// </summary>
/// <param name="filename"></param>
public void SaveData(string filename)
{
if(File.Exists(filename))
{
File.Delete(filename);
}
if(_storages.Count==0) throw new Exception("В хранилище отсутсвуют коллекции для сохранения");
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
sb.Append(Environment.NewLine);
// Не сохраняем пустые коллекции
if (value.Value.Count == 0) continue;
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data=item?.GetDataForSave() ?? string.Empty;
if(string.IsNullOrEmpty(data)) continue;
sb.Append(data);
sb.Append(_separatorItems);
}
}
using FileStream fs=new(filename, FileMode.Create);
byte[] info=new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
}
/// <summary>
/// Загрузка информации по установкам в хранилище из файла
/// </summary>
/// <param name="filename"></param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader reader = File.OpenText(filename))
{
string str = reader.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = reader.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningCun() is T gun)
{
try
{
if (!collection.Insert(gun))
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowExecption ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
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,27 @@
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4,
/// <summary>
/// Неизвестно направление
/// </summary>
Unknow = -1
}

View File

@ -0,0 +1,61 @@
using AntiAircraftGun.Entities;
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта
/// </summary>
public class DrawningAntiAircraftGun:DrawningGun
{
public DrawningAntiAircraftGun(EntityGun gun) : base(gun)
{
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="optionalElementsColor"></param>
/// <param name="barrelLenth"></param>
/// <param name="hatchHeight"></param>
public DrawningAntiAircraftGun(int speed, double weight, Color bodyColor, Color optionalElementsColor,bool hatchHeight, bool radar) : base(150,115) //140, 65
{
EntityGun = new EntityAntiAircraftGun(speed,weight,bodyColor,optionalElementsColor,hatchHeight,radar);
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
_startPosX += 10;
_startPosY += 50;
base.DrawTransport(g);
_startPosX -= 10;
_startPosY -= 50;
if (EntityGun == null || !_startPosX.HasValue || !_startPosY.HasValue || EntityGun is not EntityAntiAircraftGun antiAircraftGun) return;
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(antiAircraftGun.OptionalElementsColor);
// Орудие
Pen penWeapon = new Pen(Color.Black, 8);
g.DrawLine(penWeapon, _startPosX.Value + 100, _startPosY.Value + 70, _startPosX.Value + 150, _startPosY.Value + 10);
// Люк
if (antiAircraftGun.Hatch)
{
Random random = new();
g.FillRectangle(additionalBrush, _startPosX.Value + 85, _startPosY.Value + 45, 20, 5);
}
// Радар
if (antiAircraftGun.Radar)
{
Pen penRadar = new Pen(Color.Green, 3);
Brush brushRadar = new SolidBrush(Color.Black);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value + 50, _startPosX.Value + 65, _startPosY.Value + 25);
g.FillEllipse(brushRadar, _startPosX.Value + 35, _startPosY.Value, 60, 25);
g.DrawLine(penRadar, _startPosX.Value + 65, _startPosY.Value + 25, _startPosX.Value + 65, _startPosY.Value);
g.DrawLine(penRadar, _startPosX.Value + 35, _startPosY.Value + 13, _startPosX.Value + 95, _startPosY.Value + 13);
}
}
}

View File

@ -0,0 +1,233 @@
using AntiAircraftGun.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Drawnings;
public class DrawningGun
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityGun? EntityGun { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
public int? GetPictureWidth() => _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
public int? GetPictureHeight() => _pictureHeight;
/// <summary>
/// Левая координата прорисовки зенитной установки
/// </summary>
protected int? _startPosX;
/// <summary>
/// Правая координата прорисовку зенитной установки
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки зенитной установки
/// </summary>
private readonly int _drawningGunWidth = 140;
/// <summary>
/// Высота прорисовки зенитной установки
/// </summary>
private readonly int _drawingGunHeight = 65;
/// <summary>
/// Координата Х объекта
/// </summary>
public int? GetPosX ()=> _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY() => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth() => _drawningGunWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight() => _drawingGunHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningGun()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Констурктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningGun(int speed, double weight, Color bodyColor):this()
{
EntityGun = new EntityGun(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningGunWidth">Ширина прорисовки ракетной установки</param>
/// <param name="drawningGunHeight">Высота прорисовки ракетной установки</param>
protected DrawningGun(int drawningGunWidth, int drawningGunHeight):this()
{
_drawingGunHeight = drawningGunHeight;
_drawningGunWidth = drawningGunWidth;
}
public DrawningGun(EntityGun gun)
{
EntityGun = gun;
}
/// <summary>
/// Установка гранц поля
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (_drawningGunWidth > width || _drawingGunHeight > height) { return false; }
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX.Value + _drawningGunWidth > width)
{
_startPosX = width - _drawningGunWidth;
}
if (_startPosY.Value + _drawingGunHeight > height)
{
_startPosY = height - _drawingGunHeight;
}
}
_pictureHeight = height;
_pictureWidth = width;
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x + _drawningGunWidth > _pictureWidth.Value )
{
_startPosX = x - (x + _drawningGunWidth - _pictureWidth.Value);
}else if (x < 0)
{
_startPosX = 0;
}
else
{
_startPosX = x;
}
if (y + _drawingGunHeight > _pictureHeight.Value )
{
_startPosY = y - (y + _drawingGunHeight - _pictureHeight.Value);
}
else if (y < 0)
{
_startPosY = 0;
}
else
{
_startPosY = y;
}
}
/// <summary>
/// Изменение напаравления перемещения
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityGun == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityGun.Step > 0)
{
_startPosX -= (int)EntityGun.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityGun.Step > 0)
{
_startPosY -= (int)EntityGun.Step;
}
return true;
// вправо
case DirectionType.Right:
//TODO прописать логику сдвига в право
if (_startPosX.Value + EntityGun.Step + _drawningGunWidth < _pictureWidth)
{
_startPosX += (int)EntityGun.Step;
}
return true;
//вниз
case DirectionType.Down:
//TODO прописать логику сдвига в вниз
if (_startPosY.Value + EntityGun.Step + _drawingGunHeight < _pictureHeight)
{
_startPosY += (int)EntityGun.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityGun == null || !_startPosX.HasValue || !_startPosY.HasValue) return;
Pen pen = new(Color.Black);
Brush MainBrush = new SolidBrush(EntityGun.BodyColor);
// Башня
g.FillRectangle(MainBrush, _startPosX.Value + 50 - 10, _startPosY.Value + 50 - 50, 60, 25);
g.FillRectangle(MainBrush, _startPosX.Value + 25 - 10, _startPosY.Value + 75 - 50, 110, 10);
// Гусеницы
g.DrawArc(pen, _startPosX.Value + 110 - 10, _startPosY.Value + 85 - 50, 40, 30, 270, 180);
g.DrawArc(pen, _startPosX.Value + 10 - 10, _startPosY.Value + 85 - 50, 40, 30, 90, 180);
g.DrawLine(pen, _startPosX.Value + 30 - 10, _startPosY.Value + 115 - 50, _startPosX.Value + 130 - 10, _startPosY.Value + 115 - 50);
// Катки большие
g.DrawEllipse(pen, _startPosX.Value + 13 - 10, _startPosY.Value + 93 - 50, 20, 20);
g.DrawEllipse(pen, _startPosX.Value + 126 - 10, _startPosY.Value + 93 - 50, 20, 20);
// Катки малые
g.DrawEllipse(pen, _startPosX.Value + 40 - 10, _startPosY.Value + 105 - 50, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 60 - 10, _startPosY.Value + 105 - 50, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 80 - 10, _startPosY.Value + 105 - 50, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 100 - 10, _startPosY.Value + 105 - 50, 10, 10);
}
}

View File

@ -0,0 +1,28 @@
namespace AntiAircraftGun.Drawnings;
public class DrawningGunCompareByColor : IComparer<DrawningGun?>
{
public int Compare(DrawningGun? x, DrawningGun? y)
{
if (x == null || x.EntityGun == null)
{
return 1;
}
if (y == null || y.EntityGun == null)
{
return -1;
}
var bodycolorCompare = x.EntityGun.BodyColor.Name.CompareTo(y.EntityGun.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityGun.Speed.CompareTo(y.EntityGun.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityGun.Weight.CompareTo(y.EntityGun.Weight);
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningGunCompareByType : IComparer<DrawningGun?>
{
public int Compare(DrawningGun? x, DrawningGun? y)
{
if (x == null || x.EntityGun == null)
{
return -1;
}
if (y == null || y.EntityGun == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityGun.Speed.CompareTo(y.EntityGun.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityGun.Weight.CompareTo(y.EntityGun.Weight);
}
}

View File

@ -0,0 +1,64 @@

using AntiAircraftGun.Entities;
using System.Diagnostics.CodeAnalysis;
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Реализатор сравнения двух объектов
/// </summary>
public class DrawningGunEqutables : IEqualityComparer<DrawningGun?>
{
public bool Equals(DrawningGun? x, DrawningGun? y)
{
if (x == null || x.EntityGun == null)
{
return false;
}
if (y == null || y.EntityGun == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityGun.Speed != y.EntityGun.Speed)
{
return false;
}
if (x.EntityGun.Weight != y.EntityGun.Weight)
{
return false;
}
if (x.EntityGun.BodyColor != y.EntityGun.BodyColor)
{
return false;
}
if (x is DrawningAntiAircraftGun xa && y is DrawningAntiAircraftGun ya )
{
// TODO доделать логику сравнения дополнительных параметров
if(xa.EntityGun is EntityAntiAircraftGun left && ya.EntityGun is EntityAntiAircraftGun right)
{
if (left.OptionalElementsColor != right.OptionalElementsColor)
{
return false;
}
if (left.Radar != right.Radar)
{
return false;
}
if (left.Hatch != right.Hatch)
{
return false;
}
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningGun? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,48 @@
using AntiAircraftGun.Entities;
namespace AntiAircraftGun.Drawnings;
/// <summary>
/// Расширение для класса EntityGun
/// </summary>
public static class ExtentionDrawningGun
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningGun? CreateDrawningCun(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityGun? gun = EntityAntiAircraftGun.CreateEntityAntiaircraftGun(strs);
if (gun != null)
{
return new DrawningAntiAircraftGun(gun);
}
gun = EntityGun.CreateEntityCar(strs);
if (gun != null)
{
return new DrawningGun(gun);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningGun drawningCun)
{
string[]? array = drawningCun?.EntityGun?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -0,0 +1,47 @@
namespace AntiAircraftGun.Entities;
/// <summary>
/// Класс-сущность "Зенитная установка"
/// </summary>
public class EntityAntiAircraftGun : EntityGun
{
private EntityGun? EntityGun;
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color OptionalElementsColor { get; private set; }
/// <summary>
/// Публичный сеттер для дополнительного цвета
/// </summary>
/// <param name="OptionalElementsColor"></param>
public void SetOptionalElemensColor(Color OptionalElementsColor)
{
this.OptionalElementsColor = OptionalElementsColor;
}
/// <summary>
/// Люк
/// </summary>
public bool Hatch { get; private set; }
/// <summary>
/// Радар
/// </summary>
public bool Radar { get; private set; }
public EntityAntiAircraftGun(int speed, double weight, Color bodyColor, Color optionalElementsColor, bool hatch, bool radar) : base(speed, weight, bodyColor)
{
EntityGun = new EntityGun(speed, weight, bodyColor);
OptionalElementsColor = optionalElementsColor;
Radar = radar;
Hatch = hatch;
}
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAntiAircraftGun), Speed.ToString(), Weight.ToString(), BodyColor.Name, OptionalElementsColor.ToString(), Hatch.ToString(), Radar.ToString() };
}
public static EntityAntiAircraftGun? CreateEntityAntiaircraftGun(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAntiAircraftGun)) return null;
return new EntityAntiAircraftGun(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

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

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class CollectionOverflowExecption : ApplicationException
{
public CollectionOverflowExecption(int count) : base("В коллекции превышено допустимое кол-во: count " + count) { }
public CollectionOverflowExecption() : base() { }
public CollectionOverflowExecption(string message) : base(message) { }
public CollectionOverflowExecption(string message, Exception innerException) : base(message, innerException) { }
protected CollectionOverflowExecption(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

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

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Exceptions;
[Serializable]
public class ObjectNotFoundException: ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception innerException) : base(message, innerException) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.Exceptions;
public class PositionOutOfCollectionException:ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception innerException) : base(message, innerException) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -1,39 +0,0 @@
namespace AntiAircraftGun
{
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 AntiAircraftGun
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,147 @@
namespace AntiAircraftGun
{
partial class FormAntiAircraftGun
{
/// <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()
{
pictureBoxAntiAircraftGun = new PictureBox();
buttonDown = new Button();
buttonLeft = new Button();
buttonUp = new Button();
buttonRight = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAntiAircraftGun).BeginInit();
SuspendLayout();
//
// pictureBoxAntiAircraftGun
//
pictureBoxAntiAircraftGun.Dock = DockStyle.Fill;
pictureBoxAntiAircraftGun.Location = new Point(0, 0);
pictureBoxAntiAircraftGun.Name = "pictureBoxAntiAircraftGun";
pictureBoxAntiAircraftGun.Size = new Size(939, 393);
pictureBoxAntiAircraftGun.TabIndex = 8;
pictureBoxAntiAircraftGun.TabStop = false;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.ArrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(838, 339);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 2;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.ArrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(797, 339);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 3;
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(838, 298);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 4;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.ArrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(876, 339);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(776, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 9;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonStrategyStep.Location = new Point(797, 65);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(130, 29);
buttonStrategyStep.TabIndex = 10;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormAntiAircraftGun
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(939, 393);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(pictureBoxAntiAircraftGun);
Name = "FormAntiAircraftGun";
Text = "Зенитная установка";
((System.ComponentModel.ISupportInitialize)pictureBoxAntiAircraftGun).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxAntiAircraftGun;
private Button buttonDown;
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -0,0 +1,124 @@
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.MovementStrategy;
namespace AntiAircraftGun
{
public partial class FormAntiAircraftGun : Form
{
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningGun? _drawningGun;
/// <summary>
/// Конуструктор формы
/// </summary>
public FormAntiAircraftGun()
{
InitializeComponent();
_abstractStrategy = null;
}
/// <summary>
/// Получение объекта
/// </summary>
public DrawningGun SetGun
{
set
{
_drawningGun = value;
_drawningGun.SetPictureSize(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
Draw();
}
}
/// <summary>
/// Метод рисования машины
/// </summary>
private void Draw()
{
if (_drawningGun == null)
{
return;
}
Bitmap bmp = new(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningGun.DrawTransport(gr);
pictureBoxAntiAircraftGun.Image = bmp;
_drawningGun.DrawTransport(gr);
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningGun == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result =
_drawningGun.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningGun.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningGun.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningGun.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningGun == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new MoveableGun(_drawningGun),
pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = 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,374 @@
namespace AntiAircraftGun
{
partial class FormGunCollections
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBox1 = new GroupBox();
panelCompanyTools = new Panel();
buttonCreateCompany = new Button();
comboBoxSelectorCompany = new ComboBox();
buttonAddGun = new Button();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
maskedTextBox = new MaskedTextBox();
buttonRemoveGun = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
textBoxCollectionName = new TextBox();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
labelNameCollection = new Label();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
downloadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBox1.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(panelCompanyTools);
groupBox1.Controls.Add(panelStorage);
groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(1011, 28);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(235, 855);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonCreateCompany);
panelCompanyTools.Controls.Add(comboBoxSelectorCompany);
panelCompanyTools.Controls.Add(buttonAddGun);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRemoveGun);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 395);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(229, 457);
panelCompanyTools.TabIndex = 9;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(9, 87);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(217, 29);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "База" });
comboBoxSelectorCompany.Location = new Point(9, 53);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(214, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// buttonAddGun
//
buttonAddGun.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddGun.Location = new Point(9, 122);
buttonAddGun.Name = "buttonAddGun";
buttonAddGun.Size = new Size(214, 52);
buttonAddGun.TabIndex = 1;
buttonAddGun.Text = "Добавление установки";
buttonAddGun.UseVisualStyleBackColor = true;
buttonAddGun.Click += ButtonAddGun_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(9, 313);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(214, 39);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(9, 274);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(214, 33);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(9, 203);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(217, 27);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonRemoveGun
//
buttonRemoveGun.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveGun.Location = new Point(9, 236);
buttonRemoveGun.Name = "buttonRemoveGun";
buttonRemoveGun.Size = new Size(214, 32);
buttonRemoveGun.TabIndex = 4;
buttonRemoveGun.Text = "Удалить установку";
buttonRemoveGun.UseVisualStyleBackColor = true;
buttonRemoveGun.Click += ButtonRemoveGun_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(labelNameCollection);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 23);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(229, 366);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(9, 326);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(217, 29);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(9, 164);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(217, 144);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(9, 120);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(217, 29);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добаваить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(9, 41);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(217, 27);
textBoxCollectionName.TabIndex = 3;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(146, 74);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 2;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(9, 74);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 1;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// labelNameCollection
//
labelNameCollection.AutoSize = true;
labelNameCollection.Location = new Point(41, 11);
labelNameCollection.Name = "labelNameCollection";
labelNameCollection.Size = new Size(155, 20);
labelNameCollection.TabIndex = 0;
labelNameCollection.Text = "Название коллекции";
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1011, 855);
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(1246, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, downloadToolStripMenuItem });
файл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;
//
// downloadToolStripMenuItem
//
downloadToolStripMenuItem.Name = "downloadToolStripMenuItem";
downloadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
downloadToolStripMenuItem.Size = new Size(227, 26);
downloadToolStripMenuItem.Text = "Загрузка";
downloadToolStripMenuItem.Click += DownloadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt files|*.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt files|*.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(9, 397);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(214, 39);
buttonSortByColor.TabIndex = 10;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(9, 358);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(214, 33);
buttonSortByType.TabIndex = 9;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormGunCollections
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1246, 883);
Controls.Add(pictureBox);
Controls.Add(groupBox1);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormGunCollections";
Text = "Коллекция установок";
groupBox1.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBox1;
private Button buttonAddGun;
private ComboBox comboBoxSelectorCompany;
private MaskedTextBox maskedTextBox;
private PictureBox pictureBox;
private Button buttonRemoveGun;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Panel panelStorage;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private TextBox textBoxCollectionName;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Label labelNameCollection;
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem downloadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -0,0 +1,355 @@
using AntiAircraftGun.CollectionGenericObjects;
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.Exceptions;
using Microsoft.Extensions.Logging;
using System.Data.Entity.Core;
namespace AntiAircraftGun;
public partial class FormGunCollections : Form
{
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
private readonly StorageCollection<DrawningGun> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormGunCollections(ILogger<FormGunCollections> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = true;
}
/// <summary>
/// Добавление установки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddGun_Click(object sender, EventArgs e)
{
FormGunConfig form = new();
// TODO передать метод
form.AddEvent(SetGun);
form.Show();
}
/// <summary>
/// Добавление автомобиля в коллекцию
/// </summary>
/// <param name="gun"></param>
private void SetGun(DrawningGun? gun)
{
try
{
if (_company == null || gun == null) { return; }
if (_company + gun)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + gun.GetDataForSave());
}
}
catch (Exceptions.ObjectNotFoundException) { }
catch (CollectionOverflowExecption ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление установки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveGun_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBox.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; }
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
}
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Передача объекта на тесты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningGun? gun = null;
int counter = 100;
try
{
while (gun == null)
{
gun = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (gun == null)
{
return;
}
FormAntiAircraftGun form = new()
{
SetGun = gun,
};
form.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <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);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text,
collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Коллекция для удаления не выбрана");
return;
}
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 ||
listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningGun>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "База":
_company = new GunSharingService(pictureBox.Width,
pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <summary>
/// Обработка нажатия "Cохранения"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DownloadToolStripMenuItem_Click(object sender, EventArgs e)
{
//TODO продумать логику
// TODO Логирование
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareGun(new DrawningGunCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareGun(new DrawningGunCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareGun(IComparer<DrawningGun?> comparer)
{
if (comparer == null) return;
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

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

View File

@ -0,0 +1,371 @@
namespace AntiAircraftGun
{
partial class FormGunConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
labelSimpleOblect = new Label();
groupBoxColors = new GroupBox();
panelIndigo = new Panel();
panelGrey = new Panel();
panelBlack = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelBlue = new Panel();
panelYellow = new Panel();
panelRed = new Panel();
checkBoxRadar = new CheckBox();
checkBoxHatch = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObjects = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObjects = new Panel();
labelOptionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObjects).BeginInit();
panelObjects.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(labelSimpleOblect);
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxRadar);
groupBoxConfig.Controls.Add(checkBoxHatch);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(682, 345);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// labelSimpleOblect
//
labelSimpleOblect.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
labelSimpleOblect.BorderStyle = BorderStyle.FixedSingle;
labelSimpleOblect.Location = new Point(277, 241);
labelSimpleOblect.Name = "labelSimpleOblect";
labelSimpleOblect.Size = new Size(131, 55);
labelSimpleOblect.TabIndex = 10;
labelSimpleOblect.Text = "Простой";
labelSimpleOblect.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleOblect.MouseDown += LabelOblect_MouseDown;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelIndigo);
groupBoxColors.Controls.Add(panelGrey);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(277, 41);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(314, 171);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelIndigo
//
panelIndigo.BackColor = Color.Indigo;
panelIndigo.Location = new Point(233, 91);
panelIndigo.Name = "panelIndigo";
panelIndigo.Size = new Size(39, 41);
panelIndigo.TabIndex = 4;
//
// panelGrey
//
panelGrey.BackColor = Color.Gray;
panelGrey.Location = new Point(163, 91);
panelGrey.Name = "panelGrey";
panelGrey.Size = new Size(39, 41);
panelGrey.TabIndex = 6;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(92, 91);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(39, 41);
panelBlack.TabIndex = 5;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(19, 91);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(39, 41);
panelWhite.TabIndex = 3;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(233, 37);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(39, 41);
panelGreen.TabIndex = 1;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(163, 37);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(39, 41);
panelBlue.TabIndex = 2;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(92, 37);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(39, 41);
panelYellow.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(19, 37);
panelRed.Name = "panelRed";
panelRed.Size = new Size(39, 41);
panelRed.TabIndex = 0;
//
// checkBoxRadar
//
checkBoxRadar.AutoSize = true;
checkBoxRadar.Location = new Point(22, 203);
checkBoxRadar.Name = "checkBoxRadar";
checkBoxRadar.Size = new Size(72, 24);
checkBoxRadar.TabIndex = 7;
checkBoxRadar.Text = "Радар";
checkBoxRadar.UseVisualStyleBackColor = true;
//
// checkBoxHatch
//
checkBoxHatch.AutoSize = true;
checkBoxHatch.Location = new Point(22, 149);
checkBoxHatch.Name = "checkBoxHatch";
checkBoxHatch.Size = new Size(60, 24);
checkBoxHatch.TabIndex = 6;
checkBoxHatch.Text = "Люк";
checkBoxHatch.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(104, 92);
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(99, 27);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(104, 41);
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(99, 27);
numericUpDownSpeed.TabIndex = 4;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(22, 94);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 3;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(22, 43);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(460, 241);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(131, 55);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelOblect_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.Location = new Point(0, 0);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(100, 23);
labelSimpleObject.TabIndex = 9;
//
// pictureBoxObjects
//
pictureBoxObjects.Location = new Point(41, 95);
pictureBoxObjects.Name = "pictureBoxObjects";
pictureBoxObjects.Size = new Size(218, 169);
pictureBoxObjects.TabIndex = 0;
pictureBoxObjects.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(731, 304);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(931, 304);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObjects
//
panelObjects.AllowDrop = true;
panelObjects.Controls.Add(labelOptionalColor);
panelObjects.Controls.Add(labelBodyColor);
panelObjects.Controls.Add(pictureBoxObjects);
panelObjects.Location = new Point(731, 12);
panelObjects.Name = "panelObjects";
panelObjects.Size = new Size(294, 284);
panelObjects.TabIndex = 4;
panelObjects.DragDrop += PanelObjects_DragDrop;
panelObjects.DragEnter += PanelObjects_DragEnter;
//
// labelOptionalColor
//
labelOptionalColor.AllowDrop = true;
labelOptionalColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
labelOptionalColor.BorderStyle = BorderStyle.FixedSingle;
labelOptionalColor.Location = new Point(164, 14);
labelOptionalColor.Name = "labelOptionalColor";
labelOptionalColor.Size = new Size(118, 42);
labelOptionalColor.TabIndex = 12;
labelOptionalColor.Text = "Доп. Цвет";
labelOptionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelOptionalColor.DragDrop += labelOptionalColor_DragDrop;
labelOptionalColor.DragEnter += labelOptionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(13, 14);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(113, 42);
labelBodyColor.TabIndex = 11;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// FormGunConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1056, 345);
Controls.Add(panelObjects);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormGunConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObjects).EndInit();
panelObjects.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelSimpleObject;
private Label labelModifiedObject;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxRadar;
private CheckBox checkBoxHatch;
private GroupBox groupBoxColors;
private Panel panelRed;
private Panel panelIndigo;
private Panel panelGrey;
private Panel panelBlack;
private Panel panelWhite;
private Panel panelGreen;
private Panel panelBlue;
private Panel panelYellow;
private PictureBox pictureBoxObjects;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObjects;
private Label labelSimpleOblect;
private Label labelBodyColor;
private Label labelOptionalColor;
}
}

View File

@ -0,0 +1,163 @@
using AntiAircraftGun.Drawnings;
using AntiAircraftGun.Entities;
using System;
namespace AntiAircraftGun;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormGunConfig : Form
{
/// <summary>
/// Объект прорисовки класса
/// </summary>
private DrawningGun? _gun;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawningGun>? _gunDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormGunConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelGrey.MouseDown += Panel_MouseDown;
panelIndigo.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
// TODO buttonCancel.Click with lambda
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к союытию
/// </summary>
/// <param name="gunDelegate"></param>
public void AddEvent(Action<DrawningGun> gunDelegate)
{
_gunDelegate += gunDelegate;
}
// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObjects.Width, pictureBoxObjects.Height);
Graphics gr = Graphics.FromImage(bmp);
_gun?.SetPictureSize(pictureBoxObjects.Width,
pictureBoxObjects.Height);
_gun?.SetPosition(15, 15);
_gun?.DrawTransport(gr);
pictureBoxObjects.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelOblect_MouseDown(object sender, MouseEventArgs e)
{
Label label=sender as Label;
if(label.Name== "labelSimpleOblect")
{
label.DoDragDrop(new DrawningGun((int)numericUpDownSpeed.Value,
(double)numericUpDownWeight.Value, Color.White), DragDropEffects.Copy);
}
else
{
Random random = new Random();
label.DoDragDrop(new
DrawningAntiAircraftGun((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value,
Color.White,
Color.Black,
checkBoxHatch.Checked, checkBoxRadar.Checked), DragDropEffects.Copy);
}
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObjects_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObjects_DragDrop(object sender, DragEventArgs e)
{
if ((DrawningGun)e.Data.GetData(typeof(DrawningGun)) != null)
{
_gun = (DrawningGun)e.Data.GetData(typeof(DrawningGun));
}
else
{
_gun = (DrawningAntiAircraftGun)e.Data.GetData(typeof(DrawningAntiAircraftGun));
}
DrawObject();
}
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
// TODO реализовать выбор цвета
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor ?? Color.Black, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_gun != null)
{
_gunDelegate?.Invoke(_gun);
Close();
}
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_gun != null)
{
_gun.EntityGun.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelBodyColor_DragEnter(object? sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
private void labelOptionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_gun.EntityGun is EntityAntiAircraftGun antiAircraftGun)
{
antiAircraftGun.SetOptionalElemensColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelOptionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_gun is DrawningAntiAircraftGun)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
}
// TODO Реализовать логику смены цветов: основного и дополнительного(для продвинутого объекта)
}

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,7 @@
using AntiAircraftGun.Drawnings;
namespace AntiAircraftGun;
/// <summary>
/// Делегат для объекта класса прорисовки
/// </summary>
/// <param name="drawningGun"></param>
public delegate void GunDelegate(DrawningGun drawningGun);

View File

@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <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,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.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,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objectParameters = GetObjectParameters();
if (objectParameters == null)
{
return false;
}
return objectParameters.RightBorder() <= FieldWidth && objectParameters.RightBorder() + GetStep() >= FieldWidth &&
objectParameters.DownBorder() <= FieldHeight && objectParameters.DownBorder() + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objectParameters=GetObjectParameters();
if(objectParameters == null) { return; }
if (objectParameters.RightBorder() < FieldWidth)
{
MoveRight();
}
if (objectParameters.DownBorder() <FieldHeight)
{
MoveDown();
}
}
}

View File

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

View File

@ -0,0 +1,71 @@
using AntiAircraftGun.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с ипользованием DrawningGun
/// </summary>
public class MoveableGun : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningGun или его наследника
/// </summary>
private readonly DrawningGun? _drawningGun = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="drawningGun"></param>
public MoveableGun(DrawningGun? drawningGun)
{
_drawningGun = drawningGun;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningGun == null || _drawningGun.EntityGun == null ||
!_drawningGun.GetPosX().HasValue ||
!_drawningGun.GetPosY().HasValue)
{
return null;
}
return new ObjectParameters(
_drawningGun.GetPosX().Value,
_drawningGun.GetPosY().Value,
_drawningGun.GetWidth(),
_drawningGun.GetHeight());
}
}
public int GetStep => (int)(_drawningGun?.EntityGun?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_drawningGun == null || _drawningGun.EntityGun == null)
{
return false;
}
return _drawningGun.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns></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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.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,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.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"></param>
/// <param name="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,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntiAircraftGun.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполянется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB