LabWork02

This commit is contained in:
Сафия Мухамадиева 2024-03-21 01:52:26 +03:00
parent 03402dd7cf
commit 83a063cde7
10 changed files with 160 additions and 99 deletions

View File

@ -1,6 +1,4 @@
using ProjectBattleship.MovementStrategy;
namespace ProjectBattleship.MovementStrategy;
namespace ProjectBattleship.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
@ -65,25 +63,25 @@ public abstract class AbstractStrategy
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false -
///неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false -
///неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false -
///неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false -
///неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
@ -116,7 +114,7 @@ protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false -
///неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{

View File

@ -12,26 +12,25 @@ public class DrawingBattleship : DrawingWarship
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="wing">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
/// <param name="turret">Признак наличия обвеса</param>
/// <param name="rocketCompartment">Признак наличия антикрыла</param>
public DrawingBattleship(int speed, double weight, Color bodyColor, Color
additionalColor, bool turret, bool rocketCompartment) : base(110, 60)
{
EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor,
turret, rocketCompartment);
EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketCompartment);
}
public override void DrawTransport(Graphics g)
{
if (EntityWarship == null || EntityWarship is not EntityBattleship sportWarship ||
if (EntityWarship == null || EntityWarship is not EntityBattleship battleship ||
!_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(sportWarship.AdditionalColor);
Brush additionalBrush = new SolidBrush(battleship.AdditionalColor);
base.DrawTransport(g);
//отсек под ракеты
if (EntityBattleship.RocketCompartment)
if (battleship.RocketCompartment)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 14,
_startPosY.Value + 14, 10, 10);
@ -51,7 +50,7 @@ public class DrawingBattleship : DrawingWarship
_startPosY.Value + 26, 10, 10);
}
//орудийная башня
if (EntityBattleship.Turret)
if (battleship.Turret)
{
Point[] turret = new Point[] {new Point(_startPosX.Value + 112,
_startPosY.Value + 19), new Point(_startPosX.Value + 112,

View File

@ -1,5 +1,4 @@
using ProjectBattleship;
using ProjectBattleship.Entities;
using ProjectBattleship.Entities;
namespace ProjectBattleship.DrawingObject;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
@ -29,11 +28,11 @@ public class DrawingWarship
/// <summary>
/// Ширина прорисовки военного корабля
/// </summary>
private readonly int _drawningWarshipWidth = 90;
private readonly int _drawingWarshipWidth = 90;
/// <summary>
/// Высота прорисовки военного корабля
/// </summary>
private readonly int _drawningWarshipHeight = 50;
private readonly int _drawingWarshipHeight = 50;
/// <summary>
/// Пустой конструктор
/// </summary>
@ -57,12 +56,12 @@ public class DrawingWarship
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningWarshipWidth">Ширина прорисовки военного корабля</param>
/// <param name="drawningWarshipHeight">Высота прорисовки военного корабля</param>
protected DrawingWarship(int drawningWarshipWidth, int drawningWarshipHeight) : this()
/// <param name="drawingWarshipWidth">Ширина прорисовки военного корабля</param>
/// <param name="drawingWarshipHeight">Высота прорисовки военного корабля</param>
protected DrawingWarship(int drawingWarshipWidth, int drawingWarshipHeight) : this()
{
_drawningWarshipWidth = drawningWarshipWidth;
_pictureHeight = drawningWarshipHeight;
_drawingWarshipWidth = drawingWarshipWidth;
_pictureHeight = drawingWarshipHeight;
}
/// <summary>
/// Установка границ поля
@ -71,14 +70,23 @@ public class DrawingWarship
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя
//разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта,
//если она была уже установлена
_pictureWidth = width;
_pictureHeight = height;
return true;
if (_drawingWarshipWidth < width && _drawingWarshipHeight < height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
SetPosition(_startPosX.Value, _startPosY.Value);
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Установка позиции
@ -91,11 +99,20 @@ public bool SetPictureSize(int width, int height)
{
return;
}
// TODO если при установке объекта в эти координаты, он будет
//"выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
_startPosX = x;
_startPosY = y;
if (x > 0 && y > 0 && x + _drawingWarshipWidth < _pictureWidth
&& y + _drawingWarshipHeight < _pictureHeight)
{
_startPosX = x;
_startPosY = y;
}
else
{
Random rnd = new();
_startPosX = rnd.Next(0, _pictureWidth.Value -
_drawingWarshipWidth);
_startPosY = rnd.Next(0, _pictureHeight.Value -
_drawingWarshipHeight);
}
}
/// <summary>
/// Изменение направления перемещения
@ -103,7 +120,7 @@ public bool SetPictureSize(int width, int height)
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение
///невозможно</returns>
public bool MoveTransport(DirectionType direction)
public bool MoveTransport(DirectionType direction)
{
if (EntityWarship == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
@ -126,13 +143,19 @@ public bool MoveTransport(DirectionType direction)
_startPosY -= (int)EntityWarship.Step;
}
return true;
// вправо
//вправо
case DirectionType.Right:
//TODO прописать логику сдвига в право
if (_startPosX + _drawingWarshipWidth + EntityWarship.Step < _pictureWidth)
{
_startPosX += (int)EntityWarship.Step;
}
return true;
//вниз
case DirectionType.Down:
//TODO прописать логику сдвига в вниз
if (_startPosY + _drawingWarshipHeight + EntityWarship.Step < _pictureHeight)
{
_startPosY += (int)EntityWarship.Step;
}
return true;
default:
return false;
@ -189,9 +212,9 @@ public bool MoveTransport(DirectionType direction)
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningWarshipWidth;
public int GetWidth => _drawingWarshipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningWarshipHeight;
public int GetHeight => _drawingWarshipHeight;
}

View File

@ -4,27 +4,9 @@ namespace ProjectBattleship.Entities;
/// <summary>
/// Класс-сущность "Линкор"
/// </summary>
public class EntityBattleship
public class EntityBattleship : EntityWarship
{
/// <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 Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия орудийной башни
/// </summary>
public bool Turret { get; private set; }
/// <summary>
/// Признак (опция) наличия отсека под ракеты
@ -33,7 +15,8 @@ public class EntityBattleship
/// <summary>
/// Шаг перемещения корабля
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
@ -43,12 +26,10 @@ public class EntityBattleship
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="turret">Признак наличия орудийной башни</param>
/// <param name="rocketCompartment">Признак наличия отсека под ракеты</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool turret, bool rocketCompartment)
public EntityBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool turret, bool rocketCompartment) : base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Turret = turret;
RocketCompartment = rocketCompartment;

View File

@ -17,19 +17,28 @@ public class EntityWarship
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
/// <summary>
/// Признак (опция) наличия орудийной башни
/// </summary>
public Color AdditionalColor { get; private set; }
public bool Turret { get; private set; }
/// <summary>
/// Признак (опция) наличия отсека под ракеты
/// </summary>
public bool RocketCompartment { get; private set; }
/// <summary>
/// Шаг перемещения корабля
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityWarship(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -58,7 +58,7 @@
buttonCreateBattleship.Name = "buttonCreateBattleship";
buttonCreateBattleship.Size = new Size(201, 40);
buttonCreateBattleship.TabIndex = 1;
buttonCreateBattleship.Text = "Создать Линкор";
buttonCreateBattleship.Text = "Создать линкор";
buttonCreateBattleship.UseVisualStyleBackColor = true;
buttonCreateBattleship.Click += ButtonCreateBattleship_Click;
//
@ -116,7 +116,9 @@
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру ", "К краю" });
comboBoxStrategy.Location = new Point(652, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(212, 38);
@ -131,6 +133,7 @@
button1.Text = "шаг";
button1.TextAlign = ContentAlignment.TopCenter;
button1.UseVisualStyleBackColor = true;
button1.Click += ButtonStrategyStep_Click;
//
// buttonCreateWarship
//
@ -140,6 +143,7 @@
buttonCreateWarship.TabIndex = 8;
buttonCreateWarship.Text = "Создать корабль";
buttonCreateWarship.UseVisualStyleBackColor = true;
buttonCreateWarship.Click += ButtonCreateWarship_Click;
//
// FormBattleship
//

View File

@ -1,7 +1,5 @@
using ProjectBattleship.MovementStrategy;
using ProjectBattleship;
using ProjectBattleship.DrawingObject;
using ProjectBattleship.MovementStrategy;
namespace ProjectBattleship;
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Ñïîðòèâíûé àâòîìîáèëü"
@ -11,7 +9,7 @@ public partial class FormBattleship : Form
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingWarship? _drawningWarship;
private DrawingWarship? _drawingWarship;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
@ -29,14 +27,14 @@ public partial class FormBattleship : Form
/// </summary>
private void Draw()
{
if (_drawningWarship == null)
if (_drawingWarship == null)
{
return;
}
Bitmap bmp = new(pictureBoxBattleship.Width,
pictureBoxBattleship.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningWarship.DrawTransport(gr);
_drawingWarship.DrawTransport(gr);
pictureBoxBattleship.Image = bmp;
}
/// <summary>
@ -49,13 +47,13 @@ public partial class FormBattleship : Form
switch (type)
{
case nameof(DrawingWarship):
_drawningWarship = new DrawingWarship(random.Next(100, 300),
_drawingWarship = new DrawingWarship(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawingBattleship):
_drawningWarship = new DrawingBattleship(random.Next(100,
_drawingWarship = new DrawingBattleship(random.Next(100,
300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256)),
@ -67,9 +65,9 @@ public partial class FormBattleship : Form
default:
return;
}
_drawningWarship.SetPictureSize(pictureBoxBattleship.Width,
_drawingWarship.SetPictureSize(pictureBoxBattleship.Width,
pictureBoxBattleship.Height);
_drawningWarship.SetPosition(random.Next(10, 100), random.Next(10, 100));
_drawingWarship.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
@ -95,7 +93,7 @@ public partial class FormBattleship : Form
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningWarship == null)
if (_drawingWarship == null)
{
return;
}
@ -104,17 +102,17 @@ public partial class FormBattleship : Form
switch (name)
{
case "buttonUp":
result = _drawningWarship.MoveTransport(DirectionType.Up);
result = _drawingWarship.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningWarship.MoveTransport(DirectionType.Down);
result = _drawingWarship.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningWarship.MoveTransport(DirectionType.Left);
result = _drawingWarship.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningWarship.MoveTransport(DirectionType.Right);
_drawingWarship.MoveTransport(DirectionType.Right);
break;
}
if (result)
@ -129,7 +127,7 @@ public partial class FormBattleship : Form
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningWarship == null)
if (_drawingWarship == null)
{
return;
}
@ -145,7 +143,7 @@ public partial class FormBattleship : Form
{
return;
}
_strategy.SetData(new MoveableWarship(_drawningWarship),
_strategy.SetData(new MoveableWarship(_drawingWarship),
pictureBoxBattleship.Width, pictureBoxBattleship.Height);
}
if (_strategy == null)

View File

@ -1,6 +1,4 @@
using ProjectBattleship.MovementStrategy;
namespace ProjectBattleship.MovementStrategy;
namespace ProjectBattleship.MovementStrategy;
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>

View File

@ -0,0 +1,53 @@
namespace ProjectBattleship.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта к краю экрана
/// </summary>
internal class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder - GetStep() <= FieldWidth
&& objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder - GetStep() <= FieldHeight
&& objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -1,6 +1,4 @@
using ProjectBattleship.MovementStrategy;
namespace ProjectBattleship.MovementStrategy;
namespace ProjectBattleship.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>