6 Commits

Author SHA1 Message Date
35fa426532 8 лабораторная 2024-06-08 03:58:44 +04:00
2db4595ab4 небольшие изменения 2024-06-08 01:18:01 +04:00
265eb071be 7 лабортаорная 2024-06-08 01:09:47 +04:00
3f7b38ad18 пока не работает 2024-04-15 11:17:15 +04:00
b2dd4bf3a1 Начала лаб 6 2024-04-15 05:09:11 +04:00
9712e38913 5 лабораторная работа 2024-04-15 04:14:52 +04:00
30 changed files with 1793 additions and 340 deletions

View File

@@ -48,7 +48,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
@@ -59,7 +59,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningPropelledArtillery propelledartillery) public static int operator +(AbstractCompany company, DrawningPropelledArtillery propelledartillery)
{ {
return company._collection.Insert(propelledartillery); return company._collection.Insert(propelledartillery, new DrawiningPropelledArtilleryEqutables());
} }
/// <summary> /// <summary>
@@ -114,4 +114,11 @@ public abstract class AbstractCompany
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningPropelledArtillery?> comparer) => _collection?.CollectionSort(comparer);
} }

View File

@@ -41,11 +41,12 @@ public class ArtilleryBase : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (_collection.Get(i) != null) try
{ {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 40, curHeight * _placeSizeHeight + 4); _collection?.Get(i)?.SetPosition(_placeSizeWidth * curWidth + 40, curHeight * _placeSizeHeight + 4);
} }
catch (Exception) { };
if (curWidth > 0) if (curWidth > 0)
curWidth--; curWidth--;
else else

View File

@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
/// <summary>
/// Класс, хранящий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?
strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

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

View File

@@ -1,56 +1,93 @@
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System.Collections.Generic;
using System.Linq;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> namespace SelfPropelledArtilleryUnit.CollectionGenericObjects
where T : class
{ {
/// <summary> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// Список объектов, которые храним where T : class
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{ {
_collection = new(); /// <summary>
} /// Список объектов, которые храним
public T? Get(int position) /// </summary>
{ private readonly List<T?> _collection;
// TODO проверка позиции public CollectionType GetCollectionType => CollectionType.List;
if (position >= Count || position < 0) return null; /// <summary>
return _collection[position]; /// Максимально допустимое число объектов в списке
} /// </summary>
public int Insert(T obj) private int _maxCount;
{ public int Count => _collection.Count;
// TODO проверка, что не превышено максимальное количество элементов public int MaxCount
// TODO вставка в конец набора {
if (Count == _maxCount) return -1; get
_collection.Add(obj); {
return Count; return Count;
} }
public int Insert(T obj, int position) set
{ {
// TODO проверка, что не превышено максимальное количество элементов if (value > 0)
// TODO проверка позиции {
// TODO вставка по позиции _maxCount = value;
if (Count == _maxCount) return -1; }
if (position >= Count || position < 0) return -1; }
_collection.Insert(position, obj); }
return position; /// <summary>
} /// Конструктор
public T Remove(int position) /// </summary>
{ public ListGenericObjects()
// TODO проверка позиции {
// TODO удаление объекта из списка _collection = new();
if (position >= Count || position < 0) return null; }
T obj = _collection[position]; public T? Get(int position)
_collection.RemoveAt(position); {
return obj; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }
} }

View File

@@ -1,4 +1,7 @@
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@@ -12,7 +15,28 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } } public CollectionType GetCollectionType => CollectionType.Massive;
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -20,15 +44,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{ {
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
} }
public T? Get(int position) public T Get(int position)
{ {
// TODO проверка позиции if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length || position < 0) return null; if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
// TODO вставка в свободное место набора if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningPropelledArtillery>).Equals(obj as DrawningPropelledArtillery, item as DrawningPropelledArtillery))
throw new ObjectIsEqualException();
}
}
int index = 0; int index = 0;
while (index < _collection.Length) while (index < _collection.Length)
{ {
@@ -39,17 +70,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
++index; ++index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
// TODO проверка позиции if (comparer != null)
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то {
// ищется свободное место после этой позиции и идет вставка туда foreach (T? item in _collection)
// если нет после, ищем до {
// TODO вставка if ((comparer as IEqualityComparer<DrawningPropelledArtillery>).Equals(obj as DrawningPropelledArtillery, item as DrawningPropelledArtillery))
if (position >= _collection.Length || position < 0) throw new ObjectIsEqualException();
return -1; }
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@@ -75,16 +108,25 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
--index; --index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
// TODO удаление объекта из массива, присвоив элементу массива значение null if (_collection[position] == null) throw new ObjectNotFoundException(position);
if (position >= _collection.Length || position < 0)
return null;
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return obj;
} }
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

@@ -1,23 +1,27 @@
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System.Collections.Generic;
using System.Text;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningPropelledArtillery
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@@ -26,14 +30,13 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
// TODO Прописать логику для добавления if (_storages.ContainsKey(collectionInfo)) return;
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return; if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive) else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>(); _storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List) else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>(); _storages[collectionInfo] = new ListGenericObjects<T>();
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
@@ -41,10 +44,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
// TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(collectionInfo))
if (_storages.ContainsKey(name)) _storages.Remove(collectionInfo);
_storages.Remove(name);
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
@@ -55,10 +57,142 @@ public class StorageCollection<T>
{ {
get get
{ {
// TODO Продумать логику получения объекта CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(collectionInfo))
return _storages[name]; return _storages[collectionInfo];
return null; return null;
} }
} }
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new 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?.CreateDrawningPropelledArtillery() is T ship)
{
try
{
if (collection.Insert(ship) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }

View File

@@ -0,0 +1,62 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawiningPropelledArtilleryEqutables : IEqualityComparer<DrawningPropelledArtillery?>
{
public bool Equals(DrawningPropelledArtillery? x, DrawningPropelledArtillery? y)
{
if (x == null || x.EntityPropelledArtillery == null)
{
return false;
}
if (y == null || y.EntityPropelledArtillery == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityPropelledArtillery.Speed != y.EntityPropelledArtillery.Speed)
{
return false;
}
if (x.EntityPropelledArtillery.Weight != y.EntityPropelledArtillery.Weight)
{
return false;
}
if (x.EntityPropelledArtillery.BodyColor != y.EntityPropelledArtillery.BodyColor)
{
return false;
}
if (x is DrawningSelfPropelledArtilleryUnit && y is DrawningSelfPropelledArtilleryUnit)
{
EntitySelfPropelledArtilleryUnit _x = (EntitySelfPropelledArtilleryUnit)x.EntityPropelledArtillery;
EntitySelfPropelledArtilleryUnit _y = (EntitySelfPropelledArtilleryUnit)x.EntityPropelledArtillery;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.TurretCannon != _y.TurretCannon)
{
return false;
}
if (_x.LaunchBattery != _y.LaunchBattery)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningPropelledArtillery obj)
{
return obj.GetHashCode();
}
}

View File

@@ -96,10 +96,13 @@ public class DrawningPropelledArtillery
protected DrawningPropelledArtillery(int drawningPropelledArtilleryWidth, int drawningPropelledArtilleryHeight):this() protected DrawningPropelledArtillery(int drawningPropelledArtilleryWidth, int drawningPropelledArtilleryHeight):this()
{ {
_drawningPropelledArtilleryWidth = drawningPropelledArtilleryWidth; this._drawningPropelledArtilleryWidth = drawningPropelledArtilleryWidth;
_drawningPropelledArtilleryHeight = drawningPropelledArtilleryHeight; this._drawningPropelledArtilleryHeight = drawningPropelledArtilleryHeight;
}
public DrawningPropelledArtillery(EntityPropelledArtillery propelledArtillery) : this()
{
EntityPropelledArtillery = new EntityPropelledArtillery(propelledArtillery.Speed, propelledArtillery.Weight, propelledArtillery.BodyColor);
} }
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>
@@ -270,8 +273,5 @@ public class DrawningPropelledArtillery
g.DrawEllipse(pen, _startPosX.Value + 93, _startPosY.Value + 78, 24, 24); g.DrawEllipse(pen, _startPosX.Value + 93, _startPosY.Value + 78, 24, 24);
g.FillRectangle(brush, _startPosX.Value + 0, _startPosY.Value + 65, 120, 13);// g.FillRectangle(brush, _startPosX.Value + 0, _startPosY.Value + 65, 120, 13);//
} }
} }

View File

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

View File

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

View File

@@ -18,6 +18,10 @@ public class DrawningSelfPropelledArtilleryUnit : DrawningPropelledArtillery
EntityPropelledArtillery = new EntitySelfPropelledArtilleryUnit(speed, weight, bodyColor, additionalColor, turretCannon, launchBattery); EntityPropelledArtillery = new EntitySelfPropelledArtilleryUnit(speed, weight, bodyColor, additionalColor, turretCannon, launchBattery);
//дописать //дописать
} }
public DrawningSelfPropelledArtilleryUnit(EntitySelfPropelledArtilleryUnit ship) : base(135, 105)
{
EntityPropelledArtillery = new EntitySelfPropelledArtilleryUnit(ship.Speed, ship.Weight, ship.BodyColor, ship.AdditionalColor, ship.TurretCannon, ship.LaunchBattery);
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {

View File

@@ -0,0 +1,50 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public static class ExtentionDrawningPropelledArtillery
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningPropelledArtillery? CreateDrawningPropelledArtillery(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityPropelledArtillery? propelledArtillery = EntitySelfPropelledArtilleryUnit.CreateEntitySelfPropelledArtilleryUnit(strs);
if (propelledArtillery != null)
{
return new DrawningSelfPropelledArtilleryUnit((EntitySelfPropelledArtilleryUnit)propelledArtillery);
}
propelledArtillery = EntityPropelledArtillery.CreateEntityPropelledArtillery(strs);
if (propelledArtillery != null)
{
return new DrawningPropelledArtillery(propelledArtillery);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningPropelledArtillery drawningPropelledArtillery)
{
string[]? array = drawningPropelledArtillery?.EntityPropelledArtillery?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -16,6 +16,10 @@ public class EntityPropelledArtillery
/// Основной цвет /// Основной цвет
/// </summary> /// </summary>
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
public void setBodyColor(Color color)
{
BodyColor = color;
}
/// <summary> /// <summary>
/// Шаг перемещения артеллерийской установки /// Шаг перемещения артеллерийской установки
/// </summary> /// </summary>
@@ -32,4 +36,26 @@ public class EntityPropelledArtillery
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityPropelledArtillery), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityPropelledArtillery? CreateEntityPropelledArtillery(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityPropelledArtillery))
{
return null;
}
return new EntityPropelledArtillery(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@@ -8,6 +8,10 @@ public class EntitySelfPropelledArtilleryUnit : EntityPropelledArtillery
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
/// <summary> /// <summary>
/// Признак - Башня с орудием /// Признак - Башня с орудием
/// </summary> /// </summary>
@@ -33,5 +37,28 @@ public class EntitySelfPropelledArtilleryUnit : EntityPropelledArtillery
TurretCannon = turretcannon; TurretCannon = turretcannon;
LaunchBattery = launchbattery; LaunchBattery = launchbattery;
} }
/// <summary>
/// Получение строк со значениями свойств продвинутого объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntitySelfPropelledArtilleryUnit), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
TurretCannon.ToString(), LaunchBattery.ToString()};
}
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntitySelfPropelledArtilleryUnit? CreateEntitySelfPropelledArtilleryUnit(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntitySelfPropelledArtilleryUnit))
{
return null;
}
return new EntitySelfPropelledArtilleryUnit(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,16 @@
using System.Runtime.Serialization;
namespace SelfPropelledArtilleryUnit.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

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

View File

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

View File

@@ -29,6 +29,14 @@
private void InitializeComponent() private void InitializeComponent()
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
maskedTextBox = new MaskedTextBox();
buttonAddPropelledArtillery = new Button();
buttonRefresh = new Button();
buttonRemovePropelledArtillery = new Button();
buttonGoToCheck = new Button();
buttonCreateCompany = new Button(); buttonCreateCompany = new Button();
panelStorage = new Panel(); panelStorage = new Panel();
buttonCollectionDel = new Button(); buttonCollectionDel = new Button();
@@ -38,19 +46,19 @@
radioButtonMassive = new RadioButton(); radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox(); textBoxCollectionName = new TextBox();
labelCollectionName = new Label(); labelCollectionName = new Label();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonRemovePropelledArtillery = new Button();
maskedTextBox = new MaskedTextBox();
buttonAddSelfPropelledArtilleryUnit = new Button();
buttonAddPropelledArtillery = new Button();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
panelCompanyTools = new Panel(); menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
panelCompanyTools.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@@ -60,13 +68,97 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(736, 0); groupBoxTools.Location = new Point(736, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 562); groupBoxTools.Size = new Size(200, 585);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonAddPropelledArtillery);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonRemovePropelledArtillery);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 343);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(188, 236);
panelCompanyTools.TabIndex = 9;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(0, 194);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(188, 23);
buttonSortByColor.TabIndex = 0;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(0, 168);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(188, 23);
buttonSortByType.TabIndex = 1;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.Click += buttonSortByType_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(0, 49);
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(188, 23);
maskedTextBox.TabIndex = 0;
//
// buttonAddPropelledArtillery
//
buttonAddPropelledArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddPropelledArtillery.Location = new Point(0, 3);
buttonAddPropelledArtillery.Name = "buttonAddPropelledArtillery";
buttonAddPropelledArtillery.Size = new Size(188, 40);
buttonAddPropelledArtillery.TabIndex = 1;
buttonAddPropelledArtillery.Text = "Добавление бронированной машины";
buttonAddPropelledArtillery.UseVisualStyleBackColor = true;
buttonAddPropelledArtillery.Click += buttonAddPropelledArtillery_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 140);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(188, 22);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// buttonRemovePropelledArtillery
//
buttonRemovePropelledArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemovePropelledArtillery.Location = new Point(0, 78);
buttonRemovePropelledArtillery.Name = "buttonRemovePropelledArtillery";
buttonRemovePropelledArtillery.Size = new Size(188, 24);
buttonRemovePropelledArtillery.TabIndex = 4;
buttonRemovePropelledArtillery.Text = "Удаление";
buttonRemovePropelledArtillery.UseVisualStyleBackColor = true;
buttonRemovePropelledArtillery.Click += buttonRemovePropelledArtillery_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(0, 108);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(188, 26);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonCreateCompany // buttonCreateCompany
// //
buttonCreateCompany.Location = new Point(6, 308); buttonCreateCompany.Location = new Point(6, 308);
@@ -159,72 +251,6 @@
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:"; labelCollectionName.Text = "Название коллекции:";
// //
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 185);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(188, 22);
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(0, 153);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(188, 26);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonRemovePropelledArtillery
//
buttonRemovePropelledArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemovePropelledArtillery.Location = new Point(0, 123);
buttonRemovePropelledArtillery.Name = "buttonRemovePropelledArtillery";
buttonRemovePropelledArtillery.Size = new Size(188, 24);
buttonRemovePropelledArtillery.TabIndex = 4;
buttonRemovePropelledArtillery.Text = "Удаление";
buttonRemovePropelledArtillery.UseVisualStyleBackColor = true;
buttonRemovePropelledArtillery.Click += buttonRemovePropelledArtillery_Click;
//
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(0, 95);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(188, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
maskedTextBox.MaskInputRejected += maskedTextBox_MaskInputRejected;
//
// buttonAddSelfPropelledArtilleryUnit
//
buttonAddSelfPropelledArtilleryUnit.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddSelfPropelledArtilleryUnit.Location = new Point(0, 49);
buttonAddSelfPropelledArtilleryUnit.Name = "buttonAddSelfPropelledArtilleryUnit";
buttonAddSelfPropelledArtilleryUnit.Size = new Size(188, 40);
buttonAddSelfPropelledArtilleryUnit.TabIndex = 2;
buttonAddSelfPropelledArtilleryUnit.Text = "Добавление самоходная арт. установки";
buttonAddSelfPropelledArtilleryUnit.UseVisualStyleBackColor = true;
buttonAddSelfPropelledArtilleryUnit.Click += buttonAddSelfPropelledArtilleryUnit_Click_1;
//
// buttonAddPropelledArtillery
//
buttonAddPropelledArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddPropelledArtillery.Location = new Point(0, 3);
buttonAddPropelledArtillery.Name = "buttonAddPropelledArtillery";
buttonAddPropelledArtillery.Size = new Size(188, 40);
buttonAddPropelledArtillery.TabIndex = 1;
buttonAddPropelledArtillery.Text = "Добавление бронированной машины";
buttonAddPropelledArtillery.UseVisualStyleBackColor = true;
buttonAddPropelledArtillery.Click += buttonAddPropelledArtillery_Click_1;
//
// comboBoxSelectorCompany // comboBoxSelectorCompany
// //
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@@ -240,42 +266,74 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(736, 562); pictureBox.Size = new Size(736, 585);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// panelCompanyTools // menuStrip
// //
panelCompanyTools.Controls.Add(maskedTextBox); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
panelCompanyTools.Controls.Add(buttonAddPropelledArtillery); menuStrip.Location = new Point(0, 0);
panelCompanyTools.Controls.Add(buttonAddSelfPropelledArtilleryUnit); menuStrip.Name = "menuStrip";
panelCompanyTools.Controls.Add(buttonRefresh); menuStrip.Size = new Size(936, 24);
panelCompanyTools.Controls.Add(buttonRemovePropelledArtillery); menuStrip.TabIndex = 2;
panelCompanyTools.Controls.Add(buttonGoToCheck); menuStrip.Text = "menuStrip1";
panelCompanyTools.Enabled = false; //
panelCompanyTools.Location = new Point(6, 343); // файлToolStripMenuItem
panelCompanyTools.Name = "panelCompanyTools"; //
panelCompanyTools.Size = new Size(200, 213); файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
panelCompanyTools.TabIndex = 9; файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
// //
// FormPropelledArtilleryCollection // FormPropelledArtilleryCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(936, 562); ClientSize = new Size(936, 609);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormPropelledArtilleryCollection"; Name = "FormPropelledArtilleryCollection";
Text = "Коллекция установок"; Text = "Коллекция установок";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
panelCompanyTools.ResumeLayout(false); menuStrip.ResumeLayout(false);
panelCompanyTools.PerformLayout(); menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -284,7 +342,6 @@
private Button buttonAddPropelledArtillery; private Button buttonAddPropelledArtillery;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private MaskedTextBox maskedTextBox; private MaskedTextBox maskedTextBox;
private Button buttonAddSelfPropelledArtilleryUnit;
private PictureBox pictureBox; private PictureBox pictureBox;
private Button buttonRefresh; private Button buttonRefresh;
private Button buttonGoToCheck; private Button buttonGoToCheck;
@@ -299,5 +356,13 @@
private Button buttonCollectionDel; private Button buttonCollectionDel;
private ListBox listBoxCollection; private ListBox listBoxCollection;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@@ -1,14 +1,8 @@
using SelfPropelledArtilleryUnit.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using SelfPropelledArtilleryUnit.CollectionGenericObjects;
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using System; using SelfPropelledArtilleryUnit.Exceptions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SelfPropelledArtilleryUnit; namespace SelfPropelledArtilleryUnit;
@@ -24,13 +18,20 @@ public partial class FormPropelledArtilleryCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormPropelledArtilleryCollection() public FormPropelledArtilleryCollection(ILogger<FormPropelledArtilleryCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@@ -43,82 +44,45 @@ public partial class FormPropelledArtilleryCollection : Form
{ {
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
} }
private void buttonAddPropelledArtillery_Click_1(object sender, EventArgs e) => CreateObject(nameof(DrawningPropelledArtillery));
private void buttonAddPropelledArtillery_Click(object sender, EventArgs e)
private void buttonAddSelfPropelledArtilleryUnit_Click_1(object sender, EventArgs e) => CreateObject(nameof(DrawningSelfPropelledArtilleryUnit)); {
FormPropelledArtilleryConfig form = new();
// /// <summary> // TODO передать метод
///// Добавление Бронированная машина form.Show();
///// </summary> form.AddEvent(SetPropelledArtillery);
///// <param name="sender"></param> }
///// <param name="e"></param>
//private void ButtonAddPropelledArtillery_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningPropelledArtillery));
// /// <summary>
// /// Добавление Самоходная арт. установка
// /// </summary>
// /// <param name="sender"></param>
// /// <param name="e"></param>
// private void ButtonAddSelfPropelledArtilleryUnit_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSelfPropelledArtilleryUnit));
/// <summary> /// <summary>
/// Создание объекта класса-перемещения /// Создание объекта класса-перемещения
/// </summary> /// </summary>
/// <param name="type">Тип создаваемого объекта</param> /// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type) private void SetPropelledArtillery(DrawningPropelledArtillery propelledArtillery)
{ {
if (_company == null) try
{ {
return; if (_company == null || propelledArtillery == null)
} {
Random random = new();
DrawningPropelledArtillery drawningPropelledArtillery;
switch (type)
{
case nameof(DrawningPropelledArtillery):
drawningPropelledArtillery = new DrawningPropelledArtillery(random.Next(100, 300),
random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningSelfPropelledArtilleryUnit):
// TODO вызов диалогового окна для выбора цвета (made)
drawningPropelledArtillery = new DrawningSelfPropelledArtilleryUnit(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return; return;
}
if (_company + propelledArtillery != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + propelledArtillery.GetDataForSave());
}
} }
if (_company + drawningPropelledArtillery != -1) catch (ObjectNotFoundException) { }
{ catch (CollectionOverflowException ex)
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} catch (ObjectIsEqualException ex)
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{ {
color = dialog.Color; MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
return color;
}
private void maskedTextBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
} }
/// <summary> /// <summary>
@@ -137,14 +101,19 @@ public partial class FormPropelledArtilleryCollection : Form
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) try
{ {
MessageBox.Show("Объект удален"); if (_company - pos != null)
pictureBox.Image = _company.Show(); {
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@@ -162,26 +131,27 @@ public partial class FormPropelledArtilleryCollection : Form
DrawningPropelledArtillery? propelledartillery = null; DrawningPropelledArtillery? propelledartillery = null;
int counter = 100; int counter = 100;
while (propelledartillery == null) try
{ {
propelledartillery = _company.GetRandomObject(); while (propelledartillery == null)
counter--;
if (counter <= 0)
{ {
break; propelledartillery = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
} }
SelfPropelledArtilleryUnit form = new()
{
SetPropelledArtillery = propelledartillery
};
form.ShowDialog();
} }
catch (Exception ex)
if (propelledartillery == null)
{ {
return; MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
SelfPropelledArtilleryUnit form = new()
{
SetPropelledArtillery = propelledartillery
};
form.ShowDialog();
} }
/// <summary> /// <summary>
@@ -206,24 +176,32 @@ public partial class FormPropelledArtilleryCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
CollectionType collectionType = CollectionType.None; try
if (radioButtonMassive.Checked)
{ {
collectionType = CollectionType.Massive; 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);
} }
else if (radioButtonList.Checked) catch (Exception ex)
{ {
collectionType = CollectionType.List; _logger.LogError("Ошибка: {Message}", ex.Message);
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
} }
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
{ {
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@@ -241,12 +219,20 @@ public partial class FormPropelledArtilleryCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) try
{ {
return; 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);
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
@@ -272,6 +258,64 @@ public partial class FormPropelledArtilleryCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
ComparePropelledArtillery(new DrawningPropelledArtilleryCompareByType());
}
private void ComparePropelledArtillery(IComparer<DrawningPropelledArtillery?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
ComparePropelledArtillery(new DrawningPropelledArtilleryCompareByColor());
}
} }

View File

@@ -117,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </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>128, 21</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root> </root>

View File

@@ -0,0 +1,366 @@
namespace SelfPropelledArtilleryUnit
{
partial class FormPropelledArtilleryConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxLaunchBattery = new CheckBox();
checkBoxTurretCannon = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxLaunchBattery);
groupBoxConfig.Controls.Add(checkBoxTurretCannon);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(575, 260);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(276, 22);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(244, 141);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
groupBoxColors.Enter += groupBoxColors_Enter;
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(182, 89);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(33, 32);
panelPurple.TabIndex = 4;
panelPurple.MouseDown += Panel_MouseDown;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(182, 37);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(33, 32);
panelYellow.TabIndex = 1;
panelYellow.MouseDown += Panel_MouseDown;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(130, 89);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(33, 32);
panelBlack.TabIndex = 6;
panelBlack.MouseDown += Panel_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(130, 37);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(33, 32);
panelBlue.TabIndex = 2;
panelBlue.MouseDown += Panel_MouseDown;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(82, 89);
panelGray.Name = "panelGray";
panelGray.Size = new Size(33, 32);
panelGray.TabIndex = 5;
panelGray.MouseDown += Panel_MouseDown;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(31, 89);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(33, 32);
panelWhite.TabIndex = 3;
panelWhite.MouseDown += Panel_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(82, 37);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(33, 32);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += Panel_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(31, 37);
panelRed.Name = "panelRed";
panelRed.Size = new Size(33, 32);
panelRed.TabIndex = 0;
panelRed.MouseDown += Panel_MouseDown;
//
// checkBoxLaunchBattery
//
checkBoxLaunchBattery.AutoSize = true;
checkBoxLaunchBattery.Location = new Point(12, 169);
checkBoxLaunchBattery.Name = "checkBoxLaunchBattery";
checkBoxLaunchBattery.Size = new Size(215, 19);
checkBoxLaunchBattery.TabIndex = 7;
checkBoxLaunchBattery.Text = "Признак - Залповая батарея сзади";
checkBoxLaunchBattery.UseVisualStyleBackColor = true;
//
// checkBoxTurretCannon
//
checkBoxTurretCannon.AutoSize = true;
checkBoxTurretCannon.Location = new Point(12, 144);
checkBoxTurretCannon.Name = "checkBoxTurretCannon";
checkBoxTurretCannon.Size = new Size(181, 19);
checkBoxTurretCannon.TabIndex = 6;
checkBoxTurretCannon.Text = "Признак - Башня с орудием";
checkBoxTurretCannon.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(80, 88);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(74, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 90);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(80, 59);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(74, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 61);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(406, 190);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(114, 32);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(276, 190);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(115, 32);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(586, 12);
panelObject.Name = "panelObject";
panelObject.Size = new Size(200, 205);
panelObject.TabIndex = 1;
panelObject.DragDrop += panelObject_DragDrop;
panelObject.DragEnter += panelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(101, 10);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(80, 36);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(20, 10);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(80, 36);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(20, 49);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(161, 138);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(589, 223);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(99, 25);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(713, 224);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormPropelledArtilleryConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(863, 260);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxConfig);
Name = "FormPropelledArtilleryConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private CheckBox checkBoxTurretCannon;
private CheckBox checkBoxLaunchBattery;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelWhite;
private Panel panelGreen;
private Panel panelRed;
private Panel panelObject;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,182 @@
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SelfPropelledArtilleryUnit;
//SelfPropelledArtilleryUnit
//PropelledArtillery
public partial class FormPropelledArtilleryConfig : Form
{
public FormPropelledArtilleryConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Объект - прорисовка автомобиля
/// </summary>
private DrawningPropelledArtillery? _propelledArtillery;
/// <summary>
/// Событие для передачи объекта
/// </summary>
public event Action<DrawningPropelledArtillery>? PropelledArtilleryDelegate;
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="propelledArtilleryDelegate"></param>
public void AddEvent(Action<DrawningPropelledArtillery> propelledArtilleryDelegate)
{
PropelledArtilleryDelegate += propelledArtilleryDelegate;
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_propelledArtillery?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_propelledArtillery?.SetPosition(15, 15);
_propelledArtillery?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_propelledArtillery = new DrawningPropelledArtillery((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.Aqua);
break;
case "labelModifiedObject":
_propelledArtillery = new DrawningSelfPropelledArtilleryUnit((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxTurretCannon.Checked, checkBoxLaunchBattery.Checked);
break;
}
DrawObject();
}
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_propelledArtillery != null)
{
_propelledArtillery.EntityPropelledArtillery.setBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_propelledArtillery.EntityPropelledArtillery is EntitySelfPropelledArtilleryUnit _selfPropelledArtilleryUnit)
{
_selfPropelledArtilleryUnit.setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_propelledArtillery is DrawningSelfPropelledArtilleryUnit)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor ?? Color.White, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_propelledArtillery != null)
{
PropelledArtilleryDelegate?.Invoke(_propelledArtillery);
Close();
}
}
private void groupBoxColors_Enter(object sender, EventArgs e)
{
}
}

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

@@ -1,4 +1,10 @@
namespace SelfPropelledArtilleryUnit using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using SelfPropelledArtilleryUnit;
using Microsoft.Extensions.Configuration;
namespace ProjectWarmlyShip
{ {
internal static class Program internal static class Program
{ {
@@ -11,7 +17,31 @@ namespace SelfPropelledArtilleryUnit
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormPropelledArtilleryCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormPropelledArtilleryCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormPropelledArtilleryCollection>()
.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,11 @@
using SelfPropelledArtilleryUnit.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit
{
public delegate void PropelledArtilleryDelegate(DrawningPropelledArtillery propelledArtillery);
}

View File

@@ -57,45 +57,6 @@ namespace SelfPropelledArtilleryUnit
_drawningPropelledArtillery.DrawTransport(gr); _drawningPropelledArtillery.DrawTransport(gr);
pictureBoxSelfPropelledArtilleryUnit.Image = bmp; pictureBoxSelfPropelledArtilleryUnit.Image = bmp;
} }
//private void CreateObject(string type)
//{
// Random random = new();
// switch (type)
// {
// case nameof(DrawningPropelledArtillery):
// _drawningPropelledArtillery = new DrawningPropelledArtillery(random.Next(100, 300), random.Next(1000, 3000),
// Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
// break;
// case nameof(DrawningSelfPropelledArtilleryUnit):
// _drawningPropelledArtillery = new DrawningSelfPropelledArtilleryUnit(random.Next(100, 300), random.Next(1000, 3000),
// Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
// Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
// Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
// break;
// default:
// return;
// }
// _drawningPropelledArtillery.SetPictureSize(pictureBoxSelfPropelledArtilleryUnit.Width, pictureBoxSelfPropelledArtilleryUnit.Height);
// _drawningPropelledArtillery.SetPosition(random.Next(10, 100), random.Next(10, 100));
// _strategy = null;
// comboBoxStrategy.Enabled = true;
// Draw();
//}
///// <summary>
///// Обработка нажатия кнопки "Создать самоходную арт.установку"
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private void buttonCreateSelfPropelledArtilleryUnit_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSelfPropelledArtilleryUnit));
///// <summary>
///// Обработка нажатия кнопки "Создать бронированную машину"
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private void buttonCreatePropelledArtillery_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningPropelledArtillery));
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {

View File

@@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@@ -23,4 +34,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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