Восьмая лабораторная работа

This commit is contained in:
allllen4a 2023-12-18 13:22:04 +03:00
parent aa62dc46fa
commit b5d90791bb
10 changed files with 385 additions and 96 deletions

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using projectDoubleDeckerBus.Drawings;
using projectDoubleDeckerBus.Entity;
namespace projectDoubleDeckerBus.Generics
{
internal class BusCompareByColor : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityBus.BodyColor.Name != y.EntityBus.BodyColor.Name)
{
return x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name);
}
if (x.GetType().Name != y.GetType().Name)
{
if (x is DrawningBus)
return -1;
else
return 1;
}
if (x.GetType().Name == y.GetType().Name && x is DrawningDoubleDeckerBus)
{
EntityDoubleDeckerBus _doubledeckerbusX = (EntityDoubleDeckerBus)x.EntityBus;
EntityDoubleDeckerBus _doubledeckerbusY = (EntityDoubleDeckerBus)y.EntityBus;
if (_doubledeckerbusX.AdditionalColor.Name != _doubledeckerbusY.AdditionalColor.Name)
{
return _doubledeckerbusX.AdditionalColor.Name.CompareTo(_doubledeckerbusY.AdditionalColor.Name);
}
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using projectDoubleDeckerBus.Drawings;
using projectDoubleDeckerBus.Entity;
namespace projectDoubleDeckerBus.Generics
{
internal class BusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare =
x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace projectDoubleDeckerBus.Generics
{
internal class BusesCollectionInfo : IEquatable<BusesCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public BusesCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(BusesCollectionInfo? other)
{
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -13,6 +13,12 @@ namespace projectDoubleDeckerBus
where T : DrawningBus
where U : IMoveableObject
{
public IEnumerable<T?> GetBuses => _collection.GetBuses();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Ширина окна прорисовки
/// </summary>
@ -53,14 +59,13 @@ namespace projectDoubleDeckerBus
/// <param name="obj"></param>
/// <returns></returns>
///
public static bool operator +(BusesGenericCollection<T, U> collect, T?
obj)
public static int operator +(BusesGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
if (obj != null)
{
return false;
return collect?._collection.Insert(obj, new DrawiningBusEqutables()) ?? -1;
}
return (bool)collect?._collection.Insert(obj);
return 0;
}
/// Перегрузка оператора вычитания
public static T? operator -(BusesGenericCollection<T, U> collect, int pos)
@ -127,7 +132,6 @@ namespace projectDoubleDeckerBus
i++;
}
}
public IEnumerable<T?> GetBuses => _collection.GetBuses();
}
}

View File

@ -13,8 +13,9 @@ namespace projectDoubleDeckerBus.Generics
{
internal class BusesGenericStorage
{
readonly Dictionary<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>> _busStorages;
public List<string> Keys => _busStorages.Keys.ToList();
readonly Dictionary<BusesCollectionInfo,
BusesGenericCollection<DrawningBus, DrawningObjectBus>> _busStorages;
public List<BusesCollectionInfo> Keys => _busStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
@ -29,56 +30,37 @@ namespace projectDoubleDeckerBus.Generics
public BusesGenericStorage(int pictureWidth, int pictureHeight)
{
_busStorages = new Dictionary<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>>();
_busStorages = new Dictionary<BusesCollectionInfo, BusesGenericCollection<DrawningBus, DrawningObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
if (_busStorages.ContainsKey(name)) return;
_busStorages[name] = new BusesGenericCollection<DrawningBus, DrawningObjectBus>(_pictureWidth, _pictureHeight);
}
public void DelSet(string name)
{
if (!_busStorages.ContainsKey(name)) return;
_busStorages.Remove(name);
}
public BusesGenericCollection<DrawningBus, DrawningObjectBus>?
this[string ind]
{
get
{
if (_busStorages.ContainsKey(ind)) return _busStorages[ind];
return null;
}
}
public void SaveData(string filename)
{
if (_busStorages.Count == 0)
throw new InvalidOperationException("Невалидная операция: нет данных для сохранения");
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>> record in _busStorages)
foreach (KeyValuePair<BusesCollectionInfo, 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}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
using (StreamWriter sw = new(filename))
{
writer.WriteLine("BusStorage");
writer.Write(data.ToString());
sw.WriteLine($"BusStorage{Environment.NewLine}{data}");
}
}
@ -91,32 +73,35 @@ namespace projectDoubleDeckerBus.Generics
public void LoadData(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException("Файл не найден");
using (StreamReader sr = new(filename))
{
throw new Exception("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string checker = reader.ReadLine();
if (checker == null)
throw new Exception("Нет данных для загрузки");
if (!checker.StartsWith("BusStorage"))
throw new Exception("Неверный формат ввода");
_busStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
if (sr.ReadLine() != "BoatStorage")
throw new FormatException("Неверный формат данных");
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
if (strs == null && firstinit)
throw new Exception("Нет данных для загрузки");
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(';'))
throw new Exception("Нет данных для загрузки");
}
_busStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
DrawningBus? bus =
data?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
str = sr.ReadLine();
continue;
}
BusesGenericCollection<DrawningBus, DrawningObjectBus>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningBus? bus = elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
try { _ = collection + bus; }
@ -130,10 +115,47 @@ namespace projectDoubleDeckerBus.Generics
}
}
}
_busStorages.Add(name, collection);
}
_busStorages.Add(new BusesCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine();
} while (str != null);
}
}
public void AddSet(string name)
{
if (_busStorages.ContainsKey(new BusesCollectionInfo(name, string.Empty)))
{
MessageBox.Show("Словарь уже содержит набор с таким названием", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
_busStorages.Add(new BusesCollectionInfo(name, string.Empty), new BusesGenericCollection<DrawningBus, DrawningObjectBus>(_pictureWidth, _pictureHeight));
}
}
public void DelSet(string name)
{
BusesGenericCollection<DrawningBus, DrawningObjectBus> bus;
if (_busStorages.TryGetValue(new BusesCollectionInfo(name, string.Empty), out bus))
{
_busStorages.Remove(new BusesCollectionInfo(name, string.Empty));
}
}
public BusesGenericCollection<DrawningBus, DrawningObjectBus>? this[string ind]
{
get
{
BusesCollectionInfo infBus = new BusesCollectionInfo(ind, string.Empty);
if (_busStorages.ContainsKey(infBus))
{
return _busStorages[infBus];
}
return null;
}
}
}
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using projectDoubleDeckerBus.Drawings;
using projectDoubleDeckerBus.Entity;
using System.Diagnostics.CodeAnalysis;
namespace projectDoubleDeckerBus.Generics
{
internal class DrawiningBusEqutables : IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBus.Speed != y.EntityBus.Speed)
{
return false;
}
if (x.EntityBus.Weight != y.EntityBus.Weight)
{
return false;
}
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
return false;
}
if (x is DrawningDoubleDeckerBus && y is DrawningDoubleDeckerBus)
{
EntityDoubleDeckerBus _doubledeckerbusX = (EntityDoubleDeckerBus)x.EntityBus;
EntityDoubleDeckerBus _doubledeckerbusY = (EntityDoubleDeckerBus)y.EntityBus;
if (_doubledeckerbusX.Floor != _doubledeckerbusY.Floor)
{
return false;
}
if (_doubledeckerbusX.Tailpipe != _doubledeckerbusY.Tailpipe)
{
return false;
}
if (_doubledeckerbusX.AdditionalColor != _doubledeckerbusY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -46,6 +46,8 @@
loadingToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
ButtonSortByType = new Button();
ButtonSortByColor = new Button();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)DrawBus).BeginInit();
menuStrip1.SuspendLayout();
@ -53,6 +55,8 @@
//
// panel1
//
panel1.Controls.Add(ButtonSortByColor);
panel1.Controls.Add(ButtonSortByType);
panel1.Controls.Add(labelSet);
panel1.Controls.Add(ButtonDelObject);
panel1.Controls.Add(listBoxStorages);
@ -67,7 +71,7 @@
panel1.Dock = DockStyle.Fill;
panel1.Location = new Point(0, 24);
panel1.Name = "panel1";
panel1.Size = new Size(813, 484);
panel1.Size = new Size(799, 484);
panel1.TabIndex = 0;
//
// labelSet
@ -81,7 +85,7 @@
//
// ButtonDelObject
//
ButtonDelObject.Location = new Point(692, 191);
ButtonDelObject.Location = new Point(692, 224);
ButtonDelObject.Name = "ButtonDelObject";
ButtonDelObject.Size = new Size(94, 36);
ButtonDelObject.TabIndex = 1;
@ -95,7 +99,7 @@
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(692, 112);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(94, 64);
listBoxStorages.Size = new Size(94, 49);
listBoxStorages.TabIndex = 1;
//
// buttonAddObject
@ -137,14 +141,14 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(692, 314);
maskedTextBoxNumber.Location = new Point(692, 330);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(94, 23);
maskedTextBoxNumber.TabIndex = 1;
//
// ButtonAddCar
//
ButtonAddCar.Location = new Point(692, 256);
ButtonAddCar.Location = new Point(692, 275);
ButtonAddCar.Name = "ButtonAddCar";
ButtonAddCar.Size = new Size(94, 34);
ButtonAddCar.TabIndex = 1;
@ -167,7 +171,7 @@
DrawBus.Dock = DockStyle.Fill;
DrawBus.Location = new Point(0, 0);
DrawBus.Name = "DrawBus";
DrawBus.Size = new Size(813, 484);
DrawBus.Size = new Size(799, 484);
DrawBus.TabIndex = 0;
DrawBus.TabStop = false;
//
@ -176,7 +180,7 @@
menuStrip1.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(813, 24);
menuStrip1.Size = new Size(799, 24);
menuStrip1.TabIndex = 1;
menuStrip1.Text = "menuStrip1";
//
@ -190,14 +194,14 @@
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(180, 22);
saveToolStripMenuItem.Size = new Size(100, 22);
saveToolStripMenuItem.Text = "Save";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadingToolStripMenuItem
//
loadingToolStripMenuItem.Name = "loadingToolStripMenuItem";
loadingToolStripMenuItem.Size = new Size(180, 22);
loadingToolStripMenuItem.Size = new Size(100, 22);
loadingToolStripMenuItem.Text = "Load";
loadingToolStripMenuItem.Click += LoadingToolStripMenuItem_Click;
//
@ -210,11 +214,31 @@
//
saveFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(692, 167);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(94, 22);
ButtonSortByType.TabIndex = 2;
ButtonSortByType.Text = "SortByType";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(692, 195);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(94, 23);
ButtonSortByColor.TabIndex = 2;
ButtonSortByColor.Text = "SortByColor";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(813, 508);
ClientSize = new Size(799, 508);
Controls.Add(panel1);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
@ -250,5 +274,7 @@
private ToolStripMenuItem loadingToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByType;
private Button ButtonSortByColor;
}
}

View File

@ -24,7 +24,7 @@ namespace projectDoubleDeckerBus
/// <summary>
/// Конструктор
/// </summary>
private readonly ILogger _logger;
public FormBusCollection(ILogger<FormBusCollection> logger)
{
@ -34,25 +34,28 @@ namespace projectDoubleDeckerBus
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
ReloadObjects();
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
if (listBoxStorages.Items.Count > 0 && (index == -1 ||
index >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
@ -176,7 +179,7 @@ namespace projectDoubleDeckerBus
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}");
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
/// <summary>
@ -206,15 +209,6 @@ namespace projectDoubleDeckerBus
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
@ -251,5 +245,25 @@ namespace projectDoubleDeckerBus
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) =>
CompareBuses(new BusCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareBuses(new BusCompareByColor());
private void CompareBuses(IComparer<DrawningBus?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
DrawBus.Image = obj.ShowBuses();
}
}
}

View File

@ -126,4 +126,7 @@
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>271, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -33,22 +33,58 @@ namespace projectDoubleDeckerBus.Generics
_maxCount = count;
_places = new List<T?>(count);
}
public void SortSet(IComparer<T?> comparer) =>
_places.Sort(comparer);
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <returns></returns>
public bool Insert(T bus)
public int Insert(T bus, IEqualityComparer<T>? equal = null)
{
return Insert(bus, 0);
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(bus, 0, equal);
return 0;
}
public bool Insert(T bus, int position)
public bool Insert(T bus, int position, IEqualityComparer<T>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new BusNotFoundException(position);
if (!(position >= 0 && position <= Count))
return false;
if (equal != null)
{
if (_places.Contains(bus, equal))
{
throw new ArgumentException((nameof(bus)));
}
}
if (_places.Count == 0 && position == 0)
{
_places.Add(bus);
return true;
}
if (Count >= _maxCount)
throw new StorageOverflowException(position);
_places.Insert(0, bus);
return true;
else if (_places.Count == 0 && position != 0)
return false;
if (_places[position] == null)
{
_places[position] = bus;
return true;
}
if (_places.Count < _maxCount)
{
_places.Add(bus);
for (int i = position; i < _places.Count; i++)
{
T temp = _places[i];
_places[i] = _places[_places.Count - 1];
_places[_places.Count - 1] = temp;
}
return true;
}
else
{
throw new StorageOverflowException();
}
}
public bool Remove(int position)
{