6 Commits

Author SHA1 Message Date
f27e0bf714 8 лабораторная работа 2024-10-16 00:28:16 +03:00
4851fb744c 7 лабораторная работа 2024-10-15 22:25:13 +03:00
613d0daa2a 6 лабораторная работа 2024-10-08 15:33:26 +03:00
cleverman1337
a7382f2382 Лабораторная работа №5 2024-06-03 22:22:58 +04:00
cleverman1337
6dcd4ac6d9 LabWork04 2024-05-16 09:36:27 +04:00
cleverman1337
87a93c30f8 LabWork03 2024-05-02 09:56:31 +04:00
30 changed files with 2100 additions and 186 deletions

View File

@@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
@@ -32,7 +33,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@@ -45,7 +46,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
@@ -56,7 +57,18 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTank tank)
{
return company._collection.Insert(tank);
try
{
return company._collection.Insert(tank, 0, new DrawningTankEqutables());
}
catch (ObjectAlreadyInCollectionException)
{
return -1;
}
catch (CollectionOverflowException)
{
return -1;
}
}
/// <summary>
@@ -65,11 +77,10 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningTank? operator -(AbstractCompany company, int position)
public static DrawningTank operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
return company._collection.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
@@ -88,23 +99,35 @@ public abstract class AbstractCompany
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
DrawBackground(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningTank? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningTank? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTank?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
protected abstract void DrawBackground(Graphics g);
/// <summary>
/// Расстановка объектов

View File

@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
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

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// Список
/// </summary>
List = 2
}

View File

@@ -1,4 +1,5 @@
using System;
using SelfPropelledArtilleryUnit.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -14,21 +15,22 @@ public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@@ -36,7 +38,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@@ -51,4 +53,20 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции (какого типа будет коллекция)
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов(элементов) коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

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

View File

@@ -1,4 +1,6 @@
using System;
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -9,15 +11,14 @@ namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -34,9 +35,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
/// <summary>
/// Конструктор
/// </summary>
public CollectionType GetCollectionType => CollectionType.Massive;
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
@@ -45,13 +45,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= _collection.Length)
{
return null;
}
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawningTank?>? comparer = null)
{
for (int i = 0; i < _collection.Length; i++)
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
@@ -59,44 +68,76 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
}
public bool Insert(T obj, int position)
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position, IEqualityComparer<DrawningTank?>? comparer = null)
{
if (position < 0 || position >= _collection.Length)
return false;
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если такой объект есть в коллекции
// TODO выброс ошибки, если переполнение
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningTank), (obj as DrawningTank)))
{
throw new ObjectAlreadyInCollectionException(i);
}
}
if (_collection[position] == null)
{
_collection[position] = obj;
return true;
return position;
}
for (int i = position; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
for (int i = 0; i < position; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
return false;
}
public T? Remove(int position)
for (int i = position + 1; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
if (position < 0 || position >= _collection.Length || _collection[position] == null) // проверка позиции и наличия объекта
return null;
T? temp = _collection[position];
if (position < 0 || position >= _collection.Length)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? obj = _collection[position];
_collection[position] = null;
return temp;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@@ -0,0 +1,209 @@
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class StorageCollection<T>
where T : DrawningTank
{
/// <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 _separatorItem = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(CollectionInfo info)
{
if (info == null || _storages.ContainsKey(info))
{
return;
}
if (info.CollectionType == CollectionType.Massive)
{
_storages.Add(info, new MassiveGenericObjects<T>());
}
if (info.CollectionType == CollectionType.List)
{
_storages.Add(info, new ListGenericObjects<T>());
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(CollectionInfo info)
{
if (info == null || !_storages.ContainsKey(info))
{
return;
}
_storages.Remove(info);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[CollectionInfo info]
{
get
{
if (_storages.ContainsKey(info))
{
return _storages[info];
}
return null;
}
}
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
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(_separatorItem);
}
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new(filename))
{
string line = sr.ReadLine();
if (line == null || line.Length == 0)
{
throw new FileFormatException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
while ((line = sr.ReadLine()) != null)
{
string[] record = line.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("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTank() is T warship)
{
try
{
if (collection.Insert(warship, new DrawningTankEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new OverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", 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

@@ -15,7 +15,7 @@ public class TankSharingService : AbstractCompany
{
}
protected override void DrawBackgound(Graphics g)
protected override void DrawBackground(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;

View File

@@ -20,7 +20,10 @@ public class DrawningArtillery : DrawningTank
{
EntityTank = new EntityArtillery(speed, weight, bodyColor, additionalColor, cannon, rocket);
}
public DrawningArtillery(EntityArtillery tank) : base(130, 20)
{
EntityTank = tank;
}
public override void DrawTransport(Graphics g)
{

View File

@@ -76,6 +76,10 @@ public class DrawningTank
_drawningTankWidth = drawningTankWidth;
_pictureHeight = drawningTankHeight;
}
public DrawningTank(EntityTank tank)
{
EntityTank = tank;
}
/// <summary>
/// Установка границ поля
/// </summary>

View File

@@ -0,0 +1,44 @@
using SelfPropelledArtilleryUnit.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawningTankCompareByColor : IComparer<DrawningTank?>
{
public int Compare(DrawningTank? x, DrawningTank? y)
{
// TODO прописать логику сравения по цветам, скорости, весу
if (x == null || x.EntityTank == null)
{
return 1;
}
if (y == null || y.EntityTank == null)
{
return -1;
}
var bodyColorCompare = y.EntityTank.BodyColor.Name.CompareTo(x.EntityTank.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x is DrawningArtillery && y is DrawningArtillery)
{
var additionalColorCompare = (y.EntityTank as EntityArtillery).AdditionalColor.Name.CompareTo(
(x.EntityTank as EntityArtillery).AdditionalColor.Name);
if (additionalColorCompare != 0)
{
return additionalColorCompare;
}
}
var speedCompare = y.EntityTank.Speed.CompareTo(x.EntityTank.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTank.Weight.CompareTo(x.EntityTank.Weight);
}
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.Drawnings;
public class DrawningTankCompareByType : IComparer<DrawningTank?>
{
public int Compare(DrawningTank? x, DrawningTank? y)
{
if (x == null || x.EntityTank == null)
{
return 1;
}
if (y == null || y.EntityTank == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return y.GetType().Name.CompareTo(x.GetType().Name);
}
var speedCompare = y.EntityTank.Speed.CompareTo(x.EntityTank.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityTank.Weight.CompareTo(x.EntityTank.Weight);
}
}

View File

@@ -0,0 +1,65 @@
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 DrawningTankEqutables : IEqualityComparer<DrawningTank?>
{
public bool Equals(DrawningTank? x, DrawningTank? y)
{
if (x == null || x.EntityTank == null)
{
return false;
}
if (y == null || y.EntityTank == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTank.Speed != y.EntityTank.Speed)
{
return false;
}
if (x.EntityTank.Weight != y.EntityTank.Weight)
{
return false;
}
if (x.EntityTank.BodyColor != y.EntityTank.BodyColor)
{
return false;
}
if (x is DrawningArtillery && y is DrawningArtillery)
{
// TODO доделать логику сравнения дополнительных параметров
if ((x.EntityTank as EntityArtillery)?.AdditionalColor !=
(y.EntityTank as EntityArtillery)?.AdditionalColor)
{
return false;
}
if ((x.EntityTank as EntityArtillery)?.Rocket !=
(y.EntityTank as EntityArtillery)?.Rocket)
{
return false;
}
if ((x.EntityTank as EntityArtillery)?.Cannon !=
(y.EntityTank as EntityArtillery)?.Cannon)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTank? obj)
{
return obj.GetHashCode();
}
}

View File

@@ -0,0 +1,51 @@
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 ExtentionDrawningTank
{
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строк характеристик
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningTank? CreateDrawningTank(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTank? tank = EntityArtillery.CreateEntityArtillery(strs);
if (tank != null && tank is EntityArtillery tankA)
{
return new DrawningArtillery(tankA);
}
tank = EntityTank.CreateEntityTank(strs);
if (tank != null)
{
return new DrawningTank(tank);
}
return null;
}
/// <summary>
/// Подготовка данных для сохранения в файл
/// </summary>
/// <param name="drawningTank"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningTank drawningTank)
{
string[]? array = drawningTank?.EntityTank?.GetStringRepresentation();
if (array == null) { return string.Empty; }
return string.Join(_separatorForObject, array);
}
}

View File

@@ -9,6 +9,10 @@ public class EntityArtillery : EntityTank
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color)
{
AdditionalColor = color;
}
/// <summary>
/// Признак (опция) наличия пушки
/// </summary>
@@ -34,6 +38,28 @@ public class EntityArtillery : EntityTank
Cannon = cannon;
Rocket = rocket;
}
/// <summary>
/// Получение строк характеристик
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityArtillery), Speed.ToString(), Weight.ToString(), BodyColor.Name,
AdditionalColor.Name, Cannon.ToString(), Rocket.ToString() };
}
/// <summary>
/// Создание объекта по строкам характеристик
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityArtillery? CreateEntityArtillery(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityArtillery)) { return null; }
return new EntityArtillery(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

@@ -8,16 +8,19 @@ public class EntityTank
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; set; }
public int Speed { get; set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; set; }
public double Weight { get; set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; set; }
public Color BodyColor { get; set; }
public void SetBodyColor(Color color)
{
BodyColor = color;
}
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
@@ -32,5 +35,22 @@ public class EntityTank
BodyColor = bodyColor;
}
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTank), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта по строкам характеристик
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTank? CreateEntityTank(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTank)) { return null; }
return new EntityTank(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.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace SelfPropelledArtilleryUnit.Exceptions;
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count : " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@@ -0,0 +1,25 @@
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]
internal class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.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 exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

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;
[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,52 +29,127 @@
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddTank = new Button();
buttonRefresh = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonGoToCheak = new Button();
buttonRemoveTank = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddTank = new Button();
buttonAddArtillery = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonRefresh);
groupBoxTools.Controls.Add(buttonGoToCheak);
groupBoxTools.Controls.Add(buttonRemoveTank);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddTank);
groupBoxTools.Controls.Add(buttonAddArtillery);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(715, 0);
groupBoxTools.Location = new Point(715, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 508);
groupBoxTools.Size = new Size(200, 528);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTank);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheak);
panelCompanyTools.Controls.Add(buttonRemoveTank);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 297);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 228);
panelCompanyTools.TabIndex = 9;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(12, 196);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(170, 23);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(12, 165);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(170, 25);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddTank
//
buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTank.Location = new Point(12, 0);
buttonAddTank.Name = "buttonAddTank";
buttonAddTank.Size = new Size(170, 30);
buttonAddTank.TabIndex = 2;
buttonAddTank.Text = "Добавление танка";
buttonAddTank.UseVisualStyleBackColor = true;
buttonAddTank.Click += ButtonAddTank_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(12, 423);
buttonRefresh.Location = new Point(12, 128);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(176, 41);
buttonRefresh.Size = new Size(170, 23);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(12, 36);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(176, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonGoToCheak
//
buttonGoToCheak.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheak.Location = new Point(12, 337);
buttonGoToCheak.Location = new Point(12, 97);
buttonGoToCheak.Name = "buttonGoToCheak";
buttonGoToCheak.Size = new Size(176, 41);
buttonGoToCheak.Size = new Size(170, 25);
buttonGoToCheak.TabIndex = 5;
buttonGoToCheak.Text = "Передать на тесты";
buttonGoToCheak.UseVisualStyleBackColor = true;
@@ -83,44 +158,105 @@
// buttonRemoveTank
//
buttonRemoveTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTank.Location = new Point(12, 215);
buttonRemoveTank.Location = new Point(12, 64);
buttonRemoveTank.Name = "buttonRemoveTank";
buttonRemoveTank.Size = new Size(176, 41);
buttonRemoveTank.Size = new Size(170, 27);
buttonRemoveTank.TabIndex = 4;
buttonRemoveTank.Text = "Удалить танк";
buttonRemoveTank.UseVisualStyleBackColor = true;
buttonRemoveTank.Click += ButtonRemoveTank_Click;
//
// maskedTextBoxPosition
// buttonCreateCompany
//
maskedTextBoxPosition.Location = new Point(12, 186);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(176, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
buttonCreateCompany.Location = new Point(5, 267);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(189, 24);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// buttonAddTank
// panelStorage
//
buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTank.Location = new Point(12, 82);
buttonAddTank.Name = "buttonAddTank";
buttonAddTank.Size = new Size(176, 41);
buttonAddTank.TabIndex = 2;
buttonAddTank.Text = "Добавление танка";
buttonAddTank.UseVisualStyleBackColor = true;
buttonAddTank.Click += ButtonAddTank_Click;
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(194, 213);
panelStorage.TabIndex = 7;
//
// buttonAddArtillery
// buttonCollectionDel
//
buttonAddArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddArtillery.Location = new Point(12, 129);
buttonAddArtillery.Name = "buttonAddArtillery";
buttonAddArtillery.Size = new Size(176, 41);
buttonAddArtillery.TabIndex = 1;
buttonAddArtillery.Text = "Добавление сау";
buttonAddArtillery.UseVisualStyleBackColor = true;
buttonAddArtillery.Click += ButtonAddArtillery_Click;
buttonCollectionDel.Location = new Point(5, 186);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(189, 24);
buttonCollectionDel.TabIndex = 7;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(6, 115);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(185, 64);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(2, 81);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(189, 24);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(78, 57);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(5, 57);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 30);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(188, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(25, 12);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(125, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
//
@@ -128,7 +264,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(12, 33);
comboBoxSelectorCompany.Location = new Point(6, 238);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(182, 23);
comboBoxSelectorCompany.TabIndex = 0;
@@ -137,25 +273,75 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(715, 508);
pictureBox.Size = new Size(715, 528);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
pictureBox.Click += pictureBox_Click;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(915, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// FormTankCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(915, 508);
ClientSize = new Size(915, 552);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTankCollection";
Text = "Коллекция сау";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -163,11 +349,28 @@
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddTank;
private Button buttonAddArtillery;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonRemoveTank;
private Button buttonRefresh;
private Button buttonGoToCheak;
private Panel panelStorage;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Button buttonCreateCompany;
private Button buttonCollectionDel;
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,7 +1,8 @@

using Microsoft.Extensions.Logging;
using NLog;
using SelfPropelledArtilleryUnit.CollectionGenericObjects;
using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit;
@@ -11,13 +12,16 @@ public partial class FormTankCollection : Form
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly StorageCollection<DrawningTank> _storageCollection;
private readonly Microsoft.Extensions.Logging.ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormTankCollection()
public FormTankCollection(ILogger<FormTankCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
@@ -28,72 +32,57 @@ public partial class FormTankCollection : Form
private void comboBoxSelectorCompany_SelectedIndexChanged_1(object sender, EventArgs e)
{
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TankSharingService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningTank>());
break;
}
panelCompanyTools.Enabled = false;
}
private void CreateObject(string type)
private void ButtonAddTank_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
FormTankConfig form = new();
form.AddEvent(SetTank);
form.Show();
}
Random random = new();
DrawningTank drawningTank;
switch (type)
/// <summary>
/// Добавление танка в коллекцию
/// </summary>
/// <param name="tank"></param>
private void SetTank(DrawningTank? tank)
{
try
{
case nameof(DrawningTank):
drawningTank = new DrawningTank(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningArtillery):
// TODO вызов диалогового окна для выбора цвета
drawningTank = new DrawningArtillery(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:
if (_company == null || tank == null)
{
return;
}
}
if (_company + drawningTank !=-1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + tank != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + tank.GetDataForSave());
}
else
{
MessageBox.Show("Такой объект уже есть в коллекции");
}
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
/// <summary>
/// Получение цвета
/// Удаление объекта
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void ButtonAddTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank));
private void ButtonAddArtillery_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningArtillery));
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveTank_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
@@ -107,14 +96,25 @@ public partial class FormTankCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show();
}
}
else
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
}
@@ -148,8 +148,6 @@ public partial class FormTankCollection : Form
};
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
@@ -161,4 +159,185 @@ public partial class FormTankCollection : Form
pictureBox.Image = _company.Show();
}
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(collectionInfo);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningTank>? collection = _storageCollection[collectionInfo];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TankSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
private void pictureBox_Click(object sender, EventArgs e)
{
}
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void 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);
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTanks(new DrawningTankCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTanks(new DrawningTankCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareTanks(IComparer<DrawningTank?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root>

View File

@@ -0,0 +1,357 @@
namespace SelfPropelledArtilleryUnit
{
partial class FormTankConfig
{
/// <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();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxRocket = new CheckBox();
checkBoxCannon = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxRocket);
groupBoxConfig.Controls.Add(checkBoxCannon);
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, 450);
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(panelGreen);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(246, 12);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(217, 113);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(129, 65);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(26, 25);
panelPurple.TabIndex = 4;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(129, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(26, 25);
panelYellow.TabIndex = 1;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(88, 65);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(26, 25);
panelBlack.TabIndex = 6;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(88, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(26, 25);
panelBlue.TabIndex = 2;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(47, 65);
panelGray.Name = "panelGray";
panelGray.Size = new Size(26, 25);
panelGray.TabIndex = 5;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(47, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(26, 25);
panelGreen.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(6, 65);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(26, 25);
panelWhite.TabIndex = 3;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(6, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(26, 25);
panelRed.TabIndex = 0;
//
// checkBoxRocket
//
checkBoxRocket.AutoSize = true;
checkBoxRocket.Location = new Point(19, 122);
checkBoxRocket.Name = "checkBoxRocket";
checkBoxRocket.Size = new Size(231, 19);
checkBoxRocket.TabIndex = 7;
checkBoxRocket.Text = "Признак наличия залповой устаноки";
checkBoxRocket.UseVisualStyleBackColor = true;
//
// checkBoxCannon
//
checkBoxCannon.AutoSize = true;
checkBoxCannon.Location = new Point(20, 93);
checkBoxCannon.Name = "checkBoxCannon";
checkBoxCannon.Size = new Size(163, 19);
checkBoxCannon.TabIndex = 6;
checkBoxCannon.Text = "Признак наличия пушки";
checkBoxCannon.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(77, 48);
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, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 48);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(26, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(77, 19);
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, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 19);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(59, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(363, 156);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(100, 23);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(246, 156);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(100, 23);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(16, 77);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(193, 91);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(597, 181);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 23);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(715, 181);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(581, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(225, 179);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(134, 19);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(75, 23);
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(16, 19);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(75, 23);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
//
// FormLocomotiveConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(818, 450);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormLocomotiveConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private Label labelWeight;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxRocket;
private CheckBox checkBoxCannon;
private GroupBox groupBoxColors;
private Panel panelRed;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,137 @@
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;
public partial class FormTankConfig : Form
{
private DrawningTank? _tank;
private event Action<DrawningTank>? TankDelegate;
public FormTankConfig()
{
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();
}
public void AddEvent(Action<DrawningTank> tankDelegate)
{
TankDelegate += tankDelegate;
}
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_tank?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_tank?.SetPosition(5, 5);
_tank?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_tank = new DrawningTank((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_tank = new DrawningArtillery((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxCannon.Checked, checkBoxRocket.Checked);
break;
}
labelBodyColor.BackColor = Color.Empty;
labelAdditionalColor.BackColor = Color.Empty;
DrawObject();
}
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
//смена цветов
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_tank != null)
{
_tank.EntityTank.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_tank != null && _tank is DrawningArtillery)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_tank != null && _tank.EntityTank is EntityArtillery _artillery)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
_artillery.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_tank != null)
{
TankDelegate?.Invoke(_tank);
Close();
}
}
}

View File

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

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using NLog.Extensions.Logging;
namespace SelfPropelledArtilleryUnit
{
internal static class Program
@@ -10,8 +15,21 @@ namespace SelfPropelledArtilleryUnit
{
// 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 FormTankCollection());
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTankCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTankCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@@ -8,6 +8,13 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="NLog" Version="5.3.4" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.14" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +30,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,13 @@
using SelfPropelledArtilleryUnit.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit;
/// <summary>
/// Делегат передачи объекта класса-прорисовки
/// </summary>
/// <param name="tank"></param>
public delegate void TankDelegate(DrawningTank tank);

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="locomotivelog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>