SemesterFirstLabSecondBomberBase

This commit is contained in:
VanyaAlekseev 2023-10-14 19:05:33 +04:00
parent b27e94da30
commit 35feab6891
14 changed files with 738 additions and 95 deletions

View File

@ -0,0 +1,133 @@
using ProjectBomber.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBomber.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false -неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectBomber.Entities;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
@ -6,14 +7,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBomber
namespace ProjectBomber.DrawningObjects
{
internal class DrawningBomber
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningBomber
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBomber EntityBomber { get; private set; }
public EntityBomber EntityBomber { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -25,47 +29,114 @@ namespace ProjectBomber
/// <summary>
/// Левая координата прорисовки бомбардировщика
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки бомбардировщика
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки бомбардировщика
/// </summary>
private int _bomberWidth = 50;
protected readonly int _bomberWidth = 60;
/// <summary>
/// Высота прорисовки бомбардировщика
/// </summary>
private int _bomberHeight = 110;
protected readonly int _bomberHeight = 55;
/// <summary>
/// Инициализация свойств
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет крыльев</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="fuelTanks">Признак наличия топливных баков</param>
/// <param name="line">Признак наличия полосы</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks, bool line, int width, int height, int bomberwidth, int bomberheight)
public DrawningBomber(int speed, double weight, Color bodyColor, int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
_bomberWidth = bomberwidth;
_bomberHeight = bomberheight;
EntityBomber = new EntityBomber();
EntityBomber.Init(speed, weight, bodyColor, additionalColor, bombs, fuelTanks, line);
EntityBomber = new EntityBomber(speed, weight, bodyColor);
if ((_bomberWidth >= _pictureWidth) || (_bomberHeight >= _pictureHeight))
{
Console.WriteLine("Объект не прошел проверку");
Console.WriteLine("Проверка не пройдена, нельзя создать объект в этих размерах");
if (_bomberWidth >= _pictureWidth)
{
_bomberWidth = _pictureWidth - _bomberWidth;
}
if (_bomberHeight >= _pictureHeight)
{
_bomberHeight = _pictureHeight - _bomberHeight;
}
}
else
{
Console.WriteLine("Объект создан");
}
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="bomberWidth">Ширина прорисовки бомбардировщика</param>
/// <param name="bomberHeight">Высота прорисовки бомбардировщика</param>
protected DrawningBomber(int speed, double weight, Color bodyColor, int width, int height, int bomberWidth, int bomberHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_bomberWidth = bomberWidth;
_bomberHeight = bomberHeight;
EntityBomber = new EntityBomber(speed, weight, bodyColor);
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _bomberWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _bomberHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityBomber == null)
{
return false;
}
return true;
if (direction == DirectionType.Left)
{
return _startPosX - EntityBomber.Step > 0;
}
else if (direction == DirectionType.Up)
{
return _startPosY - EntityBomber.Step > 0;
}
else if (direction == DirectionType.Down)
{
return _startPosY + EntityBomber.Step < _pictureHeight;
}
else if (direction == DirectionType.Right)
{
return _startPosX + EntityBomber.Step < _pictureWidth;
}
return false; // Возвращаем false в случае неподдерживаемого направления
}
/// <summary>
/// Установка позиции
/// </summary>
@ -73,6 +144,7 @@ namespace ProjectBomber
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
// TODO: Изменение x, y, если при установке объект выходит за границы
_startPosX = x;
_startPosY = y;
// если выходит за границы, возвращаем на форму
@ -135,25 +207,14 @@ namespace ProjectBomber
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityBomber == null)
{
return;
}
Pen pen = new Pen(Color.Black);
Brush additionalBrush = new SolidBrush(EntityBomber.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityBomber.BodyColor);
// Бомбы
if (EntityBomber.Bombs)
{
g.FillRectangle(additionalBrush, _startPosX + 15, _startPosY + 18, 18, 4);
g.FillRectangle(additionalBrush, _startPosX + 15, _startPosY + 48, 18, 4);
}
// крыло 1
GraphicsPath path = new GraphicsPath();
path.StartFigure();
@ -212,17 +273,6 @@ namespace ProjectBomber
g.FillPath(brOrange, path1);
// Рисуем контур линии
g.DrawPath(pen, path1);
// баки с топливом
if (EntityBomber.FuelTanks)
{
g.FillRectangle(additionalBrush, _startPosX + 40, _startPosY + 28, 10, 3);
g.FillRectangle(additionalBrush, _startPosX + 40, _startPosY + 40, 10, 3);
}
// линия
if (EntityBomber.Line)
{
g.FillRectangle(additionalBrush, _startPosX + 10, _startPosY + 34, 50, 2);
}
}
}
}

View File

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBomber.Entities;
namespace ProjectBomber.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningBomberAdvanced : DrawningBomber
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия обвеса</param>
/// <param name="fuelTanks">Признак наличия антикрыла</param>
/// <param name="line">Признак наличия гоночной полосы</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningBomberAdvanced(int speed, double weight, Color bodyColor, Color
additionalColor, bool bombs, bool fuelTanks, bool line, int width, int height) :
base(speed, weight, bodyColor, width, height, 60, 60)
{
if (EntityBomber != null)
{
EntityBomber = new EntityBomberAdvanced(speed, weight, bodyColor,
additionalColor, bombs, fuelTanks, line);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityBomber is EntityBomberAdvanced bomber)
{
Pen pen = new Pen(Color.Black);
Brush additionalBrush = new SolidBrush(bomber.AdditionalColor);
// Бомбы
if (bomber.Bombs)
{
g.FillRectangle(additionalBrush, _startPosX + 15, _startPosY + 18, 18, 4);
g.FillRectangle(additionalBrush, _startPosX + 15, _startPosY + 48, 18, 4);
}
base.DrawTransport(g);
// баки с топливом
if (bomber.FuelTanks)
{
g.FillRectangle(additionalBrush, _startPosX + 40, _startPosY + 28, 10, 3);
g.FillRectangle(additionalBrush, _startPosX + 40, _startPosY + 40, 10, 3);
}
// линия
if (bomber.Line)
{
g.FillRectangle(additionalBrush, _startPosX + 10, _startPosY + 34, 50, 2);
}
}
}
}
}

View File

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

View File

@ -5,9 +5,12 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBomber
namespace ProjectBomber.Entities
{
internal class EntityBomber
/// <summary>
/// Класс-сущность "Бомбардировщик"
/// </summary>
public class EntityBomber
{
/// <summary>
/// Скорость
@ -22,45 +25,20 @@ namespace ProjectBomber
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
/// <summary>
/// Признак (опция) наличия топливных баков
/// </summary>
public bool FuelTanks { get; private set; }
/// <summary>
/// Признак (опция) наличия воздушного пространства
/// </summary>
public bool Line { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес бомбардировщика</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="fuelTanks">Признак наличия топливных баков</param>
/// <param name="line">Признак наличия линии</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool bombs, bool fuelTanks, bool line)
public EntityBomber(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Bombs = bombs;
FuelTanks = fuelTanks;
Line = line;
}
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBomber.Entities;
namespace ProjectBomber.Entities
{
/// <summary>
/// Класс-сущность "Бомбардировщик"
/// </summary>
public class EntityBomberAdvanced : EntityBomber
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
/// <summary>
/// Признак (опция) наличия топливных баков
/// </summary>
public bool FuelTanks { get; private set; }
/// <summary>
/// Признак (опция) наличия полосы
/// </summary>
public bool Line { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="fuelTanks">Признак наличия топливных баков</param>
/// <param name="line">Признак наличия полосы</param>
public EntityBomberAdvanced(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks, bool line):
base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Bombs = bombs;
FuelTanks = fuelTanks;
Line = line;
}
}
}

View File

@ -30,11 +30,14 @@
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBomber));
this.pictureBoxBomber = new System.Windows.Forms.PictureBox();
this.buttonCreate = new System.Windows.Forms.Button();
this.ButtonCreateBomber = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.comboBox1Strategy = new System.Windows.Forms.ComboBox();
this.ButtonCreatePlane = new System.Windows.Forms.Button();
this.ButtonStep = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxBomber)).BeginInit();
this.SuspendLayout();
//
@ -48,16 +51,16 @@
this.pictureBoxBomber.TabIndex = 0;
this.pictureBoxBomber.TabStop = false;
//
// buttonCreate
// ButtonCreateBomber
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(12, 422);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(87, 27);
this.buttonCreate.TabIndex = 2;
this.buttonCreate.Text = "Создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
this.ButtonCreateBomber.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ButtonCreateBomber.Location = new System.Drawing.Point(12, 421);
this.ButtonCreateBomber.Name = "ButtonCreateBomber";
this.ButtonCreateBomber.Size = new System.Drawing.Size(150, 27);
this.ButtonCreateBomber.TabIndex = 2;
this.ButtonCreateBomber.Text = "Создать бомбардировщик";
this.ButtonCreateBomber.UseVisualStyleBackColor = true;
this.ButtonCreateBomber.Click += new System.EventHandler(this.ButtonCreateBomber_Click);
//
// buttonUp
//
@ -107,15 +110,50 @@
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// comboBox1Strategy
//
this.comboBox1Strategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1Strategy.FormattingEnabled = true;
this.comboBox1Strategy.Items.AddRange(new object[] {
"_abstractStrategy",
"_MyabstractStrategy"});
this.comboBox1Strategy.Location = new System.Drawing.Point(712, 12);
this.comboBox1Strategy.Name = "comboBox1Strategy";
this.comboBox1Strategy.Size = new System.Drawing.Size(150, 21);
this.comboBox1Strategy.TabIndex = 8;
//
// ButtonCreatePlane
//
this.ButtonCreatePlane.Location = new System.Drawing.Point(168, 421);
this.ButtonCreatePlane.Name = "ButtonCreatePlane";
this.ButtonCreatePlane.Size = new System.Drawing.Size(121, 27);
this.ButtonCreatePlane.TabIndex = 9;
this.ButtonCreatePlane.Text = "Создать самолет";
this.ButtonCreatePlane.UseVisualStyleBackColor = true;
this.ButtonCreatePlane.Click += new System.EventHandler(this.ButtonCreatePlane_Click);
//
// ButtonStep
//
this.ButtonStep.Location = new System.Drawing.Point(712, 39);
this.ButtonStep.Name = "ButtonStep";
this.ButtonStep.Size = new System.Drawing.Size(150, 22);
this.ButtonStep.TabIndex = 10;
this.ButtonStep.Text = "Шаг";
this.ButtonStep.UseVisualStyleBackColor = true;
this.ButtonStep.Click += new System.EventHandler(this.ButtonStep_Click);
//
// FormBomber
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
this.ClientSize = new System.Drawing.Size(884, 461);
this.Controls.Add(this.ButtonStep);
this.Controls.Add(this.ButtonCreatePlane);
this.Controls.Add(this.comboBox1Strategy);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.ButtonCreateBomber);
this.Controls.Add(this.pictureBoxBomber);
this.Name = "FormBomber";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
@ -129,11 +167,14 @@
#endregion
private System.Windows.Forms.PictureBox pictureBoxBomber;
private System.Windows.Forms.Button buttonCreate;
private System.Windows.Forms.Button ButtonCreateBomber;
private System.Windows.Forms.Button buttonUp;
private System.Windows.Forms.Button buttonLeft;
private System.Windows.Forms.Button buttonDown;
private System.Windows.Forms.Button buttonRight;
private System.Windows.Forms.ComboBox comboBox1Strategy;
private System.Windows.Forms.Button ButtonCreatePlane;
private System.Windows.Forms.Button ButtonStep;
}
}

View File

@ -1,4 +1,6 @@
using System;
using ProjectBomber.DrawningObjects;
using ProjectBomber.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -12,7 +14,14 @@ namespace ProjectBomber
{
public partial class FormBomber : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningBomber _drawningBomber;
/// <summary>
/// Стратегии перемещения
/// </summary>
private AbstractStrategy _abstractStrategy;
public FormBomber()
{
InitializeComponent();
@ -29,20 +38,32 @@ namespace ProjectBomber
pictureBoxBomber.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать бомбардировщик"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
private void ButtonCreateBomber_Click(object sender, EventArgs e)
{
Random random = new Random();
_drawningBomber = new DrawningBomber();
_drawningBomber.Init(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
_drawningBomber = new DrawningBomberAdvanced(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)),
pictureBoxBomber.Width, pictureBoxBomber.Height, 60, 70);
_drawningBomber.SetPosition(random.Next(0, 50),
random.Next(0, 50));
pictureBoxBomber.Width, pictureBoxBomber.Height);
_drawningBomber.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать самолёт"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreatePlane_Click(object sender, EventArgs e)
{
Random random = new Random();
_drawningBomber = new DrawningBomber(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)), pictureBoxBomber.Width, pictureBoxBomber.Height);
_drawningBomber.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
@ -74,5 +95,42 @@ namespace ProjectBomber
}
Draw();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningBomber == null)
{
return;
}
if (comboBox1Strategy.Enabled)
{
int selectedIndex = comboBox1Strategy.SelectedIndex;
if (selectedIndex == 0)
{
_abstractStrategy = new MoveToCenter();
}
else if (selectedIndex == 1)
{
_abstractStrategy = new MoveToBottomRight();
}
if (_abstractStrategy != null)
{
_abstractStrategy.SetData(new DrawningObjectBomber(_drawningBomber), pictureBoxBomber.Width, pictureBoxBomber.Height);
comboBox1Strategy.Enabled = false;
}
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBox1Strategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

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

View File

@ -0,0 +1,43 @@
using ProjectBomber.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBomber
{
public class MoveToBottomRight : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = FieldWidth - objParams.RightBorder;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
var diffY = FieldHeight - objParams.DownBorder;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBomber.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBomber.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -46,17 +46,26 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AbstractStrategy.cs" />
<Compile Include="Direction.cs" />
<Compile Include="DrawningBomber.cs" />
<Compile Include="DrawningBomberAdvanced.cs" />
<Compile Include="DrawningObjectBomber.cs" />
<Compile Include="EntityBomber.cs" />
<Compile Include="EntityBomberAdvanced.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="IMoveableObject.cs" />
<Compile Include="MoveToBottomRight.cs" />
<Compile Include="MoveToCenter.cs" />
<Compile Include="ObjectParameters.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Status.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBomber.MovementStrategy
{
public enum Status
{
/// <summary>
/// Вверх
/// </summary>
NotInit = 1,
/// <summary>
/// Вниз
/// </summary>
InProgress = 2,
/// <summary>
/// Влево
/// </summary>
Finish = 3
}
}