22 Commits

Author SHA1 Message Date
caf208b305 Доработка классов. Готовая лаба. 2023-12-29 06:20:55 +04:00
ec986c5a2c Внесение правок. Сдана работа 2023-12-29 03:24:17 +04:00
825ad3cdf5 Изменние класов. appsettings.json 2023-12-29 03:16:00 +04:00
fce83f96d5 Создание классов исключений. Обновление SetGeneric 2023-12-29 02:08:37 +04:00
5630e074f1 Редактирование. Готовая работа 2023-12-13 18:28:26 +04:00
0027078048 Правки,изменения, дополнение и изменение классов. 2023-12-13 18:25:07 +04:00
9123f0442e Создание и наполнение класса Extention DrwawingTractor. Изменние других классов 2023-12-13 18:22:58 +04:00
4e82bda63b Лаба5 2023-12-13 17:46:06 +04:00
ef93a0293c Внесение небольших правок. Сдана работа. 2023-12-13 17:44:18 +04:00
16b6400b36 Измение логики многих форм. 2023-12-13 17:38:05 +04:00
c53647752a Создание новой формы FormBulldozerConfig. Изменение файлов Entities. 2023-12-13 17:21:33 +04:00
e03720990d Исправление ошибок. Форматирование кода 2023-11-30 03:15:19 +04:00
9bbe889440 Добавление элементов на форму FormBulldozerCollection 2023-11-30 02:46:03 +04:00
a92d29b242 Создание класса TractorGenericStorage 2023-11-30 02:42:46 +04:00
e173941bbc Изменения в BulldozerGenericCollection 2023-11-30 02:33:36 +04:00
b97db5b022 Начало Lab04. Изменения класса SetGeneric. 2023-11-30 02:31:42 +04:00
7a993d4956 Доработка логик в классах и форматирование. 2023-11-30 02:23:07 +04:00
2a3a472f5c Создание второй формы FormBulldozerCollection 2023-11-30 02:11:18 +04:00
90ecee7735 Создание класса BulldozerGenericCollection, редактирование классов прорисовки 2023-11-30 02:09:48 +04:00
9e12aee1d5 Создание класса SetGeneric 2023-11-30 01:42:41 +04:00
87de7c65b3 Выполнение всех требований по второй лабораторной 2023-11-23 01:37:55 +04:00
e9c0b5160f Добавлен класс сущности базового и продвинутого объектов 2023-11-23 01:10:37 +04:00
46 changed files with 2589 additions and 362 deletions

View File

@@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer
{
internal enum Direction
{
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
}

View File

@@ -0,0 +1,10 @@
namespace ProjectBulldozer
{
public enum DirectionType
{
Up = 1,
Down = 2,
Left = 3,
Right = 4,
}
}

View File

@@ -0,0 +1,64 @@
using ProjectBulldozer.Entities;
namespace ProjectBulldozer.Drawning
{
public class DrawingBulldozer : DrawingTractor
{
public DrawingBulldozer(int speed, double weight, Color bodyColor, Color additionalColor,
bool otval, bool thirdWheel, int width, int height) : base(speed, weight, bodyColor, width, height, 120, 110)
{
if (EntityTractor != null)
{
EntityTractor = new EntityBulldozer(speed, width, bodyColor, additionalColor, otval, thirdWheel);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityTractor is not EntityBulldozer Bulldozer)
{
return;
}
Pen pen = new(Color.Black);
Brush blackBrush = new SolidBrush(Color.Black);
Brush additionalColor = new SolidBrush(Bulldozer.AdditionalColor);
Brush grayBrush = new SolidBrush(Color.Gray);
if (Bulldozer.Otval)
{
//otval
Point[] Otval =
{
new Point(_startPosX + 118, _startPosY + 50),
new Point(_startPosX + 148, _startPosY + 111),
new Point(_startPosX+ 118, _startPosY + 111),
};
g.FillPolygon(additionalColor, Otval);
g.DrawPolygon(pen, Otval);
}
//гусеницы
Brush gg = new SolidBrush(Color.LightGray);
g.FillEllipse(gg, _startPosX + 16, _startPosY + 65, 101, 63);
g.DrawEllipse(pen, _startPosX + 16, _startPosY + 65, 101, 63);
if (Bulldozer.ThirdWheel)
{
g.FillEllipse(grayBrush, _startPosX + 65, _startPosY + 100, 13, 13);
g.DrawEllipse(pen, _startPosX + 65, _startPosY + 100, 13, 13);
}
Point[] Ttt =
{
new Point(_startPosX + 16, _startPosY + 79),
new Point(_startPosX + 16, _startPosY + 120),
new Point(_startPosX, _startPosY + 48),
};
g.FillPolygon(blackBrush, Ttt);
g.DrawPolygon(pen, Ttt);
g.FillRectangle(blackBrush, _startPosX + 110, _startPosY + 60, 5, 10);
base.DrawTransport(g);
}
}
}

View File

@@ -0,0 +1,129 @@
using ProjectBulldozer.Entities;
using ProjectBulldozer.MovementStrategy;
namespace ProjectBulldozer.Drawning
{
public class DrawingTractor
{
public EntityTractor? EntityTractor { get; protected set; }
public int _pictureWidth;
public int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected readonly int _tractWidth = 120;
protected readonly int _tractHeight = 110;
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _tractWidth;
public int GetHeight => _tractHeight;
public IMoveableObject GetMoveableObject => new DrawingObjectTractor(this);
public DrawingTractor(int speed, double weight, Color bodyColor, int width, int heigth)
{
if (width < _tractWidth || heigth < _tractHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = heigth;
EntityTractor = new EntityTractor(speed, weight, bodyColor);
}
protected DrawingTractor(int speed, double weight, Color bodyColor, int width,
int height, int tractWidth, int tractHeight)
{
if (width < _tractWidth || height < _tractHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_tractWidth = tractWidth;
_tractHeight = tractHeight;
EntityTractor = new EntityTractor(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)
{
if (x < 0 || x + _tractWidth > _pictureWidth)
{
x = _pictureWidth - _tractWidth;
}
if (y < 0 || y + _tractHeight > _pictureHeight)
{
y = _pictureHeight - _tractHeight;
}
_startPosX = x;
_startPosY = y;
}
public void MoveTransport(DirectionType direction)
{
if (EntityTractor == null)
{
return;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX - EntityTractor.Step > 0)
{
_startPosX -= (int)EntityTractor.Step;
}
break;
case DirectionType.Up:
if (_startPosY - EntityTractor.Step > 0)
{
_startPosY -= (int)EntityTractor.Step;
}
break;
case DirectionType.Right:
if (_startPosX + EntityTractor.Step + _tractWidth < _pictureWidth)
{
_startPosX += (int)EntityTractor.Step;
}
break;
case DirectionType.Down:
if (_startPosY + EntityTractor.Step + _tractHeight < _pictureHeight)
{
_startPosY += (int)EntityTractor.Step;
}
break;
}
}
public virtual void DrawTransport(Graphics g)
{
{
if (EntityTractor == null) return;
}
Pen pen = new(Color.Black);
Brush brownBrush = new SolidBrush(Color.Brown);
Brush windows = new SolidBrush(Color.LightYellow);
Brush bodyColor = new SolidBrush(EntityTractor.BodyColor);
Brush grayBrush = new SolidBrush(Color.Gray);
//основное тело
g.FillRectangle(bodyColor, _startPosX + 18, _startPosY + 42, 99, 56);
g.DrawRectangle(pen, _startPosX + 18, _startPosY + 42, 99, 56);
//кабина водителя
g.FillRectangle(windows, _startPosX + 18, _startPosY + 4 , 37, 37);
g.DrawRectangle(pen, _startPosX + 18, _startPosY +4 , 37, 37);
//колеса
g.FillEllipse(grayBrush, _startPosX + 19, _startPosY + 76, 45, 45);
g.DrawEllipse(pen, _startPosX + 19, _startPosY + 76, 45, 45);
g.FillEllipse(grayBrush, _startPosX + 80, _startPosY + 87, 33, 33);
g.DrawEllipse(pen, _startPosX + 80, _startPosY + 87, 33, 33);
//выхлопная труба
g.FillRectangle(brownBrush, _startPosX + 88, _startPosY+ 6, 14, 35);
g.DrawRectangle(pen, _startPosX + 88, _startPosY + 6, 14, 35);
}
public bool CanMove(DirectionType direction)
{
if (EntityTractor == null)
{
return false;
}
return direction switch
{
DirectionType.Left => _startPosX - EntityTractor.Step > 0,
DirectionType.Up => _startPosY - EntityTractor.Step > 0,
DirectionType.Right => _startPosX + EntityTractor.Step < _pictureWidth,
DirectionType.Down => _startPosY + EntityTractor.Step < _pictureHeight,
};
}
}
}

View File

@@ -0,0 +1,48 @@
using ProjectBulldozer.Drawning;
using ProjectBulldozer.Entities;
namespace ProjectBulldozer.Drawing
{
public static class ExtentionDrawingTractor
{
public static DrawingTractor? CreateDrawingTractor(this string info,
char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingTractor(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawingBulldozer(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 DrawingTractor drawingTractor,
char separatorForObject)
{
var tractor = drawingTractor.EntityTractor;
if (tractor == null)
{
return string.Empty;
}
var str =
$"{tractor.Speed}{separatorForObject}{tractor.Weight}{separatorForObject}{tractor.BodyColor.Name}";
if (tractor is not EntityBulldozer bulldozer)
{
return str;
}
return
$"{str}{separatorForObject}{bulldozer.AdditionalColor.Name}{separatorForObject}" +
$"{bulldozer.ThirdWheel}{separatorForObject}{bulldozer.Otval}{separatorForObject}";
}
}
}

View File

@@ -1,207 +0,0 @@

namespace ProjectBulldozer
{
internal class DrawningBulldozer
{
public EntityBulldozer? EntityBulldozer { get; private set; }
private int _pictureWidth;
private int _pictureHeight;
private int _startPosX;
private int _startPosY;
private readonly int _BulldozerWidth = 180;
private readonly int _BulldozerHeight = 140;
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool additionalEngine, bool additionalCompartment, int width, int height)
{
if (_pictureWidth < _BulldozerWidth | _pictureHeight < _BulldozerHeight)
{
_pictureWidth = width;
_pictureHeight = height;
EntityBulldozer = new EntityBulldozer();
EntityBulldozer.Init(speed, weight, bodyColor, additionalColor,
additionalEngine, additionalCompartment);
return true;
}
else return false;
}
public void SetPosition(int x, int y)
{
if (_startPosY + _BulldozerHeight < _pictureHeight)
_startPosY = y;
else
_startPosY = _pictureHeight - _BulldozerHeight;
if (_startPosX + _BulldozerWidth < _pictureWidth)
_startPosX = x;
else
_startPosX = _pictureWidth - _BulldozerWidth;
}
public void MoveTransport(Direction direction)
{
if (EntityBulldozer == null)
{
return;
}
switch (direction)
{
//влево
case Direction.Left:
if (_startPosX - EntityBulldozer.Step > 0)
{
_startPosX -= (int)EntityBulldozer.Step;
}
else _startPosX = 0;
break;
//вверх
case Direction.Up:
if (_startPosY - EntityBulldozer.Step > 0)
{
_startPosY -= (int)EntityBulldozer.Step;
}
else _startPosY = 0;
break;
// вправо
case Direction.Right:
if (_startPosX + _BulldozerWidth + EntityBulldozer.Step < _pictureWidth)
{
_startPosX += (int)EntityBulldozer.Step;
}
else _startPosX = _pictureWidth - _BulldozerWidth;
break;
//вниз
case Direction.Down:
if (_startPosY + _BulldozerHeight + EntityBulldozer.Step < _pictureHeight)
{
_startPosY += (int)EntityBulldozer.Step;
}
else _startPosY = _pictureHeight - _BulldozerHeight;
break;
}
}
public void DrawTransport(Graphics g)
{
if (EntityBulldozer == null)
{
return;
}
Pen pen = new(Color.Black);
Brush brush = new SolidBrush(Color.Black);
Brush bl = new SolidBrush(EntityBulldozer.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityBulldozer.BodyColor);
Brush bodyBrush2 = new SolidBrush(EntityBulldozer.AdditionalColor);
//основное тело
g.FillRectangle(bodyBrush, _startPosX + 20, _startPosY + 40, 120, 60);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 40, 120, 60);
//Гусеницы
Brush gg = new SolidBrush(Color.LightGray);
g.FillEllipse(gg, _startPosX + 23, _startPosY + 101, 118, 35);
g.DrawEllipse(pen, _startPosX + 23, _startPosY + 101, 118, 35);
g.DrawEllipse(pen, _startPosX + 26, _startPosY + 103, 110, 30);
//катки в гусеницах
Brush gr = new SolidBrush(Color.Gray);
g.FillEllipse(gr, _startPosX + 40, _startPosY + 108, 20, 20);
g.DrawEllipse(pen, _startPosX + 40, _startPosY + 108, 20, 20);
g.FillEllipse(gr, _startPosX + 65, _startPosY + 110, 20, 20);
g.DrawEllipse(pen, _startPosX + 65, _startPosY + 110, 20, 20);
g.FillEllipse(gr, _startPosX + 115, _startPosY + 110, 15, 15);
g.DrawEllipse(pen, _startPosX + 115, _startPosY + 110, 15, 15);
g.FillEllipse(gr, _startPosX + 90, _startPosY + 110, 20, 20);
g.DrawEllipse(pen, _startPosX + 90, _startPosY + 110, 20, 20);
//кабина водителя
g.FillRectangle(bodyBrush2, _startPosX + 20, _startPosY, 40, 40);
g.DrawRectangle(pen, _startPosX + 20, _startPosY, 40, 40);
//выхлопная труба
Brush brBr = new SolidBrush(Color.Brown);
g.FillRectangle(brBr, _startPosX + 110, _startPosY, 15, 40);
g.DrawRectangle(pen, _startPosX + 110, _startPosY, 15, 40);
//Brush bl = new SolidBrush(Color.LightYellow);
/////////отвал
///
Point[] Otval =
{
new Point(_startPosX + 142, _startPosY + 70),
new Point(_startPosX + 172, _startPosY + 130),
new Point(_startPosX+ 142, _startPosY + 130),
};
g.FillPolygon(bl, Otval);
g.DrawPolygon(pen, Otval);
Brush black = new SolidBrush(Color.Black);
Point[] Rihl =
{
new Point(_startPosX + 18 , _startPosY + 60),
new Point(_startPosX + 18, _startPosY + 80),
new Point(_startPosX, _startPosY + 120),
};
g.FillPolygon(black, Rihl);
g.DrawPolygon(pen, Rihl);
Point[] Ttt =
{
new Point(_startPosX + 18 , _startPosY + 80),
new Point(_startPosX + 18, _startPosY + 120),
new Point(_startPosX, _startPosY + 50),
};
g.FillPolygon(black, Ttt);
g.DrawPolygon(pen, Ttt);
}
}
}

View File

@@ -0,0 +1,21 @@
namespace ProjectBulldozer.Entities
{
public class EntityBulldozer : EntityTractor
{
public Color AdditionalColor { get; private set; }
public bool Otval { get; private set; }
public bool ThirdWheel { get; private set; }
public EntityBulldozer(int speed, double weight, Color bodyColor, Color additionalColor,
bool otval, bool thirdWheel) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Otval = otval;
ThirdWheel = thirdWheel;
}
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@@ -0,0 +1,20 @@
namespace ProjectBulldozer.Entities
{
public class EntityTractor
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public double Step => (double)Speed * 100 / Weight;
public EntityTractor(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
public void setBodyColor(Color color)
{
BodyColor = color;
}
}
}

View File

@@ -1,43 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBulldozer
{
public class EntityBulldozer
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public Color AdditionalColor { get; private set; }
public bool AdditionalEngine { get; private set; }
public bool AdditionalCompartment { get; private set; }
public double Step => (double)Speed * 240 / Weight;
/// <summary>
/// Инициализация полей объекта-класса бульдозера
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес бульдозера</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalEngine">Признак наличия дополнительного катка</param>
/// <param name="additionalCompartment">Признак наличия гусениц</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool additionalEngine, bool additionalCompartment)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalEngine = additionalEngine;
AdditionalColor = additionalColor;
AdditionalCompartment = additionalCompartment;
}
}
}

View File

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

View File

@@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ProjectBulldozer.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

@@ -1,40 +1,21 @@
namespace ProjectBulldozer namespace Bulldozer
{ {
partial class FormBulldozer partial class FormBulldozer
{ {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null; 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() private void InitializeComponent()
{ {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBulldozer)); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBulldozer));
pictureBoxBulldozer = new PictureBox(); pictureBoxBulldozer = new PictureBox();
buttonCreate = new Button(); buttonCreateBulldozer = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonDown = new Button(); buttonDown = new Button();
comboBoxStrategy = new ComboBox();
buttonCreateTractor = new Button();
buttonStep = new Button();
ButtonSelect_Tractor = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBulldozer).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxBulldozer).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@@ -42,31 +23,34 @@
// //
pictureBoxBulldozer.Dock = DockStyle.Fill; pictureBoxBulldozer.Dock = DockStyle.Fill;
pictureBoxBulldozer.Location = new Point(0, 0); pictureBoxBulldozer.Location = new Point(0, 0);
pictureBoxBulldozer.Margin = new Padding(2);
pictureBoxBulldozer.Name = "pictureBoxBulldozer"; pictureBoxBulldozer.Name = "pictureBoxBulldozer";
pictureBoxBulldozer.Size = new Size(884, 461); pictureBoxBulldozer.Size = new Size(870, 572);
pictureBoxBulldozer.SizeMode = PictureBoxSizeMode.AutoSize; pictureBoxBulldozer.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxBulldozer.TabIndex = 0; pictureBoxBulldozer.TabIndex = 0;
pictureBoxBulldozer.TabStop = false; pictureBoxBulldozer.TabStop = false;
// //
// buttonCreate // buttonCreateBulldozer
// //
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateBulldozer.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 426); buttonCreateBulldozer.Location = new Point(20, 514);
buttonCreate.Name = "buttonCreate"; buttonCreateBulldozer.Margin = new Padding(2);
buttonCreate.Size = new Size(75, 23); buttonCreateBulldozer.Name = "buttonCreateBulldozer";
buttonCreate.TabIndex = 1; buttonCreateBulldozer.Size = new Size(88, 48);
buttonCreate.Text = "Создать"; buttonCreateBulldozer.TabIndex = 1;
buttonCreate.UseVisualStyleBackColor = true; buttonCreateBulldozer.Text = "Создать бульдозер";
buttonCreate.Click += buttonCreate_Click; buttonCreateBulldozer.UseVisualStyleBackColor = true;
buttonCreateBulldozer.Click += buttonCreateBulldozer_Click;
// //
// buttonLeft // buttonLeft
// //
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage"); buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom; buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(769, 419); buttonLeft.Location = new Point(732, 522);
buttonLeft.Margin = new Padding(2);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30); buttonLeft.Size = new Size(40, 33);
buttonLeft.TabIndex = 2; buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true; buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click; buttonLeft.Click += buttonMove_Click;
@@ -76,11 +60,11 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage"); buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage");
buttonUp.BackgroundImageLayout = ImageLayout.Zoom; buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(805, 383); buttonUp.Location = new Point(776, 485);
buttonUp.Margin = new Padding(2);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30); buttonUp.Size = new Size(40, 33);
buttonUp.TabIndex = 3; buttonUp.TabIndex = 3;
buttonUp.TextAlign = ContentAlignment.BottomRight;
buttonUp.UseVisualStyleBackColor = true; buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click; buttonUp.Click += buttonMove_Click;
// //
@@ -89,9 +73,10 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage"); buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage");
buttonRight.BackgroundImageLayout = ImageLayout.Zoom; buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(841, 419); buttonRight.Location = new Point(819, 522);
buttonRight.Margin = new Padding(2);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30); buttonRight.Size = new Size(40, 33);
buttonRight.TabIndex = 4; buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click; buttonRight.Click += buttonMove_Click;
@@ -101,38 +86,96 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage"); buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom; buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(805, 419); buttonDown.Location = new Point(776, 522);
buttonDown.Margin = new Padding(2);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30); buttonDown.Size = new Size(40, 33);
buttonDown.TabIndex = 5; buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click; buttonDown.Click += buttonMove_Click;
// //
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "В центр", "В угол" });
comboBoxStrategy.Location = new Point(740, 8);
comboBoxStrategy.Margin = new Padding(2);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(113, 23);
comboBoxStrategy.TabIndex = 6;
comboBoxStrategy.SelectedIndexChanged += comboBoxStrategy_SelectedIndexChanged;
//
// buttonCreateTractor
//
buttonCreateTractor.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTractor.Location = new Point(122, 514);
buttonCreateTractor.Margin = new Padding(2);
buttonCreateTractor.Name = "buttonCreateTractor";
buttonCreateTractor.Size = new Size(88, 48);
buttonCreateTractor.TabIndex = 7;
buttonCreateTractor.Text = "Создать трактор";
buttonCreateTractor.UseVisualStyleBackColor = true;
buttonCreateTractor.Click += buttonCreateTractor_Click;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(755, 39);
buttonStep.Margin = new Padding(2);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(88, 28);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// ButtonSelect_Tractor
//
ButtonSelect_Tractor.Anchor = AnchorStyles.Top | AnchorStyles.Right;
ButtonSelect_Tractor.Location = new Point(755, 71);
ButtonSelect_Tractor.Margin = new Padding(2);
ButtonSelect_Tractor.Name = "ButtonSelect_Tractor";
ButtonSelect_Tractor.Size = new Size(88, 28);
ButtonSelect_Tractor.TabIndex = 9;
ButtonSelect_Tractor.Text = "Выбрать";
ButtonSelect_Tractor.UseVisualStyleBackColor = true;
ButtonSelect_Tractor.Click += ButtonSelect_Tractor_Click;
//
// FormBulldozer // FormBulldozer
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461); ClientSize = new Size(870, 572);
Controls.Add(ButtonSelect_Tractor);
Controls.Add(buttonStep);
Controls.Add(buttonCreateTractor);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreate); Controls.Add(buttonCreateBulldozer);
Controls.Add(pictureBoxBulldozer); Controls.Add(pictureBoxBulldozer);
Margin = new Padding(2);
Name = "FormBulldozer"; Name = "FormBulldozer";
Text = "FormBulldozer"; StartPosition = FormStartPosition.CenterScreen;
Text = "Bulldozer";
((System.ComponentModel.ISupportInitialize)pictureBoxBulldozer).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxBulldozer).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
#endregion
private PictureBox pictureBoxBulldozer; private PictureBox pictureBoxBulldozer;
private Button buttonCreate; private Button buttonCreateBulldozer;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonRight; private Button buttonRight;
private Button buttonDown; private Button buttonDown;
private ComboBox comboBoxStrategy;
private Button buttonCreateTractor;
private Button buttonStep;
private Button ButtonSelect_Tractor;
private EventHandler comboBoxStrategy_SelectedIndexChanged;
} }
} }

View File

@@ -1,51 +1,69 @@
namespace ProjectBulldozer using ProjectBulldozer;
using ProjectBulldozer.Drawning;
using ProjectBulldozer.MovementStrategy;
namespace Bulldozer
{ {
public partial class FormBulldozer : Form public partial class FormBulldozer : Form
{ {
private DrawingTractor? _drawingTractor;
private DrawningBulldozer? _drawningBulldozer; private AbstractStrategy? _abstractStrategy;
public DrawingTractor? SelectedTractor { get; private set; }
public FormBulldozer() public FormBulldozer()
{ {
InitializeComponent(); InitializeComponent();
_abstractStrategy = null;
SelectedTractor = null;
} }
private void Draw() private void Draw()
{ {
if (_drawningBulldozer == null) if (_drawingTractor == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxBulldozer.Width, Bitmap bmp = new(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height);
pictureBoxBulldozer.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningBulldozer.DrawTransport(gr); _drawingTractor.DrawTransport(gr);
pictureBoxBulldozer.Image = bmp; pictureBoxBulldozer.Image = bmp;
} }
private void buttonCreateBulldozer_Click(object sender, EventArgs e)
private void buttonCreate_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new Random();
_drawningBulldozer = new DrawningBulldozer(); Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
_drawningBulldozer.Init(random.Next(100, 300),
random.Next(1000, 3000), ColorDialog colorDialog = new ColorDialog();
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)), if (colorDialog.ShowDialog() == DialogResult.OK)
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), {
random.Next(0, 256)), color = colorDialog.Color;
Convert.ToBoolean(random.Next(0, 2)), }
Convert.ToBoolean(random.Next(0, 2)), Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
if (colorDialog.ShowDialog() == DialogResult.OK)
{
dopColor = colorDialog.Color;
}
_drawingTractor = new DrawingBulldozer(random.Next(100, 300), random.Next(1000, 3000), color, dopColor,
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxBulldozer.Width, pictureBoxBulldozer.Height); pictureBoxBulldozer.Width, pictureBoxBulldozer.Height);
_drawningBulldozer.SetPosition(random.Next(10, 100), _drawingTractor.SetPosition(random.Next(10, 100), random.Next(10, 100));
random.Next(10, 100)); Draw();
}
private void buttonCreateTractor_Click(object sender, EventArgs e)
{
Random rnd = new Random();
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog colorDialog = new ColorDialog();
if (colorDialog.ShowDialog() == DialogResult.OK)
{
color = colorDialog.Color;
}
_drawingTractor = new DrawingTractor(rnd.Next(100, 300), rnd.Next(1000, 3000), color,
pictureBoxBulldozer.Width, pictureBoxBulldozer.Height);
_drawingTractor.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100));
Draw(); Draw();
} }
private void buttonMove_Click(object sender, EventArgs e) private void buttonMove_Click(object sender, EventArgs e)
{ {
if (_drawningBulldozer == null) if (_drawingTractor == null)
{ {
return; return;
} }
@@ -53,20 +71,58 @@ namespace ProjectBulldozer
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
_drawningBulldozer.MoveTransport(Direction.Up); _drawingTractor.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
_drawningBulldozer.MoveTransport(Direction.Down); _drawingTractor.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
_drawningBulldozer.MoveTransport(Direction.Left); _drawingTractor.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
_drawningBulldozer.MoveTransport(Direction.Right); _drawingTractor.MoveTransport(DirectionType.Right);
break; break;
} }
Draw(); Draw();
} }
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingTractor == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToRightCorner(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(_drawingTractor.GetMoveableObject, pictureBoxBulldozer.Width,
pictureBoxBulldozer.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void ButtonSelect_Tractor_Click(object sender, EventArgs e)
{
SelectedTractor = _drawingTractor;
DialogResult = DialogResult.OK;
}
} }
} }

View File

@@ -0,0 +1,297 @@
using System.ComponentModel;
namespace ProjectBulldozer
{
partial class FormTractorCollections
{
private System.ComponentModel.IContainer components = null;
private void InitializeComponent()
{
maskedTextBoxNumber = new MaskedTextBox();
ButtonRefreshCollection = new Button();
ButtonRemoveTractor = new Button();
ButtonAddTractor = new Button();
pictureBoxCollections = new PictureBox();
textBoxStorageName = new TextBox();
groupBox1 = new GroupBox();
listBoxStorage = new ListBox();
ButtonAddObject = new Button();
ButtonRemoveObject = new Button();
Instruments = new GroupBox();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
сохранитьToolStripMenuItem = new ToolStripMenuItem();
загрузитьToolStripMenuItem = new ToolStripMenuItem();
toolStripMenuItem1 = new ToolStripMenuItem();
ButtonSortByType = new Button();
ButtonSortByColor = new Button();
((ISupportInitialize)pictureBoxCollections).BeginInit();
groupBox1.SuspendLayout();
Instruments.SuspendLayout();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxNumber.Location = new Point(35, 379);
maskedTextBoxNumber.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(132, 23);
maskedTextBoxNumber.TabIndex = 4;
//
// ButtonRefreshCollection
//
ButtonRefreshCollection.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
ButtonRefreshCollection.Location = new Point(33, 441);
ButtonRefreshCollection.Margin = new Padding(3, 2, 3, 2);
ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(131, 31);
ButtonRefreshCollection.TabIndex = 2;
ButtonRefreshCollection.Text = "Обновить все";
ButtonRefreshCollection.UseVisualStyleBackColor = true;
ButtonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// ButtonRemoveTractor
//
ButtonRemoveTractor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
ButtonRemoveTractor.Location = new Point(35, 406);
ButtonRemoveTractor.Margin = new Padding(3, 2, 3, 2);
ButtonRemoveTractor.Name = "ButtonRemoveTractor";
ButtonRemoveTractor.Size = new Size(131, 31);
ButtonRemoveTractor.TabIndex = 1;
ButtonRemoveTractor.Text = "Удалить объект";
ButtonRemoveTractor.UseVisualStyleBackColor = true;
ButtonRemoveTractor.Click += ButtonRemoveTractor_Click;
//
// ButtonAddTractor
//
ButtonAddTractor.Anchor = AnchorStyles.Top;
ButtonAddTractor.Location = new Point(35, 337);
ButtonAddTractor.Margin = new Padding(3, 2, 3, 2);
ButtonAddTractor.Name = "ButtonAddTractor";
ButtonAddTractor.Size = new Size(131, 29);
ButtonAddTractor.TabIndex = 0;
ButtonAddTractor.Text = "Добавить объект";
ButtonAddTractor.UseVisualStyleBackColor = true;
ButtonAddTractor.Click += ButtonAddTractor_Click;
//
// pictureBoxCollections
//
pictureBoxCollections.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
pictureBoxCollections.Location = new Point(0, 26);
pictureBoxCollections.Margin = new Padding(3, 2, 3, 2);
pictureBoxCollections.Name = "pictureBoxCollections";
pictureBoxCollections.Size = new Size(697, 474);
pictureBoxCollections.TabIndex = 1;
pictureBoxCollections.TabStop = false;
pictureBoxCollections.Click += pictureBoxCollections_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(27, 22);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(131, 23);
textBoxStorageName.TabIndex = 5;
//
// groupBox1
//
groupBox1.Controls.Add(listBoxStorage);
groupBox1.Controls.Add(ButtonAddObject);
groupBox1.Controls.Add(ButtonRemoveObject);
groupBox1.Controls.Add(textBoxStorageName);
groupBox1.Location = new Point(6, 22);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(189, 219);
groupBox1.TabIndex = 5;
groupBox1.TabStop = false;
groupBox1.Text = "Наборы";
//
// listBoxStorage
//
listBoxStorage.FormattingEnabled = true;
listBoxStorage.ItemHeight = 15;
listBoxStorage.Location = new Point(27, 84);
listBoxStorage.Name = "listBoxStorage";
listBoxStorage.Size = new Size(131, 94);
listBoxStorage.TabIndex = 9;
listBoxStorage.SelectedIndexChanged += listBoxStorage_SelectedIndexChanged;
//
// ButtonAddObject
//
ButtonAddObject.Anchor = AnchorStyles.Top;
ButtonAddObject.Location = new Point(27, 50);
ButtonAddObject.Margin = new Padding(3, 2, 3, 2);
ButtonAddObject.Name = "ButtonAddObject";
ButtonAddObject.Size = new Size(131, 29);
ButtonAddObject.TabIndex = 7;
ButtonAddObject.Text = "Добавить набор";
ButtonAddObject.UseVisualStyleBackColor = true;
ButtonAddObject.Click += ButtonAddObject_Click;
//
// ButtonRemoveObject
//
ButtonRemoveObject.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
ButtonRemoveObject.Location = new Point(27, 181);
ButtonRemoveObject.Margin = new Padding(3, 2, 3, 2);
ButtonRemoveObject.Name = "ButtonRemoveObject";
ButtonRemoveObject.Size = new Size(131, 33);
ButtonRemoveObject.TabIndex = 8;
ButtonRemoveObject.Text = "Удалить набор";
ButtonRemoveObject.UseVisualStyleBackColor = true;
ButtonRemoveObject.Click += ButtonRemoveObject_Click;
//
// Instruments
//
Instruments.Controls.Add(ButtonSortByColor);
Instruments.Controls.Add(ButtonSortByType);
Instruments.Controls.Add(ButtonRefreshCollection);
Instruments.Controls.Add(groupBox1);
Instruments.Controls.Add(maskedTextBoxNumber);
Instruments.Controls.Add(ButtonAddTractor);
Instruments.Controls.Add(ButtonRemoveTractor);
Instruments.Location = new Point(703, 26);
Instruments.Name = "Instruments";
Instruments.Size = new Size(201, 464);
Instruments.TabIndex = 6;
Instruments.TabStop = false;
Instruments.Text = "Инструменты";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
openFileDialog.FileOk += openFileDialog_FileOk;
//
// saveFileDialog
//
saveFileDialog.FileName = "saveFileDialog";
saveFileDialog.Filter = "txt file | *.txt";
saveFileDialog.FileOk += saveFileDialog_FileOk;
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(5, 2, 0, 2);
menuStrip1.RenderMode = ToolStripRenderMode.System;
menuStrip1.Size = new Size(904, 24);
menuStrip1.TabIndex = 6;
menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { сохранитьToolStripMenuItem, загрузитьToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(50, 20);
файлToolStripMenuItem.Text = "Файл";
файлToolStripMenuItem.Click += файлToolStripMenuItem_Click;
//
// сохранитьToolStripMenuItem
//
сохранитьToolStripMenuItem.Name = "сохранитьToolStripMenuItem";
сохранитьToolStripMenuItem.Size = new Size(135, 22);
сохранитьToolStripMenuItem.Text = "Сохранить";
сохранитьToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// загрузитьToolStripMenuItem
//
загрузитьToolStripMenuItem.Name = агрузитьToolStripMenuItem";
загрузитьToolStripMenuItem.Size = new Size(135, 22);
загрузитьToolStripMenuItem.Text = "Загрузить";
загрузитьToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// toolStripMenuItem1
//
toolStripMenuItem1.Name = "toolStripMenuItem1";
toolStripMenuItem1.Size = new Size(32, 19);
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(33, 247);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(131, 41);
ButtonSortByType.TabIndex = 7;
ButtonSortByType.Text = "Сортировать по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(33, 294);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(131, 38);
ButtonSortByColor.TabIndex = 8;
ButtonSortByColor.Text = "Сортировать по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// FormTractorCollections
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(904, 509);
Controls.Add(Instruments);
Controls.Add(pictureBoxCollections);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Margin = new Padding(3, 2, 3, 2);
Name = "FormTractorCollections";
Text = "Набор объектов";
((ISupportInitialize)pictureBoxCollections).EndInit();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
Instruments.ResumeLayout(false);
Instruments.PerformLayout();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
private void файлToolStripMenuItem_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
{
throw new NotImplementedException();
}
private void openFileDialog_FileOk(object sender, CancelEventArgs e)
{
throw new NotImplementedException();
}
private void pictureBoxCollections_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private Button ButtonRefreshCollection;
private Button ButtonRemoveTractor;
private Button ButtonAddTractor;
private PictureBox pictureBoxCollections;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBox1;
private TextBox textBoxStorageName;
private ListBox listBoxStorage;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonAddObject;
private Button ButtonRemoveObject;
private GroupBox Instruments;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранитьToolStripMenuItem;
private ToolStripMenuItem загрузитьToolStripMenuItem;
private ToolStripMenuItem toolStripMenuItem1;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@@ -0,0 +1,234 @@
using Bulldozer;
using ProjectBulldozer.Generics;
using ProjectBulldozer.Drawning;
using ProjectBulldozer.Exceptions;
using Microsoft.Extensions.Logging;
namespace ProjectBulldozer
{
public partial class FormTractorCollections : Form
{
private readonly TractorGenericStorage _storage;
private readonly ILogger _logger;
readonly int countPlace = 12;
public FormTractorCollections()
{
InitializeComponent();
_storage = new TractorGenericStorage(pictureBoxCollections.Width, pictureBoxCollections.Height);
}
public FormTractorCollections(ILogger<FormTractorCollections> logger)
{
InitializeComponent();
_storage = new TractorGenericStorage(pictureBoxCollections.Width, pictureBoxCollections.Height);
_logger = logger;
}
private void ReloadObjects()
{
int index = listBoxStorage.SelectedIndex;
listBoxStorage.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorage.Items.Add(_storage.Keys[i]);
}
if (listBoxStorage.Items.Count > 0 && (index == -1 || index >= listBoxStorage.Items.Count))
{
listBoxStorage.SelectedIndex = 0;
}
else if (listBoxStorage.Items.Count > 0 && index > -1 && index < listBoxStorage.Items.Count)
{
listBoxStorage.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"!!Ошибка!! Не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollections.Image = _storage[listBoxStorage.SelectedItem?.ToString() ?? string.Empty]?.ShowTractors();
}
private void ButtonRemoveObject_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1)
{
_logger.LogWarning($"Удаление не выбранного набора");
return;
}
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
private void ButtonAddTractor_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
var formBulldozerConfig = new FormBulldozerConfig();
formBulldozerConfig.AddEvent(AddTractor);
formBulldozerConfig.Show();
}
private void AddTractor(DrawingTractor tractor)
{
tractor._pictureWidth = pictureBoxCollections.Width;
tractor._pictureHeight = pictureBoxCollections.Height;
if (listBoxStorage.SelectedIndex == -1) return;
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (obj == null)
{
return;
}
try
{
int addedIndex = obj + tractor;
if (addedIndex != -1 && addedIndex < countPlace)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollections.Image = obj.ShowTractors();
_logger.LogInformation($"В набор {name} добавлен объект");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message}. Не удалось добавить объект");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message}. Не удалось добавить объект");
}
}
private void ButtonRemoveTractor_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1) return;
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
if (maskedTextBoxNumber.Text == "") { return; }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollections.Image = obj.ShowTractors();
_logger.LogInformation($"Из набора {name} удален объект");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Не удалось удалить объект");
}
}
catch (BulldozerNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message}. Не удалось удалить объект");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1) return;
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollections.Image = obj.ShowTractors();
}
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("Сохранение");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка сохранения");
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка произошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка загрузки");
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareTractors(new TractorCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareTractors(new TractorCompareByColor());
private void CompareTractors(IComparer<DrawingTractor?> comparer)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollections.Image = obj.ShowTractors();
}
}
}

View File

@@ -0,0 +1,132 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>286, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@@ -0,0 +1,412 @@
namespace Bulldozer
{
partial class FormBulldozerConfig
{
private System.ComponentModel.IContainer components = null;
private void InitializeComponent()
{
groupBox1 = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
GroupColor = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxKovsh = new CheckBox();
checkBoxThirdWheel = new CheckBox();
label2 = new Label();
label1 = new Label();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
ButtonOk = new Button();
ButtonCancel = new Button();
label_body_color = new Label();
label_additional_color = new Label();
pictureBoxObject = new PictureBox();
label4 = new Label();
PanelObject = new Panel();
groupBox1.SuspendLayout();
GroupColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
PanelObject.SuspendLayout();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(labelModifiedObject);
groupBox1.Controls.Add(labelSimpleObject);
groupBox1.Controls.Add(GroupColor);
groupBox1.Controls.Add(checkBoxKovsh);
groupBox1.Controls.Add(checkBoxThirdWheel);
groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(label1);
groupBox1.Controls.Add(numericUpDownWeight);
groupBox1.Controls.Add(numericUpDownSpeed);
groupBox1.ForeColor = SystemColors.ControlLightLight;
groupBox1.Location = new Point(10, 9);
groupBox1.Margin = new Padding(3, 2, 3, 2);
groupBox1.Name = "groupBox1";
groupBox1.Padding = new Padding(3, 2, 3, 2);
groupBox1.Size = new Size(542, 405);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Параметры";
groupBox1.Enter += groupBox1_Enter;
//
// labelModifiedObject
//
labelModifiedObject.AllowDrop = true;
labelModifiedObject.BackColor = SystemColors.Info;
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.ForeColor = SystemColors.ControlText;
labelModifiedObject.Location = new Point(377, 170);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(132, 53);
labelModifiedObject.TabIndex = 9;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.AllowDrop = true;
labelSimpleObject.BackColor = SystemColors.Info;
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.ForeColor = SystemColors.ControlText;
labelSimpleObject.Location = new Point(225, 170);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(132, 53);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// GroupColor
//
GroupColor.Controls.Add(panelPurple);
GroupColor.Controls.Add(panelYellow);
GroupColor.Controls.Add(panelBlack);
GroupColor.Controls.Add(panelBlue);
GroupColor.Controls.Add(panelGray);
GroupColor.Controls.Add(panelGreen);
GroupColor.Controls.Add(panelWhite);
GroupColor.Controls.Add(panelRed);
GroupColor.ForeColor = SystemColors.ControlLightLight;
GroupColor.Location = new Point(225, 20);
GroupColor.Margin = new Padding(3, 2, 3, 2);
GroupColor.Name = "GroupColor";
GroupColor.Padding = new Padding(3, 2, 3, 2);
GroupColor.Size = new Size(302, 131);
GroupColor.TabIndex = 6;
GroupColor.TabStop = false;
GroupColor.Text = "Цвета";
GroupColor.Enter += GroupColor_Enter;
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(226, 76);
panelPurple.Margin = new Padding(3, 2, 3, 2);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(68, 41);
panelPurple.TabIndex = 3;
panelPurple.Paint += panelPurple_Paint;
panelPurple.MouseDown += PanelColor_MouseDown;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(226, 24);
panelYellow.Margin = new Padding(3, 2, 3, 2);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(68, 41);
panelYellow.TabIndex = 1;
panelYellow.Paint += panelYellow_Paint;
panelYellow.MouseDown += PanelColor_MouseDown;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(152, 76);
panelBlack.Margin = new Padding(3, 2, 3, 2);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(68, 41);
panelBlack.TabIndex = 4;
panelBlack.MouseDown += PanelColor_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(152, 24);
panelBlue.Margin = new Padding(3, 2, 3, 2);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(68, 41);
panelBlue.TabIndex = 1;
panelBlue.Paint += panelBlue_Paint;
panelBlue.MouseDown += PanelColor_MouseDown;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(79, 76);
panelGray.Margin = new Padding(3, 2, 3, 2);
panelGray.Name = "panelGray";
panelGray.Size = new Size(68, 41);
panelGray.TabIndex = 5;
panelGray.MouseDown += PanelColor_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.Lime;
panelGreen.Location = new Point(79, 24);
panelGreen.Margin = new Padding(3, 2, 3, 2);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(68, 41);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += PanelColor_MouseDown;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(5, 76);
panelWhite.Margin = new Padding(3, 2, 3, 2);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(68, 41);
panelWhite.TabIndex = 2;
panelWhite.MouseDown += PanelColor_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(5, 24);
panelRed.Margin = new Padding(3, 2, 3, 2);
panelRed.Name = "panelRed";
panelRed.Size = new Size(68, 41);
panelRed.TabIndex = 0;
panelRed.MouseDown += PanelColor_MouseDown;
//
// checkBoxKovsh
//
checkBoxKovsh.AutoSize = true;
checkBoxKovsh.ForeColor = SystemColors.ControlLightLight;
checkBoxKovsh.Location = new Point(18, 132);
checkBoxKovsh.Margin = new Padding(3, 2, 3, 2);
checkBoxKovsh.Name = "checkBoxKovsh";
checkBoxKovsh.Size = new Size(182, 19);
checkBoxKovsh.TabIndex = 5;
checkBoxKovsh.Text = "Третье колесо в гусеницах";
checkBoxKovsh.UseVisualStyleBackColor = true;
checkBoxKovsh.CheckedChanged += GroupColor_Enter;
//
// checkBoxThirdWheel
//
checkBoxThirdWheel.AutoSize = true;
checkBoxThirdWheel.ForeColor = SystemColors.ControlLightLight;
checkBoxThirdWheel.Location = new Point(18, 106);
checkBoxThirdWheel.Margin = new Padding(3, 2, 3, 2);
checkBoxThirdWheel.Name = "checkBoxThirdWheel";
checkBoxThirdWheel.Size = new Size(60, 19);
checkBoxThirdWheel.TabIndex = 4;
checkBoxThirdWheel.Text = "Отвал";
checkBoxThirdWheel.UseVisualStyleBackColor = true;
checkBoxThirdWheel.CheckedChanged += checkBoxOtval_CheckedChanged;
//
// label2
//
label2.AutoSize = true;
label2.ForeColor = SystemColors.ControlLightLight;
label2.Location = new Point(5, 70);
label2.Name = "label2";
label2.Size = new Size(31, 15);
label2.TabIndex = 3;
label2.Text = "Вес:";
//
// label1
//
label1.AutoSize = true;
label1.ForeColor = SystemColors.ControlLightLight;
label1.Location = new Point(5, 38);
label1.Name = "label1";
label1.Size = new Size(63, 15);
label1.TabIndex = 2;
label1.Text = "Скорость:";
//
// numericUpDownWeight
//
numericUpDownWeight.BackColor = SystemColors.Info;
numericUpDownWeight.Location = new Point(88, 68);
numericUpDownWeight.Margin = new Padding(3, 2, 3, 2);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(131, 23);
numericUpDownWeight.TabIndex = 1;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.BackColor = SystemColors.Info;
numericUpDownSpeed.Location = new Point(88, 36);
numericUpDownSpeed.Margin = new Padding(3, 2, 3, 2);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(131, 23);
numericUpDownSpeed.TabIndex = 0;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// ButtonOk
//
ButtonOk.BackColor = SystemColors.Info;
ButtonOk.ForeColor = SystemColors.ControlText;
ButtonOk.Location = new Point(27, 345);
ButtonOk.Margin = new Padding(3, 2, 3, 2);
ButtonOk.Name = "ButtonOk";
ButtonOk.Size = new Size(93, 44);
ButtonOk.TabIndex = 12;
ButtonOk.Text = "Добавить";
ButtonOk.UseVisualStyleBackColor = false;
ButtonOk.Click += ButtonOk_Click;
//
// ButtonCancel
//
ButtonCancel.BackColor = SystemColors.Info;
ButtonCancel.ForeColor = SystemColors.ControlText;
ButtonCancel.Location = new Point(203, 345);
ButtonCancel.Margin = new Padding(3, 2, 3, 2);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(93, 44);
ButtonCancel.TabIndex = 13;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = false;
ButtonCancel.Click += ButtonCancel_Click;
//
// label_body_color
//
label_body_color.AllowDrop = true;
label_body_color.BackColor = SystemColors.Info;
label_body_color.BorderStyle = BorderStyle.FixedSingle;
label_body_color.ForeColor = SystemColors.ControlText;
label_body_color.Location = new Point(27, 7);
label_body_color.Name = "label_body_color";
label_body_color.Size = new Size(93, 42);
label_body_color.TabIndex = 10;
label_body_color.Text = "Осн. цвет";
label_body_color.TextAlign = ContentAlignment.MiddleCenter;
label_body_color.DragDrop += PanelColor_DragDrop;
label_body_color.DragEnter += PanelColor_DragEnter;
//
// label_additional_color
//
label_additional_color.AllowDrop = true;
label_additional_color.BackColor = SystemColors.Info;
label_additional_color.BorderStyle = BorderStyle.FixedSingle;
label_additional_color.ForeColor = SystemColors.ControlText;
label_additional_color.Location = new Point(207, 7);
label_additional_color.Name = "label_additional_color";
label_additional_color.Size = new Size(89, 42);
label_additional_color.TabIndex = 10;
label_additional_color.Text = "Доп. цвет";
label_additional_color.TextAlign = ContentAlignment.MiddleCenter;
label_additional_color.DragDrop += PanelColor_DragDrop;
label_additional_color.DragEnter += PanelColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(27, 53);
pictureBoxObject.Margin = new Padding(3, 2, 3, 2);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(306, 288);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
pictureBoxObject.Click += pictureBoxObject_Click;
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(449, 278);
label4.Name = "label4";
label4.Size = new Size(0, 15);
label4.TabIndex = 2;
//
// PanelObject
//
PanelObject.AllowDrop = true;
PanelObject.Controls.Add(ButtonCancel);
PanelObject.Controls.Add(ButtonOk);
PanelObject.Controls.Add(pictureBoxObject);
PanelObject.Controls.Add(label_body_color);
PanelObject.Controls.Add(label_additional_color);
PanelObject.Location = new Point(558, 19);
PanelObject.Margin = new Padding(3, 2, 3, 2);
PanelObject.Name = "PanelObject";
PanelObject.Size = new Size(347, 395);
PanelObject.TabIndex = 15;
PanelObject.DragDrop += PanelObject_DragDrop;
PanelObject.DragEnter += PanelObject_DragEnter;
//
// FormBulldozerConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = SystemColors.WindowFrame;
ClientSize = new Size(917, 419);
Controls.Add(PanelObject);
Controls.Add(label4);
Controls.Add(groupBox1);
Margin = new Padding(3, 2, 3, 2);
Name = "FormBulldozerConfig";
Text = "FormBulldozerlConfig";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
GroupColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
PanelObject.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
private GroupBox groupBox1;
private Label label2;
private Label label1;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private GroupBox GroupColor;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private CheckBox checkBoxKovsh;
private CheckBox checkBoxThirdWheel;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private PictureBox pictureBoxObject;
private Label label4;
private Button ButtonOk;
private Button ButtonCancel;
private Panel PanelObject;
private Label label_body_color;
private Label label_additional_color;
private EventHandler groupBox1_Enter;
private PaintEventHandler panelPurple_Paint;
private PaintEventHandler panelYellow_Paint;
private PaintEventHandler panelBlue_Paint;
private EventHandler checkBoxOtval_CheckedChanged;
private EventHandler pictureBoxObject_Click;
public EventHandler GroupColor_Enter { get; private set; }
public EventHandler ButtonCancel_Click { get; private set; }
}
}

View File

@@ -0,0 +1,119 @@
using ProjectBulldozer.Drawning;
using ProjectBulldozer.Entities;
namespace Bulldozer
{
public partial class FormBulldozerConfig : Form
{
DrawingTractor? _tractor = null;
public event Action<DrawingTractor>? EventAddTractor;
public FormBulldozerConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
ButtonCancel.Click += (s, e) => Close();
}
private void DrawTractor()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_tractor?.SetPosition(pictureBoxObject.Width / 10, pictureBoxObject.Height / 10);
_tractor?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Copy | DragDropEffects.Move);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_tractor = new DrawingTractor((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_tractor = new DrawingBulldozer((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxThirdWheel.Checked,
checkBoxKovsh.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawTractor();
}
private void PanelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelColor_DragDrop(object sender, DragEventArgs e)
{
if (_tractor == null)
{
return;
}
switch (((Label)sender).Name)
{
case "label_body_color":
_tractor?.EntityTractor?.setBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "label_additional_color":
if (!(_tractor is DrawingBulldozer))
{
return;
}
(_tractor.EntityTractor as EntityBulldozer)?
.setAdditionalColor(color: (Color)e.Data.GetData(typeof(Color)));
break;
}
DrawTractor();
}
public void AddEvent(Action<DrawingTractor> ev)
{
if (EventAddTractor == null)
{
EventAddTractor = ev;
}
else
{
EventAddTractor += ev;
}
}
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddTractor?.Invoke(obj: _tractor);
Close();
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,89 @@
using ProjectBulldozer.Drawning;
using ProjectBulldozer.MovementStrategy;
namespace ProjectBulldozer.Generics
{
internal class TractorGenericCollection<T, U> where T : DrawingTractor where U : IMoveableObject
{
//ширина/высота окна
private readonly int _pictureWidth;
private readonly int _pictureHeight;
//ширина/высота занимаемого места
private readonly int _placeSizeWidth = 150;
private readonly int _placeSizeHeight = 130;
private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetTractors => _collection.GetTractors();
public TractorGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static int operator +(TractorGenericCollection<T, U> collect, T? tractor)
{
if (tractor == null) return -1;
return collect?._collection.Insert(tractor, new DrawingBulldozerEqutables())??-1;
}
public static T? operator -(TractorGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
public Bitmap ShowTractors()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
//линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 3, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void DrawObjects(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
{
// Получение объекта
var obj = _collection[i];
// Установка позиции
obj?.SetPosition(
(int)((width - 1) * _placeSizeWidth - (i % width * _placeSizeWidth)),
(int)((height - 1) * _placeSizeHeight - (i / width * _placeSizeHeight))
);
// Прорисовка объекта
obj?.DrawTransport(g);
}
}
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
}
}

View File

@@ -0,0 +1,55 @@
using System.Diagnostics.CodeAnalysis;
using ProjectBulldozer.Drawning;
using ProjectBulldozer.Entities;
namespace ProjectBulldozer.Generics
{
internal class DrawingBulldozerEqutables : IEqualityComparer<DrawingTractor?>
{
public bool Equals(DrawingTractor? x, DrawingTractor? y)
{
if (x == null || x.EntityTractor == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTractor == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTractor.Speed != y.EntityTractor.Speed)
{
return false;
}
if (x.EntityTractor.Weight != y.EntityTractor.Weight)
{
return false;
}
if (x.EntityTractor.BodyColor != y.EntityTractor.BodyColor)
{
return false;
}
if (x is DrawingBulldozer && y is DrawingBulldozer)
{
if ((x.EntityTractor as EntityBulldozer).Otval != (y.EntityTractor as EntityBulldozer).Otval)
{
return false;
}
if ((x.EntityTractor as EntityBulldozer).ThirdWheel != (y.EntityTractor as EntityBulldozer).ThirdWheel)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingTractor obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -0,0 +1,86 @@
using ProjectBulldozer.Exceptions;
namespace ProjectBulldozer.Generics
{
internal class SetGeneric<T> where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
/// Максимальное количество объектов в списке
private readonly int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// Добавление объекта в набор
public int Insert(T tractor, IEqualityComparer<T?>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(tractor, 0, equal);
return 0;
}
public bool Insert(T tractor, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
{
throw new BulldozerNotFoundException(position);
}
if (Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (equal != null)
{
foreach (var i in _places)
{
if (equal.Equals(i, tractor))
{
throw new ApplicationException($"Объект уже существует");
}
}
}
_places.Insert(position, tractor);
return true;
}
public bool Remove(int position)
{
if (position < 0 || position >= _maxCount)
{
return false;
}
if (_places[position] == null)
{
throw new BulldozerNotFoundException(position);
}
_places[position] = null;
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position >= Count) return null;
return _places[position];
}
set
{
if (position < 0 || position >= Count || Count == _maxCount) return;
_places.Insert(position, value);
}
}
public IEnumerable<T?> GetTractors(int? maxTracts = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxTracts.HasValue && i == maxTracts.Value)
{
yield break;
}
}
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
}
}

View File

@@ -0,0 +1,9 @@
namespace ProjectBulldozer.MovementStrategy
{
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@@ -0,0 +1,38 @@
using ProjectBulldozer.Drawning;
using ProjectBulldozer.Entities;
namespace ProjectBulldozer.Generics
{
internal class TractorCompareByColor : IComparer<DrawingTractor?>
{
public int Compare(DrawingTractor? x, DrawingTractor? y)
{
if (x == null || x.EntityTractor == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTractor == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityTractor.BodyColor != y.EntityTractor.BodyColor)
{
return x.EntityTractor.BodyColor.Name.CompareTo(y.EntityTractor.BodyColor.Name);
}
if (x.EntityTractor is EntityBulldozer _BulldozerX && y.EntityTractor is EntityBulldozer _BulldozertY)
{
var ElementsColorCompare = _BulldozerX.AdditionalColor.Name.CompareTo(_BulldozertY.AdditionalColor.Name);
if (ElementsColorCompare != 0)
{
return ElementsColorCompare;
}
}
var speedCompare = x.EntityTractor.Speed.CompareTo(y.EntityTractor.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTractor.Weight.CompareTo(y.EntityTractor.Weight);
}
}
}

View File

@@ -0,0 +1,29 @@
using ProjectBulldozer.Drawning;
namespace ProjectBulldozer.Generics
{
internal class TractorCompareByType : IComparer<DrawingTractor?>
{
public int Compare(DrawingTractor? x, DrawingTractor? y)
{
if (x == null || x.EntityTractor == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityTractor == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTractor.Speed.CompareTo(y.EntityTractor.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTractor.Weight.CompareTo(y.EntityTractor.Weight);
}
}
}

View File

@@ -0,0 +1,123 @@
using ProjectBulldozer.Drawing;
using ProjectBulldozer.Drawning;
using System.Text;
namespace ProjectBulldozer.Generics
{
internal class TractorGenericStorage
{
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
readonly Dictionary<TractorsCollectionInfo, TractorGenericCollection<DrawingTractor, DrawingObjectTractor>> _TractorsStorage;
public List<TractorsCollectionInfo> Keys => _TractorsStorage.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
public TractorGenericStorage(int pictureWidth, int pictureHeight)
{
_TractorsStorage = new Dictionary<TractorsCollectionInfo, TractorGenericCollection<DrawingTractor, DrawingObjectTractor>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
if (!_TractorsStorage.ContainsKey(new TractorsCollectionInfo(name, "")))
{
_TractorsStorage.Add(new TractorsCollectionInfo(name, ""), new TractorGenericCollection<DrawingTractor, DrawingObjectTractor>(_pictureWidth, _pictureHeight));
}
}
public void DelSet(string name)
{
if (_TractorsStorage.ContainsKey(new TractorsCollectionInfo(name, "")))
{
_TractorsStorage.Remove(new TractorsCollectionInfo(name, ""));
}
}
public TractorGenericCollection<DrawingTractor, DrawingObjectTractor>? this[string ind]
{
get
{
var info = new TractorsCollectionInfo(ind, "");
if (_TractorsStorage.ContainsKey(info)) return _TractorsStorage[info];
return null;
}
}
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<TractorsCollectionInfo, TractorGenericCollection<DrawingTractor, DrawingObjectTractor>> record in _TractorsStorage)
{
StringBuilder records = new();
foreach (DrawingTractor? elem in record.Value.GetTractors)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
}
using StreamWriter sw = new(filename);
sw.Write($"TractorsStorage{Environment.NewLine}{data}");
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = File.OpenText(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith("TractorsStorage"))
{
throw new FormatException("Неверный формат данных");
}
_TractorsStorage.Clear();
string strs = "";
while ((strs = sr.ReadLine()) != null)
{
if (strs == null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
TractorGenericCollection<DrawingTractor, DrawingObjectTractor> collection =
new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingTractor? tractor = elem?.CreateDrawingTractor(_separatorForObject,
_pictureWidth, _pictureHeight);
if (tractor != null)
{
if ((collection + tractor)==-1)
{
throw new ApplicationException("Ошибка добавления в коллекцию");
}
}
}
_TractorsStorage.Add(new TractorsCollectionInfo(record[0], string.Empty), collection);
}
return true;
}
}
}
}

View File

@@ -0,0 +1,29 @@
namespace ProjectBulldozer.Generics
{
internal class TractorsCollectionInfo : IEquatable<TractorsCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public TractorsCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(TractorsCollectionInfo? other)
{
return Name == other.Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override string ToString()
{
return Name;
}
}
}

View File

@@ -0,0 +1,67 @@
namespace ProjectBulldozer.MovementStrategy
{
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private Status _state = Status.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public Status GetStatus() { return _state; }
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(DirectionType.Left);
protected bool MoveRight() => MoveTo(DirectionType.Right);
protected bool MoveUp() => MoveTo(DirectionType.Up);
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// Параметры объекта
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestinaion();
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,27 @@
using ProjectBulldozer.MovementStrategy;
namespace ProjectBulldozer.Drawning
{
public class DrawingObjectTractor : IMoveableObject
{
private readonly DrawingTractor? _drawningTractor = null;
public DrawingObjectTractor(DrawingTractor drawningTractor)
{
_drawningTractor = drawningTractor;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningTractor == null || _drawningTractor.EntityTractor == null)
{
return null;
}
return new ObjectParameters(_drawningTractor.GetPosX,
_drawningTractor.GetPosY, _drawningTractor.GetWidth, _drawningTractor.GetHeight);
}
}
public int GetStep => (int)(_drawningTractor?.EntityTractor?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawningTractor?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawningTractor?.MoveTransport(direction);
}
}

View File

@@ -0,0 +1,11 @@
using Bulldozer;
namespace ProjectBulldozer.MovementStrategy
{
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
bool CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);
}
}

View File

@@ -0,0 +1,44 @@
namespace ProjectBulldozer.MovementStrategy
{
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null) return false;
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal
+ GetStep() >= FieldWidth / 2 && objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null) return;
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@@ -0,0 +1,21 @@
namespace ProjectBulldozer.MovementStrategy
{
public class MoveToRightCorner : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null) return false;
return objParams.RightBorder >= FieldWidth - GetStep() && objParams.DownBorder >= FieldHeight - GetStep();
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null) return;
if (objParams.RightBorder < FieldWidth - GetStep()) MoveRight();
if (objParams.DownBorder < FieldHeight - GetStep()) MoveDown();
}
}
}

View File

@@ -0,0 +1,21 @@
namespace ProjectBulldozer.MovementStrategy
{
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
public int RightBorder => _x + _width;
public int DownBorder => _y + _height;
public int ObjectMiddleHorizontal => _x + _width / 2;
public int ObjectMiddleVertical => _y + _height / 2;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@@ -1,17 +1,40 @@
namespace ProjectBulldozer using ProjectBulldozer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Bulldozer
{ {
internal static class Program internal static class Program
{ {
/// <summary> private static Serilog.ILogger? logger;
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// 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 FormBulldozer()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTractorCollections>());
}
}
private static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<FormTractorCollections>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string appPath = "";
for (int i = 0; i < path.Length - 3; i++)
{
appPath += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().AddJsonFile($"{appPath}appsettings.json").Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@@ -8,6 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.7" />
<PackageReference Include="NLog.Config" Version="4.7.15" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="NLog.Schema" Version="5.2.7" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.7" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@@ -59,5 +59,45 @@ namespace ProjectBulldozer.Properties {
resourceCulture = value; resourceCulture = value;
} }
} }
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap down1 {
get {
object obj = ResourceManager.GetObject("down1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap left1 {
get {
object obj = ResourceManager.GetObject("left1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right1 {
get {
object obj = ResourceManager.GetObject("right1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap up1 {
get {
object obj = ResourceManager.GetObject("up1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
} }
} }

View File

@@ -117,4 +117,17 @@
<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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="down1" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\down1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="left1" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\left1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="right1" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\right1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="up1" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\up1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root> </root>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

View File

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