5 Commits
Lab3 ... 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
7ed90109f5 Lab6_DONE 2024-10-03 00:44:06 +03:00
46283ecf8f Lab5_DONE 2024-10-03 00:43:12 +03:00
af5ff49bc8 Lab4_DONE 2024-10-03 00:42:04 +03:00
29 changed files with 1677 additions and 223 deletions

View File

@@ -11,7 +11,6 @@ namespace ProjectGasolineTanker.Drawings
public class DrawingGasolineTanker : DrawingTruck 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) 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) if (EntityTruck != null)
@@ -31,14 +30,14 @@ namespace ProjectGasolineTanker.Drawings
Brush additionalBrush = new SolidBrush(GasolineTanker.Add_Color); Brush additionalBrush = new SolidBrush(GasolineTanker.Add_Color);
base.DrawTransport(g); base.DrawTransport(g);
if (GasolineTanker.Tank) if (GasolineTanker.IsTank)
{ {
g.FillRectangle(additionalBrush, _startPosX + 45, _startPosY + 53, 35, 20); g.FillRectangle(additionalBrush, _startPosX + 45, _startPosY + 53, 35, 20);
g.DrawLine(pen, _startPosX + 45, _startPosY + 53, _startPosX + 80, _startPosY + 73); g.DrawLine(pen, _startPosX + 45, _startPosY + 53, _startPosX + 80, _startPosY + 73);
g.DrawLine(pen, _startPosX + 80, _startPosY + 53, _startPosX + 45, _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); Brush gr = new SolidBrush(Color.Gray);
g.FillEllipse(additionalBrush, _startPosX + 85, _startPosY + 55, 22, 22); g.FillEllipse(additionalBrush, _startPosX + 85, _startPosY + 55, 22, 22);

View File

@@ -19,7 +19,7 @@ namespace ProjectGasolineTanker.Drawings
private int _pictureWidth; private int _pictureWidth;
private int _pictureHeight; private int _pictureHeight;
protected int _startPosX; protected int _startPosX;
protected int _startPosY; protected int _startPosY;
@@ -38,7 +38,7 @@ namespace ProjectGasolineTanker.Drawings
public DrawingTruck(int speed, double weight, Color bodyColor, int width, int height) public DrawingTruck(int speed, double weight, Color bodyColor, int width, int height)
{ {
// TODO: Продумать проверки
if (width < _tankerWidth || height < _tankerHeight) if (width < _tankerWidth || height < _tankerHeight)
{ {
return; return;
@@ -177,6 +177,12 @@ namespace ProjectGasolineTanker.Drawings
_ => false, _ => false,
}; };
} }
public void ChangePictureSize(int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
}
} }
} }

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,20 @@ namespace ProjectGasolineTanker.Entities
{ {
public Color Add_Color { get; private set; } 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) public EntityGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool tank, bool wheel) : base(speed, weight, bodyColor)
{ {
Add_Color = additionalColor; Add_Color = additionalColor;
Tank = tank; IsTank = tank;
Wheel = wheel; IsWheel = wheel;
}
public void ChangeAdditionalColor(Color additionalColor)
{
Add_Color = additionalColor;
} }
} }
} }

View File

@@ -25,5 +25,10 @@ namespace ProjectGasolineTanker.Entities
BodyColor = bodyColor; BodyColor = bodyColor;
} }
public void ChangeBodyColor(Color color)
{
BodyColor = color;
}
} }
} }

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

@@ -4,14 +4,23 @@ using ProjectGasolineTanker.MovementStratg;
namespace ProjectGasolineTanker namespace ProjectGasolineTanker
{ {
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
public partial class FormGasolineTanker : Form public partial class FormGasolineTanker : Form
{ {
/// <summary>
/// <20><><EFBFBD><EFBFBD>-<2D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
private DrawingTruck? _drawingTruck; private DrawingTruck? _drawingTruck;
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
private AbstractStrategy? _abstractStrategy; private AbstractStrategy? _abstractStrategy;
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
public DrawingTruck? SelectedTruck { get; private set; } public DrawingTruck? SelectedTruck { get; private set; }
public FormGasolineTanker() public FormGasolineTanker()
@@ -20,7 +29,9 @@ namespace ProjectGasolineTanker
_abstractStrategy = null; _abstractStrategy = null;
SelectedTruck = null; SelectedTruck = null;
} }
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
private void Draw() private void Draw()
{ {
if (_drawingTruck == null) if (_drawingTruck == null)
@@ -33,7 +44,11 @@ namespace ProjectGasolineTanker
pictureBoxGasolineTanker.Image = bmp; pictureBoxGasolineTanker.Image = bmp;
} }
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateProjectGasolineTanker_Click(object sender, EventArgs e) private void buttonCreateProjectGasolineTanker_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
@@ -56,7 +71,11 @@ namespace ProjectGasolineTanker
_drawingTruck.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingTruck.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
} }
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ProjectGasolineTanker"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateTruck_Click(object sender, EventArgs e) private void buttonCreateTruck_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
@@ -75,7 +94,11 @@ namespace ProjectGasolineTanker
Draw(); Draw();
} }
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e) private void buttonMove_Click(object sender, EventArgs e)
{ {
if (_drawingTruck == null) if (_drawingTruck == null)
@@ -100,7 +123,11 @@ namespace ProjectGasolineTanker
} }
Draw(); Draw();
} }
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "<22><><EFBFBD>"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e) private void buttonStep_Click(object sender, EventArgs e)
{ {
if (_drawingTruck == null) if (_drawingTruck == null)

View File

@@ -28,89 +28,230 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.buttonAddTruck = new System.Windows.Forms.Button();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.labelInstruments = new System.Windows.Forms.Label(); this.labelInstruments = new System.Windows.Forms.Label();
this.buttonAdd = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.TextBox();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonUpdate = new System.Windows.Forms.Button(); this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDeleteTruck = new System.Windows.Forms.Button();
this.colorDialog = new System.Windows.Forms.ColorDialog();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.label1 = new System.Windows.Forms.Label();
this.listBoxStorages = new System.Windows.Forms.ListBox();
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();
this.sort_type_button = new System.Windows.Forms.Button();
this.sort_color_button = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.menuStrip.SuspendLayout();
this.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(660, 315);
this.buttonAddTruck.Name = "buttonAddTruck";
this.buttonAddTruck.Size = new System.Drawing.Size(137, 28);
this.buttonAddTruck.TabIndex = 0;
this.buttonAddTruck.Text = "Добавить грузовик";
this.buttonAddTruck.UseVisualStyleBackColor = true;
this.buttonAddTruck.Click += new System.EventHandler(this.buttonAddTruck_Click);
//
// pictureBoxCollection // pictureBoxCollection
// //
this.pictureBoxCollection.Location = new System.Drawing.Point(2, 1); this.pictureBoxCollection.Location = new System.Drawing.Point(0, 27);
this.pictureBoxCollection.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.pictureBoxCollection.Name = "pictureBoxCollection"; this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(803, 376); this.pictureBoxCollection.Size = new System.Drawing.Size(626, 436);
this.pictureBoxCollection.TabIndex = 0; this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false; this.pictureBoxCollection.TabStop = false;
// //
// labelInstruments // labelInstruments
// //
this.labelInstruments.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.labelInstruments.AutoSize = true; this.labelInstruments.AutoSize = true;
this.labelInstruments.Location = new System.Drawing.Point(852, 22); 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(677, 9);
this.labelInstruments.Name = "labelInstruments"; this.labelInstruments.Name = "labelInstruments";
this.labelInstruments.Size = new System.Drawing.Size(83, 15); this.labelInstruments.Size = new System.Drawing.Size(108, 21);
this.labelInstruments.TabIndex = 1; this.labelInstruments.TabIndex = 2;
this.labelInstruments.Text = "Инструменты"; this.labelInstruments.Text = "Инструменты";
// //
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(840, 64);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(161, 44);
this.buttonAdd.TabIndex = 2;
this.buttonAdd.Text = "Добавить грузовик";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAddTruck_Click);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(874, 140);
this.maskedTextBoxNumber.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(110, 23);
this.maskedTextBoxNumber.TabIndex = 3;
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(840, 167);
this.buttonDelete.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(165, 45);
this.buttonDelete.TabIndex = 4;
this.buttonDelete.Text = "Удалить грузовик";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonRemoveTruck_Click);
//
// buttonUpdate // buttonUpdate
// //
this.buttonUpdate.Location = new System.Drawing.Point(840, 260); this.buttonUpdate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.buttonUpdate.Location = new System.Drawing.Point(666, 129);
this.buttonUpdate.Name = "buttonUpdate"; this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(165, 45); this.buttonUpdate.Size = new System.Drawing.Size(131, 25);
this.buttonUpdate.TabIndex = 5; this.buttonUpdate.TabIndex = 3;
this.buttonUpdate.Text = "Обновить"; this.buttonUpdate.Text = "Обновить набор";
this.buttonUpdate.UseVisualStyleBackColor = true; this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonRefreshCollection_Click); this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click);
//
// 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(660, 403);
this.buttonDeleteTruck.Name = "buttonDeleteTruck";
this.buttonDeleteTruck.Size = new System.Drawing.Size(137, 28);
this.buttonDeleteTruck.TabIndex = 4;
this.buttonDeleteTruck.Text = "Удалить грузовик";
this.buttonDeleteTruck.UseVisualStyleBackColor = true;
this.buttonDeleteTruck.Click += new System.EventHandler(this.buttonDeleteTruck_Click);
//
// 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(660, 360);
this.maskedTextBoxNumber.Mask = "00";
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(138, 23);
this.maskedTextBoxNumber.TabIndex = 5;
this.maskedTextBoxNumber.ValidatingType = typeof(int);
//
// label1
//
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(666, 47);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(52, 15);
this.label1.TabIndex = 7;
this.label1.Text = "Наборы";
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
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(132, 49);
this.listBoxStorages.TabIndex = 8;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged);
//
// buttonAddStorage
//
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(131, 25);
this.buttonAddStorage.TabIndex = 9;
this.buttonAddStorage.Text = "Добавить набор";
this.buttonAddStorage.UseVisualStyleBackColor = true;
this.buttonAddStorage.Click += new System.EventHandler(this.buttonAddStorage_Click);
//
// buttonDeleteStorage
//
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(131, 25);
this.buttonDeleteStorage.TabIndex = 10;
this.buttonDeleteStorage.Text = "Удалить набор";
this.buttonDeleteStorage.UseVisualStyleBackColor = true;
this.buttonDeleteStorage.Click += new System.EventHandler(this.buttonDeleteStorage_Click);
//
// textBoxStorageName
//
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(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(815, 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(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(133, 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";
//
// 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 // FormTruckCollection
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1152, 382); this.ClientSize = new System.Drawing.Size(815, 465);
this.Controls.Add(this.buttonUpdate); this.Controls.Add(this.sort_color_button);
this.Controls.Add(this.buttonDelete); this.Controls.Add(this.sort_type_button);
this.Controls.Add(this.textBoxStorageName);
this.Controls.Add(this.buttonDeleteStorage);
this.Controls.Add(this.buttonAddStorage);
this.Controls.Add(this.listBoxStorages);
this.Controls.Add(this.label1);
this.Controls.Add(this.buttonAddTruck);
this.Controls.Add(this.maskedTextBoxNumber); this.Controls.Add(this.maskedTextBoxNumber);
this.Controls.Add(this.buttonAdd); this.Controls.Add(this.buttonDeleteTruck);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.labelInstruments); this.Controls.Add(this.labelInstruments);
this.Controls.Add(this.pictureBoxCollection); this.Controls.Add(this.pictureBoxCollection);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormTruckCollection"; this.Name = "FormTruckCollection";
this.Text = "Грузовик"; this.Text = "Набор грузовиков";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
@@ -118,11 +259,25 @@
#endregion #endregion
private Button buttonAddTruck;
private PictureBox pictureBoxCollection; private PictureBox pictureBoxCollection;
private Label labelInstruments; private Label labelInstruments;
private Button buttonAdd;
private TextBox maskedTextBoxNumber;
private Button buttonDelete;
private Button buttonUpdate; private Button buttonUpdate;
private Button buttonDeleteTruck;
private ColorDialog colorDialog;
private MaskedTextBox maskedTextBoxNumber;
private Label label1;
private ListBox listBoxStorages;
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;
private Button sort_type_button;
private Button sort_color_button;
} }
} }

View File

@@ -1,4 +1,5 @@
using System; using System;
using Microsoft.Extensions.Logging;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@@ -7,79 +8,250 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.Generic; using ProjectGasolineTanker.Generic;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.MovementStratg; using ProjectGasolineTanker.MovementStratg;
using ProjectGasolineTanker.Exceptions;
using ProjectGasolineTanker;
using System.Xml.Linq;
using ProjectGasolineTanker.Generics;
namespace ProjectGasolineTanker namespace ProjectGasolineTanker
{ {
public partial class FormTruckCollection : Form public partial class FormTruckCollection : Form
{ {
// Набор объектов
private readonly TruckGenericStorage _storage;
// Логер
private readonly ILogger _logger;
private readonly TruckGenericCollection<DrawingTruck, DrawingObjectTruck> _truck; public FormTruckCollection(ILogger<FormTruckCollection> logger)
public FormTruckCollection()
{ {
InitializeComponent(); InitializeComponent();
_truck = new TruckGenericCollection<DrawingTruck, DrawingObjectTruck>(pictureBoxCollection.Width, pictureBoxCollection.Height); _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();
}
// заполнение лист бокс
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
} }
private void ButtonAddTruck_Click(object sender, EventArgs e) // добавить набор в коллекцию
private void buttonAddStorage_Click(object sender, EventArgs e)
{ {
FormGasolineTanker form = new(); if (string.IsNullOrEmpty(textBoxStorageName.Text))
if (form.ShowDialog() == DialogResult.OK)
{ {
if (_truck + form.SelectedTruck != -1) MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
// выбрать набор
private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTruck();
}
// удалить набор
private void buttonDeleteStorage_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удалён набор: {name}");
}
}
private void buttonAddTruck_Click(object sender, EventArgs e)
{
var formTruckConfig = new FormTruckConfig();
formTruckConfig.AddEvent(AddTruck);
formTruckConfig.Show();
}
private void AddTruck(DrawingTruck selectedTruck)
{
if (listBoxStorages.SelectedIndex == -1)
{
MessageBox.Show("Не выбран набор");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
selectedTruck.ChangePictureSize(Width, Height);
try
{
if (obj + selectedTruck != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _truck.ShowTruck(); pictureBoxCollection.Image = obj.ShowTruck();
_logger.LogInformation($"Добавлен объект: {selectedTruck.EntityTruck.BodyColor}");
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); 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 ButtonRemoveTruck_Click(object sender, EventArgs e)
private void buttonDeleteTruck_Click(object sender, EventArgs e)
{ {
if (MessageBox.Show("Удалить объект?", "Удаление", if (listBoxStorages.SelectedIndex == -1)
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) {
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos = 0;
try 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("Неверный формат ввода");
_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)
{ {
MessageBox.Show("Ошибка ввода данных");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (_truck - (_truck.ReturnLength() - pos)) if (obj == null)
{ {
MessageBox.Show("Объект удален"); return;
pictureBoxCollection.Image = _truck.ShowTruck();
}
else
{
MessageBox.Show("Не удалось удалить объект");
} }
pictureBoxCollection.Image = obj.ShowTruck();
}
} private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
private void ButtonRefreshCollection_Click(object sender, EventArgs
e)
{ {
pictureBoxCollection.Image = _truck.ShowTruck(); 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

@@ -57,4 +57,19 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<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>
</root> </root>

View File

@@ -0,0 +1,382 @@
namespace ProjectGasolineTanker
{
partial class FormTruckConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.labelAdvancedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
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.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();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.panelObject = new System.Windows.Forms.Panel();
this.labelAdditionalColor = new System.Windows.Forms.Label();
this.labelMainColor = new System.Windows.Forms.Label();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.panelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelAdvancedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColor);
this.groupBoxConfig.Controls.Add(this.checkBoxWheel);
this.groupBoxConfig.Controls.Add(this.checkBoxTanker);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.labelWeight);
this.groupBoxConfig.Controls.Add(this.labelSpeed);
this.groupBoxConfig.Location = new System.Drawing.Point(14, 48);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(570, 251);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// labelAdvancedObject
//
this.labelAdvancedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAdvancedObject.Location = new System.Drawing.Point(440, 188);
this.labelAdvancedObject.Name = "labelAdvancedObject";
this.labelAdvancedObject.Size = new System.Drawing.Size(120, 30);
this.labelAdvancedObject.TabIndex = 8;
this.labelAdvancedObject.Text = "Продвинутый";
this.labelAdvancedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAdvancedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(283, 188);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(120, 30);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColor
//
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.panelLawnGreen);
this.groupBoxColor.Location = new System.Drawing.Point(283, 32);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Size = new System.Drawing.Size(277, 145);
this.groupBoxColor.TabIndex = 6;
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelIndigo
//
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;
//
// panelBlack
//
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.Purple;
this.panelPurple.Location = new System.Drawing.Point(145, 85);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(50, 40);
this.panelPurple.TabIndex = 0;
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(215, 85);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(50, 40);
this.panelGray.TabIndex = 0;
//
// panelGreen
//
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);
this.panelGreen.TabIndex = 0;
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Gold;
this.panelYellow.Location = new System.Drawing.Point(145, 25);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(50, 40);
this.panelYellow.TabIndex = 0;
//
// panelOrange
//
this.panelOrange.BackColor = System.Drawing.Color.Cyan;
this.panelOrange.Location = new System.Drawing.Point(75, 25);
this.panelOrange.Name = "panelOrange";
this.panelOrange.Size = new System.Drawing.Size(50, 40);
this.panelOrange.TabIndex = 0;
//
// panelLawnGreen
//
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
//
this.checkBoxWheel.AutoSize = true;
this.checkBoxWheel.Location = new System.Drawing.Point(13, 149);
this.checkBoxWheel.Name = "checkBoxWheel";
this.checkBoxWheel.Size = new System.Drawing.Size(173, 24);
this.checkBoxWheel.TabIndex = 5;
this.checkBoxWheel.Text = "Наличие доп колеса";
this.checkBoxWheel.UseVisualStyleBackColor = true;
//
// checkBoxTanker
//
this.checkBoxTanker.AutoSize = true;
this.checkBoxTanker.Location = new System.Drawing.Point(13, 119);
this.checkBoxTanker.Name = "checkBoxTanker";
this.checkBoxTanker.Size = new System.Drawing.Size(128, 24);
this.checkBoxTanker.TabIndex = 4;
this.checkBoxTanker.Text = "Наличие бака";
this.checkBoxTanker.UseVisualStyleBackColor = true;
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(94, 32);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(150, 27);
this.numericUpDownSpeed.TabIndex = 3;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(94, 83);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(150, 27);
this.numericUpDownWeight.TabIndex = 2;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(6, 85);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(36, 20);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес:";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(6, 32);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(76, 20);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость:";
//
// pictureBoxObject
//
this.pictureBoxObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBoxObject.Location = new System.Drawing.Point(35, 84);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(327, 205);
this.pictureBoxObject.TabIndex = 1;
this.pictureBoxObject.TabStop = false;
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelAdditionalColor);
this.panelObject.Controls.Add(this.labelMainColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(613, 29);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(401, 301);
this.panelObject.TabIndex = 2;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelAdditionalColor
//
this.labelAdditionalColor.AllowDrop = true;
this.labelAdditionalColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAdditionalColor.Location = new System.Drawing.Point(233, 19);
this.labelAdditionalColor.Name = "labelAdditionalColor";
this.labelAdditionalColor.Size = new System.Drawing.Size(90, 50);
this.labelAdditionalColor.TabIndex = 3;
this.labelAdditionalColor.Text = "Доп. цвет";
this.labelAdditionalColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAdditionalColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelAdditionalColor_DragDrop);
this.labelAdditionalColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelAdditionalColor_DragEnter);
//
// labelMainColor
//
this.labelMainColor.AllowDrop = true;
this.labelMainColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelMainColor.Location = new System.Drawing.Point(77, 19);
this.labelMainColor.Name = "labelMainColor";
this.labelMainColor.Size = new System.Drawing.Size(90, 50);
this.labelMainColor.TabIndex = 2;
this.labelMainColor.Text = "Цвет";
this.labelMainColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelMainColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelMainColor_DragDrop);
this.labelMainColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelMainColor_DragEnter);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(689, 337);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 3;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(846, 339);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormTruckConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1032, 383);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormTruckConfig";
this.Text = "FormTruckConfig";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.panelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private NumericUpDown numericUpDownSpeed;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxWheel;
private CheckBox checkBoxTanker;
private GroupBox groupBoxColor;
private Panel panelIndigo;
private Panel panelBlack;
private Panel panelPurple;
private Panel panelGray;
private Panel panelGreen;
private Panel panelYellow;
private Panel panelOrange;
private Panel panelLawnGreen;
private Label labelAdvancedObject;
private Label labelSimpleObject;
private PictureBox pictureBoxObject;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelMainColor;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker
{
public partial class FormTruckConfig : Form
{
DrawingTruck? _truck = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingTruck>? EventAddTruck;
/// <summary>
/// Конструктор
/// </summary>
public FormTruckConfig()
{
InitializeComponent();
panelLawnGreen.MouseDown += PanelColor_MouseDown;
panelOrange.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelGreen.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);
Graphics gr = Graphics.FromImage(bmp);
_truck?.SetPosition(5, 5);
_truck?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>labelSimpleObject
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный методlabelSimpleObject</param>labelSimpleObject
public void AddEvent(Action<DrawingTruck> ev)
{
if (EventAddTruck == null)
{
EventAddTruck = ev;
}
else
{
EventAddTruck += ev;
}
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
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())
{
case "labelSimpleObject":
_truck = new DrawingTruck(
(int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.White,
pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelAdvancedObject":
_truck = new DrawingGasolineTanker(
(int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.White, Color.Black,
checkBoxTanker.Checked, checkBoxWheel.Checked,
pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
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)
{
e.Effect = DragDropEffects.Copy;
}
else
{
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));
_truck.EntityTruck.ChangeBodyColor(color);
DrawTruck();
}
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _truck != null && _truck is DrawingGasolineTanker)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
EntityGasolineTanker? _gasolinetanker = _truck.EntityTruck as EntityGasolineTanker;
_gasolinetanker.ChangeAdditionalColor(color);
DrawTruck();
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_truck == null)
return;
EventAddTruck?.Invoke(_truck);
Close();
}
}
}

View File

@@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

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,104 +3,99 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ProjectGasolineTanker.Exceptions;
namespace ProjectGasolineTanker.Generic namespace ProjectGasolineTanker.Generic
{ {
internal class SetGeneric<T> internal class SetGeneric<T>
where T : class where T : class
{ {
// список объектов
private readonly T?[] _places; private readonly List<T?> _places;
// кол-во объектов
public int Count => _places.Length - 1; public int Count => _places.Count;
// максимальное количество
private readonly int _maxCount;
public SetGeneric(int count) public SetGeneric(int count)
{ {
_places = new T?[count]; _maxCount = count;
_places = new List<T?>(count);
} }
public int Insert(T truck) // Добавление объекта в начало
public int Insert(T truck, IEqualityComparer<T?>? equal = null)
{
return Insert(truck, 0, equal);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
// Добавление объекта в набор на конкретную позицию
public int Insert(T truck, int position, IEqualityComparer<T?>? equal = null)
{ {
int pos = Count - 1; if (Count >= _maxCount)
if (_places[Count] != null)
{ {
throw new StorageOverflowException(_maxCount);
for (int i = pos; i > 0; --i)
{
if (_places[i] == null)
{
pos = i;
break;
}
}
for (int i = pos + 1; i <= Count; ++i)
{
_places[i - 1] = _places[i];
}
} }
if (position < 0 || position >= _maxCount)
_places[Count] = truck; {
return pos; throw new IndexOutOfRangeException("Индекс вне границ коллекции");
}
if (equal != null && _places.Contains(truck, equal))
{
throw new ArgumentException("Данный объект уже есть в коллекции");
}
_places.Insert(position, truck);
return 0;
} }
// Удаление объекта из набора с конкретной позиции
public bool Insert(T truck, int position)
{
// TODO проверка позиции
if (position < 0 || position > Count)
{
return false;
}
if (_places[Count] != null)
{
int pos = Count;
for (int i = Count; i > 0; --i)
{
if (_places[i] == null)
{
pos = i;
break;
}
}
for (int i = Count; i >= pos; --i)
{
_places[i - 1] = _places[i];
}
}
_places[Count] = truck;
return true;
}
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count)
if (position < 0 || position > Count)
{ {
return false; throw new TruckNotFoundException(position);
} }
_places[position] = null; _places.RemoveAt(position);
return true; return true;
} }
// Получение объекта из набора по позиции
public T? Get(int position) public T? this[int position]
{ {
get
if (position < 0 || position > Count)
{ {
return null; // TODO проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
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)
{
yield return _places[i];
if (maxTruck.HasValue && i == maxTruck.Value)
{
yield break;
}
} }
return _places[position];
} }
} }
} }

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.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ProjectGasolineTanker.Drawings; using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.Generics;
using ProjectGasolineTanker.MovementStratg; using ProjectGasolineTanker.MovementStratg;
namespace ProjectGasolineTanker.Generic namespace ProjectGasolineTanker.Generic
@@ -14,13 +15,12 @@ namespace ProjectGasolineTanker.Generic
{ {
private readonly int _pictureWidth; private readonly int _pictureWidth;
private readonly int _pictureHeight; private readonly int _pictureHeight;
// Размер занимаемого места
private readonly int _placeSizeWidth = 200; private readonly int _placeSizeWidth = 200;
private readonly int _placeSizeHeight = 80; private readonly int _placeSizeHeight = 80;
// коллекция
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
public TruckGenericCollection(int picWidth, int picHeight) public TruckGenericCollection(int picWidth, int picHeight)
{ {
int width = picWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;
@@ -30,34 +30,37 @@ namespace ProjectGasolineTanker.Generic
_collection = new SetGeneric<T>(width * height); _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) public static int operator +(TruckGenericCollection<T, U> collect, T? obj)
{ {
if (obj != null) if (obj != null)
{ {
return collect._collection.Insert(obj); return collect._collection.Insert(obj, new DrawingTruckEqutables());
} }
return -1; return -1;
} }
public static bool operator -(TruckGenericCollection<T, U> collect, int pos) public static bool operator -(TruckGenericCollection<T, U> collect, int pos)
{ {
if (collect._collection.Get(pos) == null) if (collect._collection.GetTruck(pos) == null)
{ {
return false; return false;
} }
return collect?._collection.Remove(pos) ?? false; return collect?._collection.Remove(pos) ?? false;
} }
public int ReturnLength() // получение объектов коллекции
{ public IEnumerable<T?> GetTruck => _collection.GetTruck();
return _collection.Count;
}
// получение объекта IMoveableObjecr
public U? GetU(int pos) public U? GetU(int pos)
{ {
return (U?)_collection.Get(pos)?.GetMoveableObject; return (U?)_collection[pos]?.GetMoveableObject;
} }
// вывод всего набора
public Bitmap ShowTruck() public Bitmap ShowTruck()
{ {
Bitmap bmp = new(_pictureWidth, _pictureHeight); Bitmap bmp = new(_pictureWidth, _pictureHeight);
@@ -67,7 +70,7 @@ namespace ProjectGasolineTanker.Generic
return bmp; return bmp;
} }
// прорисовка фона
private void DrawBackground(Graphics gr) private void DrawBackground(Graphics gr)
{ {
Pen pen = new(Color.Black, 3); Pen pen = new(Color.Black, 3);
@@ -75,6 +78,7 @@ namespace ProjectGasolineTanker.Generic
{ {
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) 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, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
gr.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight); gr.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
} }
@@ -83,36 +87,25 @@ namespace ProjectGasolineTanker.Generic
private void DrawObjects(Graphics g) private void DrawObjects(Graphics g)
{ {
// координаты
int x = 0; int x = 0;
int y = 0; int y = _pictureHeight / _placeSizeHeight - 1;
int index = -1;
for (int i = 0; i <= _collection.Count; ++i) foreach (var truck in _collection.GetTruck())
{ {
if (truck != null)
DrawingTruck _truck = _collection.Get(i);
x = 0;
y = 0;
if (_truck != null)
{ {
// TODO получение объекта
index = i; if (x > _pictureWidth / _placeSizeWidth - 1)
while (index - _pictureWidth / _placeSizeWidth >= 0)
{
y++;
index -= _pictureWidth / _placeSizeWidth;
}
if (index > 0)
{ {
x += index; x = 0;
--y;
} }
// TODO установка позиции
x = _pictureWidth / _placeSizeWidth - 1 - x; truck.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y);
_truck.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y); // TODO прорисовка объекта
_truck.DrawTransport(g); truck.DrawTransport(g);
++x;
} }
} }
} }

View File

@@ -0,0 +1,159 @@
using System;
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
{
internal class TruckGenericStorage
{
//Словарь (хранилище)
readonly Dictionary<TruckCollectionInfo, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> _TruckStorages;
//Возвращение списка названий наборов
public List<TruckCollectionInfo> 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<TruckCollectionInfo, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
// Добавление набора
public void AddSet(string name)
{
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(set))
{
return;
}
_TruckStorages.Remove(set);
}
// Доступ к набору
public TruckGenericCollection<DrawingTruck, DrawingObjectTruck>? this[string ind]
{
get
{
TruckCollectionInfo set = new TruckCollectionInfo(ind, string.Empty);
// TODO Продумать логику получения набора
if (!_TruckStorages.ContainsKey(set))
{
return null;
}
return _TruckStorages[set];
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<TruckCollectionInfo,
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.Name}{_separatorForKeyValue}{records}");
}
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 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(new TruckCollectionInfo(record[0],
string.Empty), collection);
}
}
}
}

View File

@@ -12,10 +12,11 @@ namespace ProjectGasolineTanker.MovementStratg
public abstract class AbstractStrategy public abstract class AbstractStrategy
{ {
private IMoveableObject? _moveableObject; private IMoveableObject? _moveableObject;
private Status _state = Status.NotInit; private Status _state = Status.NotInit;
protected int FieldWidth { get; private set; } protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; } protected int FieldHeight { get; private set; }
@@ -54,7 +55,7 @@ namespace ProjectGasolineTanker.MovementStratg
protected bool MoveRight() => MoveTo(DirectionType.Right); protected bool MoveRight() => MoveTo(DirectionType.Right);
protected bool MoveUp() => MoveTo(DirectionType.Up); protected bool MoveUp() => MoveTo(DirectionType.Up);
protected bool MoveDown() => MoveTo(DirectionType.Down); protected bool MoveDown() => MoveTo(DirectionType.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
@@ -71,7 +72,7 @@ namespace ProjectGasolineTanker.MovementStratg
protected abstract void MoveToTarget(); protected abstract void MoveToTarget();
protected abstract bool IsTargetDestinaion(); protected abstract bool IsTargetDestinaion();
private bool MoveTo(DirectionType directionType) private bool MoveTo(DirectionType directionType)
{ {
if (_state != Status.InProgress) if (_state != Status.InProgress)

View File

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

View File

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

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace ProjectGasolineTanker.MovementStratg namespace ProjectGasolineTanker.MovementStratg
{ {
public class MoveToCenter : AbstractStrategy public class MoveToCenter : AbstractStrategy
{ {
protected override bool IsTargetDestinaion() protected override bool IsTargetDestinaion()

View File

@@ -6,6 +6,7 @@ using System.Threading.Tasks;
namespace ProjectGasolineTanker.MovementStratg namespace ProjectGasolineTanker.MovementStratg
{ {
public class ObjectParameters public class ObjectParameters
{ {
private readonly int _x; private readonly int _x;

View File

@@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectGasolineTanker namespace ProjectGasolineTanker
{ {
internal static class Program internal static class Program
@@ -7,11 +13,36 @@ namespace ProjectGasolineTanker
/// </summary> /// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); 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> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <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"
}
}
}