ПИбд-14 Бочкарёва Е. П. Лабораторная работа №2 #2

Closed
vettaql wants to merge 1 commits from Lab2 into Lab1
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>
public class DrawningTank
public class DrawningTank2
Review

Имя элемента проекта не соответствует указанному в задании

Имя элемента проекта не соответствует указанному в задании
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityTank? EntityTank { get; private set; }
public EntityTank2? EntityTank2 { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -19,39 +22,70 @@ public class DrawningTank
/// <summary>
/// Левая координата прорисовки танка
/// </summary>
private int? _startPosX;
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки танка
/// </summary>
private int? _startPosY;
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки танка
/// </summary>
private readonly int _drawningTankWidth = 200;
private readonly int _drawningTankWidth = 160;
/// <summary>
/// Высота прорисовки танка
/// </summary>
private readonly int _drawningTankHeight = 100;
private readonly int _drawningTankHeight = 94;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </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 void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool gunTurret, bool machineGun, bool v)
public int? GetPosY => _startPosY;
/// <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;
_pictureHeight = null;
_startPosX = 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>
/// Установка границ поля
@ -64,19 +98,16 @@ public class DrawningTank
if (_drawningTankWidth < width && _drawningTankHeight < height)
{
_pictureWidth = width; _pictureHeight = height;
{
if (_startPosX.HasValue&&_startPosY.HasValue)
{
if (_startPosX.HasValue && _startPosY.HasValue)
SetPosition(_startPosX.Value, _startPosY.Value);
}
return true;
}
return false;
return true;
}
return false;
}
/// <summary>
/// Установка позиции
@ -91,10 +122,11 @@ public class DrawningTank
{
return;
}
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;
} else
}
else
{
_startPosX = x;
_startPosY = y;
@ -108,7 +140,7 @@ public class DrawningTank
public bool MoveTransport(DirectionType direction)
{
if (EntityTank == null || !_startPosX.HasValue ||
if (EntityTank2 == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
@ -117,32 +149,32 @@ public class DrawningTank
{
//влево
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;
//вверх
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;
// вниз
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;
// вправо
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;
default:
@ -153,65 +185,45 @@ public class DrawningTank
/// Прорисовка объекта
/// </summary>
/// <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)
{
return;
}
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 + 49, _startPosY.Value + 56, 137, 13);
g.DrawRectangle(pen, _startPosX.Value + 48, _startPosY.Value + 39, 55, 17);
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 + 88, _startPosY.Value + 65, 29, 23);
g.DrawEllipse(pen, _startPosX.Value + 148, _startPosY.Value + 65, 29, 23);
g.DrawEllipse(pen, _startPosX.Value + 128, _startPosY.Value + 73, 18, 15);
g.DrawEllipse(pen, _startPosX.Value + 108, _startPosY.Value + 73, 18, 15);
g.DrawEllipse(pen, _startPosX.Value + 88, _startPosY.Value + 73, 18, 15);
g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 59, 160, 35);
g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 65, 29, 23);
g.DrawEllipse(pen, _startPosX.Value + 111, _startPosY.Value + 65, 29, 23);
g.DrawEllipse(pen, _startPosX.Value + 91, _startPosY.Value + 73, 18, 15);
g.DrawEllipse(pen, _startPosX.Value + 71, _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);
g.FillRectangle(br, _startPosX.Value + 85, _startPosY.Value + 39, 55, 17);
g.FillRectangle(br, _startPosX.Value + 49, _startPosY.Value + 56, 137, 13);
Brush br = new SolidBrush(EntityTank2.BodyColor);
g.FillRectangle(br, _startPosX.Value + 48, _startPosY.Value + 39, 55, 17);
g.FillRectangle(br, _startPosX.Value + 12, _startPosY.Value + 56, 137, 13);
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);
g.FillEllipse(brBlue, _startPosX.Value + 56, _startPosY.Value + 65, 29, 23);
g.FillEllipse(brBlue, _startPosX.Value + 148, _startPosY.Value + 65, 29, 23);
g.FillEllipse(brBlue, _startPosX.Value + 128, _startPosY.Value + 73, 18, 15);
g.FillEllipse(brBlue, _startPosX.Value + 108, _startPosY.Value + 73, 18, 15);
g.FillEllipse(brBlue, _startPosX.Value + 88, _startPosY.Value + 73, 18, 15);
g.FillEllipse(brBlue, _startPosX.Value + 19, _startPosY.Value + 65, 29, 23);
g.FillEllipse(brBlue, _startPosX.Value + 111, _startPosY.Value + 65, 29, 23);
g.FillEllipse(brBlue, _startPosX.Value + 91, _startPosY.Value + 73, 18, 15);
g.FillEllipse(brBlue, _startPosX.Value + 71, _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;
/// <summary>
/// Класс-сущность "Танк"
/// </summary>
public class EntityTank
public class EntityTank : 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; }
public EntityTank(int speed, double weight, Color bodyColor) : base(speed, weight, bodyColor)
{
}
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
@ -32,10 +24,6 @@ public class EntityTank
/// </summary>
public bool MachineGun { get; private set; }
/// <summary>
/// Шаг перемещения танка
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
/// <param name="speed">Скорость</param>
@ -44,12 +32,10 @@ public class EntityTank
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="gunTurret">Признак наличия башни с орудием</param>
/// <param name="machineGun">Признак наличия пулемёта</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool gunTurret, bool machineGun)
public EntityTank(int speed, double weight, Color bodyColor, Color
additionalColor, bool gunTurret, bool machineGun) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
GunTurret = gunTurret;
MachineGun = machineGun;
@ -59,7 +45,7 @@ public class MyClass
{
private int PrivateField;
public int PublicProperty {private get; set; }
public int PublicProperty { private get; set; }
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
{
@ -29,11 +33,14 @@
private void InitializeComponent()
{
pictureBoxTank = new PictureBox();
buttonCreate = new Button();
buttonCreateTank = new Button();
buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonCreateTank2 = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit();
SuspendLayout();
//
@ -42,42 +49,54 @@
pictureBoxTank.Dock = DockStyle.Fill;
pictureBoxTank.Location = new Point(0, 0);
pictureBoxTank.Name = "pictureBoxTank";
pictureBoxTank.Size = new Size(800, 450);
pictureBoxTank.Size = new Size(923, 597);
pictureBoxTank.TabIndex = 0;
pictureBoxTank.TabStop = false;
//
// buttonCreate
// buttonCreateTank
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 415);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreateTank_Click;
buttonCreateTank.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTank.Location = new Point(12, 562);
buttonCreateTank.Name = "buttonCreateTank";
buttonCreateTank.Size = new Size(223, 23);
buttonCreateTank.TabIndex = 1;
buttonCreateTank.Text = "Создать танк с пулемётом";
buttonCreateTank.UseVisualStyleBackColor = true;
buttonCreateTank.Click += ButtonCreateTank_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.Left;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(671, 409);
buttonLeft.Location = new Point(787, 550);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
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.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.Down;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(712, 409);
buttonDown.Location = new Point(828, 550);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 3;
buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
@ -86,38 +105,60 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.Right;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(753, 409);
buttonRight.Location = new Point(869, 550);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 4;
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonUp
// buttonCreateTank2
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.Up;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(712, 368);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 5;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
buttonCreateTank2.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTank2.Location = new Point(250, 562);
buttonCreateTank2.Name = "buttonCreateTank2";
buttonCreateTank2.Size = new Size(223, 23);
buttonCreateTank2.TabIndex = 6;
buttonCreateTank2.Text = "Создать обычный танк";
buttonCreateTank2.UseVisualStyleBackColor = true;
buttonCreateTank2.Click += ButtonCreateTank2_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
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonUp);
ClientSize = new Size(923, 597);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateTank2);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonCreate);
Controls.Add(buttonCreateTank);
Controls.Add(pictureBoxTank);
Name = "FormTank";
Text = "Танк";
Text = "Танк с пулемётом";
((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit();
ResumeLayout(false);
}
@ -125,10 +166,13 @@
#endregion
private PictureBox pictureBoxTank;
private Button buttonCreate;
private Button buttonCreateTank;
private Button buttonLeft;
private Button buttonUp;
private Button buttonDown;
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
{
private DrawningTank? _drawningTank;
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningTank2? _drawningTank2;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormTank()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
@ -12,32 +28,59 @@ public partial class FormTank : Form
/// </summary>
private void Draw()
{
if (_drawningTank == null)
if (_drawningTank2 == null)
{
return;
}
Bitmap bmp = new(pictureBoxTank.Width, pictureBoxTank.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningTank.DrawTransport(gr);
_drawningTank2.DrawTransport(gr);
pictureBoxTank.Image = bmp;
}
/// <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>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank));
/// <summary>
/// Обработка нажатия кнопки "Создать обычный танк"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTank_Click(object sender, EventArgs e)
{
Random random = new();
_drawningTank = new DrawningTank();
_drawningTank.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)), Convert.ToBoolean(random.Next(0, 2)));
_drawningTank.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height);
_drawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonCreateTank2_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank2));
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
@ -45,36 +88,82 @@ public partial class FormTank : Form
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningTank == null)
if (_drawningTank2 == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result =
_drawningTank.MoveTransport(DirectionType.Up);
result = _drawningTank2.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningTank.MoveTransport(DirectionType.Down);
result = _drawningTank2.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningTank.MoveTransport(DirectionType.Left);
result = _drawningTank2.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningTank.MoveTransport(DirectionType.Right);
result = _drawningTank2.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
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)
Review

Пустых методов быть не должно

Пустых методов быть не должно
{
}
}

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,23 +1,27 @@
namespace ProjectTank;
namespace ProjectTank.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

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
}