9 Commits
Lab05 ... Lab08

Author SHA1 Message Date
84e4affbde final 2024-06-05 13:22:48 +04:00
e971b264e6 LAB08 2024-06-05 12:32:48 +04:00
93274b9a00 переделал метод прорисовки заднего фона 2024-05-21 03:46:06 +04:00
ef1bec9f3c переделал метод прорисовки заднего фона 2024-05-21 03:45:30 +04:00
6ead7f2b69 finish 2024-05-21 03:28:00 +04:00
5e46d4770d 1 2024-05-21 03:17:11 +04:00
1dc111bb61 123 2024-05-21 01:53:54 +04:00
c61f10fa34 Lab06 Finish 2024-05-21 01:03:29 +04:00
ed6631e1ea Class finish 2024-05-21 00:47:54 +04:00
28 changed files with 1157 additions and 357 deletions

View File

@@ -8,6 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -1,9 +0,0 @@
using AirBomber.Drawnings;
namespace AirBomber;
/// <summary>
/// Делегар передачи объекта класса прорисовки
/// </summary>
/// <param name="airplane"></param>
public delegate void AirPlaneDelegate(DrawningAirPlane airplane);

View File

@@ -40,7 +40,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@@ -53,7 +53,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
@@ -62,9 +62,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="boat">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningAirPlane boat)
public static int operator +(AbstractCompany company, DrawningAirPlane airPlane)
{
return company._collection?.Insert(boat) ?? -1;
return company._collection?.Insert(airPlane, new DrawningAirPlaneEqutables()) ?? -1;
}
/// <summary>
@@ -101,8 +101,13 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningAirPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningAirPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;
@@ -118,4 +123,6 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}
public void Sort(IComparer<DrawningAirPlane?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@@ -32,10 +32,12 @@ public class AirPlaneSharingService : AbstractCompany
int offsetX = 10, offsetY = -12;
int x = _pictureWidth - _placeSizeWidth, y = offsetY;
numRows = 0;
while (y + _placeSizeHeight <= _pictureHeight)
int adjustedHeight = _pictureHeight - (_placeSizeHeight + 5 + offsetY);
while (y + _placeSizeHeight <= adjustedHeight)
{
int numCols = 0;
int initialX = x; // сохраняем начальное значение x
int initialX = x;
while (x >= 0)
{
numCols++;
@@ -45,12 +47,13 @@ public class AirPlaneSharingService : AbstractCompany
x -= _placeSizeWidth + 2;
}
numRows++;
x = initialX; // возвращаем x к начальному значению после завершения строки
x = initialX;
y += _placeSizeHeight + 5 + offsetY;
}
numCols = numCols; // сохраняем значение numCols для использования в других методах
numCols = numCols;
}
protected override void SetObjectsPosition()
{
if (locCoord == null || _collection == null)
@@ -60,8 +63,12 @@ public class AirPlaneSharingService : AbstractCompany
int row = numRows - 1, col = numCols;
for (int i = 0; i < _collection?.Count; i++, col--)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
try
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
}
catch (Exception) { }
if (col == 1)
{
col = numCols + 1;

View File

@@ -0,0 +1,45 @@
using AirBomber.CollectionGenericObjects;
namespace AirBomber.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?
strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@@ -1,8 +1,10 @@
using System;
using AirBomber.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Drawnings;
public interface ICollectionGenericObjects<T>
where T : class
@@ -15,14 +17,14 @@ public interface ICollectionGenericObjects<T>
/// <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<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@@ -30,7 +32,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@@ -45,4 +47,21 @@ 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

@@ -1,4 +1,6 @@
using System;
using AirBomber.Drawnings;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -16,7 +18,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@@ -28,30 +42,38 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
else
{
return null;
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) { return -1; }
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)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count || Count == _maxCount)
if (comparer != null)
{
return -1;
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj);
return position;
@@ -59,9 +81,22 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Remove(int position)
{
if (position >= Count || position < 0) return null;
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 < _collection.Count; ++i)
{
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -1,4 +1,6 @@
using System;
using AirBomber.Drawnings;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -15,8 +17,12 @@ where T : class
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -33,6 +39,8 @@ where T : class
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -43,16 +51,21 @@ where T : class
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?> comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningAirPlane>).Equals(obj as DrawningAirPlane, item as DrawningAirPlane))
throw new ObjectIsEqualException();
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@@ -61,14 +74,22 @@ where T : class
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningAirPlane>).Equals(obj as DrawningAirPlane, item as DrawningAirPlane))
throw new ObjectIsEqualException();
}
}
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
@@ -93,17 +114,31 @@ where T : class
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
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,4 +1,6 @@
using System;
using AirBomber.Drawnings;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -10,24 +12,39 @@ namespace AirBomber.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningAirPlane
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@@ -37,17 +54,18 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return;
}
switch (collectionType)
{
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
break;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
break;
default:
return;
@@ -60,11 +78,11 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
}
/// <summary>
@@ -76,11 +94,131 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
{
return _storages[name];
}
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
continue;
sb.Append(data);
sb.Append(_separatorItems);
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (!str.StartsWith(_collectionKey))
throw new Exception("В файле неверные данные");
_storages.Clear();
string strs = "";
while ((strs = sr.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?.CreateDrawningAirPlane() is T boat)
{
try
{
if (collection.Insert(boat) == -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

@@ -28,6 +28,14 @@ public class DrawningAirBomber : DrawningAirPlane
EntityAirPlane = new EntityAirBomber(speed, weight, bodyColor, additionalColor, bombs, fuelTanks);
}
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="entityAirPlane"></param>
public DrawningAirBomber(EntityAirPlane entityAirPlane) : base()
{
EntityAirPlane = entityAirPlane;
}
public override void DrawTransport(Graphics g)
{
if (EntityAirPlane == null || EntityAirPlane is not EntityAirBomber airbomber || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@@ -69,7 +69,7 @@ public class DrawningAirPlane
/// Пустой конструктор
/// </summary>
///
private DrawningAirPlane()
protected DrawningAirPlane()
{
_pictureHeight = null;
_pictureHeight = null;
@@ -92,11 +92,20 @@ public class DrawningAirPlane
/// </summary>
/// <param name="drawningAirBomberWidth">Ширина прорисовки самолета</param>
/// <param name="drawningAirBomberWidth">Высота прорисовки самолета</param>
protected DrawningAirPlane(int drawningAirBomberWidth, int drawningAirBomberHeight) : this()
public DrawningAirPlane(int drawningAirBomberWidth, int drawningAirBomberHeight) : this()
{
_drawningAirPlaneHeight = drawningAirBomberHeight;
_drawningAirPlaneWidth = drawningAirBomberWidth;
}
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="entityAirPlane"></param>
public DrawningAirPlane(EntityAirPlane entityAirPlane) : base()
{
EntityAirPlane = entityAirPlane;
}
/// <summary>
/// Установка границ поля

View File

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

View File

@@ -0,0 +1,29 @@
namespace AirBomber.Drawnings;
public class DrawningAirPlaneCompareByType : IComparer<DrawningAirPlane?>
{
public int Compare(DrawningAirPlane? x, DrawningAirPlane? y)
{
if (x == null || x.EntityAirPlane == null)
{
return 1;
}
if (y == null || y.EntityAirPlane == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityAirPlane.Speed.CompareTo(y.EntityAirPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAirPlane.Weight.CompareTo(y.EntityAirPlane.Weight);
}
}

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using AirBomber.Entities;
namespace AirBomber.Drawnings;
public class DrawningAirPlaneEqutables : IEqualityComparer<DrawningAirPlane>
{
public bool Equals(DrawningAirPlane? x, DrawningAirPlane? y)
{
if (x == null || x.EntityAirPlane == null)
{
return false;
}
if (y == null || y.EntityAirPlane == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityAirPlane.Speed != y.EntityAirPlane.Speed)
{
return false;
}
if (x.EntityAirPlane.Weight != y.EntityAirPlane.Weight)
{
return false;
}
if (x.EntityAirPlane.BodyColor != y.EntityAirPlane.BodyColor)
{
return false;
}
if (x is DrawningAirBomber && y is DrawningAirBomber)
{
EntityAirBomber _x = (EntityAirBomber)x.EntityAirPlane;
EntityAirBomber _y = (EntityAirBomber)x.EntityAirPlane;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Bombs != _y.Bombs)
{
return false;
}
if (_x.FuelTanks != _y.FuelTanks)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningAirPlane obj)
{
return obj.GetHashCode();
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Entities;
namespace AirBomber.Drawnings;
public static class ExtentionDrawningAirPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningAirPlane? CreateDrawningAirPlane(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityAirPlane? airPlane = EntityAirBomber.CreateEntityAirBomber(strs);
if (airPlane != null)
{
return new DrawningAirBomber(airPlane);
}
airPlane = EntityAirPlane.CreateEntityAirPlane(strs);
if (airPlane != null)
{
return new DrawningAirPlane(airPlane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirPlane">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningAirPlane drawningAirPlane)
{
string[]? array = drawningAirPlane?.EntityAirPlane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -4,38 +4,52 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber.Entities
namespace AirBomber.Entities;
public class EntityAirBomber : EntityAirPlane
{
public class EntityAirBomber : EntityAirPlane
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color) => AdditionalColor = color;
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительных топливных баков
/// </summary>
public bool FuelTanks { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="fuelTanks">Признак наличия дополнительных топливных баков</param>
public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(speed, weight, bodyColor)
{
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color) => AdditionalColor = color;
AdditionalColor = additionalColor;
Bombs = bombs;
FuelTanks = fuelTanks;
}
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительных топливных баков
/// </summary>
public bool FuelTanks { get; private set; }
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bombs.ToString(), FuelTanks.ToString() };
}
/// <summary>
///
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="fuelTanks">Признак наличия дополнительных топливных баков</param>
public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(speed, weight, bodyColor)
public static EntityAirBomber? CreateEntityAirBomber(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAirBomber))
{
AdditionalColor = additionalColor;
Bombs = bombs;
FuelTanks = fuelTanks;
return null;
}
return new EntityAirBomber(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

@@ -42,4 +42,28 @@ public class EntityAirPlane
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirPlane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAirPlane? CreateEntityAirPlane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityAirPlane))
{
return null;
}
return new EntityAirPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace AirBomber.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 AirBomber.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 AirBomber.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 AirBomber.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

@@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddAirPlane = new Button();
maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button();
@@ -46,10 +48,17 @@
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
@@ -61,24 +70,46 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(752, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(208, 644);
groupBoxTools.Size = new Size(208, 659);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструманты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddAirPlane);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonDelAirPlane);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Location = new Point(14, 342);
panelCompanyTools.Location = new Point(12, 315);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(184, 214);
panelCompanyTools.Size = new Size(184, 339);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(6, 295);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(175, 37);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(6, 255);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(175, 38);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddAirPlane
//
buttonAddAirPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@@ -101,9 +132,9 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(6, 182);
buttonRefresh.Location = new Point(6, 212);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(175, 22);
buttonRefresh.Size = new Size(175, 37);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -114,7 +145,7 @@
buttonDelAirPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelAirPlane.Location = new Point(6, 124);
buttonDelAirPlane.Name = "buttonDelAirPlane";
buttonDelAirPlane.Size = new Size(175, 23);
buttonDelAirPlane.Size = new Size(175, 38);
buttonDelAirPlane.TabIndex = 4;
buttonDelAirPlane.Text = "Удалить Самолет";
buttonDelAirPlane.UseVisualStyleBackColor = true;
@@ -122,9 +153,9 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(6, 154);
buttonGoToCheck.Location = new Point(6, 168);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(175, 22);
buttonGoToCheck.Size = new Size(175, 38);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@@ -192,7 +223,7 @@
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(88, 72);
radioButtonList.Location = new Point(84, 72);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
@@ -247,15 +278,57 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(752, 644);
pictureBox.Size = new Size(752, 659);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(752, 24);
menuStrip.TabIndex = 3;
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.Filter = "txt file | *.txt";
//
// FormAirPlaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(960, 644);
ClientSize = new Size(960, 659);
Controls.Add(menuStrip);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormAirPlaneCollection";
@@ -267,7 +340,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -290,5 +366,13 @@
private ListBox listBoxCollection;
private Button buttonCreateCompany;
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

@@ -9,109 +9,111 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using AirBomber.Exceptions;
namespace AirBomber
namespace AirBomber;
public partial class FormAirPlaneCollection : Form
{
public partial class FormAirPlaneCollection : Form
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningAirPlane> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormAirPlaneCollection(ILogger<FormAirPlaneCollection> logger)
{
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningAirPlane> _storageCollection;
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company;
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Конструктор
/// </summary>
public FormAirPlaneCollection()
{
InitializeComponent();
_storageCollection = new();
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddAirPlane_Click(object sender, EventArgs e)
{
FormAirPlaneConfig form = new();
//TODO передать метод
form.Show();
form.AddEvent(SetAirPlane);
}
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddAirPlane_Click(object sender, EventArgs e)
{
FormAirPlaneConfig form = new();
//TODO передать метод
form.Show();
form.AddEvent(SetAirPlane);
}
/// <summary>
/// Добавление самолета в коллекцию
/// </summary>
/// <param name="airplane"></param>
private void SetAirPlane(DrawningAirPlane airplane)
/// <summary>
/// Добавление самолета в коллекцию
/// </summary>
/// <param name="airplane"></param>
private void SetAirPlane(DrawningAirPlane airplane)
{
try
{
if (_company == null || airplane == null)
{
return;
}
if (_company + airplane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave());
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
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;
MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Такой объект уже существует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e)
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e)
{
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
throw new Exception("Входные данные отсутствуют");
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
@@ -119,35 +121,40 @@ namespace AirBomber
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Объект удален");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (_company == null)
{
return;
}
MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
DrawningAirPlane? airplane = null;
int counter = 100;
while (airplane == null)
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningAirPlane? airPlane = null;
int counter = 100;
try
{
while (airPlane == null)
{
airplane = _company.GetRandomObject();
airPlane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
@@ -155,43 +162,51 @@ namespace AirBomber
}
}
if (airplane == null)
if (airPlane == null)
{
return;
}
FormAirBomber form = new FormAirBomber();
form.SetAirPlane = airplane;
form.SetAirPlane = airPlane;
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (_company == null)
{
return;
}
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
pictureBox.Image = _company.Show();
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
private void FormAirPlaneCollection_Load(object sender, EventArgs e)
{
pictureBox.Image = _company.Show();
}
private void FormAirPlaneCollection_Load(object sender, EventArgs e)
{
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
try
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@@ -204,64 +219,148 @@ namespace AirBomber
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text);
}
private void RefreshListBoxItems()
catch (Exception ex)
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
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))
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCompany_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningAirPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
MessageBox.Show("Коллекция не выбрана");
return;
_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);
}
ICollectionGenericObjects<DrawningAirPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
}
/// <summary>
/// Обработка кнопки загрузки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_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)
{
CompareAirPlane(new DrawningAirPlaneCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareAirPlane(new DrawningBoatCompareByColor());
}
private void CompareAirPlane(IComparer<DrawningAirPlane?> 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

@@ -73,10 +73,8 @@
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Margin = new Padding(3, 4, 3, 4);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Padding = new Padding(3, 4, 3, 4);
groupBoxConfig.Size = new Size(629, 346);
groupBoxConfig.Size = new Size(550, 260);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
@@ -91,11 +89,9 @@
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(360, 16);
groupBoxColors.Margin = new Padding(3, 4, 3, 4);
groupBoxColors.Location = new Point(315, 12);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Padding = new Padding(3, 4, 3, 4);
groupBoxColors.Size = new Size(259, 149);
groupBoxColors.Size = new Size(227, 112);
groupBoxColors.TabIndex = 11;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
@@ -103,83 +99,74 @@
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(201, 88);
panelPurple.Margin = new Padding(3, 4, 3, 4);
panelPurple.Location = new Point(176, 66);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(39, 45);
panelPurple.Size = new Size(34, 34);
panelPurple.TabIndex = 3;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(201, 29);
panelYellow.Margin = new Padding(3, 4, 3, 4);
panelYellow.Location = new Point(176, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(39, 45);
panelYellow.Size = new Size(34, 34);
panelYellow.TabIndex = 1;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(137, 88);
panelBlack.Margin = new Padding(3, 4, 3, 4);
panelBlack.Location = new Point(120, 66);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(39, 45);
panelBlack.Size = new Size(34, 34);
panelBlack.TabIndex = 4;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(77, 88);
panelGray.Margin = new Padding(3, 4, 3, 4);
panelGray.Location = new Point(67, 66);
panelGray.Name = "panelGray";
panelGray.Size = new Size(39, 45);
panelGray.Size = new Size(34, 34);
panelGray.TabIndex = 5;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(137, 29);
panelBlue.Margin = new Padding(3, 4, 3, 4);
panelBlue.Location = new Point(120, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(39, 45);
panelBlue.Size = new Size(34, 34);
panelBlue.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(17, 88);
panelWhite.Margin = new Padding(3, 4, 3, 4);
panelWhite.Location = new Point(15, 66);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(39, 45);
panelWhite.Size = new Size(34, 34);
panelWhite.TabIndex = 2;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(77, 29);
panelGreen.Margin = new Padding(3, 4, 3, 4);
panelGreen.Location = new Point(67, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(39, 45);
panelGreen.Size = new Size(34, 34);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(17, 29);
panelRed.Margin = new Padding(3, 4, 3, 4);
panelRed.Location = new Point(15, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(39, 45);
panelRed.Size = new Size(34, 34);
panelRed.TabIndex = 0;
panelRed.MouseDown += Panel_MouseDown;
//
// checkBoxFuelTanks
//
checkBoxFuelTanks.AutoSize = true;
checkBoxFuelTanks.Location = new Point(14, 237);
checkBoxFuelTanks.Margin = new Padding(3, 4, 3, 4);
checkBoxFuelTanks.Location = new Point(12, 178);
checkBoxFuelTanks.Name = "checkBoxFuelTanks";
checkBoxFuelTanks.Size = new Size(312, 24);
checkBoxFuelTanks.Size = new Size(248, 19);
checkBoxFuelTanks.TabIndex = 7;
checkBoxFuelTanks.Text = "Признак наличия доп. топливных баков";
checkBoxFuelTanks.UseVisualStyleBackColor = true;
@@ -187,60 +174,57 @@
// checkBoxBombs
//
checkBoxBombs.AutoSize = true;
checkBoxBombs.Location = new Point(14, 176);
checkBoxBombs.Margin = new Padding(3, 4, 3, 4);
checkBoxBombs.Location = new Point(12, 132);
checkBoxBombs.Name = "checkBoxBombs";
checkBoxBombs.Size = new Size(196, 24);
checkBoxBombs.Size = new Size(156, 19);
checkBoxBombs.TabIndex = 6;
checkBoxBombs.Text = "Признак наличия бомб";
checkBoxBombs.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(91, 109);
numericUpDownWeight.Margin = new Padding(3, 4, 3, 4);
numericUpDownWeight.Location = new Point(80, 82);
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(101, 27);
numericUpDownWeight.Size = new Size(88, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(14, 112);
labelWeight.Location = new Point(12, 84);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(91, 51);
numericUpDownSpeed.Margin = new Padding(3, 4, 3, 4);
numericUpDownSpeed.Location = new Point(80, 38);
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(101, 27);
numericUpDownSpeed.Size = new Size(88, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(14, 53);
labelSpeed.Location = new Point(12, 40);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(466, 222);
labelModifiedObject.Location = new Point(408, 166);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(117, 53);
labelModifiedObject.Size = new Size(103, 40);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
@@ -249,9 +233,9 @@
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(330, 222);
labelSimpleObject.Location = new Point(289, 166);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(117, 53);
labelSimpleObject.Size = new Size(103, 40);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
@@ -259,19 +243,17 @@
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(15, 69);
pictureBoxObject.Margin = new Padding(3, 4, 3, 4);
pictureBoxObject.Location = new Point(13, 45);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(194, 161);
pictureBoxObject.Size = new Size(170, 136);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(672, 254);
buttonAdd.Margin = new Padding(3, 4, 3, 4);
buttonAdd.Location = new Point(588, 190);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(101, 53);
buttonAdd.Size = new Size(88, 40);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
@@ -279,10 +261,9 @@
//
// buttonCancel
//
buttonCancel.Location = new Point(786, 254);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Location = new Point(688, 190);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(102, 53);
buttonCancel.Size = new Size(89, 40);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@@ -293,10 +274,9 @@
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(679, 0);
panelObject.Margin = new Padding(3, 4, 3, 4);
panelObject.Location = new Point(594, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(222, 246);
panelObject.Size = new Size(194, 184);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
@@ -305,9 +285,9 @@
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(15, 12);
labelBodyColor.Location = new Point(13, 9);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(85, 43);
labelBodyColor.Size = new Size(75, 33);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
@@ -318,9 +298,9 @@
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(123, 12);
labelAdditionalColor.Location = new Point(108, 9);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(85, 43);
labelAdditionalColor.Size = new Size(75, 33);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. Цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
@@ -329,14 +309,13 @@
//
// FormAirPlaneConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(909, 346);
ClientSize = new Size(795, 260);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Margin = new Padding(3, 4, 3, 4);
Name = "FormAirPlaneConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);

View File

@@ -18,7 +18,7 @@
<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="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>

View File

@@ -1,17 +1,45 @@
namespace AirBomber
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirBomber;
internal static class Program
{
internal static class Program
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAirPlaneCollection());
}
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormAirPlaneCollection>());
}
}
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<FormAirPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger());
});
}
}

15
AirBomber/serilog.json Normal file
View File

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