7 Commits

23 changed files with 1414 additions and 138 deletions

View File

@@ -1,4 +1,5 @@
using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Exceptions;
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
@@ -48,7 +49,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
@@ -80,7 +81,14 @@ public abstract class AbstractCompany
public DrawningWarship? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
try
{
return _collection?.Get(rnd.Next(GetMaxCount));
}
catch (ObjectNotFoundException)
{
return null;
}
}
/// <summary>
@@ -96,8 +104,15 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningWarship? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningWarship? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
}
return bitmap;

View File

@@ -1,5 +1,6 @@

using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Exceptions;
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
@@ -40,21 +41,28 @@ public class Docks : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection?.Get(i) != null)
try
{
int x = 5 + _placeSizeWidth * n;
int y = (10 + _placeSizeHeight * (_pictureHeight / _placeSizeHeight - 1)) - _placeSizeHeight * m;
if (_collection?.Get(i) != null)
{
int x = 5 + _placeSizeWidth * n;
int y = (10 + _placeSizeHeight * (_pictureHeight / _placeSizeHeight - 1)) - _placeSizeHeight * m;
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x, y);
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x, y);
}
if (n < _pictureWidth / _placeSizeWidth) n++;
else
{
n = 0;
m++;
}
}
if (n < _pictureWidth / _placeSizeWidth)
n++;
else
catch (ObjectNotFoundException)
{
n = 0;
m++;
break;
}
}
}

View File

@@ -15,7 +15,8 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@@ -45,5 +46,16 @@ 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();
}

View File

@@ -1,4 +1,4 @@
using System.CodeDom.Compiler;
using ProjectAircraftCarrier_.Exceptions;
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
@@ -6,7 +6,7 @@ namespace ProjectAircraftCarrier_.CollectionGenericObjects;
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObject<T> : ICollectionGenericObjects<T>
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
@@ -21,21 +21,24 @@ public class ListGenericObject<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObject()
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
// TODO выброс ошибки, если выход за границы списка
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
@@ -43,9 +46,10 @@ public class ListGenericObject<T> : ICollectionGenericObjects<T>
public int Insert(T obj)
{
// TODO выброс ошибки, если переполнение
if (Count == _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
@@ -54,25 +58,39 @@ public class ListGenericObject<T> : ICollectionGenericObjects<T>
public int Insert(T obj, int position)
{
if (Count == _maxCount || position < 0 || position > Count)
// TODO выброс ошибки, если выход за границы списка
// TODO выброс ошибки, если переполнение
if (position < 0 || position > Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
// TODO выброс ошибки, если выход за границы списка
if (position < 0 || position > Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
T? obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,6 @@
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
using ProjectAircraftCarrier_.Exceptions;
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -14,8 +16,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -32,6 +38,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -42,15 +50,23 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если объект пустой
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position];
}
public int Insert(T obj)
{
// TODO выброс ошибки, если переполнение
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@@ -59,14 +75,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если переполнение
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
@@ -93,19 +112,33 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position < 0 || position >= Count || _collection[position] == null)
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если объект пустой
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];
}
}
}

View File

@@ -1,6 +1,6 @@
using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.CollectionGenericObjects;
using System.Xml.Linq;
using ProjectAircraftCarrier_.Exceptions;
using System.Text;
namespace ProjectAircraftCarrier_.CollectionGenericObjects;
@@ -9,7 +9,7 @@ namespace ProjectAircraftCarrier_.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningWarship
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@@ -21,6 +21,19 @@ public class StorageCollection<T>
/// </summary>
public List<string> 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>
@@ -48,7 +61,7 @@ public class StorageCollection<T>
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObject<T>());
_storages.Add(name, new ListGenericObjects<T>());
}
}
@@ -83,4 +96,134 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new StreamWriter(filename))
{
sw.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.GetCollectionType);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sw.Write(data);
sw.Write(_separatorItems);
}
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new(filename))
{
string line = sr.ReadLine();
if (line == null || line.Length == 0)
{
throw new FileFormatException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
while ((line = sr.ReadLine()) != null)
{
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningWarship() is T warship)
{
try
{
if (collection.Insert(warship) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new OverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], 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

@@ -17,9 +17,20 @@ public class DrawningAircraftCarrier : DrawningWarship
/// <param name="deckForAircraftTakeOff">Палуба для взлета самолетов</param>
/// <param name="controlCabin">Рубка управления</param>
/// <param name="fighterJet">Истребитель</param>
public DrawningAircraftCarrier(int speed, double weight, Color bodyColor, Color additionalColor, bool deckForAircraftTakeOff, bool controlCabin, bool fighterJet) : base(140, 50)
public DrawningAircraftCarrier(int speed, double weight, Color bodyColor, Color additionalColor,
bool deckForAircraftTakeOff, bool controlCabin, bool fighterJet) : base(140, 50)
{
EntityWarship = new EntityAircraftCarrier(speed, weight, bodyColor, additionalColor, deckForAircraftTakeOff, controlCabin, fighterJet);
EntityWarship = new EntityAircraftCarrier(speed, weight, bodyColor, additionalColor,
deckForAircraftTakeOff, controlCabin, fighterJet);
}
/// <summary>
/// Конструктор для класса Extention
/// </summary>
/// <param name="airplan"></param>
public DrawningAircraftCarrier(EntityWarship? aircraftCarrier) : base(aircraftCarrier)
{
EntityWarship = aircraftCarrier;
}
public override void DrawTransport(Graphics g)

View File

@@ -95,6 +95,15 @@ public class DrawningWarship
_drawningWarshipHeight = DrawningWarshiprierHeight;
}
/// <summary>
/// Конструктор для класса Extention
/// </summary>
/// <param name="warship"></param>
public DrawningWarship(EntityWarship? warship) : this()
{
EntityWarship = warship;
}
/// <summary>
/// Установка границ поля
/// </summary>

View File

@@ -0,0 +1,56 @@
using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Entities;
namespace ProjectAircraftCarrier_.Drawnings;
/// <summary>
/// Расширение для класса EntityWarship
/// </summary>
public static class ExtentionDrawningWarship
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningWarship? CreateDrawningWarship(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityWarship? warship = EntityAircraftCarrier.CreateEntityAircraftCarrier(strs);
if (warship != null)
{
return new DrawningAircraftCarrier(warship);
}
warship = EntityWarship.CreateEntityWarship(strs);
if (warship != null)
{
return new DrawningWarship(warship);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningWarship">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningWarship drawningWarship)
{
string[]? array = drawningWarship?.EntityWarship?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -42,4 +42,44 @@ public class EntityAircraftCarrier : EntityWarship
ControlCabin = controlCabin;
FighterJet = fighterJet;
}
/// <summary>
/// Смена дополнительного цвета
/// </summary>
/// <param name="newColor"></param>
public void AdditionalColorChange(Color newColor)
{
AdditionalColor = newColor;
}
public override string[] GetStringRepresentation()
{
return new[]
{
nameof(EntityAircraftCarrier),
Speed.ToString(),
Weight.ToString(),
BodyColor.Name,
AdditionalColor.Name,
DeckForAircraftTakeOff.ToString(),
ControlCabin.ToString(),
FighterJet.ToString()
};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAircraftCarrier? CreateEntityAircraftCarrier(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityAircraftCarrier))
{
return null;
}
return new EntityAircraftCarrier(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

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

View File

@@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAircraftCarrier_.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,20 @@
using System.Runtime.Serialization;
namespace ProjectAircraftCarrier_.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,20 @@
using System.Runtime.Serialization;
namespace ProjectAircraftCarrier_.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,7 +30,6 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddAircraftCarrier = new Button();
buttonAddWarship = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
@@ -47,10 +46,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
@@ -60,16 +66,15 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1176, 0);
groupBoxTools.Location = new Point(1187, 38);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(326, 961);
groupBoxTools.Size = new Size(326, 904);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddAircraftCarrier);
panelCompanyTools.Controls.Add(buttonAddWarship);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@@ -77,22 +82,11 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 529);
panelCompanyTools.Location = new Point(3, 518);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(320, 429);
panelCompanyTools.Size = new Size(320, 383);
panelCompanyTools.TabIndex = 9;
//
// buttonAddAircraftCarrier
//
buttonAddAircraftCarrier.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAircraftCarrier.Location = new Point(3, 81);
buttonAddAircraftCarrier.Name = "buttonAddAircraftCarrier";
buttonAddAircraftCarrier.Size = new Size(314, 72);
buttonAddAircraftCarrier.TabIndex = 2;
buttonAddAircraftCarrier.Text = "Добавление авианосца";
buttonAddAircraftCarrier.UseVisualStyleBackColor = true;
buttonAddAircraftCarrier.Click += ButtonAddAircraftCarrier_Click;
//
// buttonAddWarship
//
buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@@ -106,7 +100,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 159);
maskedTextBoxPosition.Location = new Point(3, 81);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(314, 35);
@@ -116,9 +110,9 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 356);
buttonRefresh.Location = new Point(3, 304);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(314, 72);
buttonRefresh.Size = new Size(314, 70);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -127,9 +121,9 @@
// buttonRemoveWarship
//
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveWarship.Location = new Point(3, 200);
buttonRemoveWarship.Location = new Point(3, 152);
buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(314, 72);
buttonRemoveWarship.Size = new Size(314, 70);
buttonRemoveWarship.TabIndex = 4;
buttonRemoveWarship.Text = "Удаление военного корабля";
buttonRemoveWarship.UseVisualStyleBackColor = true;
@@ -138,9 +132,9 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 278);
buttonGoToCheck.Location = new Point(3, 228);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(314, 72);
buttonGoToCheck.Size = new Size(314, 70);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@@ -253,19 +247,62 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 38);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1176, 961);
pictureBox.Size = new Size(1187, 904);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(28, 28);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1513, 38);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(80, 34);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(317, 40);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(317, 40);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormWarshipCollection
//
AutoScaleDimensions = new SizeF(12F, 30F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1502, 961);
ClientSize = new Size(1513, 942);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormWarshipCollection";
Text = "Коллекция военных кораблей";
groupBoxTools.ResumeLayout(false);
@@ -274,15 +311,16 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private Button buttonAddWarship;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddAircraftCarrier;
private PictureBox pictureBox;
private Button buttonRefresh;
private Button buttonGoToCheck;
@@ -298,5 +336,12 @@
private Button buttonCollectionAdd;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private Button buttonAddWarship;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@@ -1,5 +1,8 @@
using ProjectAircraftCarrier_.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectAircraftCarrier_.CollectionGenericObjects;
using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Exceptions;
using System.Xml.Linq;
namespace ProjectAircraftCarrier_;
@@ -18,13 +21,19 @@ public partial class FormWarshipCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormWarshipCollection()
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@@ -37,73 +46,44 @@ public partial class FormWarshipCollection : Form
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningWarship drawningWarship;
switch (type)
{
case nameof(DrawningWarship):
drawningWarship = new DrawningWarship(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningAircraftCarrier):
drawningWarship = new DrawningAircraftCarrier(random.Next(100, 300), random.Next(1000, 3000), GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningWarship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Добавление военного корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddWarship_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningWarship));
private void ButtonAddWarship_Click(object sender, EventArgs e)
{
FormWarshipConfig form = new();
form.AddEvent(SetWarship);
form.Show();
}
/// <summary>
/// Добавление авианосца
/// Добавление военного корабля в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAircraftCarrier_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAircraftCarrier));
/// <param name="warship"></param>
private void SetWarship(DrawningWarship? warship)
{
try
{
if (_company == null || warship == null)
{
return;
}
if (_company + warship != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {warship.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
}
catch (CollectionOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
/// <summary>
/// Удаление объекта
@@ -122,16 +102,27 @@ public partial class FormWarshipCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show();
}
}
else
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
}
/// <summary>
@@ -195,6 +186,7 @@ public partial class FormWarshipCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
@@ -209,6 +201,7 @@ public partial class FormWarshipCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
RerfreshListBoxItems();
}
@@ -230,6 +223,7 @@ public partial class FormWarshipCollection : Form
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
RerfreshListBoxItems();
}
@@ -278,4 +272,51 @@ public partial class FormWarshipCollection : Form
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из фала: {filename}", openFileDialog.FileName);
}
catch(Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

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>183, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>398, 17</value>
</metadata>
</root>

View File

@@ -0,0 +1,378 @@
namespace ProjectAircraftCarrier_
{
partial class FormWarshipConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelBlack = new Panel();
panelPink = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelBlue = new Panel();
panelOrange = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxFighterJet = new CheckBox();
checkBoxControlCabin = new CheckBox();
checkBoxDeckForAircraftTakeOff = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColors);
groupBoxConfig.Controls.Add(checkBoxFighterJet);
groupBoxConfig.Controls.Add(checkBoxControlCabin);
groupBoxConfig.Controls.Add(checkBoxDeckForAircraftTakeOff);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(918, 328);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelPink);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelOrange);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(533, 34);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(362, 181);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(193, 109);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(55, 55);
panelBlack.TabIndex = 3;
panelBlack.MouseDown += Panel_MouseDown;
//
// panelPink
//
panelPink.BackColor = Color.Pink;
panelPink.Location = new Point(274, 109);
panelPink.Name = "panelPink";
panelPink.Size = new Size(55, 55);
panelPink.TabIndex = 4;
panelPink.MouseDown += Panel_MouseDown;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(109, 109);
panelGray.Name = "panelGray";
panelGray.Size = new Size(55, 55);
panelGray.TabIndex = 5;
panelGray.MouseDown += Panel_MouseDown;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(27, 109);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(55, 55);
panelWhite.TabIndex = 2;
panelWhite.MouseDown += Panel_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(193, 34);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(55, 55);
panelBlue.TabIndex = 1;
panelBlue.MouseDown += Panel_MouseDown;
//
// panelOrange
//
panelOrange.BackColor = Color.Orange;
panelOrange.Location = new Point(274, 34);
panelOrange.Name = "panelOrange";
panelOrange.Size = new Size(55, 55);
panelOrange.TabIndex = 1;
panelOrange.MouseDown += Panel_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(109, 34);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(55, 55);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += Panel_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(27, 34);
panelRed.Name = "panelRed";
panelRed.Size = new Size(55, 55);
panelRed.TabIndex = 0;
panelRed.MouseDown += Panel_MouseDown;
//
// checkBoxFighterJet
//
checkBoxFighterJet.AutoSize = true;
checkBoxFighterJet.Location = new Point(12, 143);
checkBoxFighterJet.Name = "checkBoxFighterJet";
checkBoxFighterJet.Size = new Size(333, 34);
checkBoxFighterJet.TabIndex = 8;
checkBoxFighterJet.Text = "Признак наличия истребителя";
checkBoxFighterJet.UseVisualStyleBackColor = true;
//
// checkBoxControlCabin
//
checkBoxControlCabin.AutoSize = true;
checkBoxControlCabin.Location = new Point(12, 197);
checkBoxControlCabin.Name = "checkBoxControlCabin";
checkBoxControlCabin.Size = new Size(388, 34);
checkBoxControlCabin.TabIndex = 7;
checkBoxControlCabin.Text = "Признак наличия рубки управления";
checkBoxControlCabin.UseVisualStyleBackColor = true;
//
// checkBoxDeckForAircraftTakeOff
//
checkBoxDeckForAircraftTakeOff.AutoSize = true;
checkBoxDeckForAircraftTakeOff.Location = new Point(12, 254);
checkBoxDeckForAircraftTakeOff.Name = "checkBoxDeckForAircraftTakeOff";
checkBoxDeckForAircraftTakeOff.Size = new Size(499, 34);
checkBoxDeckForAircraftTakeOff.TabIndex = 6;
checkBoxDeckForAircraftTakeOff.Text = "Признак наличия палубы для взлета самолетов";
checkBoxDeckForAircraftTakeOff.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(125, 91);
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(155, 35);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 93);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(51, 30);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(125, 42);
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(155, 35);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 44);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(107, 30);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(726, 242);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(169, 56);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(533, 242);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(169, 56);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(9, 68);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(308, 171);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(933, 276);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(138, 40);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(1103, 276);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(138, 40);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(924, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(326, 254);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(179, 9);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(138, 41);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. Цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(9, 9);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(138, 41);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
//
// FormWarshipConfig
//
AutoScaleDimensions = new SizeF(12F, 30F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1253, 328);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormWarshipConfig";
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private CheckBox checkBoxDeckForAircraftTakeOff;
private CheckBox checkBoxControlCabin;
private CheckBox checkBoxFighterJet;
private GroupBox groupBoxColors;
private Panel panelBlue;
private Panel panelOrange;
private Panel panelGreen;
private Panel panelRed;
private Panel panelBlack;
private Panel panelPink;
private Panel panelGray;
private Panel panelWhite;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,174 @@
using ProjectAircraftCarrier_.Drawnings;
using ProjectAircraftCarrier_.Entities;
namespace ProjectAircraftCarrier_;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormWarshipConfig : Form
{
/// <summary>
/// Объект - прорисовка автомобиля
/// </summary>
private DrawningWarship? _warship;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawningWarship>? WarshipDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormWarshipConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelOrange.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPink.MouseDown += Panel_MouseDown;
// TODO buttonCancel.Click привязать анонимный метод через lambda с закрытием формы +
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="warshipDelegate"></param>
public void AddEvent(Action<DrawningWarship> warshipDelegate)
{
WarshipDelegate += warshipDelegate;
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_warship?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_warship?.SetPosition(85, 60);
_warship?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label(Объект)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации(Объект) (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации(Объект)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_warship = new DrawningWarship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_warship = new DrawningAircraftCarrier((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxDeckForAircraftTakeOff.Checked, checkBoxControlCabin.Checked, checkBoxFighterJet.Checked);
break;
}
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатии на Panel(Цвет)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
// TODO отправка цвета в Drag&Drop +
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor ?? Color.Black, DragDropEffects.Move | DragDropEffects.Copy);
}
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта) +
/// <summary>
/// Проверка получаемой информации(Основной цвет) (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации(Основной цвет)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
_warship?.EntityWarship?.BodyColorChange((Color)e.Data?.GetData(typeof(Color)));
DrawObject();
}
/// <summary>
/// Проверка получаемой информации(Доп. цвет) (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации(Доп. цвет)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_warship?.EntityWarship is EntityAircraftCarrier _aircraftCarrier)
{
_aircraftCarrier.AdditionalColorChange((Color)e.Data?.GetData(typeof(Color)));
}
DrawObject();
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_warship != null)
{
WarshipDelegate?.Invoke(_warship);
Close();
}
}
}

View File

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

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace ProjectAircraftCarrier_
{
internal static class Program
@@ -11,7 +16,31 @@ namespace ProjectAircraftCarrier_
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormWarshipCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormWarshipCollection>());
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services
.AddSingleton<FormWarshipCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
}
}
}

View File

@@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +35,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,25 @@
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "C:\\Users\\Андрей\\OneDrive\\Рабочий стол\\уник\\ООП\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}"
}
}
]
}
}