Поменял название проекта

This commit is contained in:
Petek1234 2024-03-19 23:30:47 +04:00
parent 70561aff1a
commit d9e4d18651
15 changed files with 612 additions and 27 deletions

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "laba 0", "laba 0\laba 0.csproj", "{20221664-1E5B-4E5F-BBF7-F0E378CB7A24}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorBoat", "laba 0\MotorBoat.csproj", "{20221664-1E5B-4E5F-BBF7-F0E378CB7A24}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -5,10 +5,15 @@
/// </summary>
public enum DirectionType
{
/// <summary>
/// неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// вверх
/// </summary>
Up=1,
Up = 1,
/// <summary>
/// вниз

View File

@ -37,12 +37,29 @@ public class DrawningB
/// <summary>
/// ширина прорисовки катера
/// </summary>
private readonly int _drawningBoatWidth = 90;
private readonly int _drawningBWidth = 120;
/// <summary>
/// высота прорисовки катера
/// </summary>
private readonly int _drawningBoatHeight = 50;
private readonly int _drawningBHeight = 50;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningBWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningBHeight;
/// <summary>
/// Пустой конструктор
@ -69,12 +86,12 @@ public class DrawningB
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="_drawningBoatWidth">ширина прорисовки катера</param>
/// <param name="_drawningBoatHeight">высота прорисовки катера</param>
protected DrawningB(int drawningBoatWidth, int drawningBoatHeight) : this()
/// <param name="_drawningBWidth">ширина прорисовки катера</param>
/// <param name="_drawningBHeight">высота прорисовки катера</param>
protected DrawningB(int drawningBWidth, int drawningBHeight) : this()
{
_drawningBoatWidth = drawningBoatWidth;
_drawningBoatHeight = drawningBoatHeight;
_drawningBWidth = drawningBWidth;
_drawningBHeight = drawningBHeight;
}
/// <summary>
@ -85,20 +102,20 @@ public class DrawningB
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
if (_drawningBoatWidth <= width && _drawningBoatHeight <= height)
if (_drawningBWidth <= width && _drawningBHeight <= height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningBoatWidth > _pictureWidth)
if (_startPosX + _drawningBWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningBoatWidth;
_startPosX = _pictureWidth - _drawningBWidth;
}
if (_startPosY + _drawningBoatHeight > _pictureHeight)
if (_startPosY + _drawningBHeight > _pictureHeight)
{
_startPosY = _drawningBoatHeight - _drawningBoatHeight;
_startPosY = _drawningBHeight - _drawningBHeight;
}
}
return true;
@ -122,18 +139,18 @@ public class DrawningB
{
x = 0; //устанавливаем позицию по оси х равную 0
}
else if (x + _drawningBoatWidth > _pictureWidth) //если новая позиция выходит за правую границу формы
else if (x + _drawningBWidth > _pictureWidth) //если новая позиция выходит за правую границу формы
{
x = _pictureWidth.Value - _drawningBoatWidth;//корректируем по оси х
x = _pictureWidth.Value - _drawningBWidth;//корректируем по оси х
}
if (y < 0)//если новая позиция выше верхней границы формы
{
y = 0;
}
else if (y + _drawningBoatHeight > _pictureHeight) //если новая позиция выходит за границу формы
else if (y + _drawningBHeight > _pictureHeight) //если новая позиция выходит за границу формы
{
y = _pictureHeight.Value - _drawningBoatHeight;//корректируем по оси у
y = _pictureHeight.Value - _drawningBHeight;//корректируем по оси у
}
_startPosX = x;
@ -161,7 +178,6 @@ public class DrawningB
_startPosX -= (int)EntityB.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityB.Step > 0)
@ -169,18 +185,16 @@ public class DrawningB
_startPosY -= (int)EntityB.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + EntityB.Step + _drawningBoatWidth < _pictureWidth)
if (_startPosX.Value + EntityB.Step + _drawningBWidth < _pictureWidth)
{
_startPosX += (int)EntityB.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityB.Step + _drawningBoatHeight < _pictureHeight)
if (_startPosY.Value + EntityB.Step + _drawningBHeight < _pictureHeight)
{
_startPosY += (int)EntityB.Step;
}
@ -203,16 +217,21 @@ public class DrawningB
}
Pen pen = new(Color.Black);
Brush BodyBrush = new SolidBrush(EntityB.BodyColor);
//корпус
g.FillRectangle(BodyBrush, _startPosX.Value + 5, _startPosY.Value, 75, 40);
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value, 75, 40);
//лестница
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 10, 20, 20);
//корма
Point point1 = new Point(_startPosX.Value + 80, _startPosY.Value);
Point point2 = new Point(_startPosX.Value + 80, _startPosY.Value + 40);
Point point3 = new Point(_startPosX.Value + 120, _startPosY.Value + 20);
Point[] curvePointsKorma = { point1, point2, point3 };
g.FillPolygon(BodyBrush, curvePointsKorma);
g.DrawPolygon(pen, curvePointsKorma);
}
}

View File

@ -17,7 +17,7 @@ public class DrawningBoat : DrawningB
/// <param name="kabina">Признак наличия кабины</param>
/// <param name="dvigatel">Признак наличия двигателя</param>
public DrawningBoat(int speed, double weight, Color bodyColor, Color additionalColor, bool kabina, bool dvigatel) : base(110, 60)
public DrawningBoat(int speed, double weight, Color bodyColor, Color additionalColor, bool kabina, bool dvigatel) : base(120, 60)
{
EntityB = new EntityBoat(speed, weight, bodyColor, additionalColor, kabina, dvigatel);
}
@ -30,12 +30,14 @@ public class DrawningBoat : DrawningB
{
Pen pen = new(Color.Black);
if (EntityB == null || EntityB is not EntityBoat Boat || !_startPosX.HasValue || !_startPosY.HasValue)
if (EntityB == null || EntityB is not EntityBoat Boat || !_startPosX.HasValue || !_startPosY.HasValue)
return;
base.DrawTransport(g);
Brush additionalBrush = new SolidBrush(Boat.AdditionalColor);
base.DrawTransport(g);
//кабина
if (Boat.kabinaBody)
{
@ -48,13 +50,12 @@ public class DrawningBoat : DrawningB
g.FillPolygon(additionalBrush, curvePointsKabina);
g.DrawPolygon(pen, curvePointsKabina);
}
//двигатель
if (Boat.dvigatelBody)
{
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 15, 5, 10);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 15, 5, 10);
}
base.DrawTransport(g);
}
}

View File

@ -36,6 +36,8 @@ partial class FormBoat
buttonUp = new Button();
buttonLeft = new Button();
ButtonCreateB = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBoat).BeginInit();
SuspendLayout();
//
@ -121,11 +123,33 @@ partial class FormBoat
ButtonCreateB.UseVisualStyleBackColor = true;
ButtonCreateB.Click += ButtonCreateB_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру ", "К краю" });
comboBoxStrategy.Location = new Point(507, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(553, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormBoat
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(640, 359);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(ButtonCreateB);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
@ -149,4 +173,6 @@ partial class FormBoat
private Button buttonUp;
private Button buttonLeft;
private Button ButtonCreateB;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}

View File

@ -8,18 +8,34 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using laba_0.Drawning;
using laba_0.MovementStrategy;
namespace laba_0;
public partial class FormBoat : Form
{
/// <summary>
/// поле-объект для прорисовки объекта
/// </summary>
private DrawningB? _drawningB;
/// <summary>
/// стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// конструктор формы
/// </summary>
public FormBoat()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки катера
/// </summary>
private void Draw()
{
if (_drawningB == null)
@ -57,6 +73,8 @@ public partial class FormBoat : Form
}
_drawningB.SetPictureSize(pictureBoxBoat.Width, pictureBoxBoat.Height);
_drawningB.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
@ -114,4 +132,49 @@ public partial class FormBoat : Form
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningB == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableB(_drawningB), pictureBoxBoat.Width, pictureBoxBoat.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,142 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace laba_0.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,24 @@
namespace laba_0.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,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace laba_0.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? 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()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace laba_0.MovementStrategy;
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using laba_0.Drawning;
namespace laba_0.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с использованием DrawningB
/// </summary>
public class MoveableB : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// </summary>
private readonly DrawningB? _B = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="B">Объект класса DrawningCar</param>
public MoveableB(DrawningB B)
{
_B = B;
}
public ObjectParameters? GetObjectPosition
{
//определение методов интерфейса
get
{
if (_B == null || _B.EntityB == null ||
!_B.GetPosX.HasValue || !_B.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_B.GetPosX.Value,
_B.GetPosY.Value, _B.GetWidth, _B.GetHeight);
}
}
public int GetStep => (int)(_B?.EntityB?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_B == null || _B.EntityB == null)
{
return false;
}
return _B.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,24 @@
namespace laba_0.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,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace laba_0.MovementStrategy;
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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace laba_0.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}