Лабораторная работа № 2

This commit is contained in:
vettaql 2024-04-04 16:09:49 +04:00
parent ba425764a3
commit 3c4acc7ca4
15 changed files with 865 additions and 173 deletions

View File

@ -0,0 +1,27 @@
namespace ProjectTank.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,63 @@
using ProjectTank.Entities;
namespace ProjectTank.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningTank : DrawningTank2
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="gunTurret">Признак наличия башни с орудием</param>
/// <param name="machineGun">Признак наличия пулемёта</param>
public DrawningTank(int speed, double weight, Color bodyColor, Color additionalColor, bool gunTurret, bool machineGun) : base(200, 100)
{
EntityTank2 = new EntityTank(speed, weight, bodyColor, additionalColor, gunTurret, machineGun);
}
public override void DrawTransport(Graphics g)
{
if (EntityTank2 == null || EntityTank2 is not EntityTank tank || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(tank.AdditionalColor);
_startPosX += 37;
_startPosY += 0;
base.DrawTransport(g);
_startPosX -= 37;
_startPosY -= 0;
if (tank.GunTurret)
{
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 42, 85, 8);
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 42, 85, 8);
}
if (tank.MachineGun)
{
g.DrawRectangle(pen, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12);
g.DrawRectangle(pen, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18);
g.DrawRectangle(pen, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12);
g.FillRectangle(additionalBrush, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18);
g.FillRectangle(additionalBrush, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5);
}
}
}

View File

@ -1,13 +1,16 @@
namespace ProjectTank; using ProjectTank.Entities;
namespace ProjectTank.Drawnings;
/// <summary> /// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
/// </summary> /// </summary>
public class DrawningTank public class DrawningTank2
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityTank? EntityTank { get; private set; } public EntityTank2? EntityTank2 { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
/// </summary> /// </summary>
@ -19,39 +22,70 @@ public class DrawningTank
/// <summary> /// <summary>
/// Левая координата прорисовки танка /// Левая координата прорисовки танка
/// </summary> /// </summary>
private int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя кооридната прорисовки танка /// Верхняя кооридната прорисовки танка
/// </summary> /// </summary>
private int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки танка /// Ширина прорисовки танка
/// </summary> /// </summary>
private readonly int _drawningTankWidth = 200; private readonly int _drawningTankWidth = 160;
/// <summary> /// <summary>
/// Высота прорисовки танка /// Высота прорисовки танка
/// </summary> /// </summary>
private readonly int _drawningTankHeight = 100; private readonly int _drawningTankHeight = 94;
/// <summary> /// <summary>
/// Инициализация свойств /// Координата X объекта
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> public int? GetPosX => _startPosX;
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param> /// <summary>
/// <param name="additionalColor">Дополнительный цвет</param> /// Координата Y объекта
/// <param name="gunTurret">Признак наличия башни с орудием</param> /// </summary>
/// <param name="machineGun">Признак наличия пулемёта</param> public int? GetPosY => _startPosY;
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool gunTurret, bool machineGun, bool v) /// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningTankWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningTankHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningTank2()
{ {
EntityTank = new EntityTank();
EntityTank.Init(speed, weight, bodyColor, additionalColor,
gunTurret, machineGun);
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
_startPosX = null; _startPosX = null;
_startPosY = null; _startPosY = null;
} }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningTank2(int speed, double weight, Color bodyColor) : this()
{
EntityTank2 = new EntityTank2(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследования
/// </summary>
/// <param name="drawningTankWidth">Ширина прорисовки танка</param>
/// <param name="drawningTankHeight">Высота прорисовки танка</param>
protected DrawningTank2(int drawningTankWidth,int drawningTankHeight) : this()
{
_drawningTankWidth = drawningTankWidth;
_drawningTankHeight = drawningTankHeight;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
@ -66,7 +100,7 @@ public class DrawningTank
_pictureWidth = width; _pictureHeight = height; _pictureWidth = width; _pictureHeight = height;
{ {
if (_startPosX.HasValue&&_startPosY.HasValue) if (_startPosX.HasValue && _startPosY.HasValue)
SetPosition(_startPosX.Value, _startPosY.Value); SetPosition(_startPosX.Value, _startPosY.Value);
} }
@ -75,9 +109,6 @@ public class DrawningTank
return false; return false;
} }
/// <summary> /// <summary>
/// Установка позиции /// Установка позиции
/// </summary> /// </summary>
@ -94,7 +125,8 @@ public class DrawningTank
if (x < 0 || x + _drawningTankWidth > _pictureWidth || y < 0 || y + _drawningTankHeight > _pictureHeight) if (x < 0 || x + _drawningTankWidth > _pictureWidth || y < 0 || y + _drawningTankHeight > _pictureHeight)
{ {
_startPosX = _pictureWidth - _drawningTankWidth; _startPosY = _pictureHeight - _drawningTankHeight; _startPosX = _pictureWidth - _drawningTankWidth; _startPosY = _pictureHeight - _drawningTankHeight;
} else }
else
{ {
_startPosX = x; _startPosX = x;
_startPosY = y; _startPosY = y;
@ -108,7 +140,7 @@ public class DrawningTank
public bool MoveTransport(DirectionType direction) public bool MoveTransport(DirectionType direction)
{ {
if (EntityTank == null || !_startPosX.HasValue || if (EntityTank2 == null || !_startPosX.HasValue ||
!_startPosY.HasValue) !_startPosY.HasValue)
{ {
return false; return false;
@ -117,32 +149,32 @@ public class DrawningTank
{ {
//влево //влево
case DirectionType.Left: case DirectionType.Left:
if (_startPosX.Value - EntityTank.Step > 0) if (_startPosX.Value - EntityTank2.Step > 0)
{ {
_startPosX -= (int)EntityTank.Step; _startPosX -= (int)EntityTank2.Step;
} }
return true; return true;
//вверх //вверх
case DirectionType.Up: case DirectionType.Up:
if (_startPosY.Value - EntityTank.Step > 0) if (_startPosY.Value - EntityTank2.Step > 0)
{ {
_startPosY -= (int)EntityTank.Step; _startPosY -= (int)EntityTank2.Step;
} }
return true; return true;
// вниз // вниз
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + EntityTank.Step + _drawningTankHeight < _pictureHeight) if (_startPosY.Value + EntityTank2.Step + _drawningTankHeight < _pictureHeight)
{ {
_startPosY += (int)EntityTank.Step; _startPosY += (int)EntityTank2.Step;
} }
return true; return true;
// вправо // вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + EntityTank.Step + _drawningTankWidth < _pictureWidth) if (_startPosX.Value + EntityTank2.Step + _drawningTankWidth < _pictureWidth)
{ {
_startPosX += (int)EntityTank.Step; _startPosX += (int)EntityTank2.Step;
} }
return true; return true;
default: default:
@ -153,65 +185,45 @@ public class DrawningTank
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
public void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntityTank == null || !_startPosX.HasValue || if (EntityTank2 == null || !_startPosX.HasValue ||
!_startPosY.HasValue) !_startPosY.HasValue)
{ {
return; return;
} }
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush additionalBrush = new
SolidBrush(EntityTank.AdditionalColor);
//границы танка + гусеницы + пулемёт + башня с оружием //границы танка + гусеницы + пулемёт + башня с оружием
g.DrawRectangle(pen, _startPosX.Value + 85, _startPosY.Value + 39, 55, 17); g.DrawRectangle(pen, _startPosX.Value + 48, _startPosY.Value + 39, 55, 17);
g.DrawRectangle(pen, _startPosX.Value + 49, _startPosY.Value + 56, 137, 13); g.DrawRectangle(pen, _startPosX.Value + 12, _startPosY.Value + 56, 137, 13);
g.DrawEllipse(pen, _startPosX.Value + 37, _startPosY.Value + 59, 160, 35); g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 59, 160, 35);
g.DrawEllipse(pen, _startPosX.Value + 88, _startPosY.Value + 65, 29, 23); g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 65, 29, 23);
g.DrawEllipse(pen, _startPosX.Value + 148, _startPosY.Value + 65, 29, 23); g.DrawEllipse(pen, _startPosX.Value + 111, _startPosY.Value + 65, 29, 23);
g.DrawEllipse(pen, _startPosX.Value + 128, _startPosY.Value + 73, 18, 15); g.DrawEllipse(pen, _startPosX.Value + 91, _startPosY.Value + 73, 18, 15);
g.DrawEllipse(pen, _startPosX.Value + 108, _startPosY.Value + 73, 18, 15); g.DrawEllipse(pen, _startPosX.Value + 71, _startPosY.Value + 73, 18, 15);
g.DrawEllipse(pen, _startPosX.Value + 88, _startPosY.Value + 73, 18, 15); g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 73, 18, 15);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 42, 85, 8);
g.DrawRectangle(pen, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12);
g.DrawRectangle(pen, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18);
g.DrawRectangle(pen, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5);
//танк //танк
Brush br = new SolidBrush(EntityTank.BodyColor); Brush br = new SolidBrush(EntityTank2.BodyColor);
g.FillRectangle(br, _startPosX.Value + 85, _startPosY.Value + 39, 55, 17); g.FillRectangle(br, _startPosX.Value + 48, _startPosY.Value + 39, 55, 17);
g.FillRectangle(br, _startPosX.Value + 49, _startPosY.Value + 56, 137, 13); g.FillRectangle(br, _startPosX.Value + 12, _startPosY.Value + 56, 137, 13);
Brush brDBlue = new SolidBrush(Color.DarkBlue); Brush brDBlue = new SolidBrush(Color.DarkBlue);
g.FillEllipse(brDBlue, _startPosX.Value + 37, _startPosY.Value + 59, 160, 35); g.FillEllipse(brDBlue, _startPosX.Value, _startPosY.Value + 59, 160, 35);
//гусеницы
Brush brBlue = new SolidBrush(Color.LightBlue); Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillEllipse(brBlue, _startPosX.Value + 56, _startPosY.Value + 65, 29, 23); g.FillEllipse(brBlue, _startPosX.Value + 19, _startPosY.Value + 65, 29, 23);
g.FillEllipse(brBlue, _startPosX.Value + 148, _startPosY.Value + 65, 29, 23); g.FillEllipse(brBlue, _startPosX.Value + 111, _startPosY.Value + 65, 29, 23);
g.FillEllipse(brBlue, _startPosX.Value + 128, _startPosY.Value + 73, 18, 15); g.FillEllipse(brBlue, _startPosX.Value + 91, _startPosY.Value + 73, 18, 15);
g.FillEllipse(brBlue, _startPosX.Value + 108, _startPosY.Value + 73, 18, 15); g.FillEllipse(brBlue, _startPosX.Value + 71, _startPosY.Value + 73, 18, 15);
g.FillEllipse(brBlue, _startPosX.Value + 88, _startPosY.Value + 73, 18, 15); g.FillEllipse(brBlue, _startPosX.Value + 51, _startPosY.Value + 73, 18, 15);
if (EntityTank.GunTurret)
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 42, 85, 8);
}
if (EntityTank.MachineGun)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12);
g.FillRectangle(additionalBrush, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18);
g.FillRectangle(additionalBrush, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5);
}
} }
} }

View File

@ -1,24 +1,16 @@
using System.Net.NetworkInformation; using ProjectTank.Entities;
namespace ProjectTank; namespace ProjectTank;
/// <summary> /// <summary>
/// Класс-сущность "Танк" /// Класс-сущность "Танк"
/// </summary> /// </summary>
public class EntityTank public class EntityTank : EntityTank2
{ {
/// <summary> public EntityTank(int speed, double weight, Color bodyColor) : base(speed, weight, bodyColor)
/// Скорость {
/// </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>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
@ -32,10 +24,6 @@ public class EntityTank
/// </summary> /// </summary>
public bool MachineGun { get; private set; } public bool MachineGun { get; private set; }
/// <summary> /// <summary>
/// Шаг перемещения танка
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля /// Инициализация полей объекта-класса спортивного автомобиля
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
@ -44,12 +32,10 @@ public class EntityTank
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="gunTurret">Признак наличия башни с орудием</param> /// <param name="gunTurret">Признак наличия башни с орудием</param>
/// <param name="machineGun">Признак наличия пулемёта</param> /// <param name="machineGun">Признак наличия пулемёта</param>
public void Init(int speed, double weight, Color bodyColor, Color public EntityTank(int speed, double weight, Color bodyColor, Color
additionalColor, bool gunTurret, bool machineGun) additionalColor, bool gunTurret, bool machineGun) : base(speed, weight, bodyColor)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
GunTurret = gunTurret; GunTurret = gunTurret;
MachineGun = machineGun; MachineGun = machineGun;
@ -59,7 +45,7 @@ public class MyClass
{ {
private int PrivateField; private int PrivateField;
public int PublicProperty {private get; set; } public int PublicProperty { private get; set; }
public void PublicMethod() public void PublicMethod()
{ {

View File

@ -0,0 +1,40 @@
namespace ProjectTank.Entities;
/// <summary>
/// Класс-сущность "Автомобиль"
/// </summary>
public class EntityTank2
{
/// <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 => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityTank2(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -1,4 +1,8 @@
namespace ProjectTank using static System.Net.Mime.MediaTypeNames;
using System.Windows.Forms;
using System.Xml.Linq;
namespace ProjectTank
{ {
partial class FormTank partial class FormTank
{ {
@ -29,11 +33,14 @@
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxTank = new PictureBox(); pictureBoxTank = new PictureBox();
buttonCreate = new Button(); buttonCreateTank = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonUp = new Button(); buttonCreateTank2 = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -42,42 +49,54 @@
pictureBoxTank.Dock = DockStyle.Fill; pictureBoxTank.Dock = DockStyle.Fill;
pictureBoxTank.Location = new Point(0, 0); pictureBoxTank.Location = new Point(0, 0);
pictureBoxTank.Name = "pictureBoxTank"; pictureBoxTank.Name = "pictureBoxTank";
pictureBoxTank.Size = new Size(800, 450); pictureBoxTank.Size = new Size(923, 597);
pictureBoxTank.TabIndex = 0; pictureBoxTank.TabIndex = 0;
pictureBoxTank.TabStop = false; pictureBoxTank.TabStop = false;
// //
// buttonCreate // buttonCreateTank
// //
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateTank.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 415); buttonCreateTank.Location = new Point(12, 562);
buttonCreate.Name = "buttonCreate"; buttonCreateTank.Name = "buttonCreateTank";
buttonCreate.Size = new Size(94, 29); buttonCreateTank.Size = new Size(223, 23);
buttonCreate.TabIndex = 1; buttonCreateTank.TabIndex = 1;
buttonCreate.Text = "Создать"; buttonCreateTank.Text = "Создать танк с пулемётом";
buttonCreate.UseVisualStyleBackColor = true; buttonCreateTank.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreateTank_Click; buttonCreateTank.Click += ButtonCreateTank_Click;
// //
// buttonLeft // buttonLeft
// //
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.Left; buttonLeft.BackgroundImage = Properties.Resources.Left;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(671, 409); buttonLeft.Location = new Point(787, 550);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35); buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2; buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true; buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click; buttonLeft.Click += ButtonMove_Click;
// //
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.Up;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(828, 509);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown // buttonDown
// //
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.Down; buttonDown.BackgroundImage = Properties.Resources.Down;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch; buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(712, 409); buttonDown.Location = new Point(828, 550);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35); buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 3; buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click; buttonDown.Click += ButtonMove_Click;
// //
@ -86,38 +105,60 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.Right; buttonRight.BackgroundImage = Properties.Resources.Right;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch; buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(753, 409); buttonRight.Location = new Point(869, 550);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35); buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 4; buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonUp // buttonCreateTank2
// //
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonCreateTank2.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonUp.BackgroundImage = Properties.Resources.Up; buttonCreateTank2.Location = new Point(250, 562);
buttonUp.BackgroundImageLayout = ImageLayout.Stretch; buttonCreateTank2.Name = "buttonCreateTank2";
buttonUp.Location = new Point(712, 368); buttonCreateTank2.Size = new Size(223, 23);
buttonUp.Name = "buttonUp"; buttonCreateTank2.TabIndex = 6;
buttonUp.Size = new Size(35, 35); buttonCreateTank2.Text = "Создать обычный танк";
buttonUp.TabIndex = 5; buttonCreateTank2.UseVisualStyleBackColor = true;
buttonUp.UseVisualStyleBackColor = true; buttonCreateTank2.Click += ButtonCreateTank2_Click;
buttonUp.Click += ButtonMove_Click; //
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(790, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(836, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
// //
// FormTank // FormTank
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450); ClientSize = new Size(923, 597);
Controls.Add(buttonUp); Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateTank2);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreate); Controls.Add(buttonCreateTank);
Controls.Add(pictureBoxTank); Controls.Add(pictureBoxTank);
Name = "FormTank"; Name = "FormTank";
Text = "Танк"; Text = "Танк с пулемётом";
((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit();
ResumeLayout(false); ResumeLayout(false);
} }
@ -125,10 +166,13 @@
#endregion #endregion
private PictureBox pictureBoxTank; private PictureBox pictureBoxTank;
private Button buttonCreate; private Button buttonCreateTank;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonUp; private Button buttonCreateTank2;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,10 +1,26 @@
namespace ProjectTank; using ProjectTank.Drawnings;
using ProjectTank.MovementStrategy;
namespace ProjectTank;
public partial class FormTank : Form public partial class FormTank : Form
{ {
private DrawningTank? _drawningTank; /// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningTank2? _drawningTank2;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormTank() public FormTank()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
@ -12,32 +28,59 @@ public partial class FormTank : Form
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawningTank == null) if (_drawningTank2 == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxTank.Width, pictureBoxTank.Height); Bitmap bmp = new(pictureBoxTank.Width, pictureBoxTank.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningTank.DrawTransport(gr); _drawningTank2.DrawTransport(gr);
pictureBoxTank.Image = bmp; pictureBoxTank.Image = bmp;
} }
/// <summary> /// <summary>
/// Обработка нажатия кнопки "Создать" /// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningTank2):
_drawningTank2 = new DrawningTank2(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningTank):
_drawningTank2 = new DrawningTank(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)));
break;
default:
return;
}
_drawningTank2.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height);
_drawningTank2.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать танк с пулемётом"
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCreateTank_Click(object sender, EventArgs e) private void ButtonCreateTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank));
{
Random random = new(); /// <summary>
_drawningTank = new DrawningTank(); /// Обработка нажатия кнопки "Создать обычный танк"
_drawningTank.Init(random.Next(100, 300), random.Next(1000, 3000), /// </summary>
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), /// <param name="sender"></param>
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), /// <param name="e"></param>
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); private void ButtonCreateTank2_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank2));
_drawningTank.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height);
_drawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary> /// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации) /// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary> /// </summary>
@ -45,36 +88,82 @@ public partial class FormTank : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawningTank == null) if (_drawningTank2 == null)
{ {
return; return;
} }
string name = ((Button)sender)?.Name ?? string.Empty; string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false; bool result = false;
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = result = _drawningTank2.MoveTransport(DirectionType.Up);
_drawningTank.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = result = _drawningTank2.MoveTransport(DirectionType.Down);
_drawningTank.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = result = _drawningTank2.MoveTransport(DirectionType.Left);
_drawningTank.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = result = _drawningTank2.MoveTransport(DirectionType.Right);
_drawningTank.MoveTransport(DirectionType.Right);
break; break;
} }
if (result) if (result)
{ {
Draw(); Draw();
} }
} }
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningTank2 == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTank2(_drawningTank2), pictureBoxTank.Width, pictureBoxTank.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
}
} }

View File

@ -0,0 +1,139 @@
namespace ProjectTank.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus 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 = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

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

View File

@ -0,0 +1,54 @@
using ProjectTank.MovementStrategy;
namespace ProjectTank.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder - GetStep() <= FieldWidth
&& objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder - GetStep() <= FieldHeight
&& objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

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

View File

@ -0,0 +1,63 @@
using ProjectTank.Drawnings;
namespace ProjectTank.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningCar
/// </summary>
public class MoveableTank2 : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// </summary>
private readonly DrawningTank2? _tank = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="tank">Объект класса DrawningCar</param>
public MoveableTank2(DrawningTank2 tank)
{
_tank = tank;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_tank == null || _tank.EntityTank2 == null || !_tank.GetPosX.HasValue || !_tank.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_tank.GetPosX.Value, _tank.GetPosY.Value, _tank.GetWidth, _tank.GetHeight);
}
}
public int GetStep => (int)(_tank?.EntityTank2?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_tank == null || _tank.EntityTank2 == null)
{
return false;
}
return _tank.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -1,21 +1,25 @@
namespace ProjectTank; namespace ProjectTank.MovementStrategy;
/// <summary> /// <summary>
/// Направление перемещения /// Направление перемещения
/// </summary> /// </summary>
public enum DirectionType public enum MovementDirection
{ {
/// <summary> /// <summary>
/// Вверх /// Вверх
/// </summary> /// </summary>
Up = 1, Up = 1,
/// <summary> /// <summary>
/// Вниз /// Вниз
/// </summary> /// </summary>
Down = 2, Down = 2,
/// <summary> /// <summary>
/// Влево /// Влево
/// </summary> /// </summary>
Left = 3, Left = 3,
/// <summary> /// <summary>
/// Вправо /// Вправо
/// </summary> /// </summary>

View File

@ -0,0 +1,72 @@
namespace ProjectTank.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
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,22 @@
namespace ProjectTank.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}