ISEbd-12 Khaliullov LabWork02 Simple #2

Closed
rakhaliullov wants to merge 3 commits from LabWork2 into LabWork1
17 changed files with 860 additions and 229 deletions

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
public enum DirectionType
{
Up = 1,
Down = 2,
Left = 3,
Right = 4,
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper.Drawnings;
public enum DirectionType
{
// Неизвестное направление
Unknow = -1,
// Вверх
Up = 1,
// Вниз
Down = 2,
// Влево
Left = 3,
// Вправо
Right = 4,
}

View File

@ -1,18 +1,16 @@
using System; using Stormtrooper.Entities;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq; using System.Linq;
using System.Reflection.Metadata;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms;
namespace Stormtrooper; namespace Stormtrooper.Drawnings;
public class DrawningStormtrooper
public class DrawningAircraft
{ {
// Класс-сущность // Класс-сущность
public EntityStormtrooper? EntityStormtrooper { get; private set; } // объявление public EntityAircraft? EntityAircraft { get; protected set; } // объявление 1
// Ширина окна // Ширина окна
@ -24,46 +22,70 @@ public class DrawningStormtrooper
// Левая координата прорисовки штурмовика // Левая координата прорисовки штурмовика
public int? _startPosX; protected int? _startPosX;
// Верхняя координата прорисовки автомобиля // Верхняя координата прорисовки автомобиля
public int? _startPosY; protected int? _startPosY;
// Ширина прорисовки штурмовика // Ширина прорисовки штурмовика
private readonly int _drawningStormtrooperWidth = 140; private readonly int _drawningAircraftWidth = 140;
// Высота прорисовки штурмовика // Высота прорисовки штурмовика
private readonly int _drawningStormtrooperHeight = 150; private readonly int _drawningAircraftHeight = 135;
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningAircraftWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningAircraftHeight;
// Инициализация свойств // Пустой конструктор
private DrawningAircraft()
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rocket">Признак наличия ракет</param>
/// <param name="bomb">Признак наличия бомбы</param>
/// <param name="wing">Признак наличия крыла</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool rocket, bool bomb, bool wing)
{ {
EntityStormtrooper = new EntityStormtrooper(); // инициализация
EntityStormtrooper.Init(speed, weight, bodyColor, additionalColor,rocket, bomb, wing);
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
_startPosX = null; _startPosX = null;
_startPosY = null; _startPosY = null;
} }
// Установка границ поля // Конструктор
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningAircraft(int speed, double weight, Color bodyColor) : this()
{
EntityAircraft = new EntityAircraft(speed, weight, bodyColor);
}
// Конструктор для наследников
/// <param name="drawningAircraftWidth">Ширина прорисовки штурмовика</param>
/// <param name="drawningAircraftHeight">Высота прорисовки штурмовика</param>
protected DrawningAircraft(int drawningAircraftWidth, int drawningAircraftHeight) : this()
{
_drawningAircraftWidth = drawningAircraftWidth;
_pictureHeight = drawningAircraftHeight;
}
/// Прорисовка объекта
/// <param name="g"></param>
/// // Установка границ поля
/// <param name="width">Ширина поля</param> /// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param> /// <param name="height">Высота поля</param>
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {
if (_drawningStormtrooperHeight > height || _drawningStormtrooperWidth > width) if (_drawningAircraftHeight > height || _drawningAircraftWidth > width)
{ {
return false; return false;
} }
@ -89,18 +111,18 @@ public class DrawningStormtrooper
return; return;
} }
if (x < 0 || x + _drawningStormtrooperWidth > _pictureWidth) if (x < 0 || x + _drawningAircraftWidth > _pictureWidth)
{ {
_startPosX = _pictureWidth - _drawningStormtrooperWidth; _startPosX = _pictureWidth - _drawningAircraftWidth;
} }
else else
{ {
_startPosX = x; _startPosX = x;
} }
if (y < 0 || y + _drawningStormtrooperHeight > _pictureHeight) if (y < 0 || y + _drawningAircraftHeight > _pictureHeight)
{ {
_startPosY = _pictureHeight - _drawningStormtrooperHeight; _startPosY = _pictureHeight - _drawningAircraftHeight;
} }
else else
{ {
@ -111,7 +133,7 @@ public class DrawningStormtrooper
// Изменение направления перемещения // Изменение направления перемещения
public bool MoveTransport(DirectionType direction) public bool MoveTransport(DirectionType direction)
{ {
if (EntityStormtrooper == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityAircraft == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return false; return false;
} }
@ -119,49 +141,46 @@ public class DrawningStormtrooper
{ {
//влево //влево
case DirectionType.Left: case DirectionType.Left:
if (_startPosX.Value - EntityStormtrooper.Step > 0) if (_startPosX.Value - EntityAircraft.Step > 0)
{ {
_startPosX -= (int)EntityStormtrooper.Step; _startPosX -= (int)EntityAircraft.Step;
} }
return true; return true;
//вверх //вверх
case DirectionType.Up: case DirectionType.Up:
if (_startPosY.Value - EntityStormtrooper.Step > 0) if (_startPosY.Value - EntityAircraft.Step > 0)
{ {
_startPosY -= (int)EntityStormtrooper.Step; _startPosY -= (int)EntityAircraft.Step;
} }
return true; return true;
// вправо // вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + EntityStormtrooper.Step + _drawningStormtrooperWidth < _pictureWidth) if (_startPosX.Value + EntityAircraft.Step + _drawningAircraftWidth < _pictureWidth)
{ {
_startPosX += (int)EntityStormtrooper.Step; _startPosX += (int)EntityAircraft.Step;
return true; return true;
} }
return true; return true;
//вниз //вниз
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + EntityStormtrooper.Step + _drawningStormtrooperHeight < _pictureHeight) if (_startPosY.Value + EntityAircraft.Step + _drawningAircraftHeight < _pictureHeight)
{ {
_startPosY += (int)EntityStormtrooper.Step; _startPosY += (int)EntityAircraft.Step;
} }
return true; return true;
default: default:
return false; return false;
} }
} }
/// Прорисовка объекта public virtual void DrawTransport(Graphics g)
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{ {
if (EntityStormtrooper == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityAircraft == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush bodyColorBrush = new SolidBrush(EntityStormtrooper.BodyColor); Brush bodyColorBrush = new SolidBrush(EntityAircraft.BodyColor);
Brush additionalBrush = new SolidBrush(EntityStormtrooper.AdditionalColor);
//нос штурмовика //нос штурмовика
Brush brBlack = new SolidBrush(Color.Black); Brush brBlack = new SolidBrush(Color.Black);
@ -206,44 +225,7 @@ public class DrawningStormtrooper
frontwings2[3].X = _startPosX.Value + 80; frontwings2[3].Y = _startPosY.Value + 80; frontwings2[3].X = _startPosX.Value + 80; frontwings2[3].Y = _startPosY.Value + 80;
g.FillPolygon(bodyColorBrush, frontwings2); g.FillPolygon(bodyColorBrush, frontwings2);
g.DrawPolygon(pen, frontwings2); g.DrawPolygon(pen, frontwings2);
//Ракеты штурмовика
if (EntityStormtrooper.Rocket)
{
Point[] rockets = new Point[3];
rockets[0].X = _startPosX.Value + 45; rockets[0].Y = _startPosY.Value + 20;
rockets[1].X = _startPosX.Value + 37; rockets[1].Y = _startPosY.Value + 22;
rockets[2].X = _startPosX.Value + 45; rockets[2].Y = _startPosY.Value + 25;
Point[] rockets2 = new Point[3];
rockets2[0].X = _startPosX.Value + 45; rockets2[0].Y = _startPosY.Value + 110;
rockets2[1].X = _startPosX.Value + 37; rockets2[1].Y = _startPosY.Value + 112;
rockets2[2].X = _startPosX.Value + 45; rockets2[2].Y = _startPosY.Value + 115;
g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 20, 15, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 110, 15, 5);
g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 20, 15, 5);
g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 110, 15, 5);
g.FillPolygon(bodyColorBrush, rockets);
g.DrawPolygon(pen, rockets);
g.FillPolygon(bodyColorBrush, rockets2);
g.DrawPolygon(pen, rockets2);
}
//Бомбы бомбардировщика
if (EntityStormtrooper.Bomb)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 40, 10, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 90, 10, 10);
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 40, 10, 10);
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 90, 10, 10);
}
} }
} }

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Stormtrooper.Entities;
namespace Stormtrooper.Drawnings;
public class DrawningStormtrooper : DrawningAircraft
{
// Конструктор
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rocket">Признак наличия ракет</param>
/// <param name="bomb">Признак наличия бомбы</param>
/// <param name="wing">Признак наличия крыла</param>
public DrawningStormtrooper(int speed, double weight, Color bodyColor, Color
additionalColor, bool rocket, bool bomb, bool wing) : base(140,135)
{
EntityAircraft = new EntityStormtrooper(speed, weight, bodyColor, additionalColor, rocket, bomb, wing);
}
public override void DrawTransport(Graphics g)
{
if (EntityAircraft == null || EntityAircraft is not EntityStormtrooper entityStormtrooper|| !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush bodyColorBrush = new SolidBrush(entityStormtrooper.BodyColor);
Brush additionalBrush = new SolidBrush(entityStormtrooper.AdditionalColor);
base.DrawTransport(g);
//Ракеты штурмовика
if (entityStormtrooper.Rocket)
{
Point[] rockets = new Point[3];
rockets[0].X = _startPosX.Value + 45; rockets[0].Y = _startPosY.Value + 20;
rockets[1].X = _startPosX.Value + 37; rockets[1].Y = _startPosY.Value + 22;
rockets[2].X = _startPosX.Value + 45; rockets[2].Y = _startPosY.Value + 25;
Point[] rockets2 = new Point[3];
rockets2[0].X = _startPosX.Value + 45; rockets2[0].Y = _startPosY.Value + 110;
rockets2[1].X = _startPosX.Value + 37; rockets2[1].Y = _startPosY.Value + 112;
rockets2[2].X = _startPosX.Value + 45; rockets2[2].Y = _startPosY.Value + 115;
g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 20, 15, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 45, _startPosY.Value + 110, 15, 5);
g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 20, 15, 5);
g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 110, 15, 5);
g.FillPolygon(bodyColorBrush, rockets);
g.DrawPolygon(pen, rockets);
g.FillPolygon(bodyColorBrush, rockets2);
g.DrawPolygon(pen, rockets2);
}
//Бомбы бомбардировщика
if (entityStormtrooper.Bomb)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 40, 10, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 50, _startPosY.Value + 90, 10, 10);
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 40, 10, 10);
g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 90, 10, 10);
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper.Entities;
// Класс-сущность "самолет"
public class EntityAircraft
{
public int Speed { get; private set; }
// скорость
public double Weight { get; private set; }
// вес
public Color BodyColor { get; private set; }
// цвет
public double Step => Speed * 100 / Weight;
// шаг в поле
/// Конструктор сущности
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес штурмовика</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityAircraft(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper.Entities;
public class EntityStormtrooper : EntityAircraft
{
public int Speed { get; private set; }
// скорость
public double Weight { get; private set; }
// вес
public Color BodyColor { get; private set; }
// цвет
public Color AdditionalColor { get; private set; }
// дополнительные цвета
public bool Rocket { get; private set; }
// ракета
public bool Bomb { get; private set; }
// бомба
public bool Wing { get; private set; }
// крыло
/// Инициализация полей объекта-класса штурмовика
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес штурмовика</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rocket">Признак наличия ракет</param>
/// <param name="bomb">Признак наличия бомб</param>
/// <param name="wing">Признак наличия крыла а</param>
public EntityStormtrooper(int speed, double weight, Color bodyColor, Color
additionalColor, bool rocket, bool bomb, bool wing) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Rocket = rocket;
Bomb = bomb;
Wing = wing;
}
}

View File

@ -1,50 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
public class EntityStormtrooper
{
public int Speed { get; private set; }
// скорость
public double Weight { get; private set; }
// вес
public Color BodyColor { get; private set; }
// цвет
public Color AdditionalColor { get; private set; }
// дополнительные цвета
public bool Rocket { get; private set; }
// ракета
public bool Bomb { get; private set; }
// бомба
public bool Wing { get; private set; }
// крыло
public double Step => Speed * 100 / Weight;
// шаг в поле
/// Инициализация полей объекта-класса штурмовика
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес штурмовика</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="rocket">Признак наличия ракет</param>
/// <param name="bomb">Признак наличия бомб</param>
/// <param name="wing">Признак наличия крыла а</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool rocket, bool bomb, bool wing)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Rocket = rocket;
Bomb = bomb;
Wing = wing;
}
}
}

View File

@ -34,6 +34,9 @@
buttonDown = new Button(); buttonDown = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreateAircraft = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -50,11 +53,11 @@
// buttonCreate // buttonCreate
// //
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 398); buttonCreate.Location = new Point(12, 395);
buttonCreate.Name = "buttonCreate"; buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29); buttonCreate.Size = new Size(205, 32);
buttonCreate.TabIndex = 1; buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать"; buttonCreate.Text = "Создать штурмовик";
buttonCreate.UseVisualStyleBackColor = true; buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click; buttonCreate.Click += ButtonCreate_Click;
// //
@ -106,11 +109,46 @@
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreateAircraft
//
buttonCreateAircraft.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAircraft.Location = new Point(239, 395);
buttonCreateAircraft.Name = "buttonCreateAircraft";
buttonCreateAircraft.Size = new Size(205, 32);
buttonCreateAircraft.TabIndex = 7;
buttonCreateAircraft.Text = "Создать самолет";
buttonCreateAircraft.UseVisualStyleBackColor = true;
buttonCreateAircraft.Click += buttonCreateAircraft_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(610, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 8;
comboBoxStrategy.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(667, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 9;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormStormtrooper // FormStormtrooper
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(773, 439); ClientSize = new Size(773, 439);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateAircraft);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonDown); Controls.Add(buttonDown);
@ -133,5 +171,8 @@
private Button buttonDown; private Button buttonDown;
private Button buttonLeft; private Button buttonLeft;
private Button buttonRight; private Button buttonRight;
private Button buttonCreateAircraft;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -7,89 +7,158 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Aircraft.MovementStrategy;
using Stormtrooper.Drawnings;
using Stormtrooper.MovementStrategy;
namespace Stormtrooper namespace Stormtrooper;
public partial class FormStormtrooper : Form
{ {
public partial class FormStormtrooper : Form // Поле объект для прорисовки объекта
public DrawningAircraft? _drawningAircraft;
// Стратегия перемещения
private AbstractStrategy? _strategy;
// Конструктор формы
public FormStormtrooper()
{ {
// Поле объект для прорисовки объекта InitializeComponent();
public DrawningStormtrooper? _drawningStormtrooper; _strategy = null;
// Конструктор формы }
public FormStormtrooper()
{
InitializeComponent();
}
// Метод прорисовки машины // Метод прорисовки машины
private void FormStormtrooper_Load(object sender, EventArgs e) private void FormStormtrooper_Load(object sender, EventArgs e)
{ {
} }
/// <summary>
// Обработка нажатия кнопки Создать /// Создание объекта класса-перемещения
private void ButtonCreate_Click(object sender, EventArgs e) /// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{ {
Random random = new(); case nameof(DrawningAircraft):
_drawningStormtrooper = new DrawningStormtrooper(); _drawningAircraft = new DrawningAircraft(random.Next(100,
_drawningStormtrooper.Init(random.Next(100, 300), random.Next(1000, 3000), 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)));
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), break;
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); case nameof(DrawningStormtrooper):
_drawningStormtrooper.SetPictureSize(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height); _drawningAircraft = new DrawningStormtrooper(random.Next(100, 300), random.Next(1000, 3000),
_drawningStormtrooper.SetPosition(random.Next(10, 100), random.Next(10, 100)); 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)),
Bitmap bmp = new(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height); Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
Graphics gr = Graphics.FromImage(bmp); break;
_drawningStormtrooper.DrawTransport(gr); default:
pictureBoxStormtrooper.Image = bmp;
}
private void Draw()
{
if (_drawningStormtrooper == null)
{
return; return;
}
Bitmap bmp = new(pictureBoxStormtrooper.Width,
pictureBoxStormtrooper.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningStormtrooper.DrawTransport(gr);
pictureBoxStormtrooper.Image = bmp;
} }
private void ButtonMove_Click(object sender, EventArgs e) _drawningAircraft.SetPictureSize(pictureBoxStormtrooper.Width,
pictureBoxStormtrooper.Height);
_drawningAircraft.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
Draw();
}
// Обработка нажатия кнопки Создать штурмовик
private void ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningStormtrooper));
// Обработка нажатия кнопки Создать самолет
private void buttonCreateAircraft_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningAircraft));
// Прорисовка
private void Draw()
{
if (_drawningAircraft == null)
{ {
if (_drawningStormtrooper == null) return;
{ }
return; Bitmap bmp = new(pictureBoxStormtrooper.Width,
} pictureBoxStormtrooper.Height);
Graphics gr = Graphics.FromImage(bmp);
string name = ((Button)sender)?.Name ?? string.Empty; _drawningAircraft.DrawTransport(gr);
bool result = false; pictureBoxStormtrooper.Image = bmp;
switch (name) }
{ // Перемещение объекта по форме
case "buttonUp": private void ButtonMove_Click(object sender, EventArgs e)
result = _drawningStormtrooper.MoveTransport(DirectionType.Up); {
break; if (_drawningAircraft == null)
case "buttonDown": {
result = _drawningStormtrooper.MoveTransport(DirectionType.Down); return;
break;
case "buttonLeft":
result = _drawningStormtrooper.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningStormtrooper.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
} }
private void pictureBoxStormtrooper_Click(object sender, EventArgs e) string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{ {
case "buttonUp":
result = _drawningAircraft.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningAircraft.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningAircraft.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningAircraft.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
} }
} }
private void pictureBoxStormtrooper_Click(object sender, EventArgs e)
Review

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

Пустых методов быть не должно
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningAircraft == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableAircraft(_drawningAircraft), pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
} }

View File

@ -0,0 +1,121 @@
namespace Stormtrooper.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,22 @@
namespace Stormtrooper.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,52 @@
namespace Stormtrooper.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта к краю экрана
/// </summary>
internal 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.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,52 @@
namespace Stormtrooper.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
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,62 @@
using Stormtrooper.Drawnings;
using Stormtrooper.MovementStrategy;
namespace Aircraft.MovementStrategy;
/// <summary>
/// класс реализация для IMoveableObject с использованием DrawningAircraft
/// </summary>
public class MoveableAircraft : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningAircraft или его наследника
/// </summary>
private readonly DrawningAircraft? _cruiser = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="cruiser">Объект класса DrawningAircraft</param>
public MoveableAircraft(DrawningAircraft cruiser)
{
_cruiser = cruiser;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_cruiser == null || _cruiser.EntityAircraft == null ||
!_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_cruiser.GetPosX.Value,
_cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight);
}
}
public int GetStep => (int)(_cruiser?.EntityAircraft?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_cruiser == null || _cruiser.EntityAircraft == null)
{
return false;
}
return _cruiser.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

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,64 @@
namespace Stormtrooper.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,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}