вроде готовая лаба 8

This commit is contained in:
Полина Чубыкина 2023-12-19 23:35:12 +04:00
parent 4bea0dc756
commit b0b6b3397f
8 changed files with 161 additions and 64 deletions

View File

@ -4,9 +4,47 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Sailboat using Sailboat.DrawingObjects;
using Sailboat.Entities;
namespace Sailboat.Generics
{ {
internal class BoatCompareByColor internal class BoatCompareByColor : IComparer<DrawingBoat?>
{ {
public int Compare(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityBoat is EntitySailboat xEntitySailboat && y.EntityBoat is EntitySailboat yEntitySailboat)
{
var dumpBoxColorCompare = xEntitySailboat.BodyColor.Name.CompareTo(yEntitySailboat.BodyColor.Name);
if (dumpBoxColorCompare != 0)
{
return dumpBoxColorCompare;
}
var tentColorCompare = xEntitySailboat.AdditionalColor.Name.CompareTo(yEntitySailboat.AdditionalColor.Name);
if (tentColorCompare != 0)
{
return tentColorCompare;
}
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
} }
} }

View File

@ -5,7 +5,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Sailboat namespace Sailboat.Generics
{ {
internal class BoatCompareByType : IComparer<DrawingBoat?> internal class BoatCompareByType : IComparer<DrawingBoat?>
{ {

View File

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

View File

@ -38,6 +38,8 @@ namespace Sailboat.Generics
/// </summary> /// </summary>
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetBoats => _collection.GetBoats(); public IEnumerable<T?> GetBoats => _collection.GetBoats();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>

View File

@ -15,11 +15,11 @@ namespace Sailboat.Generics
/// <summary> /// <summary>
/// Словарь (хранилище) /// Словарь (хранилище)
/// </summary> /// </summary>
readonly Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages; readonly Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
/// <summary> /// <summary>
/// Возвращение списка названий наборов /// Возвращение списка названий наборов
/// </summary> /// </summary>
public List<string> Keys => _boatStorages.Keys.ToList(); public List<BoatsCollectionInfo> Keys => _boatStorages.Keys.ToList();
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -47,7 +47,7 @@ namespace Sailboat.Generics
/// <param name="pictureHeight"></param> /// <param name="pictureHeight"></param>
public BoatsGenericStorage(int pictureWidth, int pictureHeight) public BoatsGenericStorage(int pictureWidth, int pictureHeight)
{ {
_boatStorages = new Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>(); _boatStorages = new Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -57,11 +57,7 @@ namespace Sailboat.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void AddSet(string name) public void AddSet(string name)
{ {
if (_boatStorages.ContainsKey(name)) _boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight));
{
return;
}
_boatStorages[name] = new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight);
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -69,11 +65,9 @@ namespace Sailboat.Generics
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_boatStorages.ContainsKey(name)) if (!_boatStorages.ContainsKey(new BoatsCollectionInfo(name, string.Empty)))
{
return; return;
} _boatStorages.Remove(new BoatsCollectionInfo(name, string.Empty));
_boatStorages.Remove(name);
} }
/// <summary> /// <summary>
/// Доступ к набору /// Доступ к набору
@ -84,10 +78,9 @@ namespace Sailboat.Generics
{ {
get get
{ {
if (_boatStorages.ContainsKey(ind)) BoatsCollectionInfo indObj = new BoatsCollectionInfo(ind, string.Empty);
{ if (_boatStorages.ContainsKey(indObj))
return _boatStorages[ind]; return _boatStorages[indObj];
}
return null; return null;
} }
} }
@ -105,14 +98,14 @@ namespace Sailboat.Generics
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages) foreach (KeyValuePair<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawingBoat? elem in record.Value.GetBoats) foreach (DrawingBoat? elem in record.Value.GetBoats)
{ {
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
} }
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
} }
if (data.Length == 0) if (data.Length == 0)
@ -137,53 +130,41 @@ namespace Sailboat.Generics
{ {
throw new FileNotFoundException("Файл не найден"); throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader sr = new(filename))
using (StreamReader reader = new StreamReader(filename)) {
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{ {
string checker = reader.ReadLine();
if (checker == null)
throw new NullReferenceException("Нет данных для загрузки"); throw new NullReferenceException("Нет данных для загрузки");
if (!checker.StartsWith("BoatStorage"))
{
//если нет такой записи, то это не те данные
throw new FormatException("Неверный формат данных");
} }
if (!str.StartsWith("BoatStorage"))
{
throw new InvalidDataException("Неверный формат данных");
}
_boatStorages.Clear(); _boatStorages.Clear();
string strs; while ((str = sr.ReadLine()) != null)
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{ {
if (strs == null && firstinit) string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
throw new NullReferenceException("Нет данных для загрузки"); if (record.Length != 2)
if (strs == null) {
break; continue;
firstinit = false; }
string name = strs.Split('|')[0];
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight); BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split('|')[1].Split(';')) string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set.Reverse())
{ {
DrawingBoat? vehicle = data?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); DrawingBoat? truck = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (vehicle != null) if (truck != null)
{ {
try if (!(collection + truck))
{ {
_ = collection + vehicle; throw new ApplicationException("Ошибка добавления в коллекцию");
}
catch (BoatNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
} }
} }
} }
_boatStorages.Add(name, collection); _boatStorages.Add(new BoatsCollectionInfo(record[0], string.Empty), collection);
} }
} }
} }
} }
} }

View File

@ -46,6 +46,8 @@
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.buttonSortByType = new System.Windows.Forms.Button();
this.buttonSortByColor = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.panelTools.SuspendLayout(); this.panelTools.SuspendLayout();
this.panelCollection.SuspendLayout(); this.panelCollection.SuspendLayout();
@ -64,6 +66,8 @@
// panelTools // panelTools
// //
this.panelTools.BackColor = System.Drawing.SystemColors.ScrollBar; this.panelTools.BackColor = System.Drawing.SystemColors.ScrollBar;
this.panelTools.Controls.Add(this.buttonSortByColor);
this.panelTools.Controls.Add(this.buttonSortByType);
this.panelTools.Controls.Add(this.panelCollection); this.panelTools.Controls.Add(this.panelCollection);
this.panelTools.Controls.Add(this.maskedTextBoxNumber); this.panelTools.Controls.Add(this.maskedTextBoxNumber);
this.panelTools.Controls.Add(this.buttonRefreshCollection); this.panelTools.Controls.Add(this.buttonRefreshCollection);
@ -82,7 +86,7 @@
this.panelCollection.Controls.Add(this.listBoxStorages); this.panelCollection.Controls.Add(this.listBoxStorages);
this.panelCollection.Controls.Add(this.buttonAddObject); this.panelCollection.Controls.Add(this.buttonAddObject);
this.panelCollection.Controls.Add(this.textBoxStorageName); this.panelCollection.Controls.Add(this.textBoxStorageName);
this.panelCollection.Location = new System.Drawing.Point(20, 166); this.panelCollection.Location = new System.Drawing.Point(21, 128);
this.panelCollection.Name = "panelCollection"; this.panelCollection.Name = "panelCollection";
this.panelCollection.Size = new System.Drawing.Size(181, 287); this.panelCollection.Size = new System.Drawing.Size(181, 287);
this.panelCollection.TabIndex = 4; this.panelCollection.TabIndex = 4;
@ -126,7 +130,7 @@
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
this.maskedTextBoxNumber.Location = new System.Drawing.Point(49, 567); this.maskedTextBoxNumber.Location = new System.Drawing.Point(50, 594);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(125, 27); this.maskedTextBoxNumber.Size = new System.Drawing.Size(125, 27);
this.maskedTextBoxNumber.TabIndex = 3; this.maskedTextBoxNumber.TabIndex = 3;
@ -143,7 +147,7 @@
// //
// buttonRemoveBoat // buttonRemoveBoat
// //
this.buttonRemoveBoat.Location = new System.Drawing.Point(21, 620); this.buttonRemoveBoat.Location = new System.Drawing.Point(20, 642);
this.buttonRemoveBoat.Name = "buttonRemoveBoat"; this.buttonRemoveBoat.Name = "buttonRemoveBoat";
this.buttonRemoveBoat.Size = new System.Drawing.Size(180, 34); this.buttonRemoveBoat.Size = new System.Drawing.Size(180, 34);
this.buttonRemoveBoat.TabIndex = 1; this.buttonRemoveBoat.TabIndex = 1;
@ -153,7 +157,7 @@
// //
// buttonAddBoat // buttonAddBoat
// //
this.buttonAddBoat.Location = new System.Drawing.Point(20, 490); this.buttonAddBoat.Location = new System.Drawing.Point(20, 544);
this.buttonAddBoat.Name = "buttonAddBoat"; this.buttonAddBoat.Name = "buttonAddBoat";
this.buttonAddBoat.Size = new System.Drawing.Size(180, 34); this.buttonAddBoat.Size = new System.Drawing.Size(180, 34);
this.buttonAddBoat.TabIndex = 0; this.buttonAddBoat.TabIndex = 0;
@ -189,14 +193,14 @@
// SaveToolStripMenuItem // SaveToolStripMenuItem
// //
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26); this.SaveToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.SaveToolStripMenuItem.Text = "Сохранение"; this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
// //
// LoadToolStripMenuItem // LoadToolStripMenuItem
// //
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26); this.LoadToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.LoadToolStripMenuItem.Text = "Загрузка"; this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
// //
@ -209,6 +213,26 @@
// //
this.saveFileDialog.Filter = "txt file | *.txt"; this.saveFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(20, 448);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(180, 34);
this.buttonSortByType.TabIndex = 6;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(20, 488);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(180, 34);
this.buttonSortByColor.TabIndex = 7;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click);
//
// FormBoatCollection // FormBoatCollection
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@ -251,5 +275,7 @@
private ToolStripMenuItem LoadToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -33,7 +33,7 @@ namespace Sailboat
listBoxStorages.Items.Clear(); listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++) 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 if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count)) >= listBoxStorages.Items.Count))
@ -220,5 +220,24 @@ namespace Sailboat
} }
} }
private void buttonSortByType_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByType());
private void buttonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor());
private void CompareBoats(IComparer<DrawingBoat?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowBoats();
}
} }
} }

View File

@ -22,6 +22,8 @@ namespace Sailboat.Generics
/// Максимальное количество объектов в списке /// Максимальное количество объектов в списке
/// </summary> /// </summary>
private readonly int _maxCount; private readonly int _maxCount;
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -59,7 +61,6 @@ namespace Sailboat.Generics
if (_places.Count >= _maxCount) if (_places.Count >= _maxCount)
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
//вот это проверить перед отправкой хз что делает
if (equal != null) if (equal != null)
{ {
if (_places.Contains(boat, equal)) if (_places.Contains(boat, equal))