Начала и закончила 7лабу

This commit is contained in:
ALINA_KURBANOVA 2023-12-29 21:05:52 +04:00
parent a1cb51e02c
commit 34fb706739
10 changed files with 258 additions and 299 deletions

View File

@ -1,12 +1,12 @@
using WarmlyLocomotive.Entities; using WarmlyLocomotive.Entities;
using WarmlyLocomotive.MovementStrategy; using WarmlyLocomotive.MovementStrategy;
namespace WarmlyLocomotive.DrawningObjects namespace WarmlyLocomotive.DrawningObjects
{ {
/// <summary> /// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary> /// </summary>
public class DrawningWarmlyLocomotive public class DrawningWarmlyLocomotive
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
@ -185,10 +185,14 @@ public class DrawningWarmlyLocomotive
g.FillEllipse(wheelBrush, _startPosX + 145, _startPosY + 50, 20, 20); g.FillEllipse(wheelBrush, _startPosX + 145, _startPosY + 50, 20, 20);
g.FillEllipse(wheelBrush, _startPosX + 170, _startPosY + 50, 20, 20); g.FillEllipse(wheelBrush, _startPosX + 170, _startPosY + 50, 20, 20);
} }
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
} }
} }

View File

@ -128,7 +128,6 @@
listBoxStorages.Name = "listBoxStorages"; listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(218, 164); listBoxStorages.Size = new Size(218, 164);
listBoxStorages.TabIndex = 1; listBoxStorages.TabIndex = 1;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
// //
// buttonAddObject // buttonAddObject
// //

View File

@ -1,33 +1,21 @@
using WarmlyLocomotive.Generics; using WarmlyLocomotive.Exceptions;
using WarmlyLocomotive.MovementStrategy; using WarmlyLocomotive.Generics;
using System; using Microsoft.Extensions.Logging;
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 System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
using WarmlyLocomotive.DrawningObjects; using WarmlyLocomotive.DrawningObjects;
using Serilog;
namespace WarmlyLocomotive namespace WarmlyLocomotive
{ {
public partial class FormWarmlyLocomotiveCollection : Form public partial class FormWarmlyLocomotiveCollection : Form
{ {
/// <summary>
/// Набор объектов
/// </summary>
private readonly WarmlyLocomotivesGenericStorage _storage; private readonly WarmlyLocomotivesGenericStorage _storage;
public FormWarmlyLocomotiveCollection() public FormWarmlyLocomotiveCollection()
{ {
InitializeComponent(); InitializeComponent();
_storage = new WarmlyLocomotivesGenericStorage(pictureBoxCollectionWarmlyLocomotive.Width, pictureBoxCollectionWarmlyLocomotive.Height); _storage = new WarmlyLocomotivesGenericStorage(pictureBoxCollectionWarmlyLocomotive.Width, pictureBoxCollectionWarmlyLocomotive.Height);
} }
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects() private void ReloadObjects()
{ {
int index = listBoxStorages.SelectedIndex; int index = listBoxStorages.SelectedIndex;
@ -47,76 +35,73 @@ namespace WarmlyLocomotive
listBoxStorages.SelectedIndex = index; listBoxStorages.SelectedIndex = index;
} }
} }
/// <summary> private void buttonAddObject_Click(object sender, EventArgs e)
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBoxCollectionWarmlyLocomotive.Image = if (string.IsNullOrEmpty(textBoxStorageName.Text))
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowWarmlyLocomotives(); {
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();
} }
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelObject_Click(object sender, EventArgs e) private void buttonDelObject_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
return; return;
} }
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
?? string.Empty); _storage.DelSet(name);
ReloadObjects(); ReloadObjects();
Log.Information($"Удален набор: {name}");
} }
} }
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e) private void buttonAdd_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
} }
FormWarmlyLocomotiveConfig form = new FormWarmlyLocomotiveConfig(pictureBoxCollectionWarmlyLocomotive.Width, pictureBoxCollectionWarmlyLocomotive.Height); FormWarmlyLocomotiveConfig form = new FormWarmlyLocomotiveConfig();
form.Show(); form.Show();
Action<DrawningWarmlyLocomotive>? warmlydelegate = new((m) => Action<DrawningWarmlyLocomotive>? warmlylocomotiveDelegate = new((warmlylocomotive) =>
{ {
bool q = (obj + m); try
if (q)
{ {
bool q = obj + warmlylocomotive;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
warmlylocomotive.ChangePictureBoxSize(pictureBoxCollectionWarmlyLocomotive.Width, pictureBoxCollectionWarmlyLocomotive.Height);
pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives(); pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives();
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
} }
}); });
form.AddEvent(warmlydelegate); Action<Color>? ColorDelegate = new((ship) =>
{
MessageBox.Show(ship.ToString());
});
form.AddEvent(warmlylocomotiveDelegate);
} }
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemove_Click(object sender, EventArgs e) private void buttonRemove_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
@ -134,22 +119,25 @@ namespace WarmlyLocomotive
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); try
if (obj - pos != null)
{ {
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives(); 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("Введите число");
} }
} }
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonreFreshCollection_Click(object sender, EventArgs e) private void buttonreFreshCollection_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
@ -164,53 +152,45 @@ namespace WarmlyLocomotive
} }
pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives(); pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives();
} }
/// <summary> private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddObject_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", try
MessageBoxButtons.OK, MessageBoxIcon.Error); {
return; _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) private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошло успешно", _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects(); ReloadObjects();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", Log.Warning("Не удалось загрузить");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", 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);
} }
} }
} }

View File

@ -317,8 +317,7 @@
labelAdditionalColor.Size = new Size(147, 62); labelAdditionalColor.Size = new Size(147, 62);
labelAdditionalColor.TabIndex = 3; labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет"; labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter; labelAdditionalColor.DragDrop += LabelColor_DragDrop;
labelAdditionalColor.DragDrop += labelAddColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter; labelAdditionalColor.DragEnter += labelColor_DragEnter;
// //
// labelMainColor // labelMainColor
@ -332,7 +331,7 @@
labelMainColor.TabIndex = 2; labelMainColor.TabIndex = 2;
labelMainColor.Text = "Цвет"; labelMainColor.Text = "Цвет";
labelMainColor.TextAlign = ContentAlignment.MiddleCenter; labelMainColor.TextAlign = ContentAlignment.MiddleCenter;
labelMainColor.DragDrop += labelColor_DragDrop; labelMainColor.DragDrop += LabelColor_DragDrop;
labelMainColor.DragEnter += labelColor_DragEnter; labelMainColor.DragEnter += labelColor_DragEnter;
// //
// FormWarmlyLocomotiveConfig // FormWarmlyLocomotiveConfig

View File

@ -1,4 +1,5 @@
using WarmlyLocomotive.DrawningObjects; using System.Windows.Forms;
using WarmlyLocomotive.DrawningObjects;
using WarmlyLocomotive.Entities; using WarmlyLocomotive.Entities;
namespace WarmlyLocomotive namespace WarmlyLocomotive
@ -9,8 +10,6 @@ namespace WarmlyLocomotive
/// <param name="warmlylocomotive"></param> /// <param name="warmlylocomotive"></param>
public partial class FormWarmlyLocomotiveConfig : Form public partial class FormWarmlyLocomotiveConfig : Form
{ {
public int _pictureWidth { get; private set; }
public int _pictureHeight { get; private set; }
/// <summary> /// <summary>
/// Переменная /// Переменная
/// </summary> /// </summary>
@ -19,10 +18,8 @@ namespace WarmlyLocomotive
/// Событие /// Событие
/// </summary> /// </summary>
public event Action<DrawningWarmlyLocomotive>? EventAddWarmlyLocomotive; public event Action<DrawningWarmlyLocomotive>? EventAddWarmlyLocomotive;
public FormWarmlyLocomotiveConfig(int pictureWidth, int pictureHeight) public FormWarmlyLocomotiveConfig()
{ {
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
InitializeComponent(); InitializeComponent();
panelRed.MouseDown += PanelColor_MouseDown; panelRed.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown; panelGreen.MouseDown += PanelColor_MouseDown;
@ -42,7 +39,12 @@ namespace WarmlyLocomotive
_warmlylocomotive?.DrawTransport(gr); _warmlylocomotive?.DrawTransport(gr);
pictureBoxObject.Image = bmp; pictureBoxObject.Image = bmp;
} }
public void AddEvent(Action<DrawningWarmlyLocomotive> ev)
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
internal void AddEvent(Action<DrawningWarmlyLocomotive> ev)
{ {
if (EventAddWarmlyLocomotive == null) if (EventAddWarmlyLocomotive == null)
{ {
@ -53,10 +55,14 @@ namespace WarmlyLocomotive
EventAddWarmlyLocomotive += ev; EventAddWarmlyLocomotive += ev;
} }
} }
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e) private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{ {
(sender as Label)?.DoDragDrop((sender as Label)?.Name, (sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
DragDropEffects.Move | DragDropEffects.Copy);
} }
/// <summary> /// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому) /// Проверка получаемой информации (ее типа на соответствие требуемому)
@ -85,53 +91,26 @@ namespace WarmlyLocomotive
{ {
case "labelBasic": case "labelBasic":
_warmlylocomotive = new DrawningWarmlyLocomotive((int)numericUpDownSpeed.Value, _warmlylocomotive = new DrawningWarmlyLocomotive((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, _pictureWidth, _pictureHeight); (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break; break;
case "labelAdvanced": case "labelAdvanced":
_warmlylocomotive = new DrawningWarmlyLocomotiveWithTrumpet((int)numericUpDownSpeed.Value, _warmlylocomotive = new DrawningWarmlyLocomotiveWithTrumpet((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxTrumpet.Checked, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxTrumpet.Checked,
checkBoxLuggage.Checked, _pictureWidth, _pictureHeight); checkBoxLuggage.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break; break;
} }
DrawWarmlyLocomotive(); 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, (sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Добавление
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();
} }
private void labelColor_DragEnter(object sender, DragEventArgs e) 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; e.Effect = DragDropEffects.Copy;
} }
@ -140,16 +119,34 @@ namespace WarmlyLocomotive
e.Effect = DragDropEffects.None; 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; return;
Color additionalColor = (Color)e.Data.GetData(typeof(Color)); switch (((Label)sender).Name)
_warmlylocomotive = new DrawningWarmlyLocomotiveWithTrumpet((int)numericUpDownSpeed.Value, {
(int)numericUpDownWeight.Value, _warmlylocomotive.EntityWarmlyLocomotive.BodyColor, additionalColor, checkBoxTrumpet.Checked, case "labelMainColor":
checkBoxLuggage.Checked, _pictureWidth, _pictureHeight); _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(); DrawWarmlyLocomotive();
} }
/// <summary>
/// Добавление машины
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
EventAddWarmlyLocomotive?.Invoke(_warmlylocomotive);
Close();
}
} }
} }

View File

@ -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 namespace WarmlyLocomotive
{ {
internal static class Program internal static class Program
{ {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\');
// see https://aka.ms/applicationconfiguration. 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(); ApplicationConfiguration.Initialize();
Application.Run(new FormWarmlyLocomotiveCollection()); Application.Run(new FormWarmlyLocomotiveCollection());
} }

View File

@ -3,108 +3,75 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
using WarmlyLocomotive.Exceptions;
using System;
namespace WarmlyLocomotive.Generics namespace WarmlyLocomotive.Generics
{ {
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T> internal class SetGeneric<T>
where T : class where T : class
{ {
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places; private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count; public int Count => _places.Count;
/// <summary> //public int startPointer = 0;
/// Максимальное количество объектов в списке
/// </summary> public int countMax = 0;
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count) public SetGeneric(int count)
{ {
_maxCount = count;
_places = new List<T?>(count); _places = new List<T?>(count);
countMax = count;
} }
/// <summary> public bool Insert(T ship)
/// Добавление объекта в набор
/// </summary>
/// <param name="warmlylocomotive">Добавляемый тепловоз</param>
/// <returns></returns>
public bool Insert(T warmlylocomotive)
{ {
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; return false;
} _places.Insert(position, ship);
Insert(warmlylocomotive, 0);
return true; return true;
} }
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="warmlylocomotive">Добавляемый тепловоз</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T warmlylocomotive, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) return false;
_places.Insert(position, warmlylocomotive);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count) return false; if (!(position >= 0 && position < Count))
throw new WarmlyLocomotiveNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position] public T? this[int position]
{ {
get get
{ {
if (position < 0 || position >= Count) return null; if (!(position >= 0 && position < Count))
return null;
return _places[position]; return _places[position];
} }
set set
{ {
if (!(position >= 0 && position < Count && _places.Count < _maxCount)) return; if (!(position >= 0 && position < Count && _places.Count < countMax))
return;
_places.Insert(position, value); _places.Insert(position, value);
return; return;
} }
} }
/// <summary> public IEnumerable<T?> GetWarmlyLocomotive(int? maxShip = null)
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetWarmlyLocomotives(int? maxWarmlyLocomotives = null)
{ {
for (int i = 0; i < _places.Count; ++i) for (int i = 0; i < _places.Count; ++i)
{ {
yield return _places[i]; yield return _places[i];
if (maxWarmlyLocomotives.HasValue && i == maxWarmlyLocomotives.Value) if (maxShip.HasValue && i == maxShip.Value)
{ {
yield break; yield break;
} }
} }
} }
} }
} }

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -9,7 +9,7 @@ namespace WarmlyLocomotive.Generics
/// <summary> /// <summary>
/// Получение объектов коллекции /// Получение объектов коллекции
/// </summary> /// </summary>
public IEnumerable<T?> GetWarmlyLocomotives => _collection.GetWarmlyLocomotives(); public IEnumerable<T?> GetWarmlyLocomotives => _collection.GetWarmlyLocomotive();
/// <summary> /// <summary>
/// Ширина окна прорисовки /// Ширина окна прорисовки
/// </summary> /// </summary>
@ -121,7 +121,7 @@ namespace WarmlyLocomotive.Generics
{ {
int i = 0; int i = 0;
int numPlacesInRow = _pictureWidth / _placeSizeWidth; int numPlacesInRow = _pictureWidth / _placeSizeWidth;
foreach (var warmlylocomotive in _collection.GetWarmlyLocomotives()) foreach (var warmlylocomotive in _collection.GetWarmlyLocomotive())
{ {
if (warmlylocomotive != null) if (warmlylocomotive != null)
{ {

View File

@ -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.DrawningObjects;
using WarmlyLocomotive.MovementStrategy; using WarmlyLocomotive.MovementStrategy;
namespace WarmlyLocomotive.Generics namespace WarmlyLocomotive.Generics
{ {
internal class WarmlyLocomotivesGenericStorage internal class WarmlyLocomotivesGenericStorage
{ {
readonly Dictionary<string, WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>> _warmlylocomotiveStorages; readonly Dictionary<string, WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive,
DrawningObjectWarmlyLocomotive>> _warmlylocomotiveStorages;
public List<string> Keys => _warmlylocomotiveStorages.Keys.ToList(); public List<string> Keys => _warmlylocomotiveStorages.Keys.ToList();
private readonly int _pictureWidth; private readonly int _pictureWidth;
private readonly int _pictureHeight; private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public WarmlyLocomotivesGenericStorage(int pictureWidth, int pictureHeight) public WarmlyLocomotivesGenericStorage(int pictureWidth, int pictureHeight)
{ {
_warmlylocomotiveStorages = new Dictionary<string, _warmlylocomotiveStorages = new Dictionary<string, WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>>();
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -31,27 +39,12 @@ namespace WarmlyLocomotive.Generics
get get
{ {
if (_warmlylocomotiveStorages.ContainsKey(ind)) if (_warmlylocomotiveStorages.ContainsKey(ind))
{
return _warmlylocomotiveStorages[ind]; return _warmlylocomotiveStorages[ind];
}
return null; return null;
} }
} }
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public bool SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
@ -59,8 +52,7 @@ namespace WarmlyLocomotive.Generics
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, foreach (KeyValuePair<string,WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>> record in _warmlylocomotiveStorages)
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>> record in _warmlylocomotiveStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawningWarmlyLocomotive? elem in record.Value.GetWarmlyLocomotives) foreach (DrawningWarmlyLocomotive? elem in record.Value.GetWarmlyLocomotives)
@ -69,74 +61,67 @@ namespace WarmlyLocomotive.Generics
} }
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
} }
if (data.Length == 0) 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; return true;
} }
/// <summary> public bool LoadData(string filename)
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new IOException("Файл не найден");
} }
string bufferTextFromFile = ""; using (StreamReader sr = new(filename))
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; string str = sr.ReadLine();
UTF8Encoding temp = new(true); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
while (fs.Read(b, 0, b.Length) > 0) if (strs == null || strs.Length == 0)
{ {
bufferTextFromFile += temp.GetString(b); throw new IOException("Нет данных для загрузки");
} }
} if (!strs[0].StartsWith("WarmlyLocomotiveStorage"))
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)
{ {
continue; throw new IOException("Неверный формат данных");
} }
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive> _warmlylocomotiveStorages.Clear();
collection = new(_pictureWidth, _pictureHeight); do
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{ {
DrawningWarmlyLocomotive? warmlylocomotive= string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
elem?.CreateDrawningWarmlyLocomotive(_separatorForObject, _pictureWidth, _pictureHeight); if (record.Length != 2)
if (warmlylocomotive != null)
{ {
if (!(collection + warmlylocomotive)) str = sr.ReadLine();
continue;
}
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive> 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; return true;
} }