2 Commits
Lab6 ... Lab8

Author SHA1 Message Date
ff0f9a1a2a Lab8_DONE 2024-10-03 00:46:41 +03:00
f4861308df Lab7_DONE 2024-10-03 00:45:35 +03:00
24 changed files with 524 additions and 177 deletions

View File

@@ -11,7 +11,6 @@ namespace ProjectGasolineTanker.Drawings
public class DrawingGasolineTanker : DrawingTruck
{
public DrawingGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool tank, bool wheel, int width, int height) : base(speed, weight, bodyColor, width, height, 130, 70)
{
if (EntityTruck != null)

View File

@@ -19,7 +19,7 @@ namespace ProjectGasolineTanker.Drawings
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;

View File

@@ -46,5 +46,5 @@ namespace ProjectGasolineTanker.Drawings
}
return $"{str}{separatorForObject}{GasolineTanker.Add_Color.Name}{separatorForObject}{GasolineTanker.IsTank}{separatorForObject}{GasolineTanker.IsWheel}";
}
}
}
}

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 ProjectGasolineTanker.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

@@ -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 ProjectGasolineTanker.Exceptions
{
[Serializable]
internal class TruckNotFoundException : ApplicationException
{
public TruckNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public TruckNotFoundException() : base() { }
public TruckNotFoundException(string message) : base(message) { }
public TruckNotFoundException(string message, Exception exception) : base(message, exception) { }
protected TruckNotFoundException(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.sort_type_button = 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();
@@ -53,7 +55,7 @@
// buttonAddTruck
//
this.buttonAddTruck.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonAddTruck.Location = new System.Drawing.Point(642, 315);
this.buttonAddTruck.Location = new System.Drawing.Point(660, 315);
this.buttonAddTruck.Name = "buttonAddTruck";
this.buttonAddTruck.Size = new System.Drawing.Size(137, 28);
this.buttonAddTruck.TabIndex = 0;
@@ -74,7 +76,7 @@
this.labelInstruments.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.labelInstruments.AutoSize = true;
this.labelInstruments.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelInstruments.Location = new System.Drawing.Point(659, 9);
this.labelInstruments.Location = new System.Drawing.Point(677, 9);
this.labelInstruments.Name = "labelInstruments";
this.labelInstruments.Size = new System.Drawing.Size(108, 21);
this.labelInstruments.TabIndex = 2;
@@ -83,7 +85,7 @@
// buttonUpdate
//
this.buttonUpdate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUpdate.Location = new System.Drawing.Point(648, 129);
this.buttonUpdate.Location = new System.Drawing.Point(666, 129);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(131, 25);
this.buttonUpdate.TabIndex = 3;
@@ -94,7 +96,7 @@
// buttonDeleteTruck
//
this.buttonDeleteTruck.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDeleteTruck.Location = new System.Drawing.Point(642, 403);
this.buttonDeleteTruck.Location = new System.Drawing.Point(660, 403);
this.buttonDeleteTruck.Name = "buttonDeleteTruck";
this.buttonDeleteTruck.Size = new System.Drawing.Size(137, 28);
this.buttonDeleteTruck.TabIndex = 4;
@@ -105,7 +107,7 @@
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.maskedTextBoxNumber.Location = new System.Drawing.Point(642, 360);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(660, 360);
this.maskedTextBoxNumber.Mask = "00";
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(138, 23);
@@ -116,7 +118,7 @@
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(648, 47);
this.label1.Location = new System.Drawing.Point(666, 47);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(52, 15);
this.label1.TabIndex = 7;
@@ -129,7 +131,7 @@
this.listBoxStorages.Location = new System.Drawing.Point(648, 157);
this.listBoxStorages.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(132, 109);
this.listBoxStorages.Size = new System.Drawing.Size(132, 49);
this.listBoxStorages.TabIndex = 8;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged);
//
@@ -169,7 +171,7 @@
this.toolStripMenuItem1});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(797, 24);
this.menuStrip.Size = new System.Drawing.Size(815, 24);
this.menuStrip.TabIndex = 12;
this.menuStrip.Text = "menuStrip1";
//
@@ -185,14 +187,14 @@
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.saveToolStripMenuItem.Size = new System.Drawing.Size(133, 22);
this.saveToolStripMenuItem.Text = "Сохранить";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// loadToolStripMenuItem
//
this.loadToolStripMenuItem.Name = "loadToolStripMenuItem";
this.loadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.loadToolStripMenuItem.Size = new System.Drawing.Size(133, 22);
this.loadToolStripMenuItem.Text = "Загрузить";
this.loadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@@ -205,11 +207,33 @@
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// sort_type_button
//
this.sort_type_button.Location = new System.Drawing.Point(649, 213);
this.sort_type_button.Name = "sort_type_button";
this.sort_type_button.Size = new System.Drawing.Size(130, 23);
this.sort_type_button.TabIndex = 13;
this.sort_type_button.Text = "Сортировка по типу";
this.sort_type_button.UseVisualStyleBackColor = true;
this.sort_type_button.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// sort_color_button
//
this.sort_color_button.Location = new System.Drawing.Point(649, 242);
this.sort_color_button.Name = "sort_color_button";
this.sort_color_button.Size = new System.Drawing.Size(131, 23);
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);
//
// FormTruckCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(797, 465);
this.ClientSize = new System.Drawing.Size(815, 465);
this.Controls.Add(this.sort_color_button);
this.Controls.Add(this.sort_type_button);
this.Controls.Add(this.textBoxStorageName);
this.Controls.Add(this.buttonDeleteStorage);
this.Controls.Add(this.buttonAddStorage);
@@ -253,5 +277,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button sort_type_button;
private Button sort_color_button;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -10,7 +11,11 @@ using System.Windows.Forms;
using ProjectGasolineTanker.Generic;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.MovementStratg;
using ProjectGasolineTanker.Exceptions;
using ProjectGasolineTanker;
using System.Xml.Linq;
using ProjectGasolineTanker.Generics;
namespace ProjectGasolineTanker
{
@@ -18,11 +23,35 @@ namespace ProjectGasolineTanker
{
// Набор объектов
private readonly TruckGenericStorage _storage;
// Логер
private readonly ILogger _logger;
public FormTruckCollection()
public FormTruckCollection(ILogger<FormTruckCollection> logger)
{
InitializeComponent();
_storage = new TruckGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void buttonSortByType_Click(object sender, EventArgs e) => CompareTruck(new TruckCompareByType());
private void Sort_Color_button_Click(object sender, EventArgs e) => CompareTruck(new TruckCompareByColor());
// Сортировка по сравнителю
private void CompareTruck(IComparer<DrawingTruck?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowTruck();
}
// заполнение лист бокс
@@ -32,7 +61,7 @@ namespace ProjectGasolineTanker
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))
{
@@ -55,6 +84,7 @@ namespace ProjectGasolineTanker
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
// выбрать набор
@@ -70,20 +100,20 @@ namespace ProjectGasolineTanker
{
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 buttonAddTruck_Click(object sender, EventArgs e)
{
var formTruckConfig = new FormTruckConfig();
// TODO Call method AddEvent from formCarConfig
var formTruckConfig = new FormTruckConfig();
formTruckConfig.AddEvent(AddTruck);
formTruckConfig.Show();
}
@@ -100,15 +130,29 @@ namespace ProjectGasolineTanker
{
return;
}
selectedTruck.ChangePictureSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
if (obj + selectedTruck != -1)
selectedTruck.ChangePictureSize(Width, Height);
try
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTruck();
if (obj + selectedTruck != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowTruck();
_logger.LogInformation($"Добавлен объект: {selectedTruck.EntityTruck.BodyColor}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
@@ -128,24 +172,29 @@ namespace ProjectGasolineTanker
{
return;
}
int pos = 0;
try
{
pos = Convert.ToInt32(maskedTextBoxNumber.Text);
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTruck();
_logger.LogInformation($"Удалён объект по позиции : {pos}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
catch
catch (FormatException ex)
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
MessageBox.Show("Неверный формат ввода");
_logger.LogWarning("Неверный формат ввода");
}
if (obj - pos)
catch (Exception ex)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowTruck();
}
else
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
@@ -169,13 +218,16 @@ namespace ProjectGasolineTanker
{
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);
}
}
}
@@ -185,19 +237,21 @@ namespace ProjectGasolineTanker
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
ReloadObjects();
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
pictureBoxCollection.Image = obj.ShowTruck();
_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

@@ -32,14 +32,14 @@
this.labelAdvancedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelLightBlue = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelIndigo = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelOrange = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.panelLawnGreen = new System.Windows.Forms.Panel();
this.checkBoxWheel = new System.Windows.Forms.CheckBox();
this.checkBoxTanker = new System.Windows.Forms.CheckBox();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
@@ -102,14 +102,14 @@
//
// groupBoxColor
//
this.groupBoxColor.Controls.Add(this.panelLightBlue);
this.groupBoxColor.Controls.Add(this.panelBlue);
this.groupBoxColor.Controls.Add(this.panelIndigo);
this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelPurple);
this.groupBoxColor.Controls.Add(this.panelGray);
this.groupBoxColor.Controls.Add(this.panelGreen);
this.groupBoxColor.Controls.Add(this.panelYellow);
this.groupBoxColor.Controls.Add(this.panelOrange);
this.groupBoxColor.Controls.Add(this.panelRed);
this.groupBoxColor.Controls.Add(this.panelLawnGreen);
this.groupBoxColor.Location = new System.Drawing.Point(283, 32);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Size = new System.Drawing.Size(277, 145);
@@ -117,25 +117,25 @@
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelLightBlue
// panelIndigo
//
this.panelLightBlue.BackColor = System.Drawing.Color.Indigo;
this.panelLightBlue.Location = new System.Drawing.Point(5, 85);
this.panelLightBlue.Name = "panelLightBlue";
this.panelLightBlue.Size = new System.Drawing.Size(50, 40);
this.panelLightBlue.TabIndex = 0;
this.panelIndigo.BackColor = System.Drawing.Color.Indigo;
this.panelIndigo.Location = new System.Drawing.Point(5, 85);
this.panelIndigo.Name = "panelIndigo";
this.panelIndigo.Size = new System.Drawing.Size(50, 40);
this.panelIndigo.TabIndex = 0;
//
// panelBlue
// panelBlack
//
this.panelBlue.BackColor = System.Drawing.Color.Black;
this.panelBlue.Location = new System.Drawing.Point(75, 85);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(50, 40);
this.panelBlue.TabIndex = 0;
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(75, 85);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(50, 40);
this.panelBlack.TabIndex = 0;
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Fuchsia;
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(145, 85);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(50, 40);
@@ -151,7 +151,7 @@
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(215, 25);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(50, 40);
@@ -173,13 +173,13 @@
this.panelOrange.Size = new System.Drawing.Size(50, 40);
this.panelOrange.TabIndex = 0;
//
// panelRed
// panelLawnGreen
//
this.panelRed.BackColor = System.Drawing.Color.LawnGreen;
this.panelRed.Location = new System.Drawing.Point(5, 25);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(50, 40);
this.panelRed.TabIndex = 0;
this.panelLawnGreen.BackColor = System.Drawing.Color.LawnGreen;
this.panelLawnGreen.Location = new System.Drawing.Point(5, 25);
this.panelLawnGreen.Name = "panelLawnGreen";
this.panelLawnGreen.Size = new System.Drawing.Size(50, 40);
this.panelLawnGreen.TabIndex = 0;
//
// checkBoxWheel
//
@@ -362,14 +362,14 @@
private CheckBox checkBoxWheel;
private CheckBox checkBoxTanker;
private GroupBox groupBoxColor;
private Panel panelLightBlue;
private Panel panelBlue;
private Panel panelIndigo;
private Panel panelBlack;
private Panel panelPurple;
private Panel panelGray;
private Panel panelGreen;
private Panel panelYellow;
private Panel panelOrange;
private Panel panelRed;
private Panel panelLawnGreen;
private Label labelAdvancedObject;
private Label labelSimpleObject;
private PictureBox pictureBoxObject;

View File

@@ -27,12 +27,12 @@ namespace ProjectGasolineTanker
public FormTruckConfig()
{
InitializeComponent();
panelRed.MouseDown += PanelColor_MouseDown;
panelLawnGreen.MouseDown += PanelColor_MouseDown;
panelOrange.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelLightBlue.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
panelIndigo.MouseDown += PanelColor_MouseDown;
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
@@ -170,6 +170,8 @@ namespace ProjectGasolineTanker
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_truck == null)
return;
EventAddTruck?.Invoke(_truck);
Close();
}

View File

@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.Generics
{
internal class DrawingTruckEqutables : IEqualityComparer<DrawingTruck?>
{
public bool Equals(DrawingTruck? x, DrawingTruck? y)
{
if (x == null && x.EntityTruck == null)
throw new ArgumentNullException(nameof(x));
if (y == null && y.EntityTruck == null)
throw new ArgumentNullException(nameof(y));
if ((x.GetType().Name != y.GetType().Name))
return false;
if (x.EntityTruck.Speed != y.EntityTruck.Speed)
return false;
if (x.EntityTruck.Weight != y.EntityTruck.Weight)
return false;
if (x.EntityTruck.BodyColor != y.EntityTruck.BodyColor)
return false;
if (x is DrawingGasolineTanker && y is DrawingGasolineTanker)
{
var xGasTruck = (EntityGasolineTanker)x.EntityTruck;
var yGasTruck = (EntityGasolineTanker)y.EntityTruck;
if (xGasTruck.Add_Color != yGasTruck.Add_Color)
return false;
if (xGasTruck.IsTank != yGasTruck.IsTank)
return false;
if (xGasTruck.IsWheel != yGasTruck.IsWheel)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingTruck? obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.Generic
{
@@ -22,37 +23,40 @@ namespace ProjectGasolineTanker.Generic
}
// Добавление объекта в начало
public int Insert(T truck)
{
_places.Insert(0, truck);
return 0;
public int Insert(T truck, IEqualityComparer<T?>? equal = null)
{
return Insert(truck, 0, equal);
}
// Добавление объекта в набор на конкретную позицию
public bool Insert(T truck, int position)
{
// TODO проверка позиции
if (position < 0 || position >= Count || Count >= _maxCount)
{
return false;
}
// TODO вставка по позиции
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
// Добавление объекта в набор на конкретную позицию
public int Insert(T truck, int position, IEqualityComparer<T?>? equal = null)
{
if (Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
{
throw new IndexOutOfRangeException("Индекс вне границ коллекции");
}
if (equal != null && _places.Contains(truck, equal))
{
throw new ArgumentException("Данный объект уже есть в коллекции");
}
_places.Insert(position, truck);
return true;
return 0;
}
// Удаление объекта из набора с конкретной позиции
public bool Remove(int position)
{
// TODO проверка позиции
if (position < 0 || position >= Count)
{
return false;
throw new TruckNotFoundException(position);
}
// TODO удаление объекта из списка
_places.RemoveAt(position);
return true;
}

View File

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

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.Generics
{
internal class TruckCompareByColor : IComparer<DrawingTruck>
{
public int Compare(DrawingTruck? x, DrawingTruck? y)
{
if (x == null || x.EntityTruck == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityTruck == null)
throw new ArgumentNullException(nameof(y));
var xTruck = x.EntityTruck;
var yTruck = y.EntityTruck;
if (xTruck.BodyColor != yTruck.BodyColor)
return xTruck.BodyColor.Name.CompareTo(yTruck.BodyColor.Name);
var speedCompare = x.EntityTruck.Speed.CompareTo(y.EntityTruck.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
}
}
}

View File

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

View File

@@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.Generics;
using ProjectGasolineTanker.MovementStratg;
namespace ProjectGasolineTanker.Generic
@@ -29,13 +30,17 @@ namespace ProjectGasolineTanker.Generic
_collection = new SetGeneric<T>(width * height);
}
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public static int operator +(TruckGenericCollection<T, U> collect, T? obj)
{
if (obj != null)
{
return collect._collection.Insert(obj);
return collect._collection.Insert(obj, new DrawingTruckEqutables());
}
return -1;
}
public static bool operator -(TruckGenericCollection<T, U> collect, int pos)
{

View File

@@ -3,7 +3,9 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.Generics;
using ProjectGasolineTanker.MovementStratg;
namespace ProjectGasolineTanker.Generic
@@ -11,9 +13,9 @@ namespace ProjectGasolineTanker.Generic
internal class TruckGenericStorage
{
//Словарь (хранилище)
readonly Dictionary<string, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> _TruckStorages;
readonly Dictionary<TruckCollectionInfo, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> _TruckStorages;
//Возвращение списка названий наборов
public List<string> Keys => _TruckStorages.Keys.ToList();
public List<TruckCollectionInfo> Keys => _TruckStorages.Keys.ToList();
//Ширина окна отрисовки
private readonly int _pictureWidth;
//Высота окна отрисовки
@@ -28,7 +30,7 @@ namespace ProjectGasolineTanker.Generic
public TruckGenericStorage(int pictureWidth, int pictureHeight)
{
_TruckStorages = new Dictionary<string, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>>();
_TruckStorages = new Dictionary<TruckCollectionInfo, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -36,28 +38,22 @@ namespace ProjectGasolineTanker.Generic
// Добавление набора
public void AddSet(string name)
{
// TODO Прописать логику для добавления
// проверка, что нет набора с таким именем
foreach (string nameStorage in Keys)
{
if (nameStorage == name)
{
MessageBox.Show("Набор с заданным именем уже занят", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
_TruckStorages.Add(name, new TruckGenericCollection<DrawingTruck, DrawingObjectTruck>(_pictureWidth, _pictureHeight));
TruckCollectionInfo set = new TruckCollectionInfo(name, string.Empty);
if (_TruckStorages.ContainsKey(set))
return;
_TruckStorages.Add(set, new TruckGenericCollection<DrawingTruck, DrawingObjectTruck>(_pictureWidth, _pictureHeight));
}
// Удаление набора
public void DelSet(string name)
{
TruckCollectionInfo set = new TruckCollectionInfo(name, string.Empty);
// TODO Прописать логику для удаления
if (_TruckStorages.ContainsKey(name))
if (!_TruckStorages.ContainsKey(set))
{
_TruckStorages.Remove(name);
return;
}
_TruckStorages.Remove(set);
}
// Доступ к набору
@@ -65,88 +61,99 @@ namespace ProjectGasolineTanker.Generic
{
get
{
TruckCollectionInfo set = new TruckCollectionInfo(ind, string.Empty);
// TODO Продумать логику получения набора
if (_TruckStorages.ContainsKey(ind))
if (!_TruckStorages.ContainsKey(set))
{
return _TruckStorages[ind];
return null;
}
return null;
return _TruckStorages[set];
}
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = File.CreateText(filename))
StringBuilder data = new();
foreach (KeyValuePair<TruckCollectionInfo,
TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> record in _TruckStorages)
{
sw.WriteLine($"TruckStorage");
foreach (var record in _TruckStorages)
StringBuilder records = new();
foreach (DrawingTruck? elem in record.Value.GetTruck)
{
StringBuilder records = new();
foreach (DrawingTruck? elem in record.Value.GetTruck)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
sw.WriteLine($"{record.Key}{_separatorForKeyValue}{records}");
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
return true;
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"CarStorage{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))
{
// 1-ая строка
string? curLine = sr.ReadLine();
// пустая или не те данные
if (curLine == null || !curLine.Contains("TruckStorage"))
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
return false;
bufferTextFromFile += temp.GetString(b);
}
// очищаем
_TruckStorages.Clear();
// загружаем данные построчно
curLine = sr.ReadLine();
while (curLine != null)
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("TruckStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_TruckStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
// загружаем запись
string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
// загружаем набор
TruckGenericCollection<DrawingTruck, DrawingObjectTruck> collection = new(_pictureWidth, _pictureHeight);
// record[0] - название набора, record[1] - куча объектов
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
continue;
}
TruckGenericCollection<DrawingTruck, DrawingObjectTruck>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingTruck? Truck =
elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight);
if (Truck != null)
{
DrawingTruck? Truck = elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight);
// проверяем, не переполнится ли коллекция
if (Truck != null)
if ((collection + Truck)==-1)
{
if (collection + Truck == -1)
{
return false;
}
throw new Exception("Ошибка добавления в коллекцию");
}
}
_TruckStorages.Add(record[0], collection);
curLine = sr.ReadLine();
}
_TruckStorages.Add(new TruckCollectionInfo(record[0],
string.Empty), collection);
}
return true;
}
}
}

View File

@@ -9,13 +9,14 @@ using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.MovementStratg
{
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private Status _state = Status.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }

View File

@@ -9,7 +9,9 @@ using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.MovementStratg
{
/// <summary>
/// Реализация интерфейса
/// </summary>
public class DrawingObjectTruck : IMoveableObject
{
private readonly DrawingTruck? _drawingTruck = null;

View File

@@ -16,7 +16,7 @@ namespace ProjectGasolineTanker.MovementStratg
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
bool CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);

View File

@@ -6,9 +6,7 @@ using System.Threading.Tasks;
namespace ProjectGasolineTanker.MovementStratg
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()

View File

@@ -21,7 +21,7 @@ namespace ProjectGasolineTanker.MovementStratg
public int RightBorder => _x + _width;
public int DownBorder => _y + _height;
public int ObjectMiddleHorizontal => _x + _width / 2;
public int ObjectMiddleVertical => _y + _height / 2;

View File

@@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectGasolineTanker
{
internal static class Program
@@ -7,11 +13,36 @@ namespace ProjectGasolineTanker
/// </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 FormTruckCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTruckCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTruckCollection>().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);
});
}
}
}

View File

@@ -8,6 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<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.Formatting.Compact" Version="2.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

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