Compare commits

...

10 Commits

Author SHA1 Message Date
765cb368d3 s 2024-06-03 03:48:20 +04:00
d7b027a859 ы 2024-06-03 03:46:12 +04:00
84f9bc92c4 s 2024-06-03 03:28:18 +04:00
6e8b05a39e s 2024-06-03 03:26:54 +04:00
d4623e82cd z 2024-06-03 03:24:59 +04:00
eed42ea361 s 2024-06-03 02:56:28 +04:00
04799863c5 s 2024-06-03 02:53:24 +04:00
eb9b6113e3 s 2024-06-03 02:51:54 +04:00
b9c5fd0ad8 s 2024-06-03 02:50:40 +04:00
c19d0da073 s 2024-06-03 02:48:55 +04:00
44 changed files with 1166 additions and 346 deletions

View File

@ -1,7 +1,7 @@
using ProjectCruiser.Drawnings;
using ProjectCruiser.Exceptions;
using ProjectPlane.Drawnings;
using ProjectPlane.Exceptions;
namespace ProjectCruiser.CollectionGenericObjects
namespace ProjectPlane.CollectionGenericObjects
{
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
@ -29,9 +29,9 @@ namespace ProjectCruiser.CollectionGenericObjects
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция крейсеров
/// Коллекция самолетов
/// </summary>
protected ICollectionGenericObjects<DrawningCruiser>? _collection = null;
protected ICollectionGenericObjects<DrawningPlane>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
@ -45,7 +45,7 @@ namespace ProjectCruiser.CollectionGenericObjects
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция автомобилей</param>
public AbstractCompany(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningCruiser> collection)
ICollectionGenericObjects<DrawningPlane> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
@ -57,11 +57,11 @@ namespace ProjectCruiser.CollectionGenericObjects
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="сruiser">Добавляемый объект</param>
/// <param name="plane">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningCruiser сruiser)
public static int operator +(AbstractCompany company, DrawningPlane plane)
{
return company._collection.Insert(сruiser);
return company._collection.Insert(plane, new DrawiningPlaneEqutables());
}
/// <summary>
@ -70,7 +70,7 @@ namespace ProjectCruiser.CollectionGenericObjects
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningCruiser operator -(AbstractCompany company, int position)
public static DrawningPlane operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
@ -79,7 +79,7 @@ namespace ProjectCruiser.CollectionGenericObjects
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningCruiser? GetRandomObject()
public DrawningPlane? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
@ -99,7 +99,7 @@ namespace ProjectCruiser.CollectionGenericObjects
{
try
{
DrawningCruiser? obj = _collection?.Get(i);
DrawningPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
@ -109,6 +109,13 @@ namespace ProjectCruiser.CollectionGenericObjects
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningPlane?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,75 @@
namespace ProjectPlane.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

@ -1,4 +1,4 @@
namespace ProjectCruiser.CollectionGenericObjects
namespace ProjectPlane.CollectionGenericObjects
{
public enum CollectionType
{

View File

@ -1,4 +1,7 @@
namespace ProjectCruiser.CollectionGenericObjects
using ProjectPlane.Drawnings;
using ProjectPlane.CollectionGenericObjects;
namespace ProjectPlane.CollectionGenericObjects
{
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@ -21,8 +24,9 @@
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// /// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<DrawningPlane?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@ -30,7 +34,7 @@
/// <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<DrawningPlane?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -56,6 +60,12 @@
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@ -1,6 +1,9 @@
using ProjectCruiser.Exceptions;
using ProjectPlane.Drawnings;
using ProjectPlane.Exceptions;
using ProjectPlane.CollectionGenericObjects;
using ProjectPlane.Exceptions;
namespace ProjectCruiser.CollectionGenericObjects
namespace ProjectPlane.CollectionGenericObjects
{
/// <summary>
/// Параметризованный набор объектов
@ -47,23 +50,38 @@ namespace ProjectCruiser.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawningPlane?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO выбром позиций, если переполнение
// TODO выброc позиций, если такой объект есть в коллекции
// TODO вставка в конец набора
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningPlane), (obj as DrawningPlane))) throw new ObjectAlreadyInCollectionException(i);
}
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<DrawningPlane?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции
// TODO вставка по позиции
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningPlane), (obj as DrawningPlane))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
@ -72,9 +90,10 @@ namespace ProjectCruiser.CollectionGenericObjects
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
// TODO выбром позиций, если выход за границы массива
// TODO удаление объекта из списка
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
@ -87,5 +106,10 @@ namespace ProjectCruiser.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}
}

View File

@ -1,6 +1,9 @@
using ProjectCruiser.Exceptions;
using ProjectPlane.Drawnings;
using ProjectPlane.Exceptions;
using ProjectPlane.CollectionGenericObjects;
using ProjectPlane.Exceptions;
namespace ProjectCruiser.CollectionGenericObjects
namespace ProjectPlane.CollectionGenericObjects
{
/// <summary>
/// Параметризованный набор объектов
@ -55,34 +58,44 @@ namespace ProjectCruiser.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawningPlane?>? comparer = null)
{
// TODO вставка в свободное место набора
// TODO выброc позиций, если переполнение
int index = 0;
while (index < Count && _collection[index] != null)
// TODO выброc позиций, если такой объект есть в коллекции
for (int i = 0; i < Count; i++)
{
index++;
if (comparer.Equals((_collection[i] as DrawningPlane), (obj as DrawningPlane))) throw new ObjectAlreadyInCollectionException(i);
}
if (index < Count)
for (int i = 0; i < Count; i++)
{
_collection[index] = obj;
return index;
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<DrawningPlane?>? comparer = null)
{
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции
// TODO выбром позиций, если выход за границы массива
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
// TODO выбром позиций, если переполнение
// TODO выбром позиций, если выход за границы массива
// TODO вставка
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningPlane), (obj as DrawningPlane))) throw new ObjectAlreadyInCollectionException(i);
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
@ -143,5 +156,10 @@ namespace ProjectCruiser.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}
}

View File

@ -1,12 +1,12 @@
using ProjectCruiser.Drawnings;
using ProjectCruiser.Exceptions;
using ProjectPlane.Drawnings;
using ProjectPlane.Exceptions;
namespace ProjectCruiser.CollectionGenericObjects
namespace ProjectPlane.CollectionGenericObjects
{
/// <summary>
/// Реализация абстрактной компании - каршеринг
/// </summary>
public class CruiserDockingService : AbstractCompany
public class PlaneDockingService : AbstractCompany
{
/// <summary>
/// Конструктор
@ -14,8 +14,8 @@ namespace ProjectCruiser.CollectionGenericObjects
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public CruiserDockingService(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningCruiser> collection) : base(picWidth, picHeight, collection)
public PlaneDockingService(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningPlane> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)

View File

@ -1,24 +1,26 @@
using ProjectCruiser.Drawnings;
using ProjectCruiser.Exceptions;
using ProjectPlane.Drawnings;
using ProjectPlane.Exceptions;
using ProjectPlane.CollectionGenericObjects;
using ProjectPlane.Exceptions;
using System.Text;
namespace ProjectCruiser.CollectionGenericObjects
namespace ProjectPlane.CollectionGenericObjects
{
// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningCruiser
where T : DrawningPlane
{
/// <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>
/// Ключевое слово, с которого должен начинаться файл
@ -40,7 +42,7 @@ namespace ProjectCruiser.CollectionGenericObjects
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -48,29 +50,40 @@ namespace ProjectCruiser.CollectionGenericObjects
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
public void AddCollection(CollectionInfo name)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name)) return;
if (name == null || _storages.ContainsKey(name))
{
return;
}
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
if (name.CollectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
}
if (name.CollectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
public void DelCollection(CollectionInfo name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
if (name == null || !_storages.ContainsKey(name))
{
return;
}
_storages.Remove(name);
}
/// <summary>
@ -78,13 +91,16 @@ namespace ProjectCruiser.CollectionGenericObjects
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo name]
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
{
return _storages[name];
}
return null;
}
}
@ -111,7 +127,7 @@ namespace ProjectCruiser.CollectionGenericObjects
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
streamWriter.Write(Environment.NewLine);
@ -122,8 +138,6 @@ namespace ProjectCruiser.CollectionGenericObjects
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
@ -164,27 +178,25 @@ namespace ProjectCruiser.CollectionGenericObjects
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
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[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningCruiser() is T aircraft)
if (elem?.CreateDrawningPlane() is T plane)
{
try
{
if (collection.Insert(aircraft) == -1)
if (collection.Insert(plane, new DrawiningPlaneEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
@ -193,9 +205,13 @@ namespace ProjectCruiser.CollectionGenericObjects
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

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

View File

@ -0,0 +1,27 @@
namespace ProjectPlane.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,54 @@
using System.Diagnostics.CodeAnalysis;
namespace ProjectPlane.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningPlaneEqutables : IEqualityComparer<DrawningPlane?>
{
public bool Equals(DrawningPlane? x, DrawningPlane? y)
{
if (x == null || x.EntityPlane == null)
{
return false;
}
if (y == null || y.EntityPlane == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityPlane.Speed != y.EntityPlane.Speed)
{
return false;
}
if (x.EntityPlane.Weight != y.EntityPlane.Weight)
{
return false;
}
if (x.EntityPlane.BodyColor != y.EntityPlane.BodyColor)
{
return false;
}
if (x is DrawningSeaPlane && y is DrawningSeaPlane)
{
// TODO доделать логику сравнения дополнительных параметров
}
return true;
}
public int GetHashCode([DisallowNull] DrawningPlane obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,90 @@
using System.Drawing.Drawing2D;
using ProjectPlane.Entities;
namespace ProjectPlane.Drawnings
{
public class DrawningSeaPlane : DrawningPlane
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="line">Признак наличия линии</param>
/// <param name="boat">Признак наличия шлюпки</param>
/// <param name="floats">Признак наличия поплавков</param>
public DrawningSeaPlane(int speed, double weight, Color bodyColor, Color additionalColor, bool line, bool boat, bool floats)
: base(150, 50)
{
EntityPlane = new EntitySeaPlane(speed, weight, bodyColor, additionalColor, line, boat, floats);
}
public DrawningSeaPlane(EntityPlane entityPlane)
{
if (entityPlane != null)
{
EntityPlane = entityPlane;
}
}
public override void DrawTransport(Graphics g)
{
if (EntityPlane == null || EntityPlane is not EntitySeaPlane entitySeaPlane || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen3 = new(EntityPlane.BodyColor, 2);
Pen pen = new(Color.Black, 2);
Pen pen5 = new(Color.Black, 4);
Pen pen2 = new(Color.Black, 6);
Pen pen4 = new(Color.White, 4);
Pen pen6 = new(Color.Black, 1);
Brush Brush = new SolidBrush(EntityPlane.BodyColor);
Brush Brush2 = new SolidBrush(Color.Black);
Brush glassBrush = new SolidBrush(Color.SkyBlue);
Brush glassBrush2 = new SolidBrush(entitySeaPlane.AdditionalColor);
Brush boatBrush = new HatchBrush(HatchStyle.ZigZag, entitySeaPlane.AdditionalColor, Color.FromArgb(163, 163, 163));
Brush additionalBrush = new SolidBrush(entitySeaPlane.AdditionalColor);
base.DrawTransport(g);
//внутренности самолета
//g.DrawRectangle(pen, _startPosX.Value + 25, _startPosY.Value + 10, 80, 30);
//g.FillRectangle(additionalBrush, _startPosX.Value + 25, _startPosY.Value + 10, 80, 30);
if (entitySeaPlane.Line)
{
Point[] points3 = { new Point(_startPosX.Value + 35, _startPosY.Value + 15), new Point(_startPosX.Value + 20, _startPosY.Value + 15), new Point(_startPosX.Value + 10, _startPosY.Value + 20), new Point(_startPosX.Value + 10, _startPosY.Value + 25), new Point(_startPosX.Value + 15, _startPosY.Value + 30), new Point(_startPosX.Value + 145, _startPosY.Value + 20), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value + 140, _startPosY.Value + 10), new Point(_startPosX.Value + 135, _startPosY.Value + 20), new Point(_startPosX.Value + 30, _startPosY.Value + 20) };
g.FillPolygon(additionalBrush, points3);
g.DrawPolygon(pen6, points3);
}
if (entitySeaPlane.Floats)
{
Point[] points4 = { new Point(_startPosX.Value + 10, _startPosY.Value + 40), new Point(_startPosX.Value + 110, _startPosY.Value + 40), new Point(_startPosX.Value + 110, _startPosY.Value + 41), new Point(_startPosX.Value + 70, _startPosY.Value + 50), new Point(_startPosX.Value + 30, _startPosY.Value + 50) };
g.FillPolygon(additionalBrush, points4);
g.DrawPolygon(pen, points4);
g.DrawLine(pen, _startPosX.Value + 30, _startPosY.Value + 45, _startPosX.Value + 80, _startPosY.Value + 45);
}
if (entitySeaPlane.Boat)
{
g.DrawRectangle(pen, _startPosX.Value + 85, _startPosY.Value + 15, 25, 10);
g.FillRectangle(boatBrush, _startPosX.Value + 85, _startPosY.Value + 15, 25, 10);
Point[] points5 = { new Point(_startPosX.Value + 80, _startPosY.Value + 15), new Point(_startPosX.Value + 85, _startPosY.Value + 10), new Point(_startPosX.Value + 115, _startPosY.Value + 10), new Point(_startPosX.Value + 115, _startPosY.Value + 15), new Point(_startPosX.Value + 85, _startPosY.Value + 15), new Point(_startPosX.Value + 85, _startPosY.Value + 25), new Point(_startPosX.Value + 115, _startPosY.Value + 25), new Point(_startPosX.Value + 115, _startPosY.Value + 30), new Point(_startPosX.Value + 85, _startPosY.Value + 30), new Point(_startPosX.Value + 80, _startPosY.Value + 25) };
g.FillPolygon(additionalBrush, points5);
g.DrawPolygon(pen, points5);
}
}
}
}

View File

@ -0,0 +1,264 @@
using ProjectPlane.Entities;
namespace ProjectPlane.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningPlane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityPlane? EntityPlane { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки самолета
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки самолета
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки самолета
/// </summary>
private readonly int _drawningPlaneWidth = 150;
/// <summary>
/// Высота прорисовки самолета
/// </summary>
private readonly int _drawningPlaneHeight = 50;
private readonly int _drawningEnginesWidth = 3;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningPlaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningPlaneHeight;
/// <summary>
/// Пустой онструктор
/// </summary>
public DrawningPlane()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningPlane(int speed, double weight, Color bodyColor) : this()
{
EntityPlane = new EntityPlane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningCarWidth">Ширина прорисовки автомобиля</param>
/// <param name="drawningCarHeight">Высота прорисовки автомобиля</param>
protected DrawningPlane(int drawningCarWidth, int drawningCarHeight) : this()
{
_drawningPlaneWidth = drawningCarWidth;
_pictureHeight = drawningCarHeight;
}
/// <summary>
/// конструктор
/// </summary>
/// <param name="entityPlane"></param>
public DrawningPlane(EntityPlane entityPlane)
{
EntityPlane = entityPlane;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта,если она была уже установлена
if (_drawningPlaneHeight > height || _drawningPlaneWidth > width)
{
return false;
}
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
SetPosition(_startPosX.Value, _startPosY.Value);
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x < 0 || x + _drawningPlaneWidth > _pictureWidth || y < 0 || y + _drawningPlaneHeight > _pictureHeight)
{
_startPosX = _pictureWidth - _drawningPlaneWidth;
_startPosY = _pictureHeight - _drawningPlaneHeight;
}
else
{
_startPosX = x;
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityPlane.Step - _drawningEnginesWidth > 0)
{
_startPosX -= (int)EntityPlane.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityPlane.Step > 0)
{
_startPosY -= (int)EntityPlane.Step;
}
return true;
// вправо
case DirectionType.Right:
//TODO прописать логику сдвига в право
if (_startPosX.Value + EntityPlane.Step + _drawningPlaneWidth < _pictureWidth)
{
_startPosX += (int)EntityPlane.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityPlane.Step + _drawningPlaneHeight < _pictureHeight)
{
_startPosY += (int)EntityPlane.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityPlane == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen3 = new(EntityPlane.BodyColor, 2);
Pen pen = new(Color.Black, 2);
Pen pen5 = new(Color.Black, 4);
Pen pen2 = new(Color.Black, 6);
Pen pen4 = new(Color.White, 4);
Pen pen6 = new(Color.Black, 1);
Brush Brush = new SolidBrush(EntityPlane.BodyColor);
Brush Brush2 = new SolidBrush(Color.Black);
Brush glassBrush = new SolidBrush(Color.SkyBlue);
//Brush glassBrush2 = new SolidBrush(EntityPlane.AdditionalColor);
//Brush boatBrush = new HatchBrush(HatchStyle.ZigZag, EntityPlane.AdditionalColor, Color.FromArgb(163, 163, 163));
//Brush additionalBrush = new SolidBrush(EntityPlane.AdditionalColor);
//границы самолета
Point[] points = { new Point(_startPosX.Value + 5, _startPosY.Value + 20), new Point(_startPosX.Value + 20, _startPosY.Value + 15), new Point(_startPosX.Value + 35, _startPosY.Value + 15), new Point(_startPosX.Value + 50, _startPosY.Value), new Point(_startPosX.Value + 70, _startPosY.Value), new Point(_startPosX.Value + 80, _startPosY.Value + 10), new Point(_startPosX.Value + 135, _startPosY.Value + 20), new Point(_startPosX.Value + 143, _startPosY.Value), new Point(_startPosX.Value + 150, _startPosY.Value), new Point(_startPosX.Value + 150, _startPosY.Value + 25), new Point(_startPosX.Value + 90, _startPosY.Value + 30), new Point(_startPosX.Value + 15, _startPosY.Value + 30), new Point(_startPosX.Value + 10, _startPosY.Value + 25) };
g.FillPolygon(Brush, points);
g.DrawPolygon(pen, points);
//стёкла
Point[] glass1 = { new Point(_startPosX.Value + 35, _startPosY.Value + 15), new Point(_startPosX.Value + 50, _startPosY.Value), new Point(_startPosX.Value + 42, _startPosY.Value + 15) };
g.FillPolygon(glassBrush, glass1);
g.DrawPolygon(pen, glass1);
Point[] glass2 = { new Point(_startPosX.Value + 47, _startPosY.Value + 15), new Point(_startPosX.Value + 55, _startPosY.Value), new Point(_startPosX.Value + 55, _startPosY.Value + 15) };
g.FillPolygon(glassBrush, glass2);
g.DrawPolygon(pen, glass2);
Point[] glass3 = { new Point(_startPosX.Value + 60, _startPosY.Value + 15), new Point(_startPosX.Value + 65, _startPosY.Value + 7), new Point(_startPosX.Value + 70, _startPosY.Value + 7), new Point(_startPosX.Value + 75, _startPosY.Value + 15) };
g.FillPolygon(glassBrush, glass3);
g.DrawPolygon(pen, glass3);
//крылья
g.FillEllipse(Brush2, _startPosX.Value + 47, _startPosY.Value - 2, 32, 7);
g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value, _startPosX.Value + 60, _startPosY.Value + 20);
g.DrawLine(pen4, _startPosX.Value + 40, _startPosY.Value - 3, _startPosX.Value + 80, _startPosY.Value - 3);
g.FillEllipse(Brush2, _startPosX.Value + 137, _startPosY.Value + 17, 15, 5);
//пропелер
Point[] points2 = { new Point(_startPosX.Value + 10, _startPosY.Value + 20), new Point(_startPosX.Value + 10, _startPosY.Value + 25), new Point(_startPosX.Value + 3, _startPosY.Value + 22) };
g.DrawPolygon(pen, points2);
g.FillEllipse(Brush2, _startPosX.Value + 1, _startPosY.Value + 10, 5, 13);
g.FillEllipse(Brush2, _startPosX.Value + 1, _startPosY.Value + 21, 5, 13);
//колёса
g.DrawLine(pen, _startPosX.Value + 20, _startPosY.Value + 30, _startPosX.Value + 30, _startPosY.Value + 40);
g.DrawLine(pen, _startPosX.Value + 50, _startPosY.Value + 30, _startPosX.Value + 40, _startPosY.Value + 40);
g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 30, _startPosX.Value + 70, _startPosY.Value + 40);
g.DrawLine(pen, _startPosX.Value + 80, _startPosY.Value + 30, _startPosX.Value + 90, _startPosY.Value + 40);
g.DrawLine(pen5, _startPosX.Value + 10, _startPosY.Value + 41, _startPosX.Value + 90, _startPosY.Value + 41);
g.DrawLine(pen, _startPosX.Value + 10, _startPosY.Value + 40, _startPosX.Value + 5, _startPosY.Value + 45);
g.DrawLine(pen, _startPosX.Value + 5, _startPosY.Value + 45, _startPosX.Value + 10, _startPosY.Value + 47);
g.DrawLine(pen, _startPosX.Value + 90, _startPosY.Value + 40, _startPosX.Value + 90, _startPosY.Value + 50);
g.FillEllipse(Brush2, _startPosX.Value + 7, _startPosY.Value + 43, 8, 8);
g.FillEllipse(Brush2, _startPosX.Value + 85, _startPosY.Value + 43, 8, 8);
}
}

View File

@ -0,0 +1,34 @@
using ProjectPlane.Entities;
namespace ProjectPlane.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningPlaneCompareByColor : IComparer<DrawningPlane?>
{
public int Compare(DrawningPlane? x, DrawningPlane? y)
{
// TODO прописать логику сравения по цветам, скорости, весу
if (x == null || x.EntityPlane == null)
{
return 1;
}
if (y == null || y.EntityPlane == null)
{
return -1;
}
var bodycolorCompare = x.EntityPlane.BodyColor.Name.CompareTo(y.EntityPlane.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityPlane.Speed.CompareTo(y.EntityPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityPlane.Weight.CompareTo(y.EntityPlane.Weight);
}
}

View File

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

View File

@ -0,0 +1,50 @@
using ProjectPlane.Entities;
namespace ProjectPlane.Drawnings
{
public static class ExtentionDrawningPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningPlane? CreateDrawningPlane(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityPlane? plane = EntitySeaPlane.CreateEntitySeaPlane(strs);
if (plane != null)
{
return new DrawningSeaPlane(plane);
}
plane = EntityPlane.CreateEntityPlane(strs);
if (plane != null)
{
return new DrawningPlane(plane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCrusier">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningPlane drawningCrusier)
{
string[]? array = drawningCrusier?.EntityPlane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}
}

View File

@ -1,9 +1,9 @@
namespace ProjectCruiser.Entities;
namespace ProjectPlane.Entities;
/// <summary>
/// Класс-сущность "крейсер"
/// Класс-сущность "самолет"
/// </summary>
public class EntityCruiser
public class EntityPlane
{
//свойства
/// <summary>
@ -31,12 +31,12 @@ public class EntityCruiser
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса крейсера
/// Инициализация полей объекта-класса самолета
/// </summary>
/// <param name="speed">скорость</param>
/// <param name="weight">вес</param>
/// <param name="bodyColor">основной цвет</param>
public EntityCruiser(int speed, double weight, Color bodyColor)
public EntityPlane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
@ -49,7 +49,7 @@ public class EntityCruiser
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityCruiser), Speed.ToString(), Weight.ToString(), BodyColor.Name };
return new[] { nameof(EntityPlane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
@ -57,13 +57,13 @@ public class EntityCruiser
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityCruiser? CreateEntityCruiser(string[] strs)
public static EntityPlane? CreateEntityPlane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityCruiser))
if (strs.Length != 4 || strs[0] != nameof(EntityPlane))
{
return null;
}
return new EntityCruiser(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
return new EntityPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -1,21 +1,21 @@
namespace ProjectCruiser.Entities
namespace ProjectPlane.Entities
{
internal class EntityMilitaryCruiser : EntityCruiser
internal class EntitySeaPlane : EntityPlane
{
/// <summary>
/// Признак (опция) наличие вертолетной площадки
/// Признак (опция) наличие линии
/// </summary>
public bool HelicopterArea { get; private set; }
public bool Line { get; private set; }
/// <summary>
/// Признак (опция) наличие шлюпок
/// Признак (опция) наличие шлюпки
/// </summary>
public bool Boat { get; private set; }
/// <summary>
/// Признак (опция) наличие пушки
/// Признак (опция) наличие поплавков
/// </summary>
public bool Weapon { get; private set; }
public bool Floats { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
@ -26,12 +26,12 @@
AdditionalColor = color;
}
public EntityMilitaryCruiser(int speed, double weight, Color bodyColor, Color additionalColor, bool helicopterArea, bool boat, bool weapon) : base(speed, weight, bodyColor)
public EntitySeaPlane(int speed, double weight, Color bodyColor, Color additionalColor, bool line, bool boat, bool floats) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
HelicopterArea = helicopterArea;
Line = line;
Boat = boat;
Weapon = weapon;
Floats = floats;
}
/// <summary>
@ -40,8 +40,8 @@
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityCruiser), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
HelicopterArea.ToString(), Boat.ToString(), Weapon.ToString() };
return new[] { nameof(EntityPlane), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
Line.ToString(), Boat.ToString(), Floats.ToString() };
}
/// <summary>
@ -49,13 +49,13 @@
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityCruiser? CreateEntityMilitaryCruiser(string[] strs)
public static EntityPlane? CreateEntitySeaPlane(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityCruiser))
if (strs.Length != 8 || strs[0] != nameof(EntityPlane))
{
return null;
}
return new EntityMilitaryCruiser(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
return new EntitySeaPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
}

View File

@ -5,7 +5,7 @@ using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.Exceptions;
namespace ProjectPlane.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectPlane.Exceptions;
[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

@ -5,7 +5,7 @@ using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.Exceptions;
namespace ProjectPlane.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента

View File

@ -5,7 +5,7 @@ using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCruiser.Exceptions;
namespace ProjectPlane.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции

View File

@ -1,6 +1,6 @@
namespace ProjectCruiser
namespace ProjectPlane
{
partial class FormCruiser
partial class FormPlane
{
/// <summary>
/// Required designer variable.
@ -28,26 +28,26 @@
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormCruiser));
pictureBoxCruiser = new PictureBox();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormPlane));
pictureBoxPlane = new PictureBox();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonLeft = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxPlane).BeginInit();
SuspendLayout();
//
// pictureBoxCruiser
// pictureBoxPlane
//
pictureBoxCruiser.Dock = DockStyle.Fill;
pictureBoxCruiser.Location = new Point(0, 0);
pictureBoxCruiser.Name = "pictureBoxCruiser";
pictureBoxCruiser.Size = new Size(800, 450);
pictureBoxCruiser.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCruiser.TabIndex = 0;
pictureBoxCruiser.TabStop = false;
pictureBoxPlane.Dock = DockStyle.Fill;
pictureBoxPlane.Location = new Point(0, 0);
pictureBoxPlane.Name = "pictureBoxPlane";
pictureBoxPlane.Size = new Size(800, 450);
pictureBoxPlane.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxPlane.TabIndex = 0;
pictureBoxPlane.TabStop = false;
//
// buttonUp
//
@ -118,7 +118,7 @@
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormCruiser
// FormPlane
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
@ -129,18 +129,18 @@
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(pictureBoxCruiser);
Name = "FormCruiser";
Text = "FormCruiser";
Controls.Add(pictureBoxPlane);
Name = "FormPlane";
Text = "FormPlane";
Click += ButtonMove_Click;
((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxPlane).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCruiser;
private PictureBox pictureBoxPlane;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;

View File

@ -1,14 +1,14 @@
using ProjectCruiser.Drawnings;
using ProjectCruiser.MovementStrategy;
using ProjectPlane.Drawnings;
using ProjectPlane.MovementStrategy;
namespace ProjectCruiser
namespace ProjectPlane
{
public partial class FormCruiser : Form
public partial class FormPlane : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningCruiser? _drawningCruiser;
private DrawningPlane? _drawningPlane;
/// <summary>
/// Стратегия перемещения
@ -18,13 +18,13 @@ namespace ProjectCruiser
/// <summary>
/// Получение объекта
/// </summary>
public DrawningCruiser SetCruiser
public DrawningPlane SetPlane
{
set
{
_drawningCruiser = value;
_drawningCruiser.SetPictureSize(pictureBoxCruiser.Width,
pictureBoxCruiser.Height);
_drawningPlane = value;
_drawningPlane.SetPictureSize(pictureBoxPlane.Width,
pictureBoxPlane.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
@ -34,26 +34,26 @@ namespace ProjectCruiser
/// <summary>
/// Конструктор формы
/// </summary>
public FormCruiser()
public FormPlane()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки круисера
/// Метод прорисовки самолета
/// </summary>
private void Draw()
{
if (_drawningCruiser == null)
if (_drawningPlane == null)
{
return;
}
Bitmap bmp = new(pictureBoxCruiser.Width,
pictureBoxCruiser.Height);
Bitmap bmp = new(pictureBoxPlane.Width,
pictureBoxPlane.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningCruiser.DrawTransport(gr);
pictureBoxCruiser.Image = bmp;
_drawningPlane.DrawTransport(gr);
pictureBoxPlane.Image = bmp;
}
/// <summary>
@ -63,7 +63,7 @@ namespace ProjectCruiser
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningCruiser == null)
if (_drawningPlane == null)
{
return;
}
@ -72,17 +72,17 @@ namespace ProjectCruiser
switch (name)
{
case "buttonUp":
result = _drawningCruiser.MoveTransport(DirectionType.Up);
result = _drawningPlane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningCruiser.MoveTransport(DirectionType.Down);
result = _drawningPlane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningCruiser.MoveTransport(DirectionType.Left);
result = _drawningPlane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningCruiser.MoveTransport(DirectionType.Right);
_drawningPlane.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -98,7 +98,7 @@ namespace ProjectCruiser
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningCruiser == null)
if (_drawningPlane == null)
{
return;
}
@ -116,7 +116,7 @@ namespace ProjectCruiser
{
return;
}
_strategy.SetData(new MoveableCruiser(_drawningCruiser), pictureBoxCruiser.Width, pictureBoxCruiser.Height);
_strategy.SetData(new MoveablePlane(_drawningPlane), pictureBoxPlane.Width, pictureBoxPlane.Height);
}
if (_strategy == null)

View File

@ -1,6 +1,6 @@
namespace ProjectCruiser
namespace ProjectPlane
{
partial class FormCruiserConfing
partial class FormPlaneConfing
{
/// <summary>
/// Required designer variable.
@ -38,9 +38,9 @@
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxWeapon = new CheckBox();
checkBoxFloats = new CheckBox();
checkBoxBoat = new CheckBox();
checkBoxHelicopterArea = new CheckBox();
checkBoxLine = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
@ -64,9 +64,9 @@
// groupBoxConfing
//
groupBoxConfing.Controls.Add(groupBoxColors);
groupBoxConfing.Controls.Add(checkBoxWeapon);
groupBoxConfing.Controls.Add(checkBoxFloats);
groupBoxConfing.Controls.Add(checkBoxBoat);
groupBoxConfing.Controls.Add(checkBoxHelicopterArea);
groupBoxConfing.Controls.Add(checkBoxLine);
groupBoxConfing.Controls.Add(numericUpDownWeight);
groupBoxConfing.Controls.Add(labelWeight);
groupBoxConfing.Controls.Add(numericUpDownSpeed);
@ -162,15 +162,15 @@
panelRed.Size = new Size(48, 47);
panelRed.TabIndex = 0;
//
// checkBoxWeapon
// checkBoxFloats
//
checkBoxWeapon.AutoSize = true;
checkBoxWeapon.Location = new Point(6, 217);
checkBoxWeapon.Name = "checkBoxWeapon";
checkBoxWeapon.Size = new Size(202, 24);
checkBoxWeapon.TabIndex = 8;
checkBoxWeapon.Text = "Признак наличие пушки";
checkBoxWeapon.UseVisualStyleBackColor = true;
checkBoxFloats.AutoSize = true;
checkBoxFloats.Location = new Point(6, 217);
checkBoxFloats.Name = "checkBoxFloats";
checkBoxFloats.Size = new Size(202, 24);
checkBoxFloats.TabIndex = 8;
checkBoxFloats.Text = "Признак наличие пушки";
checkBoxFloats.UseVisualStyleBackColor = true;
//
// checkBoxBoat
//
@ -182,15 +182,15 @@
checkBoxBoat.Text = "Признак наличие шлюпок";
checkBoxBoat.UseVisualStyleBackColor = true;
//
// checkBoxHelicopterArea
// checkBoxLine
//
checkBoxHelicopterArea.AutoSize = true;
checkBoxHelicopterArea.Location = new Point(6, 123);
checkBoxHelicopterArea.Name = "checkBoxHelicopterArea";
checkBoxHelicopterArea.Size = new Size(321, 24);
checkBoxHelicopterArea.TabIndex = 6;
checkBoxHelicopterArea.Text = "Признак наличие вертолетной площадки";
checkBoxHelicopterArea.UseVisualStyleBackColor = true;
checkBoxLine.AutoSize = true;
checkBoxLine.Location = new Point(6, 123);
checkBoxLine.Name = "checkBoxLine";
checkBoxLine.Size = new Size(321, 24);
checkBoxLine.TabIndex = 6;
checkBoxLine.Text = "Признак наличие вертолетной площадки";
checkBoxLine.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
@ -318,7 +318,7 @@
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// FormCruiserConfing
// FormPlaneConfing
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
@ -327,7 +327,7 @@
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfing);
Name = "FormCruiserConfing";
Name = "FormPlaneConfing";
Text = "Создание объекта";
groupBoxConfing.ResumeLayout(false);
groupBoxConfing.PerformLayout();
@ -348,9 +348,9 @@
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxHelicopterArea;
private CheckBox checkBoxLine;
private CheckBox checkBoxBoat;
private CheckBox checkBoxWeapon;
private CheckBox checkBoxFloats;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelBlack;

View File

@ -1,36 +1,36 @@
using ProjectCruiser.Drawnings;
using ProjectCruiser.Entities;
using ProjectPlane.Drawnings;
using ProjectPlane.Entities;
namespace ProjectCruiser
namespace ProjectPlane
{
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormCruiserConfing : Form
public partial class FormPlaneConfing : Form
{
/// <summary>
/// Объект - прорисовка крейсера
/// Объект - прорисовка самолета
/// </summary>
private DrawningCruiser _cruiser;
private DrawningPlane _plane;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawningCruiser>? CruiserDelegate;
private event Action<DrawningPlane>? PlaneDelegate;
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="carDelegate"></param>
public void AddEvent(Action<DrawningCruiser> cruiserDelegate)
public void AddEvent(Action<DrawningPlane> planeDelegate)
{
CruiserDelegate += cruiserDelegate;
PlaneDelegate += planeDelegate;
}
/// <summary>
/// Конструктор
/// </summary>
public FormCruiserConfing()
public FormPlaneConfing()
{
InitializeComponent();
@ -53,9 +53,9 @@ namespace ProjectCruiser
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_cruiser?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_cruiser?.SetPosition(15, 15);
_cruiser?.DrawTransport(gr);
_plane?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_plane?.SetPosition(15, 15);
_plane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
@ -90,12 +90,12 @@ namespace ProjectCruiser
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_cruiser = new DrawningCruiser((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
_plane = new DrawningPlane((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_cruiser = new
DrawningMilitaryCruiser((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxHelicopterArea.Checked, checkBoxBoat.Checked, checkBoxWeapon.Checked);
_plane = new
DrawningSeaPlane((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxLine.Checked, checkBoxBoat.Checked, checkBoxFloats.Checked);
break;
}
DrawObject();
@ -128,16 +128,16 @@ namespace ProjectCruiser
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_cruiser != null)
if (_plane != null)
{
_cruiser.EntityCruiser.setBodyColor((Color)e.Data.GetData(typeof(Color)));
_plane.EntityPlane.setBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_cruiser is DrawningCruiser)
if (_plane is DrawningPlane)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
@ -152,9 +152,9 @@ namespace ProjectCruiser
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_cruiser.EntityCruiser is EntityMilitaryCruiser militaryCruiser)
if (_plane.EntityPlane is EntitySeaPlane seaPlane)
{
militaryCruiser.setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
seaPlane.setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
@ -166,9 +166,9 @@ namespace ProjectCruiser
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_cruiser != null)
if (_plane != null)
{
CruiserDelegate?.Invoke(_cruiser);
PlaneDelegate?.Invoke(_plane);
Close();
}
}

View File

@ -1,6 +1,6 @@
namespace ProjectCruiser
namespace ProjectPlane
{
partial class FormCruisersCollection
partial class FormPlanesCollection
{
/// <summary>
/// Required designer variable.
@ -40,12 +40,14 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
panelCompanyTools = new Panel();
ButtonAddCruiser = new Button();
buttonSortByColor = new Button();
buttonSortByType = new Button();
ButtonAddPlane = new Button();
buttonRefresh = new Button();
ButtonRemoveCruiser = new Button();
ButtonRemovePlane = new Button();
maskedTextBoxPosision = new MaskedTextBox();
buttonGetToTest = new Button();
pictureBoxCruiser = new PictureBox();
pictureBoxPlane = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
@ -55,7 +57,7 @@
groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxPlane).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
@ -66,18 +68,21 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(631, 28);
groupBoxTools.Location = new Point(552, 24);
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(222, 651);
groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(194, 485);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты";
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(21, 345);
buttonCreateCompany.Location = new Point(18, 259);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(186, 27);
buttonCreateCompany.Size = new Size(163, 20);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@ -93,16 +98,18 @@
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 23);
panelStorage.Location = new Point(3, 18);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(216, 283);
panelStorage.Size = new Size(188, 212);
panelStorage.TabIndex = 6;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(17, 247);
buttonCollectionDel.Location = new Point(15, 185);
buttonCollectionDel.Margin = new Padding(3, 2, 3, 2);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(186, 27);
buttonCollectionDel.Size = new Size(163, 20);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
@ -111,17 +118,19 @@
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(17, 137);
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(15, 103);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(186, 104);
listBoxCollection.Size = new Size(163, 79);
listBoxCollection.TabIndex = 5;
//
// buttonCollecctionAdd
//
buttonCollecctionAdd.Location = new Point(17, 104);
buttonCollecctionAdd.Location = new Point(15, 78);
buttonCollecctionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollecctionAdd.Name = "buttonCollecctionAdd";
buttonCollecctionAdd.Size = new Size(186, 27);
buttonCollecctionAdd.Size = new Size(163, 20);
buttonCollecctionAdd.TabIndex = 4;
buttonCollecctionAdd.Text = "Добавить коллекцию";
buttonCollecctionAdd.UseVisualStyleBackColor = true;
@ -130,9 +139,10 @@
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(123, 75);
radioButtonList.Location = new Point(108, 56);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
@ -141,9 +151,10 @@
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(17, 75);
radioButtonMassive.Location = new Point(15, 56);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
@ -151,17 +162,18 @@
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(17, 32);
textBoxCollectionName.Location = new Point(15, 24);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(186, 27);
textBoxCollectionName.Size = new Size(163, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(26, 9);
labelCollectionName.Location = new Point(23, 7);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(155, 20);
labelCollectionName.Size = new Size(122, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
//
@ -170,87 +182,121 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(21, 311);
comboBoxSelectorCompany.Location = new Point(18, 233);
comboBoxSelectorCompany.Margin = new Padding(3, 2, 3, 2);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(186, 28);
comboBoxSelectorCompany.Size = new Size(163, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged_1;
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(ButtonAddCruiser);
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(ButtonAddPlane);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ButtonRemoveCruiser);
panelCompanyTools.Controls.Add(ButtonRemovePlane);
panelCompanyTools.Controls.Add(maskedTextBoxPosision);
panelCompanyTools.Controls.Add(buttonGetToTest);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 379);
panelCompanyTools.Location = new Point(3, 284);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(216, 274);
panelCompanyTools.Size = new Size(189, 206);
panelCompanyTools.TabIndex = 8;
//
// ButtonAddCruiser
// buttonSortByColor
//
ButtonAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddCruiser.BackgroundImageLayout = ImageLayout.Center;
ButtonAddCruiser.Location = new Point(18, 3);
ButtonAddCruiser.Name = "ButtonAddCruiser";
ButtonAddCruiser.Size = new Size(186, 40);
ButtonAddCruiser.TabIndex = 1;
ButtonAddCruiser.Text = "добваление крейсера";
ButtonAddCruiser.UseVisualStyleBackColor = true;
ButtonAddCruiser.Click += ButtonAddCruiser_Click;
buttonSortByColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSortByColor.Location = new Point(17, 171);
buttonSortByColor.Margin = new Padding(3, 2, 3, 2);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(163, 23);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Right;
buttonSortByType.Location = new Point(17, 138);
buttonSortByType.Margin = new Padding(3, 2, 3, 2);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(163, 28);
buttonSortByType.TabIndex = 6;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// ButtonAddPlane
//
ButtonAddPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddPlane.BackgroundImageLayout = ImageLayout.Center;
ButtonAddPlane.Location = new Point(16, 2);
ButtonAddPlane.Margin = new Padding(3, 2, 3, 2);
ButtonAddPlane.Name = "ButtonAddPlane";
ButtonAddPlane.Size = new Size(163, 30);
ButtonAddPlane.TabIndex = 1;
ButtonAddPlane.Text = "добваление самолета";
ButtonAddPlane.UseVisualStyleBackColor = true;
ButtonAddPlane.Click += ButtonAddPlane_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRefresh.Location = new Point(18, 227);
buttonRefresh.Location = new Point(17, 112);
buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(186, 41);
buttonRefresh.Size = new Size(163, 22);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// ButtonRemoveCruiser
// ButtonRemovePlane
//
ButtonRemoveCruiser.Anchor = AnchorStyles.Right;
ButtonRemoveCruiser.Location = new Point(18, 138);
ButtonRemoveCruiser.Name = "ButtonRemoveCruiser";
ButtonRemoveCruiser.Size = new Size(186, 40);
ButtonRemoveCruiser.TabIndex = 3;
ButtonRemoveCruiser.Text = "удалить крейсер";
ButtonRemoveCruiser.UseVisualStyleBackColor = true;
ButtonRemoveCruiser.Click += ButtonRemoveCruiser_Click;
ButtonRemovePlane.Anchor = AnchorStyles.Right;
ButtonRemovePlane.Location = new Point(17, 62);
ButtonRemovePlane.Margin = new Padding(3, 2, 3, 2);
ButtonRemovePlane.Name = "ButtonRemovePlane";
ButtonRemovePlane.Size = new Size(163, 21);
ButtonRemovePlane.TabIndex = 3;
ButtonRemovePlane.Text = "удалить самолет";
ButtonRemovePlane.UseVisualStyleBackColor = true;
ButtonRemovePlane.Click += ButtonRemovePlane_Click;
//
// maskedTextBoxPosision
//
maskedTextBoxPosision.Location = new Point(17, 105);
maskedTextBoxPosision.Location = new Point(16, 37);
maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision";
maskedTextBoxPosision.Size = new Size(187, 27);
maskedTextBoxPosision.Size = new Size(164, 23);
maskedTextBoxPosision.TabIndex = 2;
maskedTextBoxPosision.ValidatingType = typeof(int);
//
// buttonGetToTest
//
buttonGetToTest.Anchor = AnchorStyles.Right;
buttonGetToTest.Location = new Point(18, 184);
buttonGetToTest.Location = new Point(17, 87);
buttonGetToTest.Margin = new Padding(3, 2, 3, 2);
buttonGetToTest.Name = "buttonGetToTest";
buttonGetToTest.Size = new Size(186, 40);
buttonGetToTest.Size = new Size(163, 20);
buttonGetToTest.TabIndex = 4;
buttonGetToTest.Text = "передать на тесты";
buttonGetToTest.UseVisualStyleBackColor = true;
buttonGetToTest.Click += ButtonGetToTest_Click;
//
// pictureBoxCruiser
// pictureBoxPlane
//
pictureBoxCruiser.Dock = DockStyle.Fill;
pictureBoxCruiser.Location = new Point(0, 28);
pictureBoxCruiser.Name = "pictureBoxCruiser";
pictureBoxCruiser.Size = new Size(631, 651);
pictureBoxCruiser.TabIndex = 1;
pictureBoxCruiser.TabStop = false;
pictureBoxPlane.Dock = DockStyle.Fill;
pictureBoxPlane.Location = new Point(0, 24);
pictureBoxPlane.Margin = new Padding(3, 2, 3, 2);
pictureBoxPlane.Name = "pictureBoxPlane";
pictureBoxPlane.Size = new Size(552, 485);
pictureBoxPlane.TabIndex = 1;
pictureBoxPlane.TabStop = false;
//
// menuStrip
//
@ -258,7 +304,8 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(853, 28);
menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(746, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
@ -266,14 +313,14 @@
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
@ -281,7 +328,7 @@
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
@ -293,23 +340,24 @@
//
openFileDialog.Filter = "txt file|*.txt";
//
// FormCruisersCollection
// FormPlanesCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(853, 679);
Controls.Add(pictureBoxCruiser);
ClientSize = new Size(746, 509);
Controls.Add(pictureBoxPlane);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormCruisersCollection";
Text = "FormCruisersCollection";
Margin = new Padding(3, 2, 3, 2);
Name = "FormPlanesCollection";
Text = "FormPlanesCollection";
groupBoxTools.ResumeLayout(false);
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxPlane).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
@ -320,11 +368,11 @@
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button ButtonAddCruiser;
private Button ButtonRemoveCruiser;
private Button ButtonAddPlane;
private Button ButtonRemovePlane;
private Button buttonRefresh;
private Button buttonGetToTest;
private PictureBox pictureBoxCruiser;
private PictureBox pictureBoxPlane;
private MaskedTextBox maskedTextBoxPosision;
private Panel panelStorage;
private TextBox textBoxCollectionName;
@ -342,5 +390,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -1,15 +1,16 @@
using Microsoft.Extensions.Logging;
using ProjectCruiser.CollectionGenericObjects;
using ProjectCruiser.Drawnings;
using ProjectPlane.CollectionGenericObjects;
using ProjectPlane.Drawnings;
using System.Windows.Forms;
namespace ProjectCruiser
namespace ProjectPlane
{
public partial class FormCruisersCollection : Form
public partial class FormPlanesCollection : Form
{
/// <summary>
/// Хранилише коллекций
/// </summary>
private readonly StorageCollection<DrawningCruiser> _storageCollection;
private readonly StorageCollection<DrawningPlane> _storageCollection;
/// <summary>
/// Компания
@ -24,7 +25,7 @@ namespace ProjectCruiser
/// <summary>
/// Конструктор
/// </summary>
public FormCruisersCollection(ILogger<FormCruisersCollection> logger)
public FormPlanesCollection(ILogger<FormPlanesCollection> logger)
{
InitializeComponent();
_storageCollection = new();
@ -46,31 +47,31 @@ namespace ProjectCruiser
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddCruiser_Click(object sender, EventArgs e)
private void ButtonAddPlane_Click(object sender, EventArgs e)
{
FormCruiserConfing form = new();
FormPlaneConfing form = new();
// TODO передать метод
form.Show();
form.AddEvent(SetCruiser);
form.AddEvent(SetPlane);
}
/// <summary>
/// Добавление крейсера в коллекцию
/// </summary>
/// <param name="cruiser"></param>
private void SetCruiser(DrawningCruiser? cruiser)
/// <param name="plane"></param>
private void SetPlane(DrawningPlane? plane)
{
if (_company == null || cruiser == null)
if (_company == null || plane == null)
{
return;
}
try
{
var res = _company + cruiser;
var res = _company + plane;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBoxCruiser.Image = _company.Show();
pictureBoxPlane.Image = _company.Show();
}
catch (Exception ex)
{
@ -85,7 +86,7 @@ namespace ProjectCruiser
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveCruiser_Click(object sender, EventArgs e)
private void ButtonRemovePlane_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosision.Text) || _company == null)
{
@ -102,7 +103,7 @@ namespace ProjectCruiser
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBoxCruiser.Image = _company.Show();
pictureBoxPlane.Image = _company.Show();
}
catch (Exception ex)
{
@ -119,24 +120,24 @@ namespace ProjectCruiser
return;
}
DrawningCruiser? cruiser = null;
DrawningPlane? plane = null;
int counter = 100;
while (cruiser == null)
while (plane == null)
{
cruiser = _company.GetRandomObject();
plane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (cruiser == null)
if (plane == null)
{
return;
}
FormCruiser form = new()
FormPlane form = new()
{
SetCruiser = cruiser
SetPlane = plane
};
form.ShowDialog();
@ -149,7 +150,7 @@ namespace ProjectCruiser
return;
}
pictureBoxCruiser.Image = _company.Show();
pictureBoxPlane.Image = _company.Show();
}
/// <summary>
@ -174,17 +175,11 @@ namespace ProjectCruiser
collectionType = CollectionType.List;
}
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(collectionInfo);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary>
@ -203,7 +198,10 @@ namespace ProjectCruiser
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
@ -216,7 +214,7 @@ namespace ProjectCruiser
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@ -237,8 +235,8 @@ namespace ProjectCruiser
return;
}
ICollectionGenericObjects<DrawningCruiser>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningPlane>? collection = _storageCollection[collectionInfo];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
@ -248,11 +246,12 @@ namespace ProjectCruiser
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new CruiserDockingService(pictureBoxCruiser.Width, pictureBoxCruiser.Height, collection);
_company = new PlaneDockingService(pictureBoxPlane.Width, pictureBoxPlane.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
@ -302,5 +301,39 @@ namespace ProjectCruiser
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
ComparePlanes(new DrawningPlaneCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
ComparePlanes(new DrawningPlaneCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void ComparePlanes(IComparer<DrawningPlane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBoxPlane.Image = _company.Show();
}
}
}

View File

@ -1,4 +1,4 @@
namespace ProjectCruiser.MovementStrategy
namespace ProjectPlane.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта

View File

@ -1,4 +1,4 @@
namespace ProjectCruiser.MovementStrategy
namespace ProjectPlane.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом

View File

@ -1,4 +1,4 @@
namespace ProjectCruiser.MovementStrategy
namespace ProjectPlane.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта к краю экрана

View File

@ -1,4 +1,4 @@
namespace ProjectCruiser.MovementStrategy
namespace ProjectPlane.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана

View File

@ -1,45 +1,45 @@
using ProjectCruiser.Drawnings;
using ProjectPlane.Drawnings;
namespace ProjectCruiser.MovementStrategy
namespace ProjectPlane.MovementStrategy
{
/// <summary>
/// класс реалтзация для IMoveableObject с использованием DrawningCruiser
/// класс реалтзация для IMoveableObject с использованием DrawningPlane
/// </summary>
public class MoveableCruiser : IMoveableObject
public class MoveablePlane : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCruiser или его наследника
/// Поле-объект класса DrawningPlane или его наследника
/// </summary>
private readonly DrawningCruiser? _cruiser = null;
private readonly DrawningPlane? _plane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="cruiser">Объект класса DrawningCruiser</param>
public MoveableCruiser(DrawningCruiser cruiser)
/// <param name="plane">Объект класса DrawningPlane</param>
public MoveablePlane(DrawningPlane plane)
{
_cruiser = cruiser;
_plane = plane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_cruiser == null || _cruiser.EntityCruiser == null ||
!_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue)
if (_plane == null || _plane.EntityPlane == null ||
!_plane.GetPosX.HasValue || !_plane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_cruiser.GetPosX.Value,
_cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight);
return new ObjectParameters(_plane.GetPosX.Value,
_plane.GetPosY.Value, _plane.GetWidth, _plane.GetHeight);
}
}
public int GetStep => (int)(_cruiser?.EntityCruiser?.Step ?? 0);
public int GetStep => (int)(_plane?.EntityPlane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_cruiser == null || _cruiser.EntityCruiser == null)
if (_plane == null || _plane.EntityPlane == null)
{
return false;
}
return _cruiser.MoveTransport(GetDirectionType(direction));
return _plane.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType

View File

@ -1,4 +1,4 @@
namespace ProjectCruiser.MovementStrategy
namespace ProjectPlane.MovementStrategy
{
/// <summary>
/// Направление перемещения

View File

@ -1,4 +1,4 @@
namespace ProjectCruiser.MovementStrategy
namespace ProjectPlane.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта

View File

@ -1,4 +1,4 @@
namespace ProjectCruiser.MovementStrategy
namespace ProjectPlane.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения

View File

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

View File

@ -3,7 +3,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectCruiser
namespace ProjectPlane
{
internal static class Program
{
@ -18,12 +18,12 @@ namespace ProjectCruiser
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormCruisersCollection>());
Application.Run(serviceProvider.GetRequiredService<FormPlanesCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormCruisersCollection>().AddLogging(option =>
services.AddSingleton<FormPlanesCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";

View File

@ -8,4 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project>

View File

@ -4,7 +4,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="cruiserlog-
<target xsi:type="File" name="tofile" fileName="planelog-
${shortdate}.log" />
</targets>
<rules>

View File

@ -14,7 +14,7 @@
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "cruiser"
"Application": "plane"
}
}
}