Шестая лабораторная работа

This commit is contained in:
allllen4a 2023-11-20 18:32:14 +03:00
parent be244e3736
commit c8222f03f5
7 changed files with 291 additions and 32 deletions

View File

@ -53,17 +53,16 @@ namespace projectDoubleDeckerBus
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
/// ///
//преобразовали bool в int
public static int operator +(BusesGenericCollection<T, U> collect, T obj) public static bool operator +(BusesGenericCollection<T, U> collect, T?
obj)
{ {
if (obj == null) if (obj == null)
{ {
return -1; return false;
} }
return (bool)collect?._collection.Insert(obj);
return collect?._collection.Insert(obj) ?? -1;
} }
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
public static T? operator -(BusesGenericCollection<T, U> collect, int pos) public static T? operator -(BusesGenericCollection<T, U> collect, int pos)
{ {
@ -131,5 +130,7 @@ namespace projectDoubleDeckerBus
i++; i++;
} }
} }
public IEnumerable<T?> GetBuses => _collection.GetBuses();
} }
} }

View File

@ -15,6 +15,17 @@ namespace projectDoubleDeckerBus.Generics
public List<string> Keys => _busStorages.Keys.ToList(); public List<string> Keys => _busStorages.Keys.ToList();
private readonly int _pictureWidth; private readonly int _pictureWidth;
private readonly int _pictureHeight; private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
public BusesGenericStorage(int pictureWidth, int pictureHeight) public BusesGenericStorage(int pictureWidth, int pictureHeight)
{ {
_busStorages = new Dictionary<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>>(); _busStorages = new Dictionary<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>>();
@ -43,5 +54,87 @@ namespace projectDoubleDeckerBus.Generics
} }
} }
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>> record in _busStorages)
{
StringBuilder records = new();
foreach (DrawningBus? elem in record.Value.GetBuses)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine("BusStorage");
writer.Write(data.ToString());
return true;
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader reader = new StreamReader(filename))
{
string checker = reader.ReadLine();
if (checker == null)
return false;
if (!checker.StartsWith("BusStorage"))
return false;
_busStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
return false;
if (strs == null)
break;
firstinit = false;
string name = strs.Split('|')[0];
BusesGenericCollection<DrawningBus, DrawningObjectBus> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split('|')[1].Split(';'))
{
DrawningBus? bus =
data?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
if (!(collection + bus))
{
return false;
}
}
}
_busStorages.Add(name, collection);
}
return true;
}
}
} }
} }

View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using projectDoubleDeckerBus.Entity;
using projectDoubleDeckerBus.Drawings;
<<<<<<< HEAD
=======
>>>>>>> 86820b55e1e9fba5d9b93973533143ca71f94485
namespace projectDoubleDeckerBus
{
public static class ExtentionDrawningBus
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningBus? CreateDrawningBus(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningBus(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningDoubleDeckerBus(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="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBus drawningBus,
char separatorForObject)
{
var bus = drawningBus.EntityBus;
if (bus == null)
{
return string.Empty;
}
var str =
$"{bus.Speed}{separatorForObject}{bus.Weight}{separatorForObject}{bus.BodyColor.Name}";
if (bus is not EntityDoubleDeckerBus doubleDeckerBus)
{
return str;
}
return
$"{str}{separatorForObject}{doubleDeckerBus.AdditionalColor.Name}{separatorForObject}{doubleDeckerBus.Floor}{separatorForObject}{doubleDeckerBus.Tailpipe}";
}
}
}

View File

@ -40,8 +40,15 @@
ButtonAddCar = new Button(); ButtonAddCar = new Button();
labelTools = new Label(); labelTools = new Label();
DrawBus = new PictureBox(); DrawBus = new PictureBox();
menuStrip1 = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadingToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
panel1.SuspendLayout(); panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)DrawBus).BeginInit(); ((System.ComponentModel.ISupportInitialize)DrawBus).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// panel1 // panel1
@ -58,9 +65,9 @@
panel1.Controls.Add(labelTools); panel1.Controls.Add(labelTools);
panel1.Controls.Add(DrawBus); panel1.Controls.Add(DrawBus);
panel1.Dock = DockStyle.Fill; panel1.Dock = DockStyle.Fill;
panel1.Location = new Point(0, 0); panel1.Location = new Point(0, 24);
panel1.Name = "panel1"; panel1.Name = "panel1";
panel1.Size = new Size(813, 508); panel1.Size = new Size(813, 484);
panel1.TabIndex = 0; panel1.TabIndex = 0;
// //
// labelSet // labelSet
@ -160,22 +167,66 @@
DrawBus.Dock = DockStyle.Fill; DrawBus.Dock = DockStyle.Fill;
DrawBus.Location = new Point(0, 0); DrawBus.Location = new Point(0, 0);
DrawBus.Name = "DrawBus"; DrawBus.Name = "DrawBus";
DrawBus.Size = new Size(813, 508); DrawBus.Size = new Size(813, 484);
DrawBus.TabIndex = 0; DrawBus.TabIndex = 0;
DrawBus.TabStop = false; DrawBus.TabStop = false;
// //
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(813, 24);
menuStrip1.TabIndex = 1;
menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadingToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(37, 20);
fileToolStripMenuItem.Text = "File";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(180, 22);
saveToolStripMenuItem.Text = "Save";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadingToolStripMenuItem
//
loadingToolStripMenuItem.Name = "loadingToolStripMenuItem";
loadingToolStripMenuItem.Size = new Size(180, 22);
loadingToolStripMenuItem.Text = "Load";
loadingToolStripMenuItem.Click += LoadingToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormBusCollection // FormBusCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(813, 508); ClientSize = new Size(813, 508);
Controls.Add(panel1); Controls.Add(panel1);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormBusCollection"; Name = "FormBusCollection";
Text = "FormBusCollection"; Text = "FormBusCollection";
panel1.ResumeLayout(false); panel1.ResumeLayout(false);
panel1.PerformLayout(); panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)DrawBus).EndInit(); ((System.ComponentModel.ISupportInitialize)DrawBus).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -193,5 +244,11 @@
private Button ButtonRemoveBus; private Button ButtonRemoveBus;
private TextBox maskedTextBoxNumber; private TextBox maskedTextBoxNumber;
private Label labelSet; private Label labelSet;
private MenuStrip menuStrip1;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadingToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@ -11,7 +11,6 @@ using projectDoubleDeckerBus.Drawings;
using projectDouble_Decker_Bus.MovementStrategy; using projectDouble_Decker_Bus.MovementStrategy;
using projectDoubleDeckerBus.Generics; using projectDoubleDeckerBus.Generics;
namespace projectDoubleDeckerBus namespace projectDoubleDeckerBus
{ {
public partial class FormBusCollection : Form public partial class FormBusCollection : Form
@ -53,16 +52,12 @@ namespace projectDoubleDeckerBus
private void AddBus(DrawningBus bus) private void AddBus(DrawningBus bus)
{ {
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
} }
if ((obj + bus) != -1) if (obj + bus)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
DrawBus.Image = obj.ShowBuses(); DrawBus.Image = obj.ShowBuses();
@ -192,5 +187,36 @@ namespace projectDoubleDeckerBus
} }
} }
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);
}
}
}
private void LoadingToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }
} }

View File

@ -117,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>271, 17</value>
</metadata>
</root> </root>

View File

@ -35,31 +35,25 @@ namespace projectDoubleDeckerBus.Generics
/// </summary> /// </summary>
/// <param name="bus">Добавляемый автобус</param> /// <param name="bus">Добавляемый автобус</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T bus) public bool Insert(T bus)
{ {
if (_places.Count >= _maxCount) return Insert(bus, 0);
return -1;
_places.Insert(0, bus);
return 0;
} }
public bool Insert(T bus, int position) public bool Insert(T bus, int position)
{ {
if (_places.Count >= _maxCount) if (position < 0 || position >= _maxCount)
return false; return false;
if (position < 0 || position > _places.Count) if (Count >= _maxCount)
return false; return false;
_places.Insert(0, bus);
if (position == _places.Count)
_places.Add(bus);
else
_places.Insert(position, bus);
return true; return true;
} }
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= _places.Count) if (position < 0 || position > _maxCount)
return false;
if (position >= Count)
return false; return false;
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
@ -70,19 +64,26 @@ namespace projectDoubleDeckerBus.Generics
return null; return null;
return _places[position]; return _places[position];
} }
public T this[int position] public T? this[int position]
{ {
get get
{ {
if (position < 0 || position >= _places.Count) if (position < 0 || position > _maxCount)
return null;
if (_places.Count <= position)
return null; return null;
return _places[position]; return _places[position];
} }
set set
{ {
Insert(value, position); if (position < 0 || position > _maxCount)
return;
if (_places.Count <= position)
return;
_places[position] = value;
} }
} }
public IEnumerable<T?> GetBuses(int? maxBuses = null) public IEnumerable<T?> GetBuses(int? maxBuses = null)
{ {
for (int i = 0; i < _places.Count; ++i) for (int i = 0; i < _places.Count; ++i)