Боровков М В ПИбд-22 2 лабораторная работа #3

Closed
bekodeg wants to merge 2 commits from labWork2 into labWork1
19 changed files with 844 additions and 192 deletions

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElectricLocomotive", "ElectricLocomotive\ElectricLocomotive.csproj", "{F2E231D6-98A4-412A-952D-87456DBD3E48}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectElectricLocomotive", "ElectricLocomotive\ProjectElectricLocomotive.csproj", "{F2E231D6-98A4-412A-952D-87456DBD3E48}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -4,28 +4,27 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectricLocomotive
namespace ProjectElectricLocomotive;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Направление перемещения
/// Вверх
/// /// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
public enum DirectionType
{
/// <summary>
/// Вверх
/// /// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,68 @@
using ProjectElectricLocomotive.Entities;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningElectricLocomotive : DrawningLocomotive
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="horns">Признак наличия рогов</param>
/// <param name="battery">Признак наличия отсека для батарей</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningElectricLocomotive(int speed, double weight, Color bodyColor,
Color additionalColor, bool horns, bool battery, int width, int height) :
base(speed, weight, bodyColor, width, height, 120, 70)
{
if (EntityLocomotive != null)
{
EntityLocomotive = new EntityElectricLocomotive(speed, weight, bodyColor, additionalColor, horns, battery);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityLocomotive is not EntityElectricLocomotive electricLocomotive)
{
return;
}
base.DrawTransport(g);
Pen pen = new(Color.Black, 5);
Brush brush = new SolidBrush(EntityLocomotive.BodyColor);
Point[] points;
// рога
if (electricLocomotive.Horns)
{
pen = new(Color.Black, 2);
points = new Point[4];
points[0] = new Point(_startPosX + 50, _startPosY + 20);
points[1] = new Point(_startPosX + 40, _startPosY + 10);
points[2] = new Point(_startPosX + 50, _startPosY);
points[3] = new Point(_startPosX + 60, _startPosY + 10);
g.DrawPolygon(pen, points);
}
// отсек для батарей
if (electricLocomotive.Battery)
{
brush = new SolidBrush(electricLocomotive.AdditionalColor);
g.FillRectangle(brush, _startPosX + 80, _startPosY + 45, 35, 9);
}
}
}
}

View File

@ -3,66 +3,97 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectElectricLocomotive.Entities;
using ProjectElectricLocomotive;
namespace ElectricLocomotive
namespace ProjectElectricLocomotive.DrawningObjects
{
internal class DrawningElectricLocomotive
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningLocomotive
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityElectricLocomotive? EntityElectricLocomotive { get; private set; }
public EntityLocomotive? EntityLocomotive { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
protected int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
protected int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _locomotiveWidth = 120;
protected readonly int _locomotiveWidth = 120;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _locomotiveHeight = 70;
protected readonly int _locomotiveHeight = 70;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _locomotiveWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _locomotiveHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="horns">Признак наличия рогов</param>
/// <param name="battery">Признак наличия отсека для батарей</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool horns, bool battery, int width, int height)
public DrawningLocomotive(int speed, double weight, Color bodyColor, int width, int height)
{
if (width < _locomotiveWidth || height < _locomotiveHeight)
{
return false;
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityElectricLocomotive = new EntityElectricLocomotive();
EntityElectricLocomotive.Init(speed, weight, bodyColor, additionalColor,
horns, battery);
return true;
EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
public DrawningLocomotive(int speed, double weight, Color bodyColor,
int width, int height, int locomotiveWidth, int locomotiveHeight)
{
if (width < _locomotiveWidth || height < _locomotiveHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_locomotiveWidth = locomotiveWidth;
_locomotiveHeight = locomotiveHeight;
EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
@ -75,62 +106,21 @@ namespace ElectricLocomotive
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityElectricLocomotive == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX - EntityElectricLocomotive.Step > 0)
{
_startPosX -= (int)EntityElectricLocomotive.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityElectricLocomotive.Step > 0)
{
_startPosY -= (int)EntityElectricLocomotive.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + _locomotiveWidth + EntityElectricLocomotive.Step < _pictureWidth)
{
_startPosX += (int)EntityElectricLocomotive.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _locomotiveHeight + EntityElectricLocomotive.Step < _pictureHeight)
{
_startPosY += (int)EntityElectricLocomotive.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityElectricLocomotive == null)
if (EntityLocomotive == null)
{
return;
}
// корпус электровоза
Pen pen = new(Color.Black, 5);
Brush brush = new SolidBrush(EntityElectricLocomotive.BodyColor);
Brush brush = new SolidBrush(EntityLocomotive.BodyColor);
Point[] points = new Point[5];
points[0] = new Point(_startPosX, _startPosY + 40);
points[1] = new Point(_startPosX + 10, _startPosY + 20);
@ -156,24 +146,6 @@ namespace ElectricLocomotive
g.FillEllipse(brush, _startPosX + 25, _startPosY + 55, 15, 15);
g.FillEllipse(brush, _startPosX + 80, _startPosY + 55, 15, 15);
g.FillEllipse(brush, _startPosX + 95, _startPosY + 55, 15, 15);
// рога
if (EntityElectricLocomotive.Horns)
{
pen = new(Color.Black, 2);
points = new Point[4];
points[0] = new Point(_startPosX + 50, _startPosY + 20);
points[1] = new Point(_startPosX + 40, _startPosY + 10);
points[2] = new Point(_startPosX + 50, _startPosY);
points[3] = new Point(_startPosX + 60, _startPosY + 10);
g.DrawPolygon(pen, points);
}
// отсек для батарей
if (EntityElectricLocomotive.Battery)
{
brush = new SolidBrush(EntityElectricLocomotive.AdditionalColor);
g.FillRectangle(brush, _startPosX + 80, _startPosY + 45, 35, 9);
}
}
/// <summary>
@ -186,5 +158,61 @@ namespace ElectricLocomotive
_pictureWidth = newSize.Width;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityLocomotive == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityLocomotive.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityLocomotive.Step > 0,
// вправо
DirectionType.Right => _startPosX + _locomotiveWidth + EntityLocomotive.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _locomotiveHeight + EntityLocomotive.Step < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityLocomotive == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityLocomotive.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityLocomotive.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityLocomotive.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityLocomotive.Step;
break;
}
}
}
}

View File

@ -1,26 +1,17 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace ElectricLocomotive
namespace ProjectElectricLocomotive.Entities
{
internal class EntityElectricLocomotive
/// <summary>
/// Класс-сущность "Электровоз"
/// </summary>
public class EntityElectricLocomotive : EntityLocomotive
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
@ -33,28 +24,23 @@ namespace ElectricLocomotive
/// Признак (опция) наличия отсека для батарей
/// </summary>
public bool Battery { 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>
/// <param name="weight">Веc поезда</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="horns">Признак наличия рогов</param>
/// <param name="battery">Признак наличия отсека для батарей</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool horns, bool battery)
public EntityElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool battery) :
base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Horns = horns;
Battery = battery;
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Entities
{
/// <summary>
/// Класс-сущность "Поезд"
/// </summary>
public class EntityLocomotive
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { 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 EntityLocomotive(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -1,6 +1,6 @@
namespace ElectricLocomotive
namespace ProjectElectricLocomotive
{
partial class FormElectricLocomotive
partial class FormLocomotive
{
/// <summary>
/// Required designer variable.
@ -30,10 +30,13 @@
{
buttonUp = new Button();
buttonRight = new Button();
buttonCreate = new Button();
buttonCreateLocomotive = new Button();
buttonDown = new Button();
buttonLeft = new Button();
pictureBoxElectricLocomotive = new PictureBox();
buttonCreateElectricLocomotive = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit();
SuspendLayout();
//
@ -42,7 +45,7 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(55, 459);
buttonUp.Location = new Point(54, 514);
buttonUp.Margin = new Padding(3, 4, 3, 4);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(34, 40);
@ -56,7 +59,7 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(96, 507);
buttonRight.Location = new Point(95, 562);
buttonRight.Margin = new Padding(3, 4, 3, 4);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(34, 40);
@ -65,24 +68,24 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonRight_Click;
//
// buttonCreate
// buttonCreateLocomotive
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(14, 559);
buttonCreate.Margin = new Padding(3, 4, 3, 4);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(117, 40);
buttonCreate.TabIndex = 2;
buttonCreate.Text = "создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCreateLocomotive.Location = new Point(816, 562);
buttonCreateLocomotive.Margin = new Padding(3, 4, 3, 4);
buttonCreateLocomotive.Name = "buttonCreateLocomotive";
buttonCreateLocomotive.Size = new Size(182, 40);
buttonCreateLocomotive.TabIndex = 2;
buttonCreateLocomotive.Text = "создать локомотив";
buttonCreateLocomotive.UseVisualStyleBackColor = true;
buttonCreateLocomotive.Click += buttonCreateLocomotive_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(55, 507);
buttonDown.Location = new Point(54, 562);
buttonDown.Margin = new Padding(3, 4, 3, 4);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(34, 40);
@ -96,7 +99,7 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(14, 507);
buttonLeft.Location = new Point(13, 562);
buttonLeft.Margin = new Padding(3, 4, 3, 4);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(34, 40);
@ -116,20 +119,58 @@
pictureBoxElectricLocomotive.TabStop = false;
pictureBoxElectricLocomotive.SizeChanged += pictureBoxElectricLocomotive_SizeChanged;
//
// FormElectricLocomotive
// buttonCreateElectricLocomotive
//
buttonCreateElectricLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCreateElectricLocomotive.Location = new Point(816, 514);
buttonCreateElectricLocomotive.Margin = new Padding(3, 4, 3, 4);
buttonCreateElectricLocomotive.Name = "buttonCreateElectricLocomotive";
buttonCreateElectricLocomotive.Size = new Size(182, 40);
buttonCreateElectricLocomotive.TabIndex = 6;
buttonCreateElectricLocomotive.Text = "создать электропоезд";
buttonCreateElectricLocomotive.UseVisualStyleBackColor = true;
buttonCreateElectricLocomotive.Click += buttonCreateElectricLocomotive_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "идти к центру экрана", "идти к краю экрана" });
comboBoxStrategy.Location = new Point(816, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(182, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(915, 47);
buttonStep.Margin = new Padding(3, 4, 3, 4);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(83, 33);
buttonStep.TabIndex = 8;
buttonStep.Text = "шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// FormLocomotive
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1010, 615);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateElectricLocomotive);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonCreate);
Controls.Add(buttonCreateLocomotive);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(pictureBoxElectricLocomotive);
Margin = new Padding(3, 4, 3, 4);
MinimumSize = new Size(100, 100);
Name = "FormElectricLocomotive";
MinimumSize = new Size(500, 300);
Name = "FormLocomotive";
Text = "ElectricLocomotive";
((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).EndInit();
ResumeLayout(false);
@ -140,9 +181,12 @@
private Button buttonUp;
private Button buttonRight;
private Button buttonCreate;
private Button buttonCreateLocomotive;
private Button buttonDown;
private Button buttonLeft;
private PictureBox pictureBoxElectricLocomotive;
private Button buttonCreateElectricLocomotive;
private ComboBox comboBoxStrategy;
private Button buttonStep;
}
}

View File

@ -1,10 +1,10 @@
namespace ElectricLocomotive
namespace ProjectElectricLocomotive
{
public partial class FormElectricLocomotive : Form
public partial class FormLocomotive : Form
{
private void buttonCreate_Click(object sender, EventArgs e)
private void buttonCreateLocomotive_Click(object sender, EventArgs e)
{
ButtonCreateElectricLocomotive_Click(sender, e);
ButtonCreateLocomotive_Click(sender, e);
}
private void buttonUp_Click(object sender, EventArgs e)
@ -31,5 +31,15 @@ namespace ElectricLocomotive
{
PictureBoxElectricLocomotive_SizeChanged(sender, e);
}
private void buttonStep_Click(object sender, EventArgs e)
{
ButtonStep_Click(sender, e);
}
private void buttonCreateElectricLocomotive_Click(object sender, EventArgs e)
{
ButtonCreateElectricLocomotive_Click(sender, e);
}
}
}

View File

@ -1,25 +1,30 @@
using ElectricLocomotive;
using ProjectElectricLocomotive.DrawningObjects;
using ProjectElectricLocomotive.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectricLocomotive
namespace ProjectElectricLocomotive
{
/// <summary>
/// Форма работы с объектом "электровоз"
/// </summary>
public partial class FormElectricLocomotive
public partial class FormLocomotive
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// <summary>
private DrawningElectricLocomotive? _drawningElectricLocomotive;
private DrawningLocomotive? _drawningLocomotive;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Инициализация формы
/// </summary>
public FormElectricLocomotive()
public FormLocomotive()
{
InitializeComponent();
}
@ -28,46 +33,80 @@ namespace ElectricLocomotive
/// </summary>
private void Draw()
{
if (_drawningElectricLocomotive == null)
if (_drawningLocomotive == null)
{
return;
}
Bitmap bmp = new(pictureBoxElectricLocomotive.Width,
pictureBoxElectricLocomotive.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningElectricLocomotive.DrawTransport(gr);
_drawningLocomotive.DrawTransport(gr);
pictureBoxElectricLocomotive.Image = bmp;
}
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать электровоз"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateElectricLocomotive_Click(object sender, EventArgs e)
{
Random random = new();
_drawningElectricLocomotive = new DrawningElectricLocomotive();
_drawningElectricLocomotive.Init(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
_drawningElectricLocomotive.SetPosition(random.Next(10, 100),
random.Next(10, 100));
_drawningLocomotive = new DrawningElectricLocomotive(
random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
_drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать локомотив"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateLocomotive_Click(object sender, EventArgs e)
{
Random random = new();
_drawningLocomotive = new DrawningLocomotive(
random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
_drawningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Изменение размеров формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PictureBoxElectricLocomotive_SizeChanged(object sender, EventArgs e)
{
Size size = ((PictureBox)sender)?.Size ?? Size.Empty;
if (_abstractStrategy != null)
{
_abstractStrategy.SetFieldSize(size);
}
if (_drawningLocomotive != null)
{
_drawningLocomotive.SetPictureSize(size);
}
}
/// <summary>
/// Изменение положения автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningElectricLocomotive == null)
if (_drawningLocomotive == null)
{
return;
}
@ -75,29 +114,63 @@ namespace ElectricLocomotive
switch (name)
{
case "buttonUp":
_drawningElectricLocomotive.MoveTransport(DirectionType.Up);
_drawningLocomotive.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningElectricLocomotive.MoveTransport(DirectionType.Down);
_drawningLocomotive.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningElectricLocomotive.MoveTransport(DirectionType.Left);
_drawningLocomotive.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningElectricLocomotive.MoveTransport(DirectionType.Right);
_drawningLocomotive.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void PictureBoxElectricLocomotive_SizeChanged(object sender, EventArgs e)
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningElectricLocomotive == null)
if (_drawningLocomotive == null)
{
return;
}
Size size = ((PictureBox)sender)?.Size ?? Size.Empty;
_drawningElectricLocomotive.SetPictureSize(size);
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectLocomotive(_drawningLocomotive), pictureBoxElectricLocomotive.Width,
pictureBoxElectricLocomotive.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,139 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.AxHost;
namespace ProjectElectricLocomotive.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;
}
public void SetFieldSize(Size newSize)
{
FieldWidth = newSize.Width;
FieldHeight = newSize.Height;
}
}
}

View File

@ -0,0 +1,42 @@
using ProjectElectricLocomotive.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningLocomotive(паттерн Adapter)
/// </summary>
public class DrawningObjectLocomotive : IMoveableObject
{
private readonly DrawningLocomotive? _drawningLocomotive = null;
public DrawningObjectLocomotive(DrawningLocomotive drawningLocomotive)
{
_drawningLocomotive = drawningLocomotive;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningLocomotive == null || _drawningLocomotive.EntityLocomotive ==
null)
{
return null;
}
return new ObjectParameters(_drawningLocomotive.GetPosX,
_drawningLocomotive.GetPosY, _drawningLocomotive.GetWidth, _drawningLocomotive.GetHeight);
}
}
public int GetStep => (int)(_drawningLocomotive?.EntityLocomotive?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawningLocomotive?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawningLocomotive?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectElectricLocomotive;
namespace ProjectElectricLocomotive.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,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта к границе экрана экрана
/// </summary>
internal class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
if (MoveRight())
{
MoveLeft();
return false;
}
if (MoveDown())
{
MoveUp();
return false;
}
return true;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
MoveRight();
MoveDown();
}
}
}

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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;
/// <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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -1,4 +1,4 @@
namespace ElectricLocomotive
namespace ProjectElectricLocomotive
{
internal static class Program
{
@ -11,7 +11,7 @@ namespace ElectricLocomotive
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormElectricLocomotive());
Application.Run(new FormLocomotive());
}
}
}

View File

@ -8,7 +8,7 @@
// </auto-generated>
//------------------------------------------------------------------------------
namespace ElectricLocomotive.Properties {
namespace ProjectElectricLocomotive.Properties {
using System;
@ -39,7 +39,7 @@ namespace ElectricLocomotive.Properties {
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ElectricLocomotive.Properties.Resources", typeof(Resources).Assembly);
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectElectricLocomotive.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;