3 Commits
Lab4 ... 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
46283ecf8f Lab5_DONE 2024-10-03 00:43:12 +03:00
22 changed files with 1151 additions and 100 deletions

View File

@@ -30,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

@@ -9,7 +9,7 @@ using ProjectGasolineTanker.MovementStratg;
namespace ProjectGasolineTanker.Drawings namespace ProjectGasolineTanker.Drawings
{ {
public class DrawingTruck public class DrawingTruck
{ {
public IMoveableObject GetMoveableObject => new DrawingObjectTruck(this); public IMoveableObject GetMoveableObject => new DrawingObjectTruck(this);
@@ -27,7 +27,7 @@ namespace ProjectGasolineTanker.Drawings
protected readonly int _tankerWidth = 130; protected readonly int _tankerWidth = 130;
protected readonly int _tankerHeight = 70; protected readonly int _tankerHeight = 70;
public int GetPosX => _startPosX; public int GetPosX => _startPosX;
public int GetPosY => _startPosY; public int GetPosY => _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;
@@ -50,7 +50,7 @@ namespace ProjectGasolineTanker.Drawings
protected DrawingTruck(int speed, double weight, Color bodyColor, int width, int height, int tankerWidth, int tankerHeight) protected DrawingTruck(int speed, double weight, Color bodyColor, int width, int height, int tankerWidth, int tankerHeight)
{ {
// TODO: Продумать проверки
if (width < _tankerWidth || height < _tankerHeight) if (width < _tankerWidth || height < _tankerHeight)
{ {
return; return;
@@ -117,11 +117,11 @@ namespace ProjectGasolineTanker.Drawings
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityTruck.BodyColor); Brush additionalBrush = new SolidBrush(EntityTruck.BodyColor);
g.FillRectangle(additionalBrush, _startPosX + 29, _startPosY + 11, 71, 28); g.FillRectangle(additionalBrush, _startPosX + 29, _startPosY + 11, 71, 28); //канистра-бак
g.FillRectangle(additionalBrush, _startPosX + 29, _startPosY + 20, 71, 9); g.FillRectangle(additionalBrush, _startPosX + 29, _startPosY + 20, 71, 9); //полосы
g.DrawRectangle(pen, _startPosX + 29, _startPosY + 11, 71, 28); g.DrawRectangle(pen, _startPosX + 29, _startPosY + 11, 71, 28); //канистра-бак
g.DrawRectangle(pen, _startPosX + 29, _startPosY + 20, 71, 9); g.DrawRectangle(pen, _startPosX + 29, _startPosY + 20, 71, 9); //полосы
Brush additionalBrush1 = new Brush additionalBrush1 = new
@@ -145,6 +145,7 @@ namespace ProjectGasolineTanker.Drawings
g.FillRectangle(additionalBrush2, _startPosX + 4, _startPosY + 40, 130, 25); g.FillRectangle(additionalBrush2, _startPosX + 4, _startPosY + 40, 130, 25);
g.DrawLine(pen, _startPosX + 4, _startPosY + 65, _startPosX + 25, _startPosY + 40); g.DrawLine(pen, _startPosX + 4, _startPosY + 65, _startPosX + 25, _startPosY + 40);
//колёса
Brush gr = new SolidBrush(Color.Gray); Brush gr = new SolidBrush(Color.Gray);
g.FillEllipse(additionalBrush, _startPosX + 15, _startPosY + 50, 26, 26); g.FillEllipse(additionalBrush, _startPosX + 15, _startPosY + 50, 26, 26);
@@ -170,12 +171,18 @@ namespace ProjectGasolineTanker.Drawings
//вверх //вверх
DirectionType.Up => _startPosY - EntityTruck.Step > 0, DirectionType.Up => _startPosY - EntityTruck.Step > 0,
// вправо // вправо
DirectionType.Right => _startPosX + _tankerWidth + EntityTruck.Step < _pictureWidth, DirectionType.Right => _startPosX + _tankerWidth + EntityTruck.Step < _pictureWidth,// TODO: Продумать логику
//вниз //вниз
DirectionType.Down => _startPosY + _tankerHeight + EntityTruck.Step < _pictureHeight, DirectionType.Down => _startPosY + _tankerHeight + EntityTruck.Step < _pictureHeight,// TODO: Продумать логику
_ => 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

@@ -9,9 +9,9 @@ namespace ProjectGasolineTanker.Entities
public class EntityTruck public class EntityTruck
{ {
public int Speed { get; private set; } public int Speed { get; private set; }
public double Weight { get; private set; } public double Weight { get; private set; }
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
@@ -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

@@ -40,16 +40,22 @@
this.buttonAddStorage = new System.Windows.Forms.Button(); this.buttonAddStorage = new System.Windows.Forms.Button();
this.buttonDeleteStorage = new System.Windows.Forms.Button(); this.buttonDeleteStorage = new System.Windows.Forms.Button();
this.textBoxStorageName = new System.Windows.Forms.TextBox(); 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(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
// //
// buttonAddTruck // buttonAddTruck
// //
this.buttonAddTruck.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); 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.Location = new System.Drawing.Point(642, 315);
this.buttonAddTruck.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonAddTruck.Name = "buttonAddTruck"; 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.TabIndex = 0;
this.buttonAddTruck.Text = "Добавить грузовик"; this.buttonAddTruck.Text = "Добавить грузовик";
this.buttonAddTruck.UseVisualStyleBackColor = true; this.buttonAddTruck.UseVisualStyleBackColor = true;
@@ -57,10 +63,9 @@
// //
// pictureBoxCollection // pictureBoxCollection
// //
this.pictureBoxCollection.Location = new System.Drawing.Point(1, 12); this.pictureBoxCollection.Location = new System.Drawing.Point(0, 27);
this.pictureBoxCollection.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.pictureBoxCollection.Name = "pictureBoxCollection"; this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(668, 381); this.pictureBoxCollection.Size = new System.Drawing.Size(626, 436);
this.pictureBoxCollection.TabIndex = 1; this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false; 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.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.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); 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.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.TabIndex = 2;
this.labelInstruments.Text = "Инструменты"; this.labelInstruments.Text = "Инструменты";
// //
// buttonUpdate // buttonUpdate
// //
this.buttonUpdate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); 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.Location = new System.Drawing.Point(648, 129);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonUpdate.Name = "buttonUpdate"; 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.TabIndex = 3;
this.buttonUpdate.Text = "Обновить набор"; this.buttonUpdate.Text = "Обновить набор";
this.buttonUpdate.UseVisualStyleBackColor = true; this.buttonUpdate.UseVisualStyleBackColor = true;
@@ -90,10 +94,9 @@
// buttonDeleteTruck // buttonDeleteTruck
// //
this.buttonDeleteTruck.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); 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.Location = new System.Drawing.Point(642, 403);
this.buttonDeleteTruck.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDeleteTruck.Name = "buttonDeleteTruck"; 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.TabIndex = 4;
this.buttonDeleteTruck.Text = "Удалить грузовик"; this.buttonDeleteTruck.Text = "Удалить грузовик";
this.buttonDeleteTruck.UseVisualStyleBackColor = true; this.buttonDeleteTruck.UseVisualStyleBackColor = true;
@@ -102,11 +105,10 @@
// maskedTextBoxNumber // maskedTextBoxNumber
// //
this.maskedTextBoxNumber.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); 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.Location = new System.Drawing.Point(642, 360);
this.maskedTextBoxNumber.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.maskedTextBoxNumber.Mask = "00"; this.maskedTextBoxNumber.Mask = "00";
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; 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.TabIndex = 5;
this.maskedTextBoxNumber.ValidatingType = typeof(int); 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.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label1.AutoSize = true; 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.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.TabIndex = 7;
this.label1.Text = "Наборы"; this.label1.Text = "Наборы";
// //
// listBoxStorages // listBoxStorages
// //
this.listBoxStorages.FormattingEnabled = true; this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 20; this.listBoxStorages.ItemHeight = 15;
this.listBoxStorages.Location = new System.Drawing.Point(741, 209); 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.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.TabIndex = 8;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged); this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged);
// //
// buttonAddStorage // 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.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.TabIndex = 9;
this.buttonAddStorage.Text = "Добавить набор"; this.buttonAddStorage.Text = "Добавить набор";
this.buttonAddStorage.UseVisualStyleBackColor = true; this.buttonAddStorage.UseVisualStyleBackColor = true;
@@ -142,27 +146,70 @@
// //
// buttonDeleteStorage // 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.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.TabIndex = 10;
this.buttonDeleteStorage.Text = "Удалить набор"; this.buttonDeleteStorage.Text = "Удалить набор";
this.buttonDeleteStorage.UseVisualStyleBackColor = true; this.buttonDeleteStorage.UseVisualStyleBackColor = true;
this.buttonDeleteStorage.TabIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged);
this.buttonDeleteStorage.Click += new System.EventHandler(this.buttonDeleteStorage_Click); this.buttonDeleteStorage.Click += new System.EventHandler(this.buttonDeleteStorage_Click);
// //
// textBoxStorageName // 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.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(150, 27); this.textBoxStorageName.Size = new System.Drawing.Size(132, 23);
this.textBoxStorageName.TabIndex = 11; 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 // 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.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(911, 689); this.ClientSize = new System.Drawing.Size(797, 465);
this.Controls.Add(this.textBoxStorageName); this.Controls.Add(this.textBoxStorageName);
this.Controls.Add(this.buttonDeleteStorage); this.Controls.Add(this.buttonDeleteStorage);
this.Controls.Add(this.buttonAddStorage); this.Controls.Add(this.buttonAddStorage);
@@ -174,10 +221,13 @@
this.Controls.Add(this.buttonUpdate); 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, 4, 3, 4); 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();
@@ -197,5 +247,11 @@
private Button buttonAddStorage; private Button buttonAddStorage;
private Button buttonDeleteStorage; private Button buttonDeleteStorage;
private TextBox textBoxStorageName; 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 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;
@@ -10,21 +11,28 @@ using System.Windows.Forms;
using ProjectGasolineTanker.Generic; using ProjectGasolineTanker.Generic;
using ProjectGasolineTanker.Drawings; using ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.MovementStratg; using ProjectGasolineTanker.MovementStratg;
using ProjectGasolineTanker.Exceptions;
using ProjectGasolineTanker; using ProjectGasolineTanker;
using System.Xml.Linq;
namespace ProjectGasolineTanker namespace ProjectGasolineTanker
{ {
public partial class FormTruckCollection : Form public partial class FormTruckCollection : Form
{ {
// Набор объектов
private readonly TruckGenericStorage _storage; private readonly TruckGenericStorage _storage;
// Логер
private readonly ILogger _logger;
public FormTruckCollection() public FormTruckCollection(ILogger<FormTruckCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new TruckGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new TruckGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
// заполнение лист бокс
private void ReloadObjects() private void ReloadObjects()
{ {
int index = listBoxStorages.SelectedIndex; int index = listBoxStorages.SelectedIndex;
@@ -44,6 +52,7 @@ namespace ProjectGasolineTanker
} }
// добавить набор в коллекцию
private void buttonAddStorage_Click(object sender, EventArgs e) private void buttonAddStorage_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
@@ -53,27 +62,41 @@ namespace ProjectGasolineTanker
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
// выбрать набор
private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e) private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTruck(); pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTruck();
} }
// удалить набор
private void buttonDeleteStorage_Click(object sender, EventArgs e) private void buttonDeleteStorage_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); _storage.DelSet(name);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удалён набор: {name}");
} }
} }
private void buttonAddTruck_Click(object sender, EventArgs e) 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) if (listBoxStorages.SelectedIndex == -1)
{ {
@@ -85,22 +108,28 @@ namespace ProjectGasolineTanker
{ {
return; return;
} }
FormGasolineTanker form = new(); selectedTruck.ChangePictureSize(Width, Height);
try
if (form.ShowDialog() == DialogResult.OK)
{ {
if (obj + form.SelectedTruck != -1) if (obj + selectedTruck != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.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);
}
} }
private void buttonDeleteTruck_Click(object sender, EventArgs e) private void buttonDeleteTruck_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
@@ -116,27 +145,33 @@ namespace ProjectGasolineTanker
{ {
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("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Неверный формат ввода");
return; _logger.LogWarning("Неверный формат ввода");
} }
if (obj - pos) catch (Exception ex)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show(ex.Message);
pictureBoxCollection.Image = obj.ShowTruck(); _logger.LogWarning(ex.Message);
}
else
{
MessageBox.Show("Не удалось удалить объект");
} }
} }
// обновить рисунок по набору
private void buttonUpdate_Click(object sender, EventArgs e) private void buttonUpdate_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
@@ -151,5 +186,44 @@ namespace ProjectGasolineTanker
} }
pictureBoxCollection.Image = obj.ShowTruck(); 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"> <metadata name="colorDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value> <value>17, 17</value>
</metadata> </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"> <metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>36</value> <value>36</value>
</metadata> </metadata>

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

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

View File

@@ -14,14 +14,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;
@@ -48,6 +46,9 @@ namespace ProjectGasolineTanker.Generic
return collect?._collection.Remove(pos) ?? false; return collect?._collection.Remove(pos) ?? false;
} }
public IEnumerable<T?> GetTruck => _collection.GetTruck();
public U? GetU(int pos) public U? GetU(int pos)
{ {
return (U?)_collection[pos]?.GetMoveableObject; return (U?)_collection[pos]?.GetMoveableObject;
@@ -79,6 +80,7 @@ namespace ProjectGasolineTanker.Generic
private void DrawObjects(Graphics g) private void DrawObjects(Graphics g)
{ {
// координаты
int x = 0; int x = 0;
int y = _pictureHeight / _placeSizeHeight - 1; int y = _pictureHeight / _placeSizeHeight - 1;
@@ -86,12 +88,15 @@ namespace ProjectGasolineTanker.Generic
{ {
if (truck != null) if (truck != null)
{ {
if (x > _pictureWidth / _placeSizeWidth - 1) if (x > _pictureWidth / _placeSizeWidth - 1)
{ {
x = 0; x = 0;
--y; --y;
} }
truck.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y); truck.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y);
truck.DrawTransport(g); truck.DrawTransport(g);
++x; ++x;
} }

View File

@@ -10,13 +10,22 @@ namespace ProjectGasolineTanker.Generic
{ {
internal class TruckGenericStorage internal class TruckGenericStorage
{ {
//Словарь (хранилище)
readonly Dictionary<string, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> _TruckStorages; readonly Dictionary<string, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>> _TruckStorages;
//Возвращение списка названий наборов
public List<string> Keys => _TruckStorages.Keys.ToList(); public List<string> Keys => _TruckStorages.Keys.ToList();
//Ширина окна отрисовки //Ширина окна отрисовки
private readonly int _pictureWidth; private readonly int _pictureWidth;
//Высота окна отрисовки //Высота окна отрисовки
private readonly int _pictureHeight; private readonly int _pictureHeight;
// Разделитель для записи ключа и значения элемента словаря
private static readonly char _separatorForKeyValue = '|';
// Разделитель для записей коллекции данных в файл
private readonly char _separatorRecords = ';';
// Разделитель для записи информации по объекту в файл
private static readonly char _separatorForObject = ':';
public TruckGenericStorage(int pictureWidth, int pictureHeight) public TruckGenericStorage(int pictureWidth, int pictureHeight)
{ {
_TruckStorages = new Dictionary<string, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>>(); _TruckStorages = new Dictionary<string, TruckGenericCollection<DrawingTruck, DrawingObjectTruck>>();
@@ -38,9 +47,10 @@ namespace ProjectGasolineTanker.Generic
_TruckStorages.Add(name, new TruckGenericCollection<DrawingTruck, DrawingObjectTruck>(_pictureWidth, _pictureHeight)); _TruckStorages.Add(name, new TruckGenericCollection<DrawingTruck, DrawingObjectTruck>(_pictureWidth, _pictureHeight));
} }
// Удаление набора
public void DelSet(string name) public void DelSet(string name)
{ {
// TODO Прописать логику для удаления
if (_TruckStorages.ContainsKey(name)) if (_TruckStorages.ContainsKey(name))
{ {
_TruckStorages.Remove(name); _TruckStorages.Remove(name);
@@ -48,10 +58,12 @@ namespace ProjectGasolineTanker.Generic
} }
// Доступ к набору
public TruckGenericCollection<DrawingTruck, DrawingObjectTruck>? this[string ind] public TruckGenericCollection<DrawingTruck, DrawingObjectTruck>? this[string ind]
{ {
get get
{ {
// TODO Продумать логику получения набора
if (_TruckStorages.ContainsKey(ind)) if (_TruckStorages.ContainsKey(ind))
{ {
return _TruckStorages[ind]; return _TruckStorages[ind];
@@ -59,5 +71,93 @@ namespace ProjectGasolineTanker.Generic
return null; 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,14 +9,16 @@ using ProjectGasolineTanker.Entities;
namespace ProjectGasolineTanker.MovementStratg 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; }
public Status GetStatus() { return _state; } public Status GetStatus() { return _state; }
@@ -53,9 +55,9 @@ 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;
protected int? GetStep() protected int? GetStep()

View File

@@ -12,11 +12,15 @@ namespace ProjectGasolineTanker.MovementStratg
public interface IMoveableObject public interface IMoveableObject
{ {
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

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

View File

@@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectGasolineTanker 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,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"
}
}
}