2 Commits
lab6 ... lab8

Author SHA1 Message Date
0014705a2f PIbd22_Kuznetsov.A.V._lab8 2023-12-29 23:19:46 +04:00
3cd45efd33 PIbd22_Kuznetsov.A.V._lab7 2023-12-29 23:15:52 +04:00
22 changed files with 496 additions and 154 deletions

View File

@@ -25,7 +25,7 @@ namespace Excavator.Drawing
return;
}
Pen pen = new(Color.Black);
Pen additionalPen = new(Excavator.Body);
Pen additionalPen = new(Excavator.AddColor);
Brush additionalBrush = new SolidBrush(Excavator.AddColor);
base.DrawTransport(g);

View File

@@ -33,7 +33,7 @@ namespace Excavator.Drawing
_pictureHeight = height;
EntityMash = new EntityMash(speed, weight, bodyColor);
}
protected DrawingMash(int speed, double weight, Color bodyColor, int width, int height, int busWidth, int busHeight)
protected DrawingMash(int speed, double weight, Color bodyColor, int width, int height, int mashWidth, int mashHeight)
{
if (width < _mashWidth || height < _mashHeight)
{
@@ -41,8 +41,8 @@ namespace Excavator.Drawing
}
_pictureWidth = width;
_pictureHeight = height;
_mashWidth = busWidth;
_mashHeight = busHeight;
_mashWidth = mashWidth;
_mashHeight = mashHeight;
EntityMash = new EntityMash(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)

View File

@@ -29,7 +29,6 @@ namespace Excavator.Drawing
}
return null;
}
public static string GetDataForSave(this DrawingMash DrawingMash, char separatorForObject)
{
var truck = DrawingMash.EntityMash;

View File

@@ -2,7 +2,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
@@ -10,7 +9,6 @@ namespace Excavator.Entities
{
public class EntityExcavator : EntityMash
{
public Color Body { get; private set; }
public Color AddColor { get; private set; }
public bool IsBucket { get; private set; }
public bool IsSupports { get; private set; }
@@ -21,6 +19,7 @@ namespace Excavator.Entities
IsBucket = bucket;
IsSupports = supports;
}
public void ChangeAdditionalColor(Color additionalColor)
{
AddColor = additionalColor;

View File

@@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +35,6 @@
</EmbeddedResource>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties serilog_1json__JsonSchema="https://dstack-runner-downloads.s3.eu-west-1.amazonaws.com/latest/schemas/configuration.json" /></VisualStudio></ProjectExtensions>
</Project>

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Excavator.Exceptions
{
[Serializable]
internal class MashNotFoundException : ApplicationException
{
public MashNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public MashNotFoundException() : base() { }
public MashNotFoundException(string message) : base(message) { }
public MashNotFoundException(string message, Exception exception) : base(message, exception) { }
protected MashNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Excavator.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException (string message) : base(message) { }
public StorageOverflowException (string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -46,6 +46,8 @@
this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.button1 = new System.Windows.Forms.Button();
this.Sort_color_button = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
@@ -133,7 +135,7 @@
this.listBoxStorages.ItemHeight = 20;
this.listBoxStorages.Location = new System.Drawing.Point(971, 213);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(150, 144);
this.listBoxStorages.Size = new System.Drawing.Size(150, 44);
this.listBoxStorages.TabIndex = 8;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged);
//
@@ -208,11 +210,35 @@
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// button1
//
this.button1.Location = new System.Drawing.Point(966, 265);
this.button1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(164, 31);
this.button1.TabIndex = 13;
this.button1.Text = "Сортировка по типу";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// Sort_color_button
//
this.Sort_color_button.Location = new System.Drawing.Point(966, 304);
this.Sort_color_button.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Sort_color_button.Name = "Sort_color_button";
this.Sort_color_button.Size = new System.Drawing.Size(165, 31);
this.Sort_color_button.TabIndex = 14;
this.Sort_color_button.Text = "Сортировка по цвету";
this.Sort_color_button.UseVisualStyleBackColor = true;
this.Sort_color_button.Click += new System.EventHandler(this.Sort_Color_button_Click);
//
// FormExcavatorCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1146, 672);
this.Controls.Add(this.Sort_color_button);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBoxStorageName);
this.Controls.Add(this.buttonDeleteStorage);
this.Controls.Add(this.buttonAddStorage);
@@ -257,5 +283,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button button1;
private Button Sort_color_button;
}
}

View File

@@ -10,18 +10,39 @@ using System.Windows.Forms;
using Excavator.Generic;
using Excavator.Drawing;
using Excavator.Move_Strategy;
using Microsoft.Extensions.Logging;
using Excavator.Exceptions;
using Excavator.Generics;
namespace Excavator
{
public partial class FormExcavatorCollection : Form
{
private readonly MashGenericStorage _storage;
public FormExcavatorCollection()
private readonly MashsGenericStorage _storage;
private readonly ILogger _logger;
public FormExcavatorCollection(ILogger<FormExcavatorCollection> logger)
{
InitializeComponent();
_storage = new MashGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_storage = new MashsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void buttonSortByType_Click(object sender, EventArgs e) => CompareMash(new MashCompareByType());
private void Sort_Color_button_Click(object sender, EventArgs e) => CompareMash(new MashCompareByColor());
private void CompareMash(IComparer<DrawingMash?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowMash();
}
private void ReloadObjects()
{
@@ -29,7 +50,7 @@ namespace Excavator
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))
{
@@ -50,6 +71,7 @@ namespace Excavator
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
@@ -61,13 +83,14 @@ namespace Excavator
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удалён набор: {name}");
}
}
private void buttonAddMash_Click(object sender, EventArgs e)
{
@@ -76,7 +99,7 @@ namespace Excavator
FormMashConfig.Show();
}
private void AddMash(DrawingMash SelectedMash)
private void AddMash(DrawingMash selectedMash)
{
if (listBoxStorages.SelectedIndex == -1)
{
@@ -88,17 +111,31 @@ namespace Excavator
{
return;
}
SelectedMash.ChangeBordersPicture(pictureBoxCollection.Width, pictureBoxCollection.Height);
if (obj + SelectedMash != -1)
selectedMash.ChangeBordersPicture(Width, Height);
try
{
if (obj + selectedMash != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowMash();
_logger.LogInformation($"Добавлен объект: {selectedMash.EntityMash.BodyColor}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
private void buttonDeleteMash_Click(object sender, EventArgs e)
{
@@ -115,26 +152,31 @@ namespace Excavator
{
return;
}
int pos = 0;
try
{
pos = Convert.ToInt32(maskedTextBoxNumber.Text);
}
catch
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowMash();
_logger.LogInformation($"Удалён объект по позиции : {pos}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
catch (FormatException ex)
{
MessageBox.Show("Неверный формат ввода");
_logger.LogWarning("Неверный формат ввода");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@@ -153,13 +195,16 @@ namespace Excavator
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл сохранён по пути: {saveFileDialog.FileName}");
}
else
catch (InvalidOperationException ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
}
}
}
@@ -167,18 +212,19 @@ namespace Excavator
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
ReloadObjects();
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
pictureBoxCollection.Image = obj.ShowMash();
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл загружен по пути: {openFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
}
}
ReloadObjects();
}
}
}

View File

@@ -40,7 +40,7 @@
this.panelYellow = new System.Windows.Forms.Panel();
this.panelRoyalBlue = new System.Windows.Forms.Panel();
this.panelFirebrick = new System.Windows.Forms.Panel();
this.checkBoxLadder = new System.Windows.Forms.CheckBox();
this.checkBoxSupports = new System.Windows.Forms.CheckBox();
this.checkBoxBucket = new System.Windows.Forms.CheckBox();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
@@ -65,7 +65,7 @@
this.groupBoxConfig.Controls.Add(this.labelAdvancedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColor);
this.groupBoxConfig.Controls.Add(this.checkBoxLadder);
this.groupBoxConfig.Controls.Add(this.checkBoxSupports);
this.groupBoxConfig.Controls.Add(this.checkBoxBucket);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
@@ -181,15 +181,15 @@
this.panelFirebrick.Size = new System.Drawing.Size(50, 40);
this.panelFirebrick.TabIndex = 0;
//
// checkBoxLadder
// checkBoxSupports
//
this.checkBoxLadder.AutoSize = true;
this.checkBoxLadder.Location = new System.Drawing.Point(13, 149);
this.checkBoxLadder.Name = "checkBoxLadder";
this.checkBoxLadder.Size = new System.Drawing.Size(132, 24);
this.checkBoxLadder.TabIndex = 5;
this.checkBoxLadder.Text = "Наличие опор";
this.checkBoxLadder.UseVisualStyleBackColor = true;
this.checkBoxSupports.AutoSize = true;
this.checkBoxSupports.Location = new System.Drawing.Point(13, 149);
this.checkBoxSupports.Name = "checkBoxSupports";
this.checkBoxSupports.Size = new System.Drawing.Size(132, 24);
this.checkBoxSupports.TabIndex = 5;
this.checkBoxSupports.Text = "Наличие опор";
this.checkBoxSupports.UseVisualStyleBackColor = true;
//
// checkBoxBucket
//
@@ -359,7 +359,7 @@
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxLadder;
private CheckBox checkBoxSupports;
private CheckBox checkBoxBucket;
private GroupBox groupBoxColor;
private Panel panelBlue;

View File

@@ -49,7 +49,6 @@ namespace Excavator
EventAddMash += ev;
}
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
@@ -84,7 +83,7 @@ namespace Excavator
(int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.White, Color.Black,
checkBoxBucket.Checked, checkBoxLadder.Checked,
checkBoxBucket.Checked, checkBoxSupports.Checked,
pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
@@ -131,13 +130,15 @@ namespace Excavator
{
var color = (Color)e.Data.GetData(typeof(Color));
EntityExcavator? _Excavator = _mash.EntityMash as EntityExcavator;
_Excavator.ChangeAdditionalColor(color);
EntityExcavator? _excavator = _mash.EntityMash as EntityExcavator;
_excavator.ChangeAdditionalColor(color);
DrawMash();
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_mash == null)
return;
EventAddMash?.Invoke(_mash);
Close();
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using Excavator.Drawing;
using Excavator.Entities;
namespace Excavator.Generics
{
internal class DrawingMashEqutables : IEqualityComparer<DrawingMash?>
{
public bool Equals(DrawingMash? x, DrawingMash? y)
{
if (x == null && x.EntityMash == null)
throw new ArgumentNullException(nameof(x));
if (y == null && y.EntityMash == null)
throw new ArgumentNullException(nameof(y));
if ((x.GetType().Name != y.GetType().Name))
return false;
if (x.EntityMash.Speed != y.EntityMash.Speed)
return false;
if (x.EntityMash.Weight != y.EntityMash.Weight)
return false;
if (x.EntityMash.BodyColor != y.EntityMash.BodyColor)
return false;
if (x is DrawingExcavator && y is DrawingExcavator)
{
var xExcavator = (EntityExcavator)x.EntityMash;
var yExcavator = (EntityExcavator)y.EntityMash;
if (xExcavator.AddColor != yExcavator.AddColor)
return false;
if (xExcavator.IsBucket != yExcavator.IsBucket)
return false;
if (xExcavator.IsSupports != yExcavator.IsSupports)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingMash? obj)
{
return obj.GetHashCode();
}
}
}

View File

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

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excavator.Drawing;
using Excavator.Entities;
namespace Excavator.Generics
{
internal class MashCompareByColor : IComparer<DrawingMash>
{
public int Compare(DrawingMash? x, DrawingMash? y)
{
if (x == null || x.EntityMash == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityMash == null)
throw new ArgumentNullException(nameof(y));
var xMash = x.EntityMash;
var yMash = y.EntityMash;
if (xMash.BodyColor != yMash.BodyColor)
return xMash.BodyColor.Name.CompareTo(yMash.BodyColor.Name);
var speedCompare = x.EntityMash.Speed.CompareTo(y.EntityMash.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityMash.Weight.CompareTo(y.EntityMash.Weight);
}
}
}

View File

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

View File

@@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excavator.Drawing;
using Excavator.Generics;
using Excavator.Move_Strategy;
namespace Excavator.Generic
@@ -27,13 +28,16 @@ namespace Excavator.Generic
_collection = new SetGeneric<T>(width * height);
}
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public static int operator +(MashGenericCollection<T, U> collect, T? obj)
{
if (obj != null)
{
return collect._collection.Insert(obj);
return collect._collection.Insert(obj, new DrawingMashEqutables());
}
return -1;
}
public static bool operator -(MashGenericCollection<T, U> collect, int pos)
{
@@ -49,7 +53,6 @@ namespace Excavator.Generic
{
return (U?)_collection[pos]?.GetMoveableObject;
}
public Bitmap ShowMash()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
@@ -58,7 +61,6 @@ namespace Excavator.Generic
DrawObjects(gr);
return bmp;
}
private void DrawBackground(Graphics gr)
{
Pen pen = new(Color.Black, 3);

View File

@@ -3,123 +3,140 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excavator.Generics;
using Excavator.Drawing;
using Excavator.Generics;
using Excavator.Move_Strategy;
namespace Excavator.Generic
{
internal class MashGenericStorage
internal class MashsGenericStorage
{
readonly Dictionary<string, MashGenericCollection<DrawingMash, DrawingObjectMash>> _mashStorages;
public List<string> Keys => _mashStorages.Keys.ToList();
readonly Dictionary<MashCollectionInfo, MashGenericCollection<DrawingMash, DrawingObjectMash>> _mashStorages;
public List<MashCollectionInfo> Keys => _mashStorages.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 MashGenericStorage(int pictureWidth, int pictureHeight)
public MashsGenericStorage(int pictureWidth, int pictureHeight)
{
_mashStorages = new Dictionary<string, MashGenericCollection<DrawingMash, DrawingObjectMash>>();
_mashStorages = new Dictionary<MashCollectionInfo, MashGenericCollection<DrawingMash, DrawingObjectMash>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
foreach (string nameStorage in Keys)
{
if (nameStorage == name)
{
MessageBox.Show("Набор с заданным именем уже есть", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
_mashStorages.Add(name, new MashGenericCollection<DrawingMash, DrawingObjectMash>(_pictureWidth, _pictureHeight));
}
MashCollectionInfo set = new MashCollectionInfo(name, string.Empty);
if (_mashStorages.ContainsKey(set))
return;
_mashStorages.Add(set, new MashGenericCollection<DrawingMash, DrawingObjectMash>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (_mashStorages.ContainsKey(name))
{
_mashStorages.Remove(name);
}
MashCollectionInfo set = new MashCollectionInfo(name, string.Empty);
if (!_mashStorages.ContainsKey(set))
return;
_mashStorages.Remove(set);
}
public MashGenericCollection<DrawingMash, DrawingObjectMash>? this[string ind]
{
get
{
if (_mashStorages.ContainsKey(ind))
MashCollectionInfo set = new MashCollectionInfo(ind, string.Empty);
if (!_mashStorages.ContainsKey(set))
{
return _mashStorages[ind];
}
return null;
}
return _mashStorages[set];
}
public bool SaveData(string filename)
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = File.CreateText(filename))
{
sw.WriteLine($"ExcavatorStorage");
foreach (var record in _mashStorages)
StringBuilder data = new();
foreach (KeyValuePair<MashCollectionInfo,
MashGenericCollection<DrawingMash, DrawingObjectMash>> record in _mashStorages)
{
StringBuilder records = new();
foreach (DrawingMash? elem in record.Value.GetMash)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
sw.WriteLine($"{record.Key}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
return true;
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"BusStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
using (StreamReader sr = File.OpenText(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
string? curLine = sr.ReadLine();
if (curLine == null || !curLine.Contains("ExcavatorStorage"))
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
return false;
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("MashStorage"))
{
throw new Exception("Неверный формат данных");
}
_mashStorages.Clear();
curLine = sr.ReadLine();
while (curLine != null)
foreach (string data in strs)
{
string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
MashGenericCollection<DrawingMash, DrawingObjectMash> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
MashGenericCollection<DrawingMash, DrawingObjectMash>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingMash? Mash = elem?.CreateDrawingMash(_separatorForObject, _pictureWidth, _pictureHeight);
DrawingMash? Mash =
elem?.CreateDrawingMash(_separatorForObject, _pictureWidth, _pictureHeight);
if (Mash != null)
{
if (collection + Mash == -1)
if ((collection + Mash) == -1)
{
return false;
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_mashStorages.Add(record[0], collection);
curLine = sr.ReadLine();
}
}
return true;
_mashStorages.Add(new MashCollectionInfo(record[0], string.Empty), collection);
}
}
}
}

View File

@@ -1,9 +1,11 @@
using System;
using Excavator.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excavator.Generic
{
internal class SetGeneric<T>
@@ -17,30 +19,36 @@ namespace Excavator.Generic
_maxCount = count;
_places = new List<T?>(count);
}
public int Insert(T bus)
public int Insert(T mash, IEqualityComparer<T?>? equal = null)
{
_places.Insert(0, bus);
return 0;
return Insert(mash, 0, equal);
}
public bool Insert(T mash, int position)
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public int Insert(T mash, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= Count || Count >= _maxCount)
if (Count >= _maxCount)
{
return false;
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
{
throw new IndexOutOfRangeException("Индекс вне границ коллекции");
}
if (equal != null && _places.Contains(mash, equal))
{
throw new ArgumentException("Данный объект уже есть в коллекции");
}
_places.Insert(position, mash);
return true;
return 0;
}
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
throw new MashNotFoundException(position);
}
_places.RemoveAt(position);
return true;
}
public T? this[int position]

View File

@@ -7,6 +7,7 @@ using Excavator.Entities;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Excavator.Move_Strategy
{
public abstract class AbstractStrategy

View File

@@ -13,24 +13,24 @@ namespace Excavator.Move_Strategy
{
public class DrawingObjectMash : IMoveableObject
{
private readonly DrawingMash? _DrawingMash = null;
private readonly DrawingMash? _drawingMash = null;
public DrawingObjectMash(DrawingMash DrawingMash)
{
_DrawingMash = DrawingMash;
_drawingMash = DrawingMash;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_DrawingMash == null || _DrawingMash.EntityMash == null)
if (_drawingMash == null || _drawingMash.EntityMash == null)
{
return null;
}
return new ObjectParameters(_DrawingMash.GetPosX, _DrawingMash.GetPosY, _DrawingMash.GetWidth, _DrawingMash.GetHeight);
return new ObjectParameters(_drawingMash.GetPosX, _drawingMash.GetPosY, _drawingMash.GetWidth, _drawingMash.GetHeight);
}
}
public int GetStep => (int)(_DrawingMash?.EntityMash?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _DrawingMash?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _DrawingMash?.MoveTransport(direction);
public int GetStep => (int)(_drawingMash?.EntityMash?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawingMash?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawingMash?.MoveTransport(direction);
}
}

View File

@@ -1,17 +1,40 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Excavator
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormExcavatorCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormExcavatorCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormExcavatorCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}serilog.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

20
Excavator/serilog.json Normal file
View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/buslog.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "ProjectAirbus"
}
}
}