From 34fb706739a19b7268e85cce0a4e42391c4aa9a4 Mon Sep 17 00:00:00 2001
From: ALINA_KURBANOVA <Алина@DESKTOP-PH8VQJA>
Date: Fri, 29 Dec 2023 21:05:52 +0400
Subject: [PATCH] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B0=D0=BB=D0=B0=20=D0=B8?=
=?UTF-8?q?=20=D0=B7=D0=B0=D0=BA=D0=BE=D0=BD=D1=87=D0=B8=D0=BB=D0=B0=207?=
=?UTF-8?q?=D0=BB=D0=B0=D0=B1=D1=83?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
WarmlyLocomotive/DrawningWarmlyLocomotive.cs | 18 +-
...FormWarmlyLocomotiveCollection.Designer.cs | 1 -
.../FormWarmlyLocomotiveCollection.cs | 172 ++++++++----------
.../FormWarmlyLocomotiveConfig.Designer.cs | 5 +-
.../FormWarmlyLocomotiveConfig.cs | 99 +++++-----
WarmlyLocomotive/Program.cs | 27 ++-
WarmlyLocomotive/SetGeneric.cs | 91 +++------
WarmlyLocomotive/WarmlyLocomotive.csproj | 11 ++
.../WarmlyLocomotivesGenericCollectioncs.cs | 4 +-
.../WarmlyLocomotivesGenericStorage.cs | 129 ++++++-------
10 files changed, 258 insertions(+), 299 deletions(-)
diff --git a/WarmlyLocomotive/DrawningWarmlyLocomotive.cs b/WarmlyLocomotive/DrawningWarmlyLocomotive.cs
index 3c5ec72..81c682c 100644
--- a/WarmlyLocomotive/DrawningWarmlyLocomotive.cs
+++ b/WarmlyLocomotive/DrawningWarmlyLocomotive.cs
@@ -1,12 +1,12 @@
using WarmlyLocomotive.Entities;
using WarmlyLocomotive.MovementStrategy;
-namespace WarmlyLocomotive.DrawningObjects
-{
-///
-/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
-///
-public class DrawningWarmlyLocomotive
+namespace WarmlyLocomotive.DrawningObjects
+{
+ ///
+ /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
+ ///
+ public class DrawningWarmlyLocomotive
{
///
/// Класс-сущность
@@ -185,10 +185,14 @@ public class DrawningWarmlyLocomotive
g.FillEllipse(wheelBrush, _startPosX + 145, _startPosY + 50, 20, 20);
g.FillEllipse(wheelBrush, _startPosX + 170, _startPosY + 50, 20, 20);
}
+ public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
+ {
+ _pictureWidth = pictureBoxWidth;
+ _pictureHeight = pictureBoxHeight;
+ }
}
}
-
diff --git a/WarmlyLocomotive/FormWarmlyLocomotiveCollection.Designer.cs b/WarmlyLocomotive/FormWarmlyLocomotiveCollection.Designer.cs
index 2ee662e..5bba14b 100644
--- a/WarmlyLocomotive/FormWarmlyLocomotiveCollection.Designer.cs
+++ b/WarmlyLocomotive/FormWarmlyLocomotiveCollection.Designer.cs
@@ -128,7 +128,6 @@
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(218, 164);
listBoxStorages.TabIndex = 1;
- listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// buttonAddObject
//
diff --git a/WarmlyLocomotive/FormWarmlyLocomotiveCollection.cs b/WarmlyLocomotive/FormWarmlyLocomotiveCollection.cs
index e44c0cb..1953b84 100644
--- a/WarmlyLocomotive/FormWarmlyLocomotiveCollection.cs
+++ b/WarmlyLocomotive/FormWarmlyLocomotiveCollection.cs
@@ -1,33 +1,21 @@
-using WarmlyLocomotive.Generics;
-using WarmlyLocomotive.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 WarmlyLocomotive.Exceptions;
+using WarmlyLocomotive.Generics;
+using Microsoft.Extensions.Logging;
using System.Windows.Forms;
-using static System.Windows.Forms.DataFormats;
using WarmlyLocomotive.DrawningObjects;
+using Serilog;
namespace WarmlyLocomotive
{
public partial class FormWarmlyLocomotiveCollection : Form
{
- ///
- /// Набор объектов
- ///
private readonly WarmlyLocomotivesGenericStorage _storage;
+
public FormWarmlyLocomotiveCollection()
{
InitializeComponent();
_storage = new WarmlyLocomotivesGenericStorage(pictureBoxCollectionWarmlyLocomotive.Width, pictureBoxCollectionWarmlyLocomotive.Height);
}
- ///
- /// Заполнение listBoxObjects
- ///
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
@@ -47,76 +35,73 @@ namespace WarmlyLocomotive
listBoxStorages.SelectedIndex = index;
}
}
- ///
- /// Выбор набора
- ///
- ///
- ///
- private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
+ private void buttonAddObject_Click(object sender, EventArgs e)
{
- pictureBoxCollectionWarmlyLocomotive.Image =
- _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowWarmlyLocomotives();
+ if (string.IsNullOrEmpty(textBoxStorageName.Text))
+ {
+ MessageBox.Show("Не все данные заполнены", "Ошибка",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
+ return;
+ }
+ _storage.AddSet(textBoxStorageName.Text);
+ ReloadObjects();
+ Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
+ }
+ private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
+ {
+ pictureBoxCollectionWarmlyLocomotive.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowWarmlyLocomotives();
}
- ///
- /// Удаление набора
- ///
- ///
- ///
private void buttonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
- if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?",
- "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
+ if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
+ MessageBoxIcon.Question) == DialogResult.Yes)
{
- _storage.DelSet(listBoxStorages.SelectedItem.ToString()
- ?? string.Empty);
+ string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
+ _storage.DelSet(name);
ReloadObjects();
+ Log.Information($"Удален набор: {name}");
}
}
-
- ///
- /// Добавление объекта в набор
- ///
- ///
- ///
private void buttonAdd_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
- var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
- string.Empty];
+ var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
- FormWarmlyLocomotiveConfig form = new FormWarmlyLocomotiveConfig(pictureBoxCollectionWarmlyLocomotive.Width, pictureBoxCollectionWarmlyLocomotive.Height);
+ FormWarmlyLocomotiveConfig form = new FormWarmlyLocomotiveConfig();
form.Show();
- Action? warmlydelegate = new((m) =>
+ Action? warmlylocomotiveDelegate = new((warmlylocomotive) =>
{
- bool q = (obj + m);
- if (q)
+ try
{
+ bool q = obj + warmlylocomotive;
MessageBox.Show("Объект добавлен");
+ warmlylocomotive.ChangePictureBoxSize(pictureBoxCollectionWarmlyLocomotive.Width, pictureBoxCollectionWarmlyLocomotive.Height);
pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives();
+ Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
- else
+ catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
+ Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
+ MessageBox.Show(ex.Message);
}
});
- form.AddEvent(warmlydelegate);
+ Action? ColorDelegate = new((ship) =>
+ {
+ MessageBox.Show(ship.ToString());
+ });
+ form.AddEvent(warmlylocomotiveDelegate);
}
-
- ///
- /// Удаление объекта из набора
- ///
- ///
- ///
private void buttonRemove_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@@ -134,22 +119,25 @@ namespace WarmlyLocomotive
{
return;
}
- int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
- if (obj - pos != null)
+ try
{
+ int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
+ var q = obj - pos;
MessageBox.Show("Объект удален");
+ Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives();
}
- else
+ catch (WarmlyLocomotiveNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
+ MessageBox.Show(ex.Message);
+ }
+ catch (FormatException)
+ {
+ Log.Warning($"Было введено не число");
+ MessageBox.Show("Введите число");
}
}
- ///
- /// Обновление рисунка по набору
- ///
- ///
- ///
private void buttonreFreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@@ -164,53 +152,45 @@ namespace WarmlyLocomotive
}
pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives();
}
- ///
- /// Добавление набора в коллекцию
- ///
- ///
- ///
- private void buttonAddObject_Click(object sender, EventArgs e)
+ private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
- if (string.IsNullOrEmpty(textBoxStorageName.Text))
+ if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- MessageBox.Show("Не все данные заполнены", "Ошибка",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
+ try
+ {
+ _storage.SaveData(saveFileDialog.FileName);
+ MessageBox.Show("Сохранение прошло успешно",
+ "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("Не удалось сохранить");
+ MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
}
- _storage.AddSet(textBoxStorageName.Text);
- ReloadObjects();
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.LoadData(openFileDialog.FileName))
+ try
{
- MessageBox.Show("Загрузка прошло успешно",
+ _storage.LoadData(openFileDialog.FileName);
+ MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
+ foreach (var collection in _storage.Keys)
+ {
+ listBoxStorages.Items.Add(collection);
+ }
ReloadObjects();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не загрузилось", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- }
- private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
- {
- if (saveFileDialog.ShowDialog() == DialogResult.OK)
- {
- if (_storage.SaveData(saveFileDialog.FileName))
- {
- MessageBox.Show("Сохранение прошло успешно",
- "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- else
- {
- MessageBox.Show("Не сохранилось", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ Log.Warning("Не удалось загрузить");
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
diff --git a/WarmlyLocomotive/FormWarmlyLocomotiveConfig.Designer.cs b/WarmlyLocomotive/FormWarmlyLocomotiveConfig.Designer.cs
index e6a6313..851c353 100644
--- a/WarmlyLocomotive/FormWarmlyLocomotiveConfig.Designer.cs
+++ b/WarmlyLocomotive/FormWarmlyLocomotiveConfig.Designer.cs
@@ -317,8 +317,7 @@
labelAdditionalColor.Size = new Size(147, 62);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
- labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
- labelAdditionalColor.DragDrop += labelAddColor_DragDrop;
+ labelAdditionalColor.DragDrop += LabelColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// labelMainColor
@@ -332,7 +331,7 @@
labelMainColor.TabIndex = 2;
labelMainColor.Text = "Цвет";
labelMainColor.TextAlign = ContentAlignment.MiddleCenter;
- labelMainColor.DragDrop += labelColor_DragDrop;
+ labelMainColor.DragDrop += LabelColor_DragDrop;
labelMainColor.DragEnter += labelColor_DragEnter;
//
// FormWarmlyLocomotiveConfig
diff --git a/WarmlyLocomotive/FormWarmlyLocomotiveConfig.cs b/WarmlyLocomotive/FormWarmlyLocomotiveConfig.cs
index 9270c79..e88e21f 100644
--- a/WarmlyLocomotive/FormWarmlyLocomotiveConfig.cs
+++ b/WarmlyLocomotive/FormWarmlyLocomotiveConfig.cs
@@ -1,4 +1,5 @@
-using WarmlyLocomotive.DrawningObjects;
+using System.Windows.Forms;
+using WarmlyLocomotive.DrawningObjects;
using WarmlyLocomotive.Entities;
namespace WarmlyLocomotive
@@ -9,8 +10,6 @@ namespace WarmlyLocomotive
///
public partial class FormWarmlyLocomotiveConfig : Form
{
- public int _pictureWidth { get; private set; }
- public int _pictureHeight { get; private set; }
///
/// Переменная
///
@@ -19,10 +18,8 @@ namespace WarmlyLocomotive
/// Событие
///
public event Action? EventAddWarmlyLocomotive;
- public FormWarmlyLocomotiveConfig(int pictureWidth, int pictureHeight)
+ public FormWarmlyLocomotiveConfig()
{
- _pictureWidth = pictureWidth;
- _pictureHeight = pictureHeight;
InitializeComponent();
panelRed.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
@@ -42,7 +39,12 @@ namespace WarmlyLocomotive
_warmlylocomotive?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
- public void AddEvent(Action ev)
+
+ ///
+ /// Добавление события
+ ///
+ /// Привязанный метод
+ internal void AddEvent(Action ev)
{
if (EventAddWarmlyLocomotive == null)
{
@@ -53,10 +55,14 @@ namespace WarmlyLocomotive
EventAddWarmlyLocomotive += ev;
}
}
+ ///
+ /// Передаем информацию при нажатии на Label
+ ///
+ ///
+ ///
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
- (sender as Label)?.DoDragDrop((sender as Label)?.Name,
- DragDropEffects.Move | DragDropEffects.Copy);
+ (sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
///
/// Проверка получаемой информации (ее типа на соответствие требуемому)
@@ -85,53 +91,26 @@ namespace WarmlyLocomotive
{
case "labelBasic":
_warmlylocomotive = new DrawningWarmlyLocomotive((int)numericUpDownSpeed.Value,
- (int)numericUpDownWeight.Value, Color.White, _pictureWidth, _pictureHeight);
+ (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
+ pictureBoxObject.Height);
break;
case "labelAdvanced":
_warmlylocomotive = new DrawningWarmlyLocomotiveWithTrumpet((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxTrumpet.Checked,
- checkBoxLuggage.Checked, _pictureWidth, _pictureHeight);
+ checkBoxLuggage.Checked, pictureBoxObject.Width,
+ pictureBoxObject.Height);
break;
}
DrawWarmlyLocomotive();
}
- private void PanelColor_MouseDown(object? sender, MouseEventArgs e)
+
+ private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
- (sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
- DragDropEffects.Move | DragDropEffects.Copy);
- }
- ///
- /// Добавление
- ///
- ///
- ///
- private void ButtonAdd_Click(object sender, EventArgs e)
- {
- if (_warmlylocomotive == null)
- return;
- EventAddWarmlyLocomotive?.Invoke(_warmlylocomotive);
- Close();
- }
- private void labelColor_DragDrop(object sender, DragEventArgs e)
- {
- if (_warmlylocomotive?.EntityWarmlyLocomotive == null)
- return;
- switch (((Label)sender).Name)
- {
- case "labelMainColor":
- _warmlylocomotive?.EntityWarmlyLocomotive?.setBodyColor((Color)e.Data.GetData(typeof(Color)));
- break;
- case "labelAdditionalColor":
- if (!(_warmlylocomotive is DrawningWarmlyLocomotiveWithTrumpet))
- return;
- (_warmlylocomotive.EntityWarmlyLocomotive as EntityWarmlyLocomotiveWithTrumpet)?.setAdditionalColor(color: (Color)e.Data.GetData(typeof(Color)));
- break;
- }
- DrawWarmlyLocomotive();
+ (sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
- if (e.Data.GetDataPresent(typeof(Color)))
+ if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
@@ -140,16 +119,34 @@ namespace WarmlyLocomotive
e.Effect = DragDropEffects.None;
}
}
- private void labelAddColor_DragDrop(object sender, DragEventArgs e)
+ private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
- if ((_warmlylocomotive?.EntityWarmlyLocomotive == null) || (_warmlylocomotive is DrawningWarmlyLocomotiveWithTrumpet == false))
+
+ if (_warmlylocomotive == null)
return;
- Color additionalColor = (Color)e.Data.GetData(typeof(Color));
- _warmlylocomotive = new DrawningWarmlyLocomotiveWithTrumpet((int)numericUpDownSpeed.Value,
- (int)numericUpDownWeight.Value, _warmlylocomotive.EntityWarmlyLocomotive.BodyColor, additionalColor, checkBoxTrumpet.Checked,
- checkBoxLuggage.Checked, _pictureWidth, _pictureHeight);
+ switch (((Label)sender).Name)
+ {
+ case "labelMainColor":
+ _warmlylocomotive.EntityWarmlyLocomotive.setBodyColor((Color)e.Data.GetData(typeof(Color)));
+ break;
+ case "labelAdditionalColor":
+ if (!(_warmlylocomotive is DrawningWarmlyLocomotiveWithTrumpet))
+ return;
+ (_warmlylocomotive.EntityWarmlyLocomotive as EntityWarmlyLocomotiveWithTrumpet).setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
+ break;
+ }
DrawWarmlyLocomotive();
}
-
+ ///
+ /// Добавление машины
+ ///
+ ///
+ ///
+
+ private void ButtonAdd_Click(object sender, EventArgs e)
+ {
+ EventAddWarmlyLocomotive?.Invoke(_warmlylocomotive);
+ Close();
+ }
}
}
\ No newline at end of file
diff --git a/WarmlyLocomotive/Program.cs b/WarmlyLocomotive/Program.cs
index 063fbae..befabd0 100644
--- a/WarmlyLocomotive/Program.cs
+++ b/WarmlyLocomotive/Program.cs
@@ -1,15 +1,32 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using Serilog.Events;
+using Serilog.Formatting.Json;
+using Serilog.Configuration;
+
namespace WarmlyLocomotive
{
internal static class Program
{
- ///
- /// The main entry point for the application.
- ///
+
[STAThread]
static void Main()
{
- // To customize application configuration such as set high DPI settings or default font,
- // see https://aka.ms/applicationconfiguration.
+ ApplicationConfiguration.Initialize(); 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}debug.json", optional: false, reloadOnChange: true)
+ .Build();
+ Log.Logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(configuration)
+ .CreateLogger();
ApplicationConfiguration.Initialize();
Application.Run(new FormWarmlyLocomotiveCollection());
}
diff --git a/WarmlyLocomotive/SetGeneric.cs b/WarmlyLocomotive/SetGeneric.cs
index eea1c51..a5148a1 100644
--- a/WarmlyLocomotive/SetGeneric.cs
+++ b/WarmlyLocomotive/SetGeneric.cs
@@ -3,108 +3,75 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using System.Windows.Forms.VisualStyles;
+using WarmlyLocomotive.Exceptions;
+using System;
namespace WarmlyLocomotive.Generics
+
{
- ///
- /// Параметризованный набор объектов
- ///
- ///
internal class SetGeneric
where T : class
{
- ///
- /// Список объектов, которые храним
- ///
private readonly List _places;
- ///
- /// Количество объектов в массиве
- ///
public int Count => _places.Count;
- ///
- /// Максимальное количество объектов в списке
- ///
- private readonly int _maxCount;
- ///
- /// Конструктор
- ///
- ///
+ //public int startPointer = 0;
+
+ public int countMax = 0;
public SetGeneric(int count)
{
- _maxCount = count;
_places = new List(count);
+ countMax = count;
}
- ///
- /// Добавление объекта в набор
- ///
- /// Добавляемый тепловоз
- ///
- public bool Insert(T warmlylocomotive)
+ public bool Insert(T ship)
{
- if (_places.Count == _maxCount)
- {
+ if (_places.Count == countMax)
+ throw new StorageOverflowException(countMax);
+ Insert(ship, 0);
+ return true;
+ }
+ public bool Insert(T ship, int position)
+ {
+ if (_places.Count == countMax)
+ throw new StorageOverflowException(countMax);
+ if (!(position >= 0 && position <= Count && _places.Count < countMax))
return false;
- }
- Insert(warmlylocomotive, 0);
+ _places.Insert(position, ship);
return true;
}
- ///
- /// Добавление объекта в набор на конкретную позицию
- ///
- /// Добавляемый тепловоз
- /// Позиция
- ///
- public bool Insert(T warmlylocomotive, int position)
- {
- if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) return false;
- _places.Insert(position, warmlylocomotive);
- return true;
- }
- ///
- /// Удаление объекта из набора с конкретной позиции
- ///
- ///
- ///
public bool Remove(int position)
{
- if (position < 0 || position >= Count) return false;
+ if (!(position >= 0 && position < Count))
+ throw new WarmlyLocomotiveNotFoundException(position);
_places.RemoveAt(position);
return true;
}
- ///
- /// Получение объекта из набора по позиции
- ///
- ///
- ///
public T? this[int position]
{
get
{
- if (position < 0 || position >= Count) return null;
+ if (!(position >= 0 && position < Count))
+ return null;
return _places[position];
}
set
{
- if (!(position >= 0 && position < Count && _places.Count < _maxCount)) return;
+ if (!(position >= 0 && position < Count && _places.Count < countMax))
+ return;
_places.Insert(position, value);
return;
}
}
- ///
- /// Проход по списку
- ///
- ///
- public IEnumerable GetWarmlyLocomotives(int? maxWarmlyLocomotives = null)
+ public IEnumerable GetWarmlyLocomotive(int? maxShip = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
- if (maxWarmlyLocomotives.HasValue && i == maxWarmlyLocomotives.Value)
+ if (maxShip.HasValue && i == maxShip.Value)
{
yield break;
}
}
}
}
-}
-
+}
\ No newline at end of file
diff --git a/WarmlyLocomotive/WarmlyLocomotive.csproj b/WarmlyLocomotive/WarmlyLocomotive.csproj
index 13ee123..ad8ac2d 100644
--- a/WarmlyLocomotive/WarmlyLocomotive.csproj
+++ b/WarmlyLocomotive/WarmlyLocomotive.csproj
@@ -8,6 +8,17 @@
enable
+
+
+
+
+
+
+
+
+
+
+
True
diff --git a/WarmlyLocomotive/WarmlyLocomotivesGenericCollectioncs.cs b/WarmlyLocomotive/WarmlyLocomotivesGenericCollectioncs.cs
index 9bb9edb..9c5b6ba 100644
--- a/WarmlyLocomotive/WarmlyLocomotivesGenericCollectioncs.cs
+++ b/WarmlyLocomotive/WarmlyLocomotivesGenericCollectioncs.cs
@@ -9,7 +9,7 @@ namespace WarmlyLocomotive.Generics
///
/// Получение объектов коллекции
///
- public IEnumerable GetWarmlyLocomotives => _collection.GetWarmlyLocomotives();
+ public IEnumerable GetWarmlyLocomotives => _collection.GetWarmlyLocomotive();
///
/// Ширина окна прорисовки
///
@@ -121,7 +121,7 @@ namespace WarmlyLocomotive.Generics
{
int i = 0;
int numPlacesInRow = _pictureWidth / _placeSizeWidth;
- foreach (var warmlylocomotive in _collection.GetWarmlyLocomotives())
+ foreach (var warmlylocomotive in _collection.GetWarmlyLocomotive())
{
if (warmlylocomotive != null)
{
diff --git a/WarmlyLocomotive/WarmlyLocomotivesGenericStorage.cs b/WarmlyLocomotive/WarmlyLocomotivesGenericStorage.cs
index 98d7575..c63e1f6 100644
--- a/WarmlyLocomotive/WarmlyLocomotivesGenericStorage.cs
+++ b/WarmlyLocomotive/WarmlyLocomotivesGenericStorage.cs
@@ -1,18 +1,26 @@
-using System.Text;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
using WarmlyLocomotive.DrawningObjects;
using WarmlyLocomotive.MovementStrategy;
+
namespace WarmlyLocomotive.Generics
{
internal class WarmlyLocomotivesGenericStorage
{
- readonly Dictionary> _warmlylocomotiveStorages;
+ readonly Dictionary> _warmlylocomotiveStorages;
public List Keys => _warmlylocomotiveStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
+ private static readonly char _separatorForKeyValue = '|';
+ private readonly char _separatorRecords = ';';
+ private static readonly char _separatorForObject = ':';
public WarmlyLocomotivesGenericStorage(int pictureWidth, int pictureHeight)
{
- _warmlylocomotiveStorages = new Dictionary>();
+ _warmlylocomotiveStorages = new Dictionary>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -31,27 +39,12 @@ namespace WarmlyLocomotive.Generics
get
{
if (_warmlylocomotiveStorages.ContainsKey(ind))
+ {
return _warmlylocomotiveStorages[ind];
+ }
return null;
}
}
- ///
- /// Разделитель для записи ключа и значения элемента словаря
- ///
- private static readonly char _separatorForKeyValue = '|';
- ///
- /// Разделитель для записей коллекции данных в файл
- ///
- private readonly char _separatorRecords = ';';
- ///
- /// Разделитель для записи информации по объекту в файл
- ///
- private static readonly char _separatorForObject = ':';
- ///
- /// Сохранение информации по автомобилям в хранилище в файл
- ///
- /// Путь и имя файла
- /// true - сохранение прошло успешно, false - ошибка при сохранении данных
public bool SaveData(string filename)
{
if (File.Exists(filename))
@@ -59,8 +52,7 @@ namespace WarmlyLocomotive.Generics
File.Delete(filename);
}
StringBuilder data = new();
- foreach (KeyValuePair> record in _warmlylocomotiveStorages)
+ foreach (KeyValuePair> record in _warmlylocomotiveStorages)
{
StringBuilder records = new();
foreach (DrawningWarmlyLocomotive? elem in record.Value.GetWarmlyLocomotives)
@@ -69,74 +61,67 @@ namespace WarmlyLocomotive.Generics
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
+
if (data.Length == 0)
{
- return false;
+ throw new IOException("Невалидная операция, нет данных для сохранения");
+ }
+ string toWrite = $"WarmlyLocomotiveStorage{Environment.NewLine}{data}";
+ var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
+
+ using (StreamWriter sw = new(filename))
+ {
+ foreach (var str in strs)
+ {
+ sw.WriteLine(str);
+ }
}
- using FileStream fs = new(filename, FileMode.Create);
- byte[] info = new
- UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}");
- fs.Write(info, 0, info.Length);
return true;
}
- ///
- /// Загрузка информации по автомобилям в хранилище из файла
- ///
- /// Путь и имя файла
- /// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new IOException("Файл не найден");
}
- string bufferTextFromFile = "";
- using (FileStream fs = new(filename, FileMode.Open))
+ using (StreamReader sr = new(filename))
{
- byte[] b = new byte[fs.Length];
- UTF8Encoding temp = new(true);
- while (fs.Read(b, 0, b.Length) > 0)
+ string str = sr.ReadLine();
+ var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
+ if (strs == null || strs.Length == 0)
{
- bufferTextFromFile += temp.GetString(b);
+ throw new IOException("Нет данных для загрузки");
}
- }
- var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
- StringSplitOptions.RemoveEmptyEntries);
- if (strs == null || strs.Length == 0)
- {
- return false;
- }
- if (!strs[0].StartsWith("CarStorage"))
- {
- //если нет такой записи, то это не те данные
- return false;
- }
- _warmlylocomotiveStorages.Clear();
- foreach (string data in strs)
- {
- string[] record = data.Split(_separatorForKeyValue,
- StringSplitOptions.RemoveEmptyEntries);
- if (record.Length != 2)
+ if (!strs[0].StartsWith("WarmlyLocomotiveStorage"))
{
- continue;
+ throw new IOException("Неверный формат данных");
}
- WarmlyLocomotivesGenericCollection
- collection = new(_pictureWidth, _pictureHeight);
- string[] set = record[1].Split(_separatorRecords,
- StringSplitOptions.RemoveEmptyEntries);
- foreach (string elem in set)
+ _warmlylocomotiveStorages.Clear();
+ do
{
- DrawningWarmlyLocomotive? warmlylocomotive=
- elem?.CreateDrawningWarmlyLocomotive(_separatorForObject, _pictureWidth, _pictureHeight);
- if (warmlylocomotive != null)
+ string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
+ if (record.Length != 2)
{
- if (!(collection + warmlylocomotive))
+ str = sr.ReadLine();
+ continue;
+ }
+ WarmlyLocomotivesGenericCollection collection = new(_pictureWidth, _pictureHeight);
+ string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
+ foreach (string elem in set)
+ {
+ DrawningWarmlyLocomotive? ship = elem?.CreateDrawningWarmlyLocomotive(_separatorForObject, _pictureWidth, _pictureHeight);
+ if (ship != null)
{
- return false;
+ if (!(collection + ship))
+ {
+ return false;
+ }
}
}
- }
- _warmlylocomotiveStorages.Add(record[0], collection);
+ _warmlylocomotiveStorages.Add(record[0], collection);
+
+ str = sr.ReadLine();
+ } while (str != null);
}
return true;
}