Compare commits

...

7 Commits
main ... Lab3

31 changed files with 1893 additions and 84 deletions

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32825.248
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bulldozer", "Bulldozer\Bulldozer.csproj", "{5971A7E3-6CB0-41D7-A8C9-F2E29DBC4C68}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bulldozer", "Bulldozer\Bulldozer.csproj", "{054C01C3-1210-4465-84BB-9B559909C149}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -11,15 +11,15 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5971A7E3-6CB0-41D7-A8C9-F2E29DBC4C68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5971A7E3-6CB0-41D7-A8C9-F2E29DBC4C68}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5971A7E3-6CB0-41D7-A8C9-F2E29DBC4C68}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5971A7E3-6CB0-41D7-A8C9-F2E29DBC4C68}.Release|Any CPU.Build.0 = Release|Any CPU
{054C01C3-1210-4465-84BB-9B559909C149}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{054C01C3-1210-4465-84BB-9B559909C149}.Debug|Any CPU.Build.0 = Debug|Any CPU
{054C01C3-1210-4465-84BB-9B559909C149}.Release|Any CPU.ActiveCfg = Release|Any CPU
{054C01C3-1210-4465-84BB-9B559909C149}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {59528A8E-08B2-4D91-8AD1-D237F3B6C1B5}
SolutionGuid = {F8B8E9BD-8990-494B-B3F6-8CBB63A85858}
EndGlobalSection
EndGlobal

View File

@ -8,4 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -0,0 +1,26 @@
namespace Bulldozer
{
/// <summary>
/// Направления движения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4,
}
}

View File

@ -0,0 +1,222 @@
using Bulldozer.Entities;
using Bulldozer.MovementStrategy;
namespace Bulldozer.DrawingObjects
{
/// <summary>
/// Класс отрисовки и перемещения объекта-сущности
/// </summary>
public class DrawingBulldozer
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBulldozer? EntityBulldozer { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Координата прорисовки по оси X
/// </summary>
protected int _startPosX;
/// <summary>
/// Координата прорисовки по оси Y
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина бульдозера
/// </summary>
protected readonly int _bulldozerWidth = 150;
/// <summary>
/// Высота бульдозера
/// </summary>
protected readonly int _bulldozerHeight = 60;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingBulldozer(int speed, double weight, Color bodyColor, Color additionalColor, int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
EntityBulldozer = new EntityBulldozer(speed, weight, bodyColor, additionalColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="carWidth">Ширина прорисовки бульдозера</param>
/// <param name="carHeight">Высота прорисовки бульдозера</param>
protected DrawingBulldozer(int speed, double weight, Color bodyColor, Color additionalColor, int width, int height, int bulldozerWidth, int bulldozerHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_bulldozerWidth = bulldozerWidth;
_bulldozerHeight = bulldozerHeight;
EntityBulldozer = new EntityBulldozer(speed, weight, bodyColor, additionalColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
// Проверка границ
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x > _pictureWidth - _bulldozerWidth) x = _pictureWidth - _bulldozerWidth;
if (y > _pictureHeight - _bulldozerHeight) y = _pictureHeight - _bulldozerHeight;
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _bulldozerWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _bulldozerHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityBulldozer == null)
{
return false;
}
return direction switch
{
// влево
DirectionType.Left => _startPosX - EntityBulldozer.Step > 0,
// вверх
DirectionType.Up => _startPosY - EntityBulldozer.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityBulldozer.Step < _pictureWidth,
// вниз
DirectionType.Down => _startPosY + EntityBulldozer.Step < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveBulldozer(DirectionType direction)
{
if (!CanMove(direction) || EntityBulldozer == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityBulldozer.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityBulldozer.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityBulldozer.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityBulldozer.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawBulldozer(Graphics g)
{
if (EntityBulldozer == null)
{
return;
}
Pen pen = new(Color.Black);
Brush bodyBrush = new SolidBrush(EntityBulldozer.BodyColor);
Brush additionalBrush = new SolidBrush(EntityBulldozer.AdditionalColor);
/// <summary>
/// Заливка гусеницы бульдозера
/// </summary>
Brush brGray = new SolidBrush(Color.Gray);
g.FillEllipse(brGray, _startPosX + 17, _startPosY + 24, 119, 40); //Гусеница
g.FillEllipse(additionalBrush, _startPosX + 20, _startPosY + 35, 20, 20); // Левое колесо гусеницы
g.FillEllipse(additionalBrush, _startPosX + 115, _startPosY + 35, 20, 20); // Правое колесо гусеницы
g.FillEllipse(additionalBrush, _startPosX + 50, _startPosY + 45, 10, 10); // 1 центральное колесо гусеницы
g.FillEllipse(additionalBrush, _startPosX + 70, _startPosY + 45, 10, 10); // 2 центральное колесо гусеницы
g.FillEllipse(additionalBrush, _startPosX + 90, _startPosY + 45, 10, 10); // 3 центральное колесо гусеницы
/// <summary>
/// Отрисовка границ бульдозера
/// </summary>
g.DrawEllipse(pen, _startPosX + 17, _startPosY + 24, 119, 40);
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 35, 20, 20); // Левое колесо гусеницы
g.DrawEllipse(pen, _startPosX + 115, _startPosY + 35, 20, 20); // Правое колесо гусеницы
g.DrawEllipse(pen, _startPosX + 50, _startPosY + 45, 10, 10); // 1 центральное колесо гусеницы
g.DrawEllipse(pen, _startPosX + 70, _startPosY + 45, 10, 10); // 2 центральное колесо гусеницы
g.DrawEllipse(pen, _startPosX + 90, _startPosY + 45, 10, 10); // 3 центральное колесо гусеницы
/// <summary>
/// Кузов бульдозера
/// </summary>
g.FillRectangle(bodyBrush, _startPosX + 102, _startPosY, 28, 24); //кабина
g.FillRectangle(bodyBrush, _startPosX + 17, _startPosY + 24, 119, 18); // основная часть
g.FillRectangle(bodyBrush, _startPosX + 30, _startPosY, 10, 24); // выхлопная труба
/// Корпус
/// </summary>
g.DrawRectangle(pen, _startPosX + 102, _startPosY, 28, 24); //кабина
g.DrawRectangle(pen, _startPosX + 17, _startPosY + 24, 119, 18); // основная часть
g.DrawRectangle(pen, _startPosX + 30, _startPosY, 10, 24); // выхлопная труба
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawingBulldozer
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectBulldozer(this);
}
}

View File

@ -0,0 +1,72 @@
using Bulldozer.Entities;
namespace Bulldozer.DrawingObjects
{
public class DrawingBulldozerUpgraded : DrawingBulldozer
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="blade">Признак наличия рыхлителя</param>
/// <param name="ripper">Признак наличия отвала</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingBulldozerUpgraded(int speed, double weight, Color bodyColor, Color additionalColor, Color dopColor, bool blade, bool ripper, int width, int height) :
base(speed, weight, bodyColor, additionalColor, width, height)
{
if (EntityBulldozer != null)
{
EntityBulldozer = new EntityBulldozerUpgraded(speed, weight, bodyColor, additionalColor, dopColor, blade, ripper);
}
}
public override void DrawBulldozer(Graphics g)
{
if (EntityBulldozer is not EntityBulldozerUpgraded upgradedBulldozer)
{
return;
}
Pen dopPen = new(upgradedBulldozer.DopColor);
Brush dopBrush = new SolidBrush(upgradedBulldozer.DopColor);
/// <summary>
/// Отрисовка отвала бульдозера
/// </summary>
base.DrawBulldozer(g);
if (upgradedBulldozer.Blade)
{
Point point1 = new Point(_startPosX + 8, _startPosY + 29);
Point point2 = new Point(_startPosX + 8, _startPosY + 50);
Point point3 = new Point(_startPosX, _startPosY + 50);
Point[] triangle = { point1, point2, point3 };
g.FillRectangle(dopBrush, _startPosX + 8, _startPosY + 29, 8, 8); // заливка основания отвала
g.FillPolygon(dopBrush, triangle); // заливка отвала
g.DrawRectangle(dopPen, _startPosX + 8, _startPosY + 29, 8, 8); // обводка основания отвала
g.DrawPolygon(dopPen, triangle); // обводка отвала
}
/// <summary>
/// Отрисовка рыхлителя бульдозера
/// </summary>
if (upgradedBulldozer.Ripper)
{
Point ripperPoint1 = new Point(_startPosX + 140, _startPosY + 37);
Point ripperPoint2 = new Point(_startPosX + 151, _startPosY + 37);
Point ripperPoint3 = new Point(_startPosX + 140, _startPosY + 60);
Point[] ripper = { ripperPoint1, ripperPoint2, ripperPoint3 };
g.FillRectangle(dopBrush, _startPosX + 136, _startPosY + 29, 15, 8); // заливка основания рыхлителя
g.FillPolygon(dopBrush, ripper); // заливка отвала
g.DrawRectangle(dopPen, _startPosX + 136, _startPosY + 29, 15, 8); // обводка основания рыхлителя
g.DrawPolygon(dopPen, ripper);
}
}
}
}

View File

@ -0,0 +1,47 @@
using System.Windows.Forms.Design;
namespace Bulldozer.Entities
{
/// <summary>
/// Класс-сущность "Бульдозер"
/// </summary>
public class EntityBulldozer
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
public Color AdditionalColor { get; private set; }
public Color DopColor { get; private set; }
/// <summary>
/// Шаг перемещения бульдозера
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес бульдозера</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityBulldozer(int speed, double weight, Color bodyColor, Color additionalColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
}
}
}

View File

@ -0,0 +1,35 @@
namespace Bulldozer.Entities
{
public class EntityBulldozerUpgraded : EntityBulldozer
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color DopColor { get; private set; }
/// <summary>
/// Отвал бульдозера
/// </summary>
public bool Blade { get; private set; }
/// <summary>
/// Рыхлитель бульдозера
/// </summary>
public bool Ripper { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса бульдозера с обвесами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="additionalColor">Цвет обвесов</param>
/// <param name="blade">Отвал бульдозера</param>
/// <param name="ripper">Рыхлитель бульдозера</param>
public EntityBulldozerUpgraded(int speed, double weight, Color bodyColor, Color additionalColor, Color dopColor, bool blade, bool ripper) :
base(speed, weight, bodyColor, additionalColor)
{
DopColor = dopColor;
Blade = blade;
Ripper = ripper;
}
}
}

View File

@ -1,39 +0,0 @@
namespace Bulldozer
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace Bulldozer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,208 @@
namespace Bulldozer
{
partial class FormBulldozer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pictureBoxBulldozer = new System.Windows.Forms.PictureBox();
this.buttonCreateBulldozer = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonStep = new System.Windows.Forms.Button();
this.buttonCreateUpgradedBulldozer = new System.Windows.Forms.Button();
this.buttonSelectBulldozer = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxBulldozer)).BeginInit();
this.SuspendLayout();
//
// pictureBoxBulldozer
//
this.pictureBoxBulldozer.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxBulldozer.Location = new System.Drawing.Point(0, 0);
this.pictureBoxBulldozer.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.pictureBoxBulldozer.Name = "pictureBoxBulldozer";
this.pictureBoxBulldozer.Size = new System.Drawing.Size(1110, 793);
this.pictureBoxBulldozer.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxBulldozer.TabIndex = 0;
this.pictureBoxBulldozer.TabStop = false;
//
// buttonCreateBulldozer
//
this.buttonCreateBulldozer.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateBulldozer.Location = new System.Drawing.Point(14, 746);
this.buttonCreateBulldozer.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonCreateBulldozer.Name = "buttonCreateBulldozer";
this.buttonCreateBulldozer.Size = new System.Drawing.Size(151, 31);
this.buttonCreateBulldozer.TabIndex = 1;
this.buttonCreateBulldozer.Text = "Создать бульдозер";
this.buttonCreateBulldozer.UseVisualStyleBackColor = true;
this.buttonCreateBulldozer.Click += new System.EventHandler(this.buttonCreateBulldozer_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Bulldozer.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonLeft.Image = global::Bulldozer.Properties.Resources.arrowLeft;
this.buttonLeft.Location = new System.Drawing.Point(967, 741);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(34, 40);
this.buttonLeft.TabIndex = 2;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Bulldozer.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonDown.Location = new System.Drawing.Point(1009, 741);
this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(34, 40);
this.buttonDown.TabIndex = 3;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Bulldozer.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Image = global::Bulldozer.Properties.Resources.arrowRight;
this.buttonRight.Location = new System.Drawing.Point(1050, 741);
this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(34, 40);
this.buttonRight.TabIndex = 4;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Bulldozer.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonUp.Image = global::Bulldozer.Properties.Resources.arrowUp;
this.buttonUp.Location = new System.Drawing.Point(1009, 693);
this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(34, 40);
this.buttonUp.TabIndex = 5;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"Движение к центру",
"Движение к правой нижней границе"});
this.comboBoxStrategy.Location = new System.Drawing.Point(834, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(264, 28);
this.comboBoxStrategy.TabIndex = 6;
//
// buttonStep
//
this.buttonStep.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonStep.Location = new System.Drawing.Point(1038, 47);
this.buttonStep.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(60, 31);
this.buttonStep.TabIndex = 7;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// buttonCreateUpgradedBulldozer
//
this.buttonCreateUpgradedBulldozer.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateUpgradedBulldozer.Location = new System.Drawing.Point(171, 746);
this.buttonCreateUpgradedBulldozer.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonCreateUpgradedBulldozer.Name = "buttonCreateUpgradedBulldozer";
this.buttonCreateUpgradedBulldozer.Size = new System.Drawing.Size(235, 31);
this.buttonCreateUpgradedBulldozer.TabIndex = 8;
this.buttonCreateUpgradedBulldozer.Text = "Создать бульдозер с обвесами";
this.buttonCreateUpgradedBulldozer.UseVisualStyleBackColor = true;
this.buttonCreateUpgradedBulldozer.Click += new System.EventHandler(this.buttonCreateUpgradedBulldozer_Click);
//
// buttonSelectBulldozer
//
this.buttonSelectBulldozer.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonSelectBulldozer.Location = new System.Drawing.Point(412, 746);
this.buttonSelectBulldozer.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonSelectBulldozer.Name = "buttonSelectBulldozer";
this.buttonSelectBulldozer.Size = new System.Drawing.Size(130, 31);
this.buttonSelectBulldozer.TabIndex = 9;
this.buttonSelectBulldozer.Text = "Выбрать объект";
this.buttonSelectBulldozer.UseVisualStyleBackColor = true;
this.buttonSelectBulldozer.Click += new System.EventHandler(this.buttonSelectBulldozer_Click);
//
// FormBulldozer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1110, 793);
this.Controls.Add(this.buttonSelectBulldozer);
this.Controls.Add(this.buttonCreateUpgradedBulldozer);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonCreateBulldozer);
this.Controls.Add(this.pictureBoxBulldozer);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormBulldozer";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Bulldozer";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxBulldozer)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private PictureBox pictureBoxBulldozer;
private Button buttonCreateBulldozer;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonUp;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonCreateUpgradedBulldozer;
private Button buttonSelectBulldozer;
}
}

View File

@ -0,0 +1,180 @@
using Bulldozer.MovementStrategy;
using Bulldozer.DrawingObjects;
namespace Bulldozer
{
public partial class FormBulldozer : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingBulldozer? _drawingBulldozer;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âûáðàííûé áóëüäîçåð
/// </summary>
public DrawingBulldozer? SelectedBulldozer { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormBulldozer()
{
InitializeComponent();
_abstractStrategy = null;
SelectedBulldozer = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè áóëüäîçåðà
/// </summary>
private void Draw()
{
if (_drawingBulldozer == null)
{
return;
}
Bitmap bmp = new(pictureBoxBulldozer.Width, pictureBoxBulldozer.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingBulldozer.DrawBulldozer(gr);
pictureBoxBulldozer.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü áóëüäîçåð ñ îáâåñàìè"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingBulldozer == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingBulldozer.MoveBulldozer(DirectionType.Up);
break;
case "buttonDown":
_drawingBulldozer.MoveBulldozer(DirectionType.Down);
break;
case "buttonLeft":
_drawingBulldozer.MoveBulldozer(DirectionType.Left);
break;
case "buttonRight":
_drawingBulldozer.MoveBulldozer(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateUpgradedBulldozer_Click(object sender, EventArgs e)
{
Random random = new Random();
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); // Îñíîâíîé öâåò
Color additionalColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); // Äîï. öâåò äëÿ EntityUpgradedBulldozer
ColorDialog colorDialog = new();
if (colorDialog.ShowDialog() == DialogResult.OK)
bodyColor = colorDialog.Color;
if (colorDialog.ShowDialog() == DialogResult.OK)
dopColor = colorDialog.Color;
_drawingBulldozer = new DrawingBulldozerUpgraded(
random.Next(100, 300), // Ñêîðîñòü
random.Next(1000, 3000), // Âåñ
bodyColor, additionalColor, dopColor,
Convert.ToBoolean(random.Next(2)),
Convert.ToBoolean(random.Next(2)),
pictureBoxBulldozer.Width,
pictureBoxBulldozer.Height
);
_drawingBulldozer.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonCreateBulldozer_Click(object sender, EventArgs e)
{
Random random = new();
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog colorDialog = new ColorDialog();
if (colorDialog.ShowDialog() == DialogResult.OK)
{
bodyColor = colorDialog.Color;
}
Color additionalColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
_drawingBulldozer = new DrawingBulldozer(random.Next(100, 300), // Ñêîðîñòü
random.Next(1000, 3000), // Âåñ
bodyColor, additionalColor,
pictureBoxBulldozer.Width,
pictureBoxBulldozer.Height);
_drawingBulldozer.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingBulldozer == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectBulldozer(_drawingBulldozer), pictureBoxBulldozer.Width, pictureBoxBulldozer.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
/// <summary>
/// Âûáîð áóëüäîçåðà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSelectBulldozer_Click(object sender, EventArgs e)
{
SelectedBulldozer = _drawingBulldozer;
DialogResult = DialogResult.OK;
}
}
}

View File

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

View File

@ -0,0 +1,124 @@
namespace Bulldozer
{
partial class FormBulldozerCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
pictureBoxCollection = new PictureBox();
panelTools = new Panel();
textBox = new TextBox();
buttonUpdateColletion = new Button();
buttonDeleteBulldozer = new Button();
buttonAddBulldozer = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Anchor = AnchorStyles.Left;
pictureBoxCollection.BackColor = SystemColors.Control;
pictureBoxCollection.Location = new Point(12, 12);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(711, 571);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// panelTools
//
panelTools.Controls.Add(textBox);
panelTools.Controls.Add(buttonUpdateColletion);
panelTools.Controls.Add(buttonDeleteBulldozer);
panelTools.Controls.Add(buttonAddBulldozer);
panelTools.Location = new Point(729, 12);
panelTools.Name = "panelTools";
panelTools.Size = new Size(234, 571);
panelTools.TabIndex = 1;
panelTools.Tag = "";
//
// textBox
//
textBox.Location = new Point(23, 164);
textBox.Name = "textBox";
textBox.Size = new Size(193, 23);
textBox.TabIndex = 3;
//
// buttonUpdateColletion
//
buttonUpdateColletion.Location = new Point(23, 263);
buttonUpdateColletion.Name = "buttonUpdateColletion";
buttonUpdateColletion.Size = new Size(193, 40);
buttonUpdateColletion.TabIndex = 2;
buttonUpdateColletion.Text = "Обновить коллекцию";
buttonUpdateColletion.UseVisualStyleBackColor = true;
buttonUpdateColletion.Click += ButtonUpdateCollection_Click;
//
// buttonDeleteBulldozer
//
buttonDeleteBulldozer.Location = new Point(23, 193);
buttonDeleteBulldozer.Name = "buttonDeleteBulldozer";
buttonDeleteBulldozer.Size = new Size(193, 40);
buttonDeleteBulldozer.TabIndex = 1;
buttonDeleteBulldozer.Text = "Удалить объект";
buttonDeleteBulldozer.UseVisualStyleBackColor = true;
buttonDeleteBulldozer.Click += ButtonDeleteBulldozer_Click;
//
// buttonAddBulldozer
//
buttonAddBulldozer.Location = new Point(23, 32);
buttonAddBulldozer.Name = "buttonAddBulldozer";
buttonAddBulldozer.Size = new Size(193, 40);
buttonAddBulldozer.TabIndex = 0;
buttonAddBulldozer.Text = "Добавить объект";
buttonAddBulldozer.UseVisualStyleBackColor = true;
buttonAddBulldozer.Click += ButtonAddBulldozer_Click;
//
// FormBulldozerCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(971, 595);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
Name = "FormBulldozerCollection";
Text = "Bulldozer Collection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panelTools;
private TextBox textBox;
private Button buttonUpdateColletion;
private Button buttonDeleteBulldozer;
private Button buttonAddBulldozer;
}
}

View File

@ -0,0 +1,60 @@
using Bulldozer.DrawingObjects;
using Bulldozer.Generics;
using Bulldozer.MovementStrategy;
namespace Bulldozer
{
public partial class FormBulldozerCollection : Form
{
private readonly BulldozersGenericCollection<DrawingBulldozer, DrawingObjectBulldozer> _bulldozers;
public FormBulldozerCollection()
{
InitializeComponent();
_bulldozers = new BulldozersGenericCollection<DrawingBulldozer,
DrawingObjectBulldozer>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
private void ButtonAddBulldozer_Click(object sender, EventArgs e)
{
FormBulldozer form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_bulldozers + form.SelectedBulldozer != null)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _bulldozers.ShowBulldozers();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
private void ButtonDeleteBulldozer_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(textBox.Text);
if (_bulldozers - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _bulldozers.ShowBulldozers();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonUpdateCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _bulldozers.ShowBulldozers();
}
}
}

View File

@ -1,17 +1,17 @@
<?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
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>
@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,129 @@
using Bulldozer.DrawingObjects;
using Bulldozer.MovementStrategy;
namespace Bulldozer.Generics
{
internal class BulldozersGenericCollection<T, U>
where T : DrawingBulldozer
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 300;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 70;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public BulldozersGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(BulldozersGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
return -1;
return collect?._collection.Insert(obj) ?? -1;
}
public static bool operator -(BulldozersGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
return collect._collection.Remove(pos);
return false;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowBulldozers()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
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 / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int heightObjCount = _pictureHeight / _placeSizeHeight;
int widthObjCount = _pictureWidth / _placeSizeWidth;
int totalObjects = _collection.Count;
for (int i = 0; i < totalObjects; i++)
{
T? type = _collection.Get(i);
if (type != null)
{
int col = widthObjCount - 1 - (i % widthObjCount);
int row = heightObjCount - 1 - (i / widthObjCount);
type.SetPosition(col * _placeSizeWidth, row * _placeSizeHeight);
type?.DrawBulldozer(g);
}
}
}
}
}

View File

@ -0,0 +1,87 @@
namespace Bulldozer.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="bulldozer">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T bulldozer)
{
if (_places[Count - 1] != null)
return -1;
return Insert(bulldozer, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="bulldozer">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T bulldozer, int position)
{
if (!(position >= 0 && position < Count))
return -1;
if (_places[position] != null)
{
int ind = position;
while (ind < Count && _places[ind] != null)
ind++;
if (ind == Count)
return -1;
for (int i = ind - 1; i >= position; i--)
_places[i + 1] = _places[i];
}
_places[position] = bulldozer;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (!(position >= 0 && position < Count) || _places[position] == null)
return false;
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
}
}

View File

@ -0,0 +1,126 @@
namespace Bulldozer.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
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;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
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,31 @@
using Bulldozer.DrawingObjects;
namespace Bulldozer.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawingObject для работы с объектом DrawingBulldozer (паттерн Adapter)
/// </summary>
public class DrawingObjectBulldozer : IMoveableObject
{
private readonly DrawingBulldozer? _drawingBulldozer = null;
public DrawingObjectBulldozer(DrawingBulldozer drawingBulldozer)
{
_drawingBulldozer = drawingBulldozer;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingBulldozer == null || _drawingBulldozer.EntityBulldozer == null)
{
return null;
}
return new ObjectParameters(_drawingBulldozer.GetPosX, _drawingBulldozer.GetPosY, _drawingBulldozer.GetWidth, _drawingBulldozer.GetHeight);
}
}
public int GetStep => (int)(_drawingBulldozer?.EntityBulldozer?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawingBulldozer?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawingBulldozer?.MoveBulldozer(direction);
}
}

View File

@ -0,0 +1,30 @@
using Bulldozer.DrawingObjects;
namespace Bulldozer.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,57 @@
using Bulldozer.DrawingObjects;
namespace Bulldozer.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в правую нижнюю границу экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
return objParams != null
&& objParams.ObjectMiddleHorizontal >= FieldWidth
&& objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth
&& objParams.ObjectMiddleVertical >= FieldHeight
&& objParams.ObjectMiddleVertical - GetStep() <= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth;
var diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,51 @@
namespace Bulldozer.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
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,52 @@
namespace Bulldozer.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
//public int DownBorder => _y + _height;
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -0,0 +1,12 @@
namespace Bulldozer.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -1,4 +1,4 @@
namespace Bulldozer
namespace Bulldozer.MovementStrategy
{
internal static class Program
{
@ -8,10 +8,8 @@ namespace Bulldozer
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
Application.Run(new FormBulldozerCollection());
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Bulldozer.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Bulldozer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowDown {
get {
object obj = ResourceManager.GetObject("arrowDown", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowLeft {
get {
object obj = ResourceManager.GetObject("arrowLeft", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowRight {
get {
object obj = ResourceManager.GetObject("arrowRight", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowUp {
get {
object obj = ResourceManager.GetObject("arrowUp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,133 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="arrowDown" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowDown.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowRight" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowRight.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowLeft" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowLeft.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowUp" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowUp.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB