Готовая лаба 8

This commit is contained in:
spacyboy 2023-12-20 20:47:04 +04:00
parent 2a19e42396
commit 96be6a40f7
9 changed files with 266 additions and 53 deletions

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using RoadTrain.Entities;
using RoadTrain.DrawingObjects;
namespace RoadTrain.Generics
{
internal class DrawingTrainEqutables : IEqualityComparer<DrawingRoadTrain?>
{
public bool Equals(DrawingRoadTrain? x, DrawingRoadTrain? y)
{
if (x == null || x.EntityRoadTrain == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityRoadTrain == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityRoadTrain.Speed != y.EntityRoadTrain.Speed)
{
return false;
}
if (x.EntityRoadTrain.Weight != y.EntityRoadTrain.Weight)
{
return false;
}
if (x.EntityRoadTrain.BodyColor != y.EntityRoadTrain.BodyColor)
{
return false;
}
if (x is DrawingRoadTrainWithTank && y is DrawingRoadTrainWithTank)
{
EntityRoadTrainWithTank EntityX = (EntityRoadTrainWithTank)x.EntityRoadTrain;
EntityRoadTrainWithTank EntityY = (EntityRoadTrainWithTank)y.EntityRoadTrain;
if (EntityX.Tank != EntityY.Tank)
return false;
if (EntityX.Brush != EntityY.Brush)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingRoadTrain obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -12,26 +12,32 @@ namespace RoadTrain.Generics
{
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public readonly int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(_maxCount);
}
public bool Insert(T train)
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public int Insert(T train, IEqualityComparer<T?>? equal = null)
{
return Insert(train, 0);
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
return Insert(train, 0, equal);
}
public bool Insert(T train, int position)
public int Insert(T train, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new StorageOverflowException("Impossible to insert");
if (position < 0 || position > _maxCount)
throw new RoadTrainNotFoundException("Вставка невозможна");
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
_places.Insert(0, train);
return true;
if (equal != null)
{
if (_places.Contains(train, equal))
throw new ArgumentException(nameof(train));
}
_places.Insert(position, train);
return position;
}
public bool Remove(int position)
{
@ -57,7 +63,6 @@ namespace RoadTrain.Generics
_places[position] = value;
}
}
public IEnumerable<T> GetTrains(int? maxTrains = null)
{
for (int i = 0; i < _places.Count; ++i)

View File

@ -29,6 +29,8 @@
private void InitializeComponent()
{
panelCollection = new Panel();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
groupBoxSets = new GroupBox();
textBoxStorageName = new TextBox();
buttonDelObject = new Button();
@ -54,6 +56,8 @@
//
// panelCollection
//
panelCollection.Controls.Add(ButtonSortByColor);
panelCollection.Controls.Add(ButtonSortByType);
panelCollection.Controls.Add(groupBoxSets);
panelCollection.Controls.Add(maskedTextBoxNumber);
panelCollection.Controls.Add(labelCollection);
@ -63,9 +67,31 @@
panelCollection.Location = new Point(763, -1);
panelCollection.Margin = new Padding(3, 2, 3, 2);
panelCollection.Name = "panelCollection";
panelCollection.Size = new Size(191, 402);
panelCollection.Size = new Size(191, 472);
panelCollection.TabIndex = 3;
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(14, 311);
ButtonSortByColor.Margin = new Padding(3, 2, 3, 2);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(165, 30);
ButtonSortByColor.TabIndex = 14;
ButtonSortByColor.Text = "Cортировка по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(14, 277);
ButtonSortByType.Margin = new Padding(3, 2, 3, 2);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(165, 30);
ButtonSortByType.TabIndex = 13;
ButtonSortByType.Text = "Сортировка по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// groupBoxSets
//
groupBoxSets.Controls.Add(textBoxStorageName);
@ -155,7 +181,7 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(14, 301);
maskedTextBoxNumber.Location = new Point(14, 379);
maskedTextBoxNumber.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(164, 23);
@ -172,7 +198,7 @@
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(14, 362);
buttonRefreshCollection.Location = new Point(14, 440);
buttonRefreshCollection.Margin = new Padding(3, 2, 3, 2);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(164, 30);
@ -183,7 +209,7 @@
//
// buttonRemoveTrain
//
buttonRemoveTrain.Location = new Point(14, 328);
buttonRemoveTrain.Location = new Point(13, 406);
buttonRemoveTrain.Margin = new Padding(3, 2, 3, 2);
buttonRemoveTrain.Name = "buttonRemoveTrain";
buttonRemoveTrain.Size = new Size(164, 30);
@ -194,7 +220,7 @@
//
// buttonAddTrain
//
buttonAddTrain.Location = new Point(14, 267);
buttonAddTrain.Location = new Point(14, 345);
buttonAddTrain.Margin = new Padding(3, 2, 3, 2);
buttonAddTrain.Name = "buttonAddTrain";
buttonAddTrain.Size = new Size(164, 30);
@ -205,10 +231,10 @@
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(2, -1);
pictureBoxCollection.Location = new Point(12, 6);
pictureBoxCollection.Margin = new Padding(3, 2, 3, 2);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(756, 402);
pictureBoxCollection.Size = new Size(746, 465);
pictureBoxCollection.TabIndex = 2;
pictureBoxCollection.TabStop = false;
//
@ -225,7 +251,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(956, 400);
ClientSize = new Size(956, 482);
Controls.Add(panelCollection);
Controls.Add(pictureBoxCollection);
MainMenuStrip = menuStrip1;
@ -260,5 +286,7 @@
private ToolStripMenuItem загрузкаToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@ -34,7 +34,7 @@ namespace RoadTrain
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))
@ -111,25 +111,28 @@ namespace RoadTrain
train.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
try
{
bool isAddedSuccessfully = obj + train;
if (isAddedSuccessfully)
if (obj + train != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTrains();
_logger.LogInformation($"Объект добавлен");
}
_logger.LogInformation($"Объект {obj.GetType()} добавлен");
}
else
{
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation($"Не удалось добавить объект");
}
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(($"Ошибка переполнения памяти"));
_logger.LogWarning(ex.ToString());
}
catch (ArgumentException ex)
{
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
_logger.LogWarning($"Добавляемый объект уже существует в коллекции {ex.Message}");
}
}
@ -227,5 +230,24 @@ namespace RoadTrain
}
ReloadObjects();
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareTrains(new TrainCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareTrains(new TrainCompareByColor());
private void CompareTrains(IComparer<DrawingRoadTrain?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowTrains();
}
}
}

View File

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

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RoadTrain.DrawingObjects;
namespace RoadTrain.Generics
{
internal class TrainCompareByColor : IComparer<DrawingRoadTrain?>
{
public int Compare(DrawingRoadTrain? x, DrawingRoadTrain? y)
{
if (x == null || x.EntityRoadTrain == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityRoadTrain == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityRoadTrain.BodyColor.Name != y.EntityRoadTrain.BodyColor.Name)
{
return x.EntityRoadTrain.BodyColor.Name.CompareTo(y.EntityRoadTrain.BodyColor.Name);
}
var speedCompare = x.EntityRoadTrain.Speed.CompareTo(y.EntityRoadTrain.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityRoadTrain.Weight.CompareTo(y.EntityRoadTrain.Weight);
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RoadTrain.DrawingObjects;
namespace RoadTrain.Generics
{
internal class TrainCompareByType : IComparer<DrawingRoadTrain?>
{
public int Compare(DrawingRoadTrain? x, DrawingRoadTrain? y)
{
if (x == null || x.EntityRoadTrain == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityRoadTrain == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare =
x.EntityRoadTrain.Speed.CompareTo(y.EntityRoadTrain.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityRoadTrain.Weight.CompareTo(y.EntityRoadTrain.Weight);
}
}
}

View File

@ -3,10 +3,8 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RoadTrain.DrawingObjects;
using RoadTrain.MovementStrategy;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace RoadTrain.Generics
{
@ -20,6 +18,7 @@ namespace RoadTrain.Generics
private readonly int _placeSizeWidth = 200;
private readonly int _placeSizeHeight = 100;
private readonly SetGeneric<T> _collection;
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public TrainsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
@ -28,13 +27,13 @@ namespace RoadTrain.Generics
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static bool operator +(TrainsGenericCollection<T, U> collect, T? obj)
public static int operator +(TrainsGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return false;
return -1;
}
return (bool)collect?._collection.Insert(obj);
return collect._collection.Insert(obj, new DrawingTrainEqutables());
}
public static T? operator -(TrainsGenericCollection<T, U> collect, int pos)
{
@ -88,4 +87,4 @@ namespace RoadTrain.Generics
}
}
}
}
}

View File

@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -12,48 +11,50 @@ namespace RoadTrain.Generics
{
internal class TrainsGenericStorage
{
readonly Dictionary<string, TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>> _trainStorages;
public List<string> Keys => _trainStorages.Keys.ToList();
readonly Dictionary<TrainCollectionInfo, TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>> _trainStorages;
public List<TrainCollectionInfo> Keys => _trainStorages.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 TrainsGenericStorage(int pictureWidth, int pictureHeight)
{
_trainStorages = new Dictionary<string,
_trainStorages = new Dictionary<TrainCollectionInfo,
TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
if (_trainStorages.ContainsKey(name))
if (_trainStorages.ContainsKey(new TrainCollectionInfo(name, string.Empty)))
{
return;
}
_trainStorages[name] = new TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>(_pictureWidth, _pictureHeight);
_trainStorages.Add(new TrainCollectionInfo(name, string.Empty), new TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (!_trainStorages.ContainsKey(name))
if (!_trainStorages.ContainsKey(new TrainCollectionInfo(name, string.Empty)))
{
return;
}
_trainStorages.Remove(name);
_trainStorages.Remove(new TrainCollectionInfo(name, string.Empty));
}
public TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>?
this[string ind]
{
get
{
if (_trainStorages.ContainsKey(ind))
TrainCollectionInfo indObj = new TrainCollectionInfo(ind, string.Empty);
if (_trainStorages.ContainsKey(indObj))
{
return _trainStorages[ind];
return _trainStorages[indObj];
}
return null;
}
}
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public void SaveData(string filename)
{
if (File.Exists(filename))
@ -61,14 +62,14 @@ namespace RoadTrain.Generics
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>> record in _trainStorages)
foreach (KeyValuePair<TrainCollectionInfo, TrainsGenericCollection<DrawingRoadTrain, DrawingObjectTrain>> record in _trainStorages)
{
StringBuilder records = new();
foreach (DrawingRoadTrain? elem in record.Value.GetTrain)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
@ -92,7 +93,6 @@ namespace RoadTrain.Generics
string line;
if (!(((line = sr.ReadLine()) != null) && line.StartsWith("TrainStorage")))
{
//если нет такой записи, то это не те данные
throw new ArgumentException("Неверный формат данных");
}
_trainStorages.Clear();
@ -115,16 +115,16 @@ namespace RoadTrain.Generics
_pictureWidth, _pictureHeight);
if (train != null)
{
if (!(collection + train))
if (collection + train == -1)
{
throw new InvalidOperationException("Ошибка добавления в коллекцию");
}
}
}
_trainStorages.Add(record[0], collection);
_trainStorages.Add(new TrainCollectionInfo(record[0], string.Empty), collection);
}
return true;
}
}
}
}
}