21 Commits

Author SHA1 Message Date
16da11f0e2 Merge branch 'LabWork_06' into LabWork_07 2023-12-20 10:35:51 +04:00
918be42c06 треш 2023-12-20 09:17:51 +04:00
9953e40a20 треш 2023-12-20 09:17:34 +04:00
6b440d6ada доигралась.... 2023-12-19 18:45:06 +04:00
a58085b4d1 lab 7 надеюсь готова 2023-12-19 18:27:50 +04:00
f3ce9dd416 Merge branch 'LabWork_05' into LabWork_06 2023-12-05 01:56:59 +04:00
7e81c6ca04 треш 2023-12-05 01:54:50 +04:00
d1356fb01e точно доделала 5 лабу( 2023-12-05 01:31:21 +04:00
c266418c75 что то доделала в 5 лабе 2023-12-05 01:23:55 +04:00
9379418cf7 тут что то доделано 2023-12-05 00:33:53 +04:00
c549fc6a3c laba6 2023-11-22 10:49:19 +04:00
737d77ac68 Готовая 5 лаба 2023-11-22 10:19:45 +04:00
71b1caa094 почти 6 2023-11-22 02:44:28 +04:00
814b0b8252 лаба 5 надеюсь готовая 2023-11-22 02:04:16 +04:00
cc83e1aa48 почти 5 2023-11-21 22:54:36 +04:00
8bcd0f4089 что то сделала 2023-11-15 11:44:37 +04:00
213ec2a858 всё сломала и вроде починила 2023-11-06 21:01:25 +04:00
7ab4e0f118 слепила новую форму 2023-11-06 19:40:12 +04:00
ccf9eb19d8 4 лаба готовая 2023-11-06 18:06:51 +04:00
54db2e3780 создала новый generic класс 2023-10-25 08:45:58 +04:00
a03be5f062 создала ветку 2023-10-25 07:59:41 +04:00
21 changed files with 1517 additions and 122 deletions

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Battleship"
}
}
}

View File

@@ -19,7 +19,7 @@ namespace Catamaran
private AbstractStrategy? _strategy;
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
public DrawningCatamaran? SelectedCatamaran { get; private set; }
@@ -83,7 +83,7 @@ namespace Catamaran
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
@@ -106,7 +106,7 @@ namespace Catamaran
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
@@ -175,7 +175,7 @@ namespace Catamaran
}
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

View File

@@ -8,6 +8,17 @@
<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" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Catamaran.Exceptions
{
[Serializable]
internal class CatamaranNotFoundException : ApplicationException
{
public CatamaranNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public CatamaranNotFoundException() : base() { }
public CatamaranNotFoundException(string message) : base(message) { }
public CatamaranNotFoundException(string message, Exception exception) :
base(message, exception)
{ }
protected CatamaranNotFoundException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -38,6 +38,10 @@ namespace Catamaran.Generics
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetCatamarans => _collection.GetCatamarans();
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
@@ -56,13 +60,13 @@ namespace Catamaran.Generics
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(CatamaransGenericCollection<T, U> collect, T? obj)
public static bool operator +(CatamaransGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
return false;
}
return collect._collection.Insert(obj);
return collect?._collection.Insert(obj) ?? false;
}
/// <summary>
/// Перегрузка оператора вычитания
@@ -70,15 +74,16 @@ namespace Catamaran.Generics
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(CatamaransGenericCollection<T, U> collect, int pos)
public static T? operator -(CatamaransGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
T? obj = collect._collection[pos];
if (obj != null)
{
return collect._collection.Remove(pos);
collect._collection.Remove(pos);
}
return false;
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
@@ -86,8 +91,9 @@ namespace Catamaran.Generics
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
@@ -126,27 +132,31 @@ namespace Catamaran.Generics
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
// TODO получение объекта
// TODO установка позиции
// TODO прорисовка объекта
T? obj;
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int diff = 1, currWidth = 0;
for (int i = 0; i < _collection.Count; i++)
{
currWidth++;
if (currWidth > width)
// TODO получение объекта
// TODO установка позиции
// TODO прорисовка объекта
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int diff = 1, currWidth = 0, i = 0;
foreach (var catamaran in _collection.GetCatamarans())
{
diff++;
currWidth = 1;
}
obj = _collection.Get(i);
if (obj != null)
{
obj.SetPosition(i % width * _placeSizeWidth + _placeSizeWidth / 40,
(height - diff) * _placeSizeHeight + _placeSizeHeight / 15);
obj.DrawTransport(g);
currWidth++;
if (currWidth > width)
{
diff++;
currWidth = 1;
}
if (catamaran != null)
{
catamaran._pictureWidth = _pictureWidth;
catamaran._pictureHeight = _pictureHeight;
catamaran.SetPosition(i % width * _placeSizeWidth + _placeSizeWidth / 40,
(height - diff) * _placeSizeHeight + _placeSizeHeight / 15);
catamaran.DrawTransport(g);
}
i++;
}
}
}

View File

@@ -0,0 +1,180 @@
using Catamaran.DrawningObjects;
using Catamaran.MovementStrategy;
using System.Text;
namespace Catamaran.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class CatamaransGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, CatamaransGenericCollection<DrawningCatamaran,
DrawningObjectCatamaran>> _catamaranStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _catamaranStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public CatamaransGenericStorage(int pictureWidth, int pictureHeight)
{
_catamaranStorages = new Dictionary<string,
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// TODO Прописать логику для добавления
if (_catamaranStorages.ContainsKey(name)) return;
_catamaranStorages[name] = new CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (!_catamaranStorages.ContainsKey(name))
return;
_catamaranStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>?
this[string ind]
{
get
{
// TODO Продумать логику получения набора
if (_catamaranStorages.ContainsKey(ind))
return _catamaranStorages[ind];
return null;
}
}
/// <summary>
/// Сохранение информации по катамаранам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>> record in _catamaranStorages)
{
StringBuilder records = new();
foreach (DrawningCatamaran? elem in record.Value.GetCatamarans)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"CatamaranStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("CatamaranStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_catamaranStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningCatamaran? catamaran =
elem?.CreateDrawningCatamaran(_separatorForObject, _pictureWidth, _pictureHeight);
if (catamaran != null)
{
if (!(collection + catamaran))
{
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_catamaranStorages.Add(record[0], collection);
}
}
}
}

View File

@@ -20,11 +20,11 @@ namespace Catamaran.DrawningObjects
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
public int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
public int _pictureHeight;
/// <summary>
/// Левая координата прорисовки катамарана
/// </summary>
@@ -220,6 +220,20 @@ namespace Catamaran.DrawningObjects
SolidBrush brushBrown = new SolidBrush(Color.Brown);
g.FillEllipse(brushBrown, _startPosX + 30, _startPosY + 60, 100, 40);
}
public void SetColor(Color color)
{
if (EntityCatamaran == null)
{
return;
}
EntityCatamaran.BodyColor = color;
}
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
}
}

View File

@@ -84,6 +84,10 @@ namespace Catamaran.DrawningObjects
g.DrawRectangle(pen, _startPosX + 70, _startPosY, 3, 85);
}
}
public void SetAddColor(Color color)
{
((EntitySailCatamaran)EntityCatamaran).AdditionalColor = color;
}
}
}

View File

@@ -22,7 +22,7 @@ namespace Catamaran.Entities
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения катамарана
/// </summary>
@@ -33,12 +33,17 @@ namespace Catamaran.Entities
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityCatamaran(int speed, double weight, Color bodyColor)
public EntityCatamaran(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
public void setBodyColor(Color color)
{
BodyColor = color;
}
}
}

View File

@@ -14,7 +14,7 @@ namespace Catamaran.Entities
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия паруса
/// </summary>
@@ -39,5 +39,9 @@ namespace Catamaran.Entities
Sail = sail;
FloatDetail = floatDetail;
}
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.Entities;
namespace Catamaran.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityCatamaran
/// </summary>
public static class ExtentionDrawningCatamaran
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningCatamaran? CreateDrawningCatamaran(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningCatamaran(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningSailCatamaran(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCatamaran">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningCatamaran drawningCatamaran,
char separatorForObject)
{
var catamaran = drawningCatamaran.EntityCatamaran;
if (catamaran == null)
{
return string.Empty;
}
var str = $"{catamaran.Speed}{separatorForObject}{catamaran.Weight}{separatorForObject}{catamaran.BodyColor.Name}";
if (catamaran is not EntitySailCatamaran sailCatamaran)
{
return str;
}
return
$"{str}{separatorForObject}{sailCatamaran.AdditionalColor.Name}{separatorForObject}{sailCatamaran.Sail}{separatorForObject}{sailCatamaran.FloatDetail}";
}
}
}

View File

@@ -30,28 +30,43 @@
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBoxTools = new System.Windows.Forms.GroupBox();
this.groupBoxSets = new System.Windows.Forms.GroupBox();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.buttonDelObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox();
this.buttonAddObject = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.ButtonRemoveCatamaran = new System.Windows.Forms.Button();
this.ButtonAddCatamaran = new System.Windows.Forms.Button();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.groupBoxTools.SuspendLayout();
this.groupBoxSets.SuspendLayout();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 1);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(741, 459);
this.pictureBoxCollection.Size = new System.Drawing.Size(736, 459);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.groupBoxSets);
this.groupBoxTools.Controls.Add(this.maskedTextBoxNumber);
this.groupBoxTools.Controls.Add(this.ButtonRefreshCollection);
this.groupBoxTools.Controls.Add(this.ButtonRemoveCatamaran);
this.groupBoxTools.Controls.Add(this.ButtonAddCatamaran);
this.groupBoxTools.Controls.Add(this.menuStrip);
this.groupBoxTools.Location = new System.Drawing.Point(739, 1);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(147, 460);
@@ -59,18 +74,68 @@
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
//
// groupBoxSets
//
this.groupBoxSets.Controls.Add(this.textBoxStorageName);
this.groupBoxSets.Controls.Add(this.buttonDelObject);
this.groupBoxSets.Controls.Add(this.listBoxStorages);
this.groupBoxSets.Controls.Add(this.buttonAddObject);
this.groupBoxSets.Location = new System.Drawing.Point(3, 63);
this.groupBoxSets.Name = "groupBoxSets";
this.groupBoxSets.Size = new System.Drawing.Size(138, 203);
this.groupBoxSets.TabIndex = 4;
this.groupBoxSets.TabStop = false;
this.groupBoxSets.Text = "Наборы";
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(6, 22);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(130, 23);
this.textBoxStorageName.TabIndex = 4;
//
// buttonDelObject
//
this.buttonDelObject.Location = new System.Drawing.Point(3, 167);
this.buttonDelObject.Name = "buttonDelObject";
this.buttonDelObject.Size = new System.Drawing.Size(134, 27);
this.buttonDelObject.TabIndex = 3;
this.buttonDelObject.Text = "Удалить набор";
this.buttonDelObject.UseVisualStyleBackColor = true;
this.buttonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click);
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 15;
this.listBoxStorages.Location = new System.Drawing.Point(6, 82);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(132, 79);
this.listBoxStorages.TabIndex = 2;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.ListBoxObjects_SelectedIndexChanged);
//
// buttonAddObject
//
this.buttonAddObject.Location = new System.Drawing.Point(6, 51);
this.buttonAddObject.Name = "buttonAddObject";
this.buttonAddObject.Size = new System.Drawing.Size(131, 25);
this.buttonAddObject.TabIndex = 1;
this.buttonAddObject.Text = "Добавить набор";
this.buttonAddObject.UseVisualStyleBackColor = true;
this.buttonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(0, 108);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(3, 321);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(141, 23);
this.maskedTextBoxNumber.Size = new System.Drawing.Size(137, 23);
this.maskedTextBoxNumber.TabIndex = 3;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(0, 211);
this.ButtonRefreshCollection.Location = new System.Drawing.Point(0, 420);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(141, 34);
this.ButtonRefreshCollection.Size = new System.Drawing.Size(140, 34);
this.ButtonRefreshCollection.TabIndex = 2;
this.ButtonRefreshCollection.Text = "Обновить коллекцию";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
@@ -78,9 +143,9 @@
//
// ButtonRemoveCatamaran
//
this.ButtonRemoveCatamaran.Location = new System.Drawing.Point(0, 157);
this.ButtonRemoveCatamaran.Location = new System.Drawing.Point(0, 363);
this.ButtonRemoveCatamaran.Name = "ButtonRemoveCatamaran";
this.ButtonRemoveCatamaran.Size = new System.Drawing.Size(141, 34);
this.ButtonRemoveCatamaran.Size = new System.Drawing.Size(140, 34);
this.ButtonRemoveCatamaran.TabIndex = 1;
this.ButtonRemoveCatamaran.Text = "Удалить катамаран";
this.ButtonRemoveCatamaran.UseVisualStyleBackColor = true;
@@ -88,26 +153,68 @@
//
// ButtonAddCatamaran
//
this.ButtonAddCatamaran.Location = new System.Drawing.Point(0, 22);
this.ButtonAddCatamaran.Location = new System.Drawing.Point(3, 270);
this.ButtonAddCatamaran.Name = "ButtonAddCatamaran";
this.ButtonAddCatamaran.Size = new System.Drawing.Size(141, 34);
this.ButtonAddCatamaran.Size = new System.Drawing.Size(137, 34);
this.ButtonAddCatamaran.TabIndex = 0;
this.ButtonAddCatamaran.Text = "Добавить катамаран";
this.ButtonAddCatamaran.UseVisualStyleBackColor = true;
this.ButtonAddCatamaran.Click += new System.EventHandler(this.ButtonAddCatamaran_Click);
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(3, 19);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(141, 24);
this.menuStrip.TabIndex = 5;
this.menuStrip.Text = "menuStrip";
//
// ToolStripMenuItem
//
this.ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.ToolStripMenuItem.Name = "ToolStripMenuItem";
this.ToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.ToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
//
// FormCatamaranCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 461);
this.ClientSize = new System.Drawing.Size(885, 461);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.pictureBoxCollection);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormCatamaranCollection";
this.Text = "FormCatamaranCollection";
this.Text = "Набор катамаранов";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
this.groupBoxSets.ResumeLayout(false);
this.groupBoxSets.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
}
@@ -120,5 +227,16 @@
private Button ButtonRefreshCollection;
private Button ButtonRemoveCatamaran;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBoxSets;
private Button buttonAddObject;
private Button buttonDelObject;
private ListBox listBoxStorages;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@@ -1,6 +1,18 @@
using Catamaran.DrawningObjects;
using Microsoft.Extensions.Logging;
using Catamaran.DrawningObjects;
using Catamaran.Exceptions;
using Catamaran.Generics;
using Catamaran.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Catamaran
{
@@ -12,59 +24,189 @@ namespace Catamaran
/// <summary>
/// Набор объектов
/// </summary>
private readonly CatamaransGenericCollection<DrawningCatamaran,
DrawningObjectCatamaran> _catamarans;
private readonly CatamaransGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormCatamaranCollection()
public FormCatamaranCollection(ILogger<FormCatamaranCollection> logger)
{
InitializeComponent();
_catamarans = new CatamaransGenericCollection<DrawningCatamaran,
DrawningObjectCatamaran>(pictureBoxCollection.Width, pictureBoxCollection.Height);
_storage = new CatamaransGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Добавление объекта в набор
/// Заполнение listBoxStorages
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}");
}
private void AddCatamaran(DrawningCatamaran drawningCatamaran)
{
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
if (obj + drawningCatamaran)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowCatamarans();
_logger.LogInformation($"Объект добавлен");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
}
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowCatamarans();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ??string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddCatamaran_Click(object sender, EventArgs e)
{
FormCatamaran form = new();
if (form.ShowDialog() == DialogResult.OK)
if (listBoxStorages.SelectedIndex == -1)
{
if (_catamarans + form.SelectedCatamaran != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _catamarans.ShowCatamarans();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
_logger.LogWarning("Коллекция не выбрана");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
var formBoatConfig = new FormCatamaranConfig();
// TODO Call method AddEvent from FormCatamaranConfig
var FormCatamaranConfig = new FormCatamaranConfig();
FormCatamaranConfig.AddEvent(AddCatamaran);
FormCatamaranConfig.Show();
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// </summary>listBoxStorages
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveCatamaran_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_catamarans - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _catamarans.ShowCatamarans();
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowCatamarans();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
else
catch (CatamaranNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"Нет объекта{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
catch (FormatException)
{
_logger.LogWarning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
/// <summary>
@@ -75,7 +217,65 @@ namespace Catamaran
private void ButtonRefreshCollection_Click(object sender, EventArgs
e)
{
pictureBoxCollection.Image = _catamarans.ShowCatamarans();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowCatamarans();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
ReloadObjects();
}
}
}
}

View File

@@ -57,4 +57,16 @@
<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>125, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>254, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>96</value>
</metadata>
</root>

View File

@@ -0,0 +1,414 @@
namespace Catamaran
{
partial class FormCatamaranConfig
{
/// <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()
{
this.groupBoxParameters = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelRed = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.checkBoxSail = new System.Windows.Forms.CheckBox();
this.checkBoxFloatDetails = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOk = new System.Windows.Forms.Button();
this.labelAddColor = new System.Windows.Forms.Label();
this.labelBodyColor = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.groupBoxParameters.SuspendLayout();
this.groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxParameters
//
this.groupBoxParameters.Controls.Add(this.labelModifiedObject);
this.groupBoxParameters.Controls.Add(this.labelSimpleObject);
this.groupBoxParameters.Controls.Add(this.groupBoxColor);
this.groupBoxParameters.Controls.Add(this.checkBoxSail);
this.groupBoxParameters.Controls.Add(this.checkBoxFloatDetails);
this.groupBoxParameters.Controls.Add(this.numericUpDownWeight);
this.groupBoxParameters.Controls.Add(this.numericUpDownSpeed);
this.groupBoxParameters.Controls.Add(this.labelWeight);
this.groupBoxParameters.Controls.Add(this.labelSpeed);
this.groupBoxParameters.Location = new System.Drawing.Point(18, 9);
this.groupBoxParameters.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxParameters.Name = "groupBoxParameters";
this.groupBoxParameters.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxParameters.Size = new System.Drawing.Size(524, 260);
this.groupBoxParameters.TabIndex = 0;
this.groupBoxParameters.TabStop = false;
this.groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelModifiedObject.Location = new System.Drawing.Point(399, 205);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(106, 28);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelSimpleObject.Location = new System.Drawing.Point(274, 205);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(109, 28);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColor
//
this.groupBoxColor.Controls.Add(this.panelRed);
this.groupBoxColor.Controls.Add(this.panelBlue);
this.groupBoxColor.Controls.Add(this.panelYellow);
this.groupBoxColor.Controls.Add(this.panelWhite);
this.groupBoxColor.Controls.Add(this.panelGray);
this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelPurple);
this.groupBoxColor.Controls.Add(this.panelGreen);
this.groupBoxColor.Location = new System.Drawing.Point(274, 28);
this.groupBoxColor.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxColor.Size = new System.Drawing.Size(231, 162);
this.groupBoxColor.TabIndex = 6;
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Tomato;
this.panelRed.Location = new System.Drawing.Point(6, 29);
this.panelRed.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 1;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.CornflowerBlue;
this.panelBlue.Location = new System.Drawing.Point(125, 29);
this.panelBlue.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(40, 40);
this.panelBlue.TabIndex = 1;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Gold;
this.panelYellow.Location = new System.Drawing.Point(187, 29);
this.panelYellow.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(40, 40);
this.panelYellow.TabIndex = 1;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(5, 86);
this.panelWhite.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(40, 40);
this.panelWhite.TabIndex = 1;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(65, 86);
this.panelGray.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(40, 40);
this.panelGray.TabIndex = 1;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(125, 86);
this.panelBlack.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 1;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Violet;
this.panelPurple.Location = new System.Drawing.Point(187, 86);
this.panelPurple.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(40, 40);
this.panelPurple.TabIndex = 1;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.LightGreen;
this.panelGreen.Location = new System.Drawing.Point(65, 29);
this.panelGreen.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
this.panelGreen.TabIndex = 0;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxSail
//
this.checkBoxSail.AutoSize = true;
this.checkBoxSail.Location = new System.Drawing.Point(13, 148);
this.checkBoxSail.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.checkBoxSail.Name = "checkBoxSail";
this.checkBoxSail.Size = new System.Drawing.Size(164, 19);
this.checkBoxSail.TabIndex = 5;
this.checkBoxSail.Text = "Признак наличия паруса";
this.checkBoxSail.UseVisualStyleBackColor = true;
//
// checkBoxFloatDetails
//
this.checkBoxFloatDetails.AutoSize = true;
this.checkBoxFloatDetails.Location = new System.Drawing.Point(13, 114);
this.checkBoxFloatDetails.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.checkBoxFloatDetails.Name = "checkBoxFloatDetails";
this.checkBoxFloatDetails.Size = new System.Drawing.Size(185, 19);
this.checkBoxFloatDetails.TabIndex = 4;
this.checkBoxFloatDetails.Text = "Признак наличия поплавков";
this.checkBoxFloatDetails.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(94, 60);
this.numericUpDownWeight.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(51, 23);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(94, 28);
this.numericUpDownSpeed.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(59, 23);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(13, 68);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(26, 15);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(13, 36);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(59, 15);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость";
//
// panel1
//
this.panel1.AllowDrop = true;
this.panel1.Controls.Add(this.buttonCancel);
this.panel1.Controls.Add(this.buttonOk);
this.panel1.Controls.Add(this.labelAddColor);
this.panel1.Controls.Add(this.labelBodyColor);
this.panel1.Controls.Add(this.pictureBoxObject);
this.panel1.Location = new System.Drawing.Point(560, 9);
this.panel1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(312, 263);
this.panel1.TabIndex = 0;
this.panel1.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panel1.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(175, 223);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(108, 24);
this.buttonCancel.TabIndex = 12;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(38, 223);
this.buttonOk.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(108, 24);
this.buttonOk.TabIndex = 11;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// labelAddColor
//
this.labelAddColor.AllowDrop = true;
this.labelAddColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAddColor.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelAddColor.Location = new System.Drawing.Point(175, 22);
this.labelAddColor.Name = "labelAddColor";
this.labelAddColor.Size = new System.Drawing.Size(109, 28);
this.labelAddColor.TabIndex = 10;
this.labelAddColor.Text = "Доп. цвет";
this.labelAddColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAddColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelAddColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelBodyColor
//
this.labelBodyColor.AllowDrop = true;
this.labelBodyColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBodyColor.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelBodyColor.Location = new System.Drawing.Point(38, 22);
this.labelBodyColor.Name = "labelBodyColor";
this.labelBodyColor.Size = new System.Drawing.Size(109, 28);
this.labelBodyColor.TabIndex = 9;
this.labelBodyColor.Text = "Цвет";
this.labelBodyColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBodyColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelBodyColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(15, 58);
this.pictureBoxObject.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(282, 160);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// FormCatamaranConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 277);
this.Controls.Add(this.panel1);
this.Controls.Add(this.groupBoxParameters);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormCatamaranConfig";
this.Text = "FormShipConfig";
this.groupBoxParameters.ResumeLayout(false);
this.groupBoxParameters.PerformLayout();
this.groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private GroupBox groupBoxColor;
private Panel panelRed;
private Panel panelBlue;
private Panel panelYellow;
private Panel panelWhite;
private Panel panelGray;
private Panel panelBlack;
private Panel panelPurple;
private Panel panelGreen;
private CheckBox checkBoxSail;
private CheckBox checkBoxFloatDetails;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Panel panel1;
private Button buttonOk;
private Label labelAddColor;
private Label labelBodyColor;
private PictureBox pictureBoxObject;
private Button buttonCancel;
}
}

View File

@@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Catamaran.DrawningObjects;
using Catamaran.Entities;
using Catamaran.Generics;
using Catamaran.MovementStrategy;
namespace Catamaran
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormCatamaranConfig : Form
{
/// <summary>
/// Переменная-выбранный катамаран
/// </summary>
DrawningCatamaran? _catamaran = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningCatamaran>? EventAddCatamaran;
/// <summary>
/// Конструктор
/// </summary>
public FormCatamaranConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
// TODO buttonCancel.Click with lambda
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать катамаран
/// </summary>
private void DrawCatamaran()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_catamaran?.SetPosition(5, 5);
_catamaran?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
internal void AddEvent(Action<DrawningCatamaran> ev)
{
if (EventAddCatamaran == null)
{
EventAddCatamaran = ev;
}
else
{
EventAddCatamaran += ev;
}
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <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,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
ILogger<FormCatamaranCollection> logger = new NullLogger<FormCatamaranCollection>();
FormCatamaranCollection form = new FormCatamaranCollection(logger);
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_catamaran = new DrawningCatamaran((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_catamaran = new DrawningSailCatamaran((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxSail.Checked,
checkBoxFloatDetails.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawCatamaran();
}
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_catamaran == null)
return;
switch (((Label)sender).Name)
{
case "labelBodyColor":
_catamaran.SetColor((Color)e.Data.GetData(typeof(Color)));
break;
case "labelAddColor":
if (!(_catamaran is DrawningSailCatamaran))
return;
(_catamaran as DrawningSailCatamaran).SetAddColor((Color)e.Data.GetData(typeof(Color)));
break;
}
DrawCatamaran();
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Добавление машины
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddCatamaran?.Invoke(_catamaran);
Close();
}
};
};

View File

@@ -0,0 +1,60 @@
<root>
<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,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Catamaran
{
internal static class Program
@@ -8,10 +14,31 @@ namespace Catamaran
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormCatamaranCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormCatamaranCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormCatamaranCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -1,10 +1,12 @@
using System;
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran
namespace Catamaran.Generics
{
/// <summary>
/// Параметризованный набор объектов
@@ -14,67 +16,50 @@ namespace Catamaran
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// Список объектов, которые храним
/// </summary>
private readonly T?[] _places;
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// Количество объектов в списке
/// </summary>
public int Count => _places.Length;
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
_maxCount = count;
_places = new List<T?>(_maxCount);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый катамаран</param>
/// <returns></returns>
public int Insert(T catamaran)
public bool Insert(T catamaran)
{
// TODO вставка в начало набора
return Insert(catamaran, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="catamaran">Добавляемый катамаран</param>
/// <param name="boat">Добавляемая лодка</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T catamaran, int position)
public bool Insert(T catamaran, int position)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой,
//если нет, то проверка, что после вставляемого элемента в массиве есть пустой элемент
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
// TODO вставка по позиции
int nullIndex = -1, i;
if (position < 0 || position >= _maxCount)
throw new CatamaranNotFoundException(position);
if (position < 0 || position >= Count)
return -1;
for (i = position; i < Count; i++)
{
if (_places[i] == null)
{
nullIndex = i;
break;
}
}
if (nullIndex < 0)
return -1;
for (i = nullIndex; i > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = catamaran;
return position;
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
_places.Insert(0, catamaran);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@@ -85,9 +70,15 @@ namespace Catamaran
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position < 0 || position >= Count) {
return false; }
_places[position] = null;
if (position >= Count || position < 0)
{
throw new CatamaranNotFoundException("Invalid operation");
}
if (_places[position] == null)
{
throw new CatamaranNotFoundException(position);
}
_places.RemoveAt(position);
return true;
}
/// <summary>
@@ -95,12 +86,40 @@ namespace Catamaran
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
public T? this[int position]
{
// TODO проверка позиции
if (position < 0 || position >= Count)
return null;
return _places[position];
get
{
// TODO проверка позиции
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
set
{
// TODO проверка позиции
// TODO проверка свободных мест в списке
// TODO вставка в список по позиции
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
return;
_places.Insert(position, value);
return;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetCatamarans(int? maxCatamarans = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxCatamarans.HasValue && i == maxCatamarans.Value)
{
yield break;
}
}
}
}
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Catamaran.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception)
: base(message, exception) { }
protected StorageOverflowException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

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