laba8: maybe ready

This commit is contained in:
bulatova_karina 2023-12-19 23:54:58 +03:00
parent 27368347ff
commit f214dc995c
10 changed files with 318 additions and 99 deletions

View File

@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
using WarmlyShip.Entities;
using System.Diagnostics.CodeAnalysis;
namespace WarmlyShip.Generics
{
internal class DrawingShipEqutables : IEqualityComparer<DrawingWarmlyShip?>
{
public bool Equals(DrawingWarmlyShip? x, DrawingWarmlyShip? y)
{
if (x == null || x.EntityWarmlyShip == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityWarmlyShip == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarmlyShip.Speed != y.EntityWarmlyShip.Speed)
{
return false;
}
if (x.EntityWarmlyShip.Weight != y.EntityWarmlyShip.Weight)
{
return false;
}
if (x.EntityWarmlyShip.BodyColor != y.EntityWarmlyShip.BodyColor)
{
return false;
}
if (x is DrawingWarmlyShipWithPipes && y is DrawingWarmlyShipWithPipes)
{
EntityWarmlyShipWithPipes xDumpTruck = (EntityWarmlyShipWithPipes)x.EntityWarmlyShip;
EntityWarmlyShipWithPipes yDumpTruck = (EntityWarmlyShipWithPipes)y.EntityWarmlyShip;
if (xDumpTruck.Pipes != yDumpTruck.Pipes)
return false;
if (xDumpTruck.Section != yDumpTruck.Section)
return false;
if (xDumpTruck.AdditionalColor != yDumpTruck.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingWarmlyShip obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -30,6 +30,8 @@
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.panelCollection = new System.Windows.Forms.Panel();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.buttonSortByType = new System.Windows.Forms.Button();
this.groupBoxSets = new System.Windows.Forms.GroupBox();
this.buttonDelObject = new System.Windows.Forms.Button();
this.textBoxStorageName = new System.Windows.Forms.MaskedTextBox();
@ -62,6 +64,8 @@
//
// panelCollection
//
this.panelCollection.Controls.Add(this.buttonSortByColor);
this.panelCollection.Controls.Add(this.buttonSortByType);
this.panelCollection.Controls.Add(this.groupBoxSets);
this.panelCollection.Controls.Add(this.maskedTextBoxNumber);
this.panelCollection.Controls.Add(this.labelCollection);
@ -74,6 +78,26 @@
this.panelCollection.Size = new System.Drawing.Size(218, 540);
this.panelCollection.TabIndex = 1;
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(16, 309);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(171, 29);
this.buttonSortByColor.TabIndex = 10;
this.buttonSortByColor.Text = "Сортировка по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(16, 274);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(171, 29);
this.buttonSortByType.TabIndex = 9;
this.buttonSortByType.Text = "Сортировка по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBoxSets
//
this.groupBoxSets.Controls.Add(this.buttonDelObject);
@ -82,14 +106,14 @@
this.groupBoxSets.Controls.Add(this.buttonAddObject);
this.groupBoxSets.Location = new System.Drawing.Point(3, 59);
this.groupBoxSets.Name = "groupBoxSets";
this.groupBoxSets.Size = new System.Drawing.Size(205, 258);
this.groupBoxSets.Size = new System.Drawing.Size(205, 209);
this.groupBoxSets.TabIndex = 7;
this.groupBoxSets.TabStop = false;
this.groupBoxSets.Text = "Наборы";
//
// buttonDelObject
//
this.buttonDelObject.Location = new System.Drawing.Point(13, 205);
this.buttonDelObject.Location = new System.Drawing.Point(13, 171);
this.buttonDelObject.Name = "buttonDelObject";
this.buttonDelObject.Size = new System.Drawing.Size(171, 29);
this.buttonDelObject.TabIndex = 3;
@ -108,7 +132,7 @@
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 20;
this.listBoxStorages.Location = new System.Drawing.Point(13, 114);
this.listBoxStorages.Location = new System.Drawing.Point(13, 101);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(171, 64);
this.listBoxStorages.TabIndex = 1;
@ -126,7 +150,7 @@
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(16, 394);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(16, 403);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(171, 27);
this.maskedTextBoxNumber.TabIndex = 6;
@ -152,7 +176,7 @@
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(16, 436);
this.buttonRemoveShip.Location = new System.Drawing.Point(16, 446);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(171, 40);
this.buttonRemoveShip.TabIndex = 4;
@ -162,7 +186,7 @@
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(16, 335);
this.buttonAddShip.Location = new System.Drawing.Point(16, 348);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(171, 40);
this.buttonAddShip.TabIndex = 2;
@ -193,14 +217,14 @@
// сохранениеToolStripMenuItem
//
this.сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
this.сохранениеToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.сохранениеToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.сохранениеToolStripMenuItem.Text = "Сохранение";
this.сохранениеToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// загрузкаToolStripMenuItem
//
this.загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
this.загрузкаToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.загрузкаToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.загрузкаToolStripMenuItem.Text = "Загрузка";
this.загрузкаToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@ -254,5 +278,7 @@
private ToolStripMenuItem загрузкаToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -40,6 +40,39 @@ namespace WarmlyShip
_logger = logger;
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) =>
CompareShips(new ShipCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByColor());
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareShips(IComparer<DrawingWarmlyShip?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowShips();
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
@ -48,7 +81,7 @@ namespace WarmlyShip
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))

View File

@ -31,19 +31,17 @@ namespace WarmlyShip.Generics
_maxCount = count;
_places = new List<T?>(count);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="warmlyship">Добавляемый теплоход</param>
/// <returns></returns>
public bool Insert(T warmlyship)
public bool Insert(T warmlyship, IEqualityComparer<T?>? equal = null)
{
if (_places.Count == _maxCount)
{
return false;
}
Insert(warmlyship, 0);
throw new StorageOverflowException(_maxCount);
Insert(warmlyship, 0, equal);
return true;
}
/// <summary>
@ -52,14 +50,18 @@ namespace WarmlyShip.Generics
/// <param name="warmlyship">Добавляемый теплоход</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T warmlyship, int position)
public bool Insert(T warmlyship, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new ShipNotFoundException(position);
if (_places.Count >= _maxCount)
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
throw new StorageOverflowException(_maxCount);
_places.Insert(0, warmlyship);
if (!(position >= 0 && position <= Count))
return false;
if (equal != null)
{
if (_places.Contains(warmlyship, equal))
throw new ArgumentException(nameof(warmlyship));
}
_places.Insert(position, warmlyship);
return true;
}
/// <summary>
@ -69,9 +71,8 @@ namespace WarmlyShip.Generics
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position > _maxCount || position >= Count)
if (!(position >= 0 && position < Count))
throw new ShipNotFoundException(position);
_places.RemoveAt(position);
return true;
}
@ -84,19 +85,14 @@ namespace WarmlyShip.Generics
{
get
{
if (position < 0 || position >= Count)
{
if (!(position >= 0 && position < Count))
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
return;
}

View File

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
using WarmlyShip.Entities;
namespace WarmlyShip.Generics
{
internal class ShipCompareByColor : IComparer<DrawingWarmlyShip?>
{
public int Compare(DrawingWarmlyShip? x, DrawingWarmlyShip? y)
{
if (x == null || x.EntityWarmlyShip == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityWarmlyShip == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityWarmlyShip.BodyColor.Name.CompareTo(y.EntityWarmlyShip.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityWarmlyShip is EntityWarmlyShipWithPipes xEntitySailCatamaran && y.EntityWarmlyShip is EntityWarmlyShipWithPipes yEntitySailCatamaran)
{
var BodyColorCompare = xEntitySailCatamaran.BodyColor.Name.CompareTo(yEntitySailCatamaran.BodyColor.Name);
if (BodyColorCompare != 0)
{
return BodyColorCompare;
}
var AdditionalColorCompare = xEntitySailCatamaran.AdditionalColor.Name.CompareTo(yEntitySailCatamaran.AdditionalColor.Name);
if (AdditionalColorCompare != 0)
{
return AdditionalColorCompare;
}
}
var speedCompare = x.EntityWarmlyShip.Speed.CompareTo(y.EntityWarmlyShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarmlyShip.Weight.CompareTo(y.EntityWarmlyShip.Weight);
}
}
}

View File

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

View File

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

View File

@ -14,6 +14,12 @@ namespace WarmlyShip.Generics
where T : DrawingWarmlyShip
where U : IMoveableObject
{
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) =>
_collection.SortSet(comparer);
/// <summary>
/// Получение объектов коллекции
/// </summary>

View File

@ -14,12 +14,11 @@ namespace WarmlyShip.Generics
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, ShipsGenericCollection<DrawingWarmlyShip,
DrawingObjectShip>> _shipStorages;
readonly Dictionary<ShipsCollectionInfo, ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>> _shipStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _shipStorages.Keys.ToList();
public List<ShipsCollectionInfo> Keys => _shipStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -35,8 +34,8 @@ namespace WarmlyShip.Generics
/// /// <param name="pictureHeight"></param>
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
{
_shipStorages = new Dictionary<string,
ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>>();
_shipStorages = new Dictionary<ShipsCollectionInfo, ShipsGenericCollection
<DrawingWarmlyShip, DrawingObjectShip>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -46,11 +45,7 @@ namespace WarmlyShip.Generics
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (_shipStorages.ContainsKey(name))
{
return;
}
_shipStorages[name] = new ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>(_pictureWidth, _pictureHeight);
_shipStorages.Add(new ShipsCollectionInfo(name, string.Empty), new ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
@ -58,12 +53,9 @@ namespace WarmlyShip.Generics
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_shipStorages.ContainsKey(name))
{
if (!_shipStorages.ContainsKey(new ShipsCollectionInfo(name, string.Empty)))
return;
}
_shipStorages.Remove(name);
_shipStorages.Remove(new ShipsCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
@ -75,10 +67,9 @@ namespace WarmlyShip.Generics
{
get
{
if (_shipStorages.ContainsKey(ind))
{
return _shipStorages[ind];
}
ShipsCollectionInfo indObj = new ShipsCollectionInfo(ind, string.Empty);
if (_shipStorages.ContainsKey(indObj))
return _shipStorages[indObj];
return null;
}
}
@ -107,7 +98,7 @@ namespace WarmlyShip.Generics
}
StringBuilder data = new();
foreach (KeyValuePair<string, ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>> record in _shipStorages)
foreach (KeyValuePair<ShipsCollectionInfo, ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>> record in _shipStorages)
{
StringBuilder records = new();
foreach (DrawingWarmlyShip? elem in record.Value.GetShips)
@ -137,54 +128,58 @@ namespace WarmlyShip.Generics
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
throw new Exception("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
string checker = reader.ReadLine();
if (checker == null)
throw new NullReferenceException("Нет данных для загрузки");
if (!checker.StartsWith("BoatStorage"))
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
//если нет такой записи, то это не те данные
throw new FormatException("Неверный формат данных");
bufferTextFromFile += temp.GetString(b);
}
_shipStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("ShipStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_shipStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
if (strs == null && firstinit)
throw new NullReferenceException("Нет данных для загрузки");
if (strs == null)
break;
firstinit = false;
string name = strs.Split('|')[0];
ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split('|')[1].Split(';'))
continue;
}
ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingWarmlyShip? ship =
elem?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null)
{
DrawingWarmlyShip? vehicle = data?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (vehicle != null)
if (!(collection + ship))
{
try
{
_ = collection + vehicle;
}
catch (ShipNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
throw new Exception("Ошибка добавления в коллекцию");
}
}
_shipStorages.Add(name, collection);
}
_shipStorages.Add(new ShipsCollectionInfo(record[0], string.Empty), collection);
}
}
}
}

View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>