Начала и закончила 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.MovementStrategy;
namespace WarmlyLocomotive.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningWarmlyLocomotive
namespace WarmlyLocomotive.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningWarmlyLocomotive
{
/// <summary>
/// Класс-сущность
@ -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;
}
}
}

View File

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

View File

@ -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
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly WarmlyLocomotivesGenericStorage _storage;
public FormWarmlyLocomotiveCollection()
{
InitializeComponent();
_storage = new WarmlyLocomotivesGenericStorage(pictureBoxCollectionWarmlyLocomotive.Width, pictureBoxCollectionWarmlyLocomotive.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
@ -47,76 +35,73 @@ namespace WarmlyLocomotive
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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<DrawningWarmlyLocomotive>? warmlydelegate = new((m) =>
Action<DrawningWarmlyLocomotive>? 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<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)
{
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("Введите число");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonreFreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -164,53 +152,45 @@ namespace WarmlyLocomotive
}
pictureBoxCollectionWarmlyLocomotive.Image = obj.ShowWarmlyLocomotives();
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
}

View File

@ -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

View File

@ -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
/// <param name="warmlylocomotive"></param>
public partial class FormWarmlyLocomotiveConfig : Form
{
public int _pictureWidth { get; private set; }
public int _pictureHeight { get; private set; }
/// <summary>
/// Переменная
/// </summary>
@ -19,10 +18,8 @@ namespace WarmlyLocomotive
/// Событие
/// </summary>
public event Action<DrawningWarmlyLocomotive>? 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<DrawningWarmlyLocomotive> ev)
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
internal void AddEvent(Action<DrawningWarmlyLocomotive> ev)
{
if (EventAddWarmlyLocomotive == null)
{
@ -53,10 +55,14 @@ namespace WarmlyLocomotive
EventAddWarmlyLocomotive += ev;
}
}
/// <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);
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
@ -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);
}
/// <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();
(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();
}
/// <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
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[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());
}

View File

@ -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
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
//public int startPointer = 0;
public int countMax = 0;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
countMax = count;
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="warmlylocomotive">Добавляемый тепловоз</param>
/// <returns></returns>
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;
}
/// <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)
{
if (position < 0 || position >= Count) return false;
if (!(position >= 0 && position < Count))
throw new WarmlyLocomotiveNotFoundException(position);
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetWarmlyLocomotives(int? maxWarmlyLocomotives = null)
public IEnumerable<T?> 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;
}
}
}
}
}
}

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.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -9,7 +9,7 @@ namespace WarmlyLocomotive.Generics
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetWarmlyLocomotives => _collection.GetWarmlyLocomotives();
public IEnumerable<T?> GetWarmlyLocomotives => _collection.GetWarmlyLocomotive();
/// <summary>
/// Ширина окна прорисовки
/// </summary>
@ -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)
{

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.MovementStrategy;
namespace WarmlyLocomotive.Generics
{
internal class WarmlyLocomotivesGenericStorage
{
readonly Dictionary<string, WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>> _warmlylocomotiveStorages;
readonly Dictionary<string, WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive,
DrawningObjectWarmlyLocomotive>> _warmlylocomotiveStorages;
public List<string> 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<string,
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>>();
_warmlylocomotiveStorages = new Dictionary<string, WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -31,27 +39,12 @@ namespace WarmlyLocomotive.Generics
get
{
if (_warmlylocomotiveStorages.ContainsKey(ind))
{
return _warmlylocomotiveStorages[ind];
}
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)
{
if (File.Exists(filename))
@ -59,8 +52,7 @@ namespace WarmlyLocomotive.Generics
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>> record in _warmlylocomotiveStorages)
foreach (KeyValuePair<string,WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>> 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;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
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<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>
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<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;
}