PIbd-23. Dolgova D.N. Lab 02 #2

Closed
darya_dolgova wants to merge 1 commits from lab2 into lab1
13 changed files with 803 additions and 139 deletions
Showing only changes of commit c4e6dfff50 - Show all commits

View File

@ -3,19 +3,19 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.Design.Behavior;
using WarmlyShip.Entities;
namespace WarmlyShip
namespace WarmlyShip.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
internal class DrawningWarmlyShip
public class DrawningShip
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityWarmlyShip? EntityWarmlyShip { get; private set; }
public EntityShip? EntityShip { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
@ -27,44 +27,81 @@ namespace WarmlyShip
/// <summary>
/// Левая координата прорисовки корабля
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки корабля
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки корабля
/// </summary>
private readonly int _shipWidth = 140;
protected readonly int _shipWidth = 140;
/// <summary>
/// Высота прорисовки корабля
/// </summary>
private readonly int _shipHeight = 60;
protected readonly int _shipHeight = 60;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _shipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _shipHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipe">Признак наличия труб</param>
/// <param name="fuelCompartment">Признак наличия отсека для топлива</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 pipe, bool fuelCompartment, int width, int height)
public DrawningShip(int speed, double weight, Color bodyColor, int
width, int height)
{
if (width < _shipWidth || height < _shipHeight)
{
return false;
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityWarmlyShip = new EntityWarmlyShip();
EntityWarmlyShip.Init(speed, weight, bodyColor, additionalColor, pipe, fuelCompartment);
return true;
EntityShip = new EntityShip(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="shipWidth">Ширина прорисовки корабля</param>
/// <param name="shipHeight">Высота прорисовки корабля</param>
protected DrawningShip(int speed, double weight, Color bodyColor, int
width, int height, int shipWidth, int shipHeight)
{
if (width < _shipWidth || height < _shipHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_shipWidth = shipWidth;
_shipHeight = shipHeight;
EntityShip = new EntityShip(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
@ -83,13 +120,39 @@ namespace WarmlyShip
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityShip == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityShip.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityShip.Step > 0,
//вправо
DirectionType.Right => _startPosX + _shipWidth + EntityShip.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _shipHeight + EntityShip.Step < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityWarmlyShip == null)
if (!CanMove(direction) || EntityShip == null)
{
return;
}
@ -97,47 +160,37 @@ namespace WarmlyShip
{
//влево
case DirectionType.Left:
if (_startPosX - EntityWarmlyShip.Step > 0)
{
_startPosX -= (int)EntityWarmlyShip.Step;
}
_startPosX -= (int)EntityShip.Step;
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityWarmlyShip.Step > 0)
{
_startPosY -= (int)EntityWarmlyShip.Step;
}
_startPosY -= (int)EntityShip.Step;
break;
// вправо
case DirectionType.Right:
if (_startPosX + _shipWidth + EntityWarmlyShip.Step < _pictureWidth)
{
_startPosX += (int)EntityWarmlyShip.Step;
}
_startPosX += (int)EntityShip.Step;
break;
//вниз
case DirectionType.Down:
if (_startPosY + _shipHeight + EntityWarmlyShip.Step < _pictureHeight)
{
_startPosY += (int)EntityWarmlyShip.Step;
}
_startPosY += (int)EntityShip.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityWarmlyShip == null)
if (EntityShip == null)
{
return;
}
Pen pen = new(Color.Black);
Brush BodyBrush = new SolidBrush(EntityWarmlyShip.BodyColor);
Brush additionalBrush = new SolidBrush(EntityWarmlyShip.AdditionalColor);
Brush BodyBrush = new SolidBrush(EntityShip.BodyColor);
// корпус
Point point1 = new Point(_startPosX, _startPosY + 30);
Point point2 = new Point(_startPosX + 140, _startPosY + 30);
@ -163,34 +216,6 @@ namespace WarmlyShip
Point point_7 = new Point(_startPosX + 129, _startPosY + 35);
Point point_8 = new Point(_startPosX + 131, _startPosY + 35);
g.DrawLine(pen, point_7, point_8);
if (EntityWarmlyShip.Pipe)
{
//трубы
g.FillRectangle(additionalBrush, _startPosX + 20, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 5, 10, 15);
g.FillRectangle(additionalBrush, _startPosX + 60, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 60, _startPosY + 5, 10, 15);
g.FillRectangle(additionalBrush, _startPosX + 100, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 100, _startPosY + 5, 10, 15);
Brush brBlack = new SolidBrush(Color.Black);
g.FillRectangle(brBlack, _startPosX + 20, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 20, _startPosY, 10, 5);
g.FillRectangle(brBlack, _startPosX + 60, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 60, _startPosY, 10, 5);
g.FillRectangle(brBlack, _startPosX + 100, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 100, _startPosY, 10, 5);
}
if (EntityWarmlyShip.FuelCompartment)
{
// отсек под топливо
g.FillRectangle(additionalBrush, _startPosX + 30, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 30, _startPosY + 45, 20, 15);
g.FillRectangle(additionalBrush, _startPosX + 50, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 50, _startPosY + 45, 20, 15);
g.FillRectangle(additionalBrush, _startPosX + 70, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 70, _startPosY + 45, 20, 15);
}
}
}
}
}

View File

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
namespace WarmlyShip.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningWarmlyShip : DrawningShip
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipe">Признак наличия труб</param>
/// <param name="fuelCompartment">Признак наличия отсека для топлива</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningWarmlyShip(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipe, bool fuelCompartment, int width, int height) :
base(speed, weight, bodyColor, width, height, 140, 60)
{
if (EntityShip != null)
{
EntityShip = new EntityWarmlyShip(speed, weight, bodyColor,
additionalColor, pipe, fuelCompartment);
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityShip is not EntityWarmlyShip warmlyShip)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(warmlyShip.AdditionalColor);
if (warmlyShip.Pipe)
{
//трубы
g.FillRectangle(additionalBrush, _startPosX + 20, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 5, 10, 15);
g.FillRectangle(additionalBrush, _startPosX + 60, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 60, _startPosY + 5, 10, 15);
g.FillRectangle(additionalBrush, _startPosX + 100, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 100, _startPosY + 5, 10, 15);
Brush brBlack = new SolidBrush(Color.Black);
g.FillRectangle(brBlack, _startPosX + 20, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 20, _startPosY, 10, 5);
g.FillRectangle(brBlack, _startPosX + 60, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 60, _startPosY, 10, 5);
g.FillRectangle(brBlack, _startPosX + 100, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 100, _startPosY, 10, 5);
}
base.DrawTransport(g);
if (warmlyShip.FuelCompartment)
{
// отсек под топливо
g.FillRectangle(additionalBrush, _startPosX + 30, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 30, _startPosY + 45, 20, 15);
g.FillRectangle(additionalBrush, _startPosX + 50, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 50, _startPosY + 45, 20, 15);
g.FillRectangle(additionalBrush, _startPosX + 70, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 70, _startPosY + 45, 20, 15);
}
}
}
}

View File

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

View File

@ -4,22 +4,13 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
namespace WarmlyShip.Entities
{
internal class EntityWarmlyShip
/// <summary>
/// Класс-сущность "Теплоход"
/// </summary>
public class EntityWarmlyShip : EntityShip
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
@ -33,10 +24,6 @@ namespace WarmlyShip
/// </summary>
public bool FuelCompartment { get; private set; }
/// <summary>
/// Шаг перемещения теплохода
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса теплохода
/// </summary>
@ -46,16 +33,12 @@ namespace WarmlyShip
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipe">Признак наличия труб</param>
/// <param name="fuelCompartment">Признак наличия отсека под топливо</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipe, bool fuelCompartment)
public EntityWarmlyShip(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipe, bool fuelCompartment) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Pipe = pipe;
FuelCompartment = fuelCompartment;
}
}
}

View File

@ -29,11 +29,14 @@
private void InitializeComponent()
{
pictureBoxWarmlyShip = new PictureBox();
buttonCreate = new Button();
buttonLeft = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonDown = new Button();
comboBoxStrategy = new ComboBox();
buttonCreateShip = new Button();
buttonStep = new Button();
buttonCreateWarmlyShip = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyShip).BeginInit();
SuspendLayout();
//
@ -47,17 +50,6 @@
pictureBoxWarmlyShip.TabIndex = 0;
pictureBoxWarmlyShip.TabStop = false;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 426);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
@ -106,16 +98,63 @@
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "к центру", "к краю" });
comboBoxStrategy.Location = new Point(751, 24);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 6;
//
// buttonCreateShip
//
buttonCreateShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateShip.Location = new Point(108, 407);
buttonCreateShip.Name = "buttonCreateShip";
buttonCreateShip.Size = new Size(80, 42);
buttonCreateShip.TabIndex = 7;
buttonCreateShip.Text = "Создать корабль";
buttonCreateShip.UseVisualStyleBackColor = true;
buttonCreateShip.Click += buttonCreateShip_Click;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(797, 53);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 23);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonCreateWarmlyShip
//
buttonCreateWarmlyShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateWarmlyShip.Location = new Point(12, 407);
buttonCreateWarmlyShip.Name = "buttonCreateWarmlyShip";
buttonCreateWarmlyShip.Size = new Size(80, 42);
buttonCreateWarmlyShip.TabIndex = 9;
buttonCreateWarmlyShip.Text = "Создать теплоход";
buttonCreateWarmlyShip.UseVisualStyleBackColor = true;
buttonCreateWarmlyShip.Click += buttonCreateWarmlyShip_Click;
//
// FormWarmlyShip
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(buttonCreateWarmlyShip);
Controls.Add(buttonStep);
Controls.Add(buttonCreateShip);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxWarmlyShip);
Name = "FormWarmlyShip";
StartPosition = FormStartPosition.CenterScreen;
@ -129,10 +168,13 @@
#endregion
private PictureBox pictureBoxWarmlyShip;
private Button buttonCreate;
private Button buttonLeft;
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
private ComboBox comboBoxStrategy;
private Button buttonCreateShip;
private Button buttonStep;
private Button buttonCreateWarmlyShip;
}
}

View File

@ -1,24 +1,19 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WarmlyShip.DrawningObjects;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
{
/// <summary>
/// Форма работы с объектом "Теплоход"
/// </summary>
public partial class FormWarmlyShip : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// Форма работы с объектом "Теплоход"
/// </summary>
private DrawningWarmlyShip? _drawningWarmlyShip;
private DrawningShip? _drawningShip;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Инициализация формы
/// </summary>
@ -27,45 +22,59 @@ namespace WarmlyShip
InitializeComponent();
}
/// <summary>
/// Метод прорисовки теплохода
/// Метод прорисовки корабля
/// </summary>
private void Draw()
{
if (_drawningWarmlyShip == null)
if (_drawningShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningWarmlyShip.DrawTransport(gr);
_drawningShip.DrawTransport(gr);
pictureBoxWarmlyShip.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать теплоход"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
private void buttonCreateWarmlyShip_Click(object sender, EventArgs e)
{
Random random = new();
_drawningWarmlyShip = new DrawningWarmlyShip();
_drawningWarmlyShip.Init(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
_drawningShip = new DrawningWarmlyShip(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)),
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawningWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Изменение размеров формы
/// Обработка нажатия кнопки "Создать корабль"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateShip_Click(object sender, EventArgs e)
{
Random random = new();
_drawningShip = new DrawningShip(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Изменение положения корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningWarmlyShip == null)
if (_drawningShip == null)
{
return;
}
@ -73,19 +82,61 @@ namespace WarmlyShip
switch (name)
{
case "buttonUp":
_drawningWarmlyShip.MoveTransport(DirectionType.Up);
_drawningShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningWarmlyShip.MoveTransport(DirectionType.Down);
_drawningShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningWarmlyShip.MoveTransport(DirectionType.Left);
_drawningShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningWarmlyShip.MoveTransport(DirectionType.Right);
_drawningShip.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningShip == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectShip(_drawningShip), pictureBoxWarmlyShip.Width,
pictureBoxWarmlyShip.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.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

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

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.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,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в правый нижний край экрана
/// </summary>
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,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.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,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.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 WarmlyShip.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}