2 Commits
Lab5 ... Lab7

Author SHA1 Message Date
f4861308df Lab7_DONE 2024-10-03 00:45:35 +03:00
7ed90109f5 Lab6_DONE 2024-10-03 00:44:06 +03:00
22 changed files with 568 additions and 137 deletions

View File

@@ -30,14 +30,14 @@ namespace ProjectGasolineTanker.Drawings
Brush additionalBrush = new SolidBrush(GasolineTanker.Add_Color);
base.DrawTransport(g);
if (GasolineTanker.Tank)
if (GasolineTanker.IsTank)
{
g.FillRectangle(additionalBrush, _startPosX + 45, _startPosY + 53, 35, 20);
g.DrawLine(pen, _startPosX + 45, _startPosY + 53, _startPosX + 80, _startPosY + 73);
g.DrawLine(pen, _startPosX + 80, _startPosY + 53, _startPosX + 45, _startPosY + 73);
}
if (GasolineTanker.Wheel)
if (GasolineTanker.IsWheel)
{
Brush gr = new SolidBrush(Color.Gray);
g.FillEllipse(additionalBrush, _startPosX + 85, _startPosY + 55, 22, 22);

View File

@@ -38,6 +38,7 @@ namespace ProjectGasolineTanker.Drawings
public DrawingTruck(int speed, double weight, Color bodyColor, int width, int height)
{
// TODO: Продумать проверки
if (width < _tankerWidth || height < _tankerHeight)
{
return;
@@ -116,16 +117,16 @@ namespace ProjectGasolineTanker.Drawings
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityTruck.BodyColor);
g.FillRectangle(additionalBrush, _startPosX + 29, _startPosY + 11, 71, 28);
g.FillRectangle(additionalBrush, _startPosX + 29, _startPosY + 20, 71, 9);
g.FillRectangle(additionalBrush, _startPosX + 29, _startPosY + 11, 71, 28); //канистра-бак
g.FillRectangle(additionalBrush, _startPosX + 29, _startPosY + 20, 71, 9); //полосы
g.DrawRectangle(pen, _startPosX + 29, _startPosY + 11, 71, 28);
g.DrawRectangle(pen, _startPosX + 29, _startPosY + 20, 71, 9);
g.DrawRectangle(pen, _startPosX + 29, _startPosY + 11, 71, 28); //канистра-бак
g.DrawRectangle(pen, _startPosX + 29, _startPosY + 20, 71, 9); //полосы
Brush additionalBrush1 = new
SolidBrush(EntityTruck.BodyColor);
//кабина
g.FillRectangle(additionalBrush1, _startPosX + 100, _startPosY + 10, 24, 16);
g.FillRectangle(additionalBrush1, _startPosX + 124, _startPosY + 10, 9, 16);
g.FillRectangle(additionalBrush1, _startPosX + 100, _startPosY + 10, 33, 16);
@@ -144,7 +145,7 @@ namespace ProjectGasolineTanker.Drawings
g.FillRectangle(additionalBrush2, _startPosX + 4, _startPosY + 40, 130, 25);
g.DrawLine(pen, _startPosX + 4, _startPosY + 65, _startPosX + 25, _startPosY + 40);
//колёса
Brush gr = new SolidBrush(Color.Gray);
g.FillEllipse(additionalBrush, _startPosX + 15, _startPosY + 50, 26, 26);
@@ -157,7 +158,6 @@ namespace ProjectGasolineTanker.Drawings
g.DrawEllipse(pen, _startPosX + 110, _startPosY + 55, 22, 22);
}
public bool CanMove(DirectionType direction)
{
if (EntityTruck == null)

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.Drawings
{
public static class ExtentionDrawingTruck
{
// создание объекта из строки
public static DrawingTruck? CreateDrawingTruck(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingTruck(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingGasolineTanker(
Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]),
width, height);
}
return null;
}
// Получение данных для сохранения в файл
public static string GetDataForSave(this DrawingTruck DrawingTruck, char separatorForObject)
{
var truck = DrawingTruck.EntityTruck;
if (truck == null)
{
return string.Empty;
}
var str = $"{truck.Speed}{separatorForObject}{truck.Weight}{separatorForObject}{truck.BodyColor.Name}";
if (truck is not EntityGasolineTanker GasolineTanker)
{
return str;
}
return $"{str}{separatorForObject}{GasolineTanker.Add_Color.Name}{separatorForObject}{GasolineTanker.IsTank}{separatorForObject}{GasolineTanker.IsWheel}";
}
}
}

View File

@@ -12,16 +12,15 @@ namespace ProjectGasolineTanker.Entities
{
public Color Add_Color { get; private set; }
public bool IsTank { get; private set; }
public bool IsWheel { get; private set; }
public bool Tank { get; private set; }
public bool Wheel { get; private set; }
public EntityGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool tank, bool wheel) : base(speed, weight, bodyColor)
{
Add_Color = additionalColor;
Tank = tank;
Wheel = wheel;
IsTank = tank;
IsWheel = wheel;
}
public void ChangeAdditionalColor(Color additionalColor)

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

@@ -40,16 +40,22 @@
this.buttonAddStorage = new System.Windows.Forms.Button();
this.buttonDeleteStorage = new System.Windows.Forms.Button();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// 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(734, 420);
this.buttonAddTruck.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonAddTruck.Location = new System.Drawing.Point(642, 315);
this.buttonAddTruck.Name = "buttonAddTruck";
this.buttonAddTruck.Size = new System.Drawing.Size(157, 37);
this.buttonAddTruck.Size = new System.Drawing.Size(137, 28);
this.buttonAddTruck.TabIndex = 0;
this.buttonAddTruck.Text = "Добавить грузовик";
this.buttonAddTruck.UseVisualStyleBackColor = true;
@@ -57,10 +63,9 @@
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCollection.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 27);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(715, 581);
this.pictureBoxCollection.Size = new System.Drawing.Size(626, 436);
this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false;
//
@@ -69,19 +74,18 @@
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(753, 12);
this.labelInstruments.Location = new System.Drawing.Point(659, 9);
this.labelInstruments.Name = "labelInstruments";
this.labelInstruments.Size = new System.Drawing.Size(136, 28);
this.labelInstruments.Size = new System.Drawing.Size(108, 21);
this.labelInstruments.TabIndex = 2;
this.labelInstruments.Text = "Инструменты";
//
// 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(741, 172);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonUpdate.Location = new System.Drawing.Point(648, 129);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(150, 33);
this.buttonUpdate.Size = new System.Drawing.Size(131, 25);
this.buttonUpdate.TabIndex = 3;
this.buttonUpdate.Text = "Обновить набор";
this.buttonUpdate.UseVisualStyleBackColor = true;
@@ -90,10 +94,9 @@
// 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(734, 537);
this.buttonDeleteTruck.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDeleteTruck.Location = new System.Drawing.Point(642, 403);
this.buttonDeleteTruck.Name = "buttonDeleteTruck";
this.buttonDeleteTruck.Size = new System.Drawing.Size(157, 37);
this.buttonDeleteTruck.Size = new System.Drawing.Size(137, 28);
this.buttonDeleteTruck.TabIndex = 4;
this.buttonDeleteTruck.Text = "Удалить грузовик";
this.buttonDeleteTruck.UseVisualStyleBackColor = true;
@@ -102,11 +105,10 @@
// 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(734, 480);
this.maskedTextBoxNumber.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(642, 360);
this.maskedTextBoxNumber.Mask = "00";
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(157, 27);
this.maskedTextBoxNumber.Size = new System.Drawing.Size(138, 23);
this.maskedTextBoxNumber.TabIndex = 5;
this.maskedTextBoxNumber.ValidatingType = typeof(int);
//
@@ -114,27 +116,29 @@
//
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(741, 63);
this.label1.Location = new System.Drawing.Point(648, 47);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(66, 20);
this.label1.Size = new System.Drawing.Size(52, 15);
this.label1.TabIndex = 7;
this.label1.Text = "Наборы";
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 20;
this.listBoxStorages.Location = new System.Drawing.Point(741, 209);
this.listBoxStorages.ItemHeight = 15;
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(150, 144);
this.listBoxStorages.Size = new System.Drawing.Size(132, 109);
this.listBoxStorages.TabIndex = 8;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged);
//
// buttonAddStorage
//
this.buttonAddStorage.Location = new System.Drawing.Point(741, 132);
this.buttonAddStorage.Location = new System.Drawing.Point(648, 99);
this.buttonAddStorage.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAddStorage.Name = "buttonAddStorage";
this.buttonAddStorage.Size = new System.Drawing.Size(150, 33);
this.buttonAddStorage.Size = new System.Drawing.Size(131, 25);
this.buttonAddStorage.TabIndex = 9;
this.buttonAddStorage.Text = "Добавить набор";
this.buttonAddStorage.UseVisualStyleBackColor = true;
@@ -142,9 +146,10 @@
//
// buttonDeleteStorage
//
this.buttonDeleteStorage.Location = new System.Drawing.Point(741, 360);
this.buttonDeleteStorage.Location = new System.Drawing.Point(648, 270);
this.buttonDeleteStorage.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDeleteStorage.Name = "buttonDeleteStorage";
this.buttonDeleteStorage.Size = new System.Drawing.Size(150, 33);
this.buttonDeleteStorage.Size = new System.Drawing.Size(131, 25);
this.buttonDeleteStorage.TabIndex = 10;
this.buttonDeleteStorage.Text = "Удалить набор";
this.buttonDeleteStorage.UseVisualStyleBackColor = true;
@@ -152,16 +157,59 @@
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(741, 99);
this.textBoxStorageName.Location = new System.Drawing.Point(648, 74);
this.textBoxStorageName.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(150, 27);
this.textBoxStorageName.Size = new System.Drawing.Size(132, 23);
this.textBoxStorageName.TabIndex = 11;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
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.TabIndex = 12;
this.menuStrip.Text = "menuStrip1";
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveToolStripMenuItem,
this.loadToolStripMenuItem});
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(48, 20);
this.toolStripMenuItem1.Text = "Файл";
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(180, 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.Text = "Загрузить";
this.loadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// FormTruckCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(911, 591);
this.ClientSize = new System.Drawing.Size(797, 465);
this.Controls.Add(this.textBoxStorageName);
this.Controls.Add(this.buttonDeleteStorage);
this.Controls.Add(this.buttonAddStorage);
@@ -173,10 +221,13 @@
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.labelInstruments);
this.Controls.Add(this.pictureBoxCollection);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormTruckCollection";
this.Text = "Набор грузовиков";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
@@ -196,5 +247,11 @@
private Button buttonAddStorage;
private Button buttonDeleteStorage;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem toolStripMenuItem1;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

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,10 @@ using System.Windows.Forms;
using ProjectGasolineTanker.Generic;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.MovementStratg;
using ProjectGasolineTanker.Exceptions;
using ProjectGasolineTanker;
using System.Xml.Linq;
namespace ProjectGasolineTanker
{
@@ -18,11 +22,14 @@ 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;
}
// заполнение лист бокс
@@ -55,6 +62,7 @@ namespace ProjectGasolineTanker
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
// выбрать набор
@@ -70,18 +78,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();
formTruckConfig.AddEvent(AddTruck);
formTruckConfig.Show();
}
@@ -98,15 +108,24 @@ 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);
}
}
@@ -126,24 +145,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);
}
}
@@ -163,6 +187,43 @@ namespace ProjectGasolineTanker
pictureBoxCollection.Image = obj.ShowTruck();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл сохранён по пути: {saveFileDialog.FileName}");
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
}
}
}
// Обработка нажатия "Загрузка"
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл загружен по пути: {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
}
}
ReloadObjects();
}
}
}

View File

@@ -60,6 +60,15 @@
<metadata name="colorDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>131, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>239, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>375, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>36</value>
</metadata>

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

@@ -16,24 +16,31 @@ namespace ProjectGasolineTanker
{
DrawingTruck? _truck = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingTruck>? EventAddTruck;
/// <summary>
/// Конструктор
/// </summary>
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();
}
/// <summary>
/// Отрисовка объекта
/// </summary>
private void DrawTruck()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
@@ -42,7 +49,10 @@ namespace ProjectGasolineTanker
_truck?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>labelSimpleObject
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный методlabelSimpleObject</param>labelSimpleObject
public void AddEvent(Action<DrawingTruck> ev)
{
if (EventAddTruck == null)
@@ -72,7 +82,11 @@ namespace ProjectGasolineTanker
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации (имени Label)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
@@ -96,13 +110,21 @@ namespace ProjectGasolineTanker
}
DrawTruck();
}
/// <summary>
/// Передача цвета при нажатии на одну из Panel с цветом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому: цвет) для Label с основным цветом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelMainColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _truck != null)
@@ -114,7 +136,11 @@ namespace ProjectGasolineTanker
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемого цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelMainColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
@@ -144,6 +170,8 @@ namespace ProjectGasolineTanker
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_truck == null)
return;
EventAddTruck?.Invoke(_truck);
Close();
}

View File

@@ -3,17 +3,18 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.Generic
{
internal class SetGeneric<T>
where T : class
{
// список объектов
private readonly List<T?> _places;
// кол-во объектов
public int Count => _places.Count;
// максимальное количество
private readonly int _maxCount;
public SetGeneric(int count)
{
@@ -21,41 +22,44 @@ namespace ProjectGasolineTanker.Generic
_places = new List<T?>(count);
}
// Добавление объекта в начало
public int Insert(T truck)
{
_places.Insert(0, truck);
return Insert(truck, 0);
}
// Добавление объекта в набор на конкретную позицию
public int Insert(T truck, int position)
{
if (Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
{
throw new IndexOutOfRangeException("Индекс вне границ коллекции");
}
_places.Insert(position, truck);
return 0;
}
public bool Insert(T truck, int position)
{
if (position < 0 || position >= Count || Count >= _maxCount)
{
return false;
}
// TODO вставка по позиции
_places.Insert(position, truck);
return true;
}
// Удаление объекта из набора с конкретной позиции
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
throw new TruckNotFoundException(position);
}
_places.RemoveAt(position);
return true;
}
// Получение объекта из набора по позиции
public T? this[int position]
{
get
{
// TODO проверка позиции
if (position < 0 || position >= Count)
{
return null;
@@ -64,14 +68,18 @@ namespace ProjectGasolineTanker.Generic
}
set
{
// TODO проверка позиции
if (position < 0 || position > Count || Count >= _maxCount)
{
return;
}
// TODO вставка в список по позиции
_places.Insert(position, value);
}
}
// Проход по списку
public IEnumerable<T?> GetTruck(int? maxTruck = null)
{
for (int i = 0; i < _places.Count; ++i)

View File

@@ -14,10 +14,10 @@ namespace ProjectGasolineTanker.Generic
{
private readonly int _pictureWidth;
private readonly int _pictureHeight;
// Размер занимаемого места
private readonly int _placeSizeWidth = 200;
private readonly int _placeSizeHeight = 80;
// коллекция
private readonly SetGeneric<T> _collection;
public TruckGenericCollection(int picWidth, int picHeight)
@@ -46,6 +46,9 @@ namespace ProjectGasolineTanker.Generic
return collect?._collection.Remove(pos) ?? false;
}
public IEnumerable<T?> GetTruck => _collection.GetTruck();
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
@@ -67,6 +70,7 @@ namespace ProjectGasolineTanker.Generic
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
// линия разметки
gr.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
gr.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
@@ -76,6 +80,7 @@ namespace ProjectGasolineTanker.Generic
private void DrawObjects(Graphics g)
{
// координаты
int x = 0;
int y = _pictureHeight / _placeSizeHeight - 1;
@@ -83,12 +88,15 @@ namespace ProjectGasolineTanker.Generic
{
if (truck != null)
{
if (x > _pictureWidth / _placeSizeWidth - 1)
{
x = 0;
--y;
}
truck.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y);
truck.DrawTransport(g);
++x;
}

View File

@@ -10,11 +10,22 @@ namespace ProjectGasolineTanker.Generic
{
internal class TruckGenericStorage
{
//Словарь (хранилище)
readonly Dictionary<string, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> _TruckStorages;
//Возвращение списка названий наборов
public List<string> Keys => _TruckStorages.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 TruckGenericStorage(int pictureWidth, int pictureHeight)
{
_TruckStorages = new Dictionary<string, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>>();
@@ -24,6 +35,7 @@ namespace ProjectGasolineTanker.Generic
public void AddSet(string name)
{
foreach (string nameStorage in Keys)
{
if (nameStorage == name)
@@ -35,9 +47,10 @@ namespace ProjectGasolineTanker.Generic
_TruckStorages.Add(name, new TruckGenericCollection<DrawingTruck, DrawingObjectTruck>(_pictureWidth, _pictureHeight));
}
// Удаление набора
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (_TruckStorages.ContainsKey(name))
{
_TruckStorages.Remove(name);
@@ -45,6 +58,7 @@ namespace ProjectGasolineTanker.Generic
}
// Доступ к набору
public TruckGenericCollection<DrawingTruck, DrawingObjectTruck>? this[string ind]
{
get
@@ -57,5 +71,93 @@ namespace ProjectGasolineTanker.Generic
return null;
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> record in _TruckStorages)
{
StringBuilder records = new();
foreach (DrawingTruck? elem in record.Value.GetTruck)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"TruckStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
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("TruckStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_TruckStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
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)
{
if ((collection + truck) == -1)
{
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_TruckStorages.Add(record[0], collection);
}
}
}
}

View File

@@ -9,6 +9,7 @@ using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.MovementStratg
{
public abstract class AbstractStrategy
{

View File

@@ -12,6 +12,7 @@ namespace ProjectGasolineTanker.MovementStratg
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
@@ -19,5 +20,7 @@ namespace ProjectGasolineTanker.MovementStratg
bool CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);
}
}

View File

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

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,21 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/trucklog.log",
"rollingInterval": "Day",
"outputTemplate": null,
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "ProjectGasolineTanker"
}
}
}