ЛабораторнаяДва

This commit is contained in:
Леонид Малафеев 2023-09-25 14:09:42 +04:00
parent 8b84170cd0
commit 08e784d05a
13 changed files with 682 additions and 105 deletions

View File

@ -1,17 +1,18 @@
using System; using Cruiser.Entities;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Cruiser namespace Cruiser.Drawing
{ {
public class DrawingCruiser public class DrawingCruiser
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityCruiser? EntityCruiser { get; private set; } public EntityCruiser? EntityCruiser { get; set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
/// </summary> /// </summary>
@ -23,11 +24,11 @@ namespace Cruiser
/// <summary> /// <summary>
/// Левая координата прорисовки Крейсера /// Левая координата прорисовки Крейсера
/// </summary> /// </summary>
private static int _startPosX; protected static int _startPosX;
/// <summary> /// <summary>
/// Верхняя кооридната прорисовки Крейсера /// Верхняя кооридната прорисовки Крейсера
/// </summary> /// </summary>
private static int _startPosY; protected static int _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки Крейсера /// Ширина прорисовки Крейсера
/// </summary> /// </summary>
@ -37,40 +38,31 @@ namespace Cruiser
/// </summary> /// </summary>
private readonly int _cruiserHeight = 60; private readonly int _cruiserHeight = 60;
/// <summary> /// <summary>
/// Цвет для палубы /// Координата X объекта
/// </summary> /// </summary>
public Color PalubaColor { get; private set; } public int GetPosX => _startPosX;
/// <summary> /// <summary>
/// Цвет для элементов /// Координата Y объекта
/// </summary> /// </summary>
public Color ElementsColor { get; private set; } public int GetPosY => _startPosY;
/// <summary> /// <summary>
/// Цвет для дополнений /// Ширина объекта
/// </summary> /// </summary>
public Color DopColor { get; private set; } public int GetWidth => _cruiserWidth;
/// <summary> /// <summary>
/// Шахты /// Высота объекта
/// </summary> /// </summary>
public bool Mines { get; private set; } public int GetHeight => _cruiserHeight;
/// <summary> /// <summary>
/// Верт. площадка /// Конструктор
/// </summary>
public bool HelicopPad { get; private set; }
/// <summary>
/// Инициализация свойств
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param> /// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
/// <param name="secColor">Элементов цвет</param> /// <param name="secColor">Элементов цвет</param>
/// <param name="dopColor">Дополнений цвет</param>
/// <param name="rocketMines">Признак наличия ракетных шахт</param>
/// <param name="helipad">Признак наличия вертолётной площадки</param>
/// <param name="width">Ширина картинки</param> /// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param> /// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, public DrawingCruiser(int speed, double weight, Color bodyColor, Color secColor, int width, int height)
///нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color secColor, Color dopColor, bool rocketMines, bool helipad, int width, int height)
{ {
if (width < _cruiserWidth || height < _cruiserHeight) if (width < _cruiserWidth || height < _cruiserHeight)
{ {
@ -79,14 +71,26 @@ namespace Cruiser
} }
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
PalubaColor = bodyColor; EntityCruiser = new EntityCruiser(speed, weight, bodyColor, secColor);
ElementsColor = secColor; }
DopColor = dopColor; /// <summary>
Mines = rocketMines; /// Конструктор
HelicopPad = helipad; /// </summary>
EntityCruiser = new EntityCruiser(); /// <param name="speed">Скорость</param>
EntityCruiser.Init(speed, weight, bodyColor, secColor, rocketMines, helipad); /// <param name="weight">Вес автомобиля</param>
return true; /// <param name="bodyColor">Основной цвет</param>
/// <param name="secColor">Элементов цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="cruiserWidth">Ширина прорисовки крейсера</param>
/// <param name="cruiserHeight">Высота прорисовки крейсера</param>
public DrawingCruiser(int speed, double weight, Color bodyColor, Color secColor, int width, int height, int cruiserWidth, int cruiserHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_cruiserHeight = cruiserHeight;
_cruiserWidth = cruiserWidth;
EntityCruiser = new EntityCruiser(speed, weight, bodyColor, secColor);
} }
/// <summary> /// <summary>
/// Установка позиции /// Установка позиции
@ -107,12 +111,35 @@ namespace Cruiser
_startPosY = y; _startPosY = y;
} }
/// <summary> /// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(Direction direction)
{
if (EntityCruiser == null)
{
return false;
}
return direction switch
{
//влево
Direction.Left => _startPosX - EntityCruiser.Step > 0,
//вверх
Direction.Up => _startPosY - EntityCruiser.Step > 0,
// вправо
Direction.Right => _startPosX + EntityCruiser.Step + _cruiserWidth < _pictureWidth,
//вниз
Direction.Down => _startPosY + EntityCruiser.Step + _cruiserHeight < _pictureHeight,
};
}
/// <summary>
/// Изменение направления перемещения /// Изменение направления перемещения
/// </summary> /// </summary>
/// <param name="direction">Направление</param> /// <param name="direction">Направление</param>
public void MoveTransport(Direction direction) public void MoveTransport(Direction direction)
{ {
if (EntityCruiser == null) if (!CanMove(direction) || EntityCruiser == null)
{ {
return; return;
} }
@ -120,41 +147,30 @@ namespace Cruiser
{ {
//влево //влево
case Direction.Left: case Direction.Left:
if (_startPosX - EntityCruiser.Step > 0)
{
_startPosX -= (int)EntityCruiser.Step; _startPosX -= (int)EntityCruiser.Step;
}
break; break;
//вверх //вверх
case Direction.Up: case Direction.Up:
if (_startPosY - EntityCruiser.Step > 0)
{
_startPosY -= (int)EntityCruiser.Step; _startPosY -= (int)EntityCruiser.Step;
}
break; break;
// вправо // вправо
case Direction.Right: case Direction.Right:
if (_startPosX + EntityCruiser.Step < _pictureWidth - _cruiserWidth)
{
_startPosX += (int)EntityCruiser.Step; _startPosX += (int)EntityCruiser.Step;
}
break; break;
//вниз //вниз
case Direction.Down: case Direction.Down:
if (_startPosY + EntityCruiser.Step < _pictureHeight - _cruiserHeight)
{
_startPosY += (int)EntityCruiser.Step; _startPosY += (int)EntityCruiser.Step;
}
break; break;
} }
} }
/// <summary> /// <summary>
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
public void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntityCruiser == null) if (EntityCruiser == null)
{ {
@ -169,7 +185,7 @@ namespace Cruiser
new Point(_startPosX + 110,_startPosY + 60), new Point(_startPosX + 110,_startPosY + 60),
new Point(_startPosX + 10,_startPosY + 60) new Point(_startPosX + 10,_startPosY + 60)
}; };
Brush brush = new SolidBrush(PalubaColor); Brush brush = new SolidBrush(EntityCruiser.BodyColor);
g.FillPolygon(brush, Paluba); g.FillPolygon(brush, Paluba);
// элементы // элементы
Point[] Elements = new Point[8] Point[] Elements = new Point[8]
@ -183,27 +199,13 @@ namespace Cruiser
new Point(_startPosX + 70,_startPosY + 40), new Point(_startPosX + 70,_startPosY + 40),
new Point(_startPosX + 50,_startPosY + 40), new Point(_startPosX + 50,_startPosY + 40),
}; };
Brush brushElem = new SolidBrush(ElementsColor); Brush brushElem = new SolidBrush(EntityCruiser.SecondColor);
g.FillPolygon(brushElem, Elements); g.FillPolygon(brushElem, Elements);
g.FillEllipse(brushElem, _startPosX + 100, _startPosY + 20, 20, 20); g.FillEllipse(brushElem, _startPosX + 100, _startPosY + 20, 20, 20);
// турбины // турбины
Brush Turbins = new SolidBrush(Color.Black); Brush Turbins = new SolidBrush(Color.Black);
g.FillRectangle(Turbins, _startPosX, _startPosY + 10, 10, 20); g.FillRectangle(Turbins, _startPosX, _startPosY + 10, 10, 20);
g.FillRectangle(Turbins, _startPosX, _startPosY + 35, 10, 20); g.FillRectangle(Turbins, _startPosX, _startPosY + 35, 10, 20);
// шахты
if (Mines)
{
Brush DopBrush = new SolidBrush(DopColor);
g.FillRectangle(DopBrush, _startPosX + 15, _startPosY + 10, 10, 15);
g.FillRectangle(DopBrush, _startPosX + 30, _startPosY + 10, 10, 15);
} }
// верт площадка
if (HelicopPad)
{
Brush DopBrush = new SolidBrush(DopColor);
g.FillEllipse(DopBrush, _startPosX + 15, _startPosY + 25, 25, 25);
}
}
} }
} }

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Entities;
namespace Cruiser.Drawing
{
public class DrawingProCruiser : DrawingCruiser
{
public DrawingProCruiser(int speed, double weight, Color bodyColor, Color secColor, Color elemColor, bool rocketMines, bool helipad, int width, int height) :
base (speed, weight, bodyColor, secColor, width, height, 150, 60)
{
if (EntityCruiser != null)
{
EntityCruiser = new EntityProCruiser(speed, weight, bodyColor, secColor, elemColor, rocketMines, helipad);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityCruiser is not EntityProCruiser cruiser)
{
return;
}
base.DrawTransport(g);
Brush DopBrush = new SolidBrush(cruiser.ElementsColor);
// шахты
if (cruiser.RocketMines)
{
g.FillRectangle(DopBrush, _startPosX + 15, _startPosY + 10, 10, 15);
g.FillRectangle(DopBrush, _startPosX + 30, _startPosY + 10, 10, 15);
}
// верт площадка
if (cruiser.Helipad)
{
g.FillEllipse(DopBrush, _startPosX + 15, _startPosY + 25, 25, 25);
}
}
}
}

View File

@ -4,8 +4,11 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Cruiser namespace Cruiser.Entities
{ {
/// <summary>
/// Класс-сущность "Крейсер"
/// </summary>
public class EntityCruiser public class EntityCruiser
{ {
/// <summary> /// <summary>
@ -25,14 +28,6 @@ namespace Cruiser
/// </summary> /// </summary>
public Color SecondColor { get; private set; } public Color SecondColor { get; private set; }
/// <summary> /// <summary>
/// Признак (опция) наличия ракетных шахт
/// </summary>
public bool RocketMines { get; private set; }
/// <summary>
/// Признак (опция) наличия вертолётной площадки
/// </summary>
public bool Helipad { get; private set; }
/// <summary>
/// Шаг перемещения Крейсера /// Шаг перемещения Крейсера
/// </summary> /// </summary>
public double Step => (double)Speed * 100 / Weight; public double Step => (double)Speed * 100 / Weight;
@ -40,16 +35,12 @@ namespace Cruiser
/// <param name="weight">Вес Крейсера</param> /// <param name="weight">Вес Крейсера</param>
/// <param name="bodyColor">Основной цвет</param> /// <param name="bodyColor">Основной цвет</param>
/// <param name="secColor">Второстепенный цвет</param> /// <param name="secColor">Второстепенный цвет</param>
/// <param name="rocketMines">Признак наличия ракетных шахт</param> public EntityCruiser(int speed, double weight, Color bodyColor, Color secColor)
/// <param name="helipad">Признак наличия вертолётной площадки</param>
public void Init(int speed, double weight, Color bodyColor, Color secColor, bool rocketMines, bool helipad)
{ {
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
SecondColor = secColor; SecondColor = secColor;
RocketMines = rocketMines;
Helipad = helipad;
} }
} }
} }

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Entities
{
public class EntityProCruiser : EntityCruiser
{
/// <summary>
/// Элементов цвет
/// </summary>
public Color ElementsColor { get; private set; }
/// <summary>
/// Признак (опция) наличия ракетных шахт
/// </summary>
public bool RocketMines { get; private set; }
/// <summary>
/// Признак (опция) наличия вертолётной площадки
/// </summary>
public bool Helipad { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса спортивного крейсера
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес Крейсера</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="secColor">Второстепенный цвет</param>
/// <param name="elemColor">Элементов цвет</param>
/// <param name="rocketMines">Признак наличия ракетных шахт</param>
/// <param name="helipad">Признак наличия вертолётной площадки</param>
public EntityProCruiser(int speed, double weight, Color bodyColor, Color secColor, Color elemColor, bool rocketMines, bool helipad) :
base(speed, weight, bodyColor, secColor)
{
RocketMines = rocketMines;
Helipad = helipad;
ElementsColor = elemColor;
}
}
}

View File

@ -29,11 +29,14 @@
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxCruiser = new PictureBox(); pictureBoxCruiser = new PictureBox();
buttonCreate = new Button(); buttonCreateLiner = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonCreateProLiner = new Button();
comboBoxStrategy = new ComboBox();
ButtonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -46,15 +49,15 @@
pictureBoxCruiser.TabIndex = 0; pictureBoxCruiser.TabIndex = 0;
pictureBoxCruiser.TabStop = false; pictureBoxCruiser.TabStop = false;
// //
// buttonCreate // buttonCreateLiner
// //
buttonCreate.Location = new Point(12, 402); buttonCreateLiner.Location = new Point(12, 396);
buttonCreate.Name = "buttonCreate"; buttonCreateLiner.Name = "buttonCreateLiner";
buttonCreate.Size = new Size(125, 36); buttonCreateLiner.Size = new Size(125, 48);
buttonCreate.TabIndex = 1; buttonCreateLiner.TabIndex = 1;
buttonCreate.Text = "Создать"; buttonCreateLiner.Text = "Создать Лайнер";
buttonCreate.UseVisualStyleBackColor = true; buttonCreateLiner.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click; buttonCreateLiner.Click += buttonCreateLiner_Click;
// //
// buttonRight // buttonRight
// //
@ -100,16 +103,49 @@
buttonUp.UseVisualStyleBackColor = true; buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click; buttonUp.Click += ButtonMove_Click;
// //
// buttonCreateProLiner
//
buttonCreateProLiner.Location = new Point(143, 396);
buttonCreateProLiner.Name = "buttonCreateProLiner";
buttonCreateProLiner.Size = new Size(125, 48);
buttonCreateProLiner.TabIndex = 6;
buttonCreateProLiner.Text = "Создать Лютый Лайнер";
buttonCreateProLiner.UseVisualStyleBackColor = true;
buttonCreateProLiner.Click += buttonCreateProLiner_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" });
comboBoxStrategy.Location = new Point(667, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// ButtonStep
//
ButtonStep.Location = new Point(713, 41);
ButtonStep.Name = "ButtonStep";
ButtonStep.Size = new Size(75, 23);
ButtonStep.TabIndex = 8;
ButtonStep.Text = "Шаг";
ButtonStep.UseVisualStyleBackColor = true;
ButtonStep.Click += ButtonStep_Click;
//
// FormCruiser // FormCruiser
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450); ClientSize = new Size(800, 450);
Controls.Add(ButtonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateProLiner);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonCreate); Controls.Add(buttonCreateLiner);
Controls.Add(pictureBoxCruiser); Controls.Add(pictureBoxCruiser);
Name = "FormCruiser"; Name = "FormCruiser";
Text = "Cruiser"; Text = "Cruiser";
@ -120,10 +156,13 @@
#endregion #endregion
private PictureBox pictureBoxCruiser; private PictureBox pictureBoxCruiser;
private Button buttonCreate; private Button buttonCreateLiner;
private Button buttonRight; private Button buttonRight;
private Button buttonDown; private Button buttonDown;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonCreateProLiner;
private ComboBox comboBoxStrategy;
private Button ButtonStep;
} }
} }

View File

@ -1,4 +1,7 @@
using System; using System;
using Cruiser.Drawing;
using Cruiser.Entities;
using Cruiser.MovementStrategy;
namespace Cruiser namespace Cruiser
{ {
@ -10,6 +13,10 @@ namespace Cruiser
/// </summary> /// </summary>
private DrawingCruiser? _drawningCruiser; private DrawingCruiser? _drawningCruiser;
/// <summary> /// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû /// Èíèöèàëèçàöèÿ ôîðìû
/// </summary> /// </summary>
public FormCruiser() public FormCruiser()
@ -36,6 +43,11 @@ namespace Cruiser
} }
/// <summary>
/// Èçìåíåíèå ïîëîæåíèÿ àâòîìîáèëÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawningCruiser == null) if (_drawningCruiser == null)
@ -60,17 +72,70 @@ namespace Cruiser
} }
Draw(); Draw();
} }
private void buttonCreate_Click(object sender, EventArgs e) /// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningCruiser == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectCar(_drawningCruiser), pictureBoxCruiser.Width,
pictureBoxCruiser.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void buttonCreateLiner_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawningCruiser = new DrawingCruiser(); _drawningCruiser = new DrawingCruiser(random.Next(100, 300),
_drawningCruiser.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)),
pictureBoxCruiser.Width,
pictureBoxCruiser.Height);
_drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonCreateProLiner_Click(object sender, EventArgs e)
{
Random random = new();
_drawningCruiser = new DrawingProCruiser(random.Next(100, 300),
random.Next(1000, 3000), 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)), 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)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(1, 2)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(1, 2)),
pictureBoxCruiser.Width, pictureBoxCruiser.Width,
pictureBoxCruiser.Height); pictureBoxCruiser.Height);
_drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100));

View File

@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Drawing;
namespace Cruiser.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(Direction.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
///false - неудача)</returns>
protected bool MoveRight() => MoveTo(Direction.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
///false - неудача)</returns>
protected bool MoveUp() => MoveTo(Direction.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
///false - неудача)</returns>
protected bool MoveDown() => MoveTo(Direction.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="direction">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false -
/// неудача)</returns>
private bool MoveTo(Direction direction)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(direction) ?? false)
{
_moveableObject.MoveObject(direction);
return true;
}
return false;
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.MovementStrategy
{
public class MoveToBorder : 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 = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
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 Cruiser.MovementStrategy
{
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,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

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