Лабораторная работа №2

This commit is contained in:
victinass 2024-03-01 20:00:22 +04:00
parent 392c1f4428
commit 57e2f225a3
14 changed files with 559 additions and 10 deletions

View File

@ -4,6 +4,11 @@
/// </summary> /// </summary>
public enum DirectionType public enum DirectionType
{ {
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary> /// <summary>
/// Вверх /// Вверх
/// </summary> /// </summary>

View File

@ -19,9 +19,9 @@ public class DrawingBattleship : DrawingWarship
/// <param name="tower">Признак наличия башни</param> /// <param name="tower">Признак наличия башни</param>
/// ///
public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base (129, 60) public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 60)
{ {
//Warship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor); EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor);
} }
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)

View File

@ -39,6 +39,26 @@ public class DrawingWarship
/// </summary> /// </summary>
private readonly int _drawingWarshipHeight = 40; private readonly int _drawingWarshipHeight = 40;
/// <summary>
/// Координата Х объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawingWarshipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawingWarshipHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
/// </summary> /// </summary>
@ -73,7 +93,7 @@ public class DrawingWarship
} }
/// <summary> /// <summary>
/// /// Установка границ поля
/// </summary> /// </summary>
/// <param name="width">Ширина поля</param> /// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param> /// <param name="height">Высота поля</param>

View File

@ -3,12 +3,8 @@
/// <summary> /// <summary>
/// Класс-сущность Линкор /// Класс-сущность Линкор
/// </summary> /// </summary>
internal class EntityBattleship : EntityWarship public class EntityBattleship : EntityWarship
{ {
public EntityBattleship(int speed, double weight, Color bodyColor) : base(speed, weight, bodyColor)
{
}
/// <summary> /// <summary>
/// Скорость /// Скорость
/// </summary> /// </summary>
@ -45,14 +41,13 @@ internal class EntityBattleship : EntityWarship
/// </summary> /// </summary>
public double Step => Speed * 100 / Weight; public double Step => Speed * 100 / Weight;
/// <summary> /// <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>
public void EntityWarship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) public EntityBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(speed, weight, bodyColor)
{ {
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;

View File

@ -35,6 +35,8 @@ partial class FormBattleship
buttonRight = new Button(); buttonRight = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonCreateWarshit = new Button(); buttonCreateWarshit = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -116,11 +118,35 @@ partial class FormBattleship
buttonCreateWarshit.UseVisualStyleBackColor = true; buttonCreateWarshit.UseVisualStyleBackColor = true;
buttonCreateWarshit.Click += buttonCreateWarshit_Click; buttonCreateWarshit.Click += buttonCreateWarshit_Click;
// //
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(795, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 6;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(851, 56);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 7;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormBattleship // FormBattleship
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(957, 559); ClientSize = new Size(957, 559);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateWarshit); Controls.Add(buttonCreateWarshit);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonRight); Controls.Add(buttonRight);
@ -143,4 +169,6 @@ partial class FormBattleship
private Button buttonUp; private Button buttonUp;
private Button buttonLeft; private Button buttonLeft;
private Button buttonCreateWarshit; private Button buttonCreateWarshit;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }

View File

@ -1,4 +1,5 @@
using Battleship.Drawings; using Battleship.Drawings;
using Battleship.MovementStrategy;
namespace Battleship; namespace Battleship;
/// <summary> /// <summary>
@ -11,9 +12,18 @@ public partial class FormBattleship : Form
/// </summary> /// </summary>
private DrawingWarship? _drawingWarship; //поля с нижнего подчеркивания private DrawingWarship? _drawingWarship; //поля с нижнего подчеркивания
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormBattleship() public FormBattleship()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
/// Метод прорисовки машины /// Метод прорисовки машины
@ -54,6 +64,8 @@ public partial class FormBattleship : Form
_drawingWarship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height); _drawingWarship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height);
_drawingWarship.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxBattleship.Width, pictureBoxBattleship.Height); _drawingWarship.SetPosition(random.Next(10, 100), random.Next(10, 100), pictureBoxBattleship.Width, pictureBoxBattleship.Height);
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw(); Draw();
} }
@ -79,6 +91,11 @@ public partial class FormBattleship : Form
} }
/// <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 (_drawingWarship == null) if (_drawingWarship == null)
@ -109,4 +126,44 @@ public partial class FormBattleship : Form
Draw(); Draw();
} }
} }
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingWarship == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableWarship(_drawingWarship),
pictureBoxBattleship.Width, pictureBoxBattleship.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,137 @@
namespace Battleship.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObjectcs? _moveableObjects;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotIInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set;}
/// <summary>
/// Статус перемещения
/// </summary>
/// <returns></returns>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObjectcs moveableObjectcs, int width, int height)
{
if (moveableObjectcs == null)
{
_state = StrategyStatus.NotIInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObjects = moveableObjectcs;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns></returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns></returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns></returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns></returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObjects?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObjects?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestination();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection"></param>
/// <returns></returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObjects?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy;
public interface IMoveableObjectcs
{
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
/// <summary>
/// Шаг объекта
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth &&
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())
{
MoveRight();
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams != null )
{
return false;
}
return objParams.ObjectMiddleHorizontall - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontall + 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.ObjectMiddleHorizontall - 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,64 @@
using Battleship.Drawings;
namespace Battleship.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObjectcs с использованием DrawingWarship
/// </summary>
public class MoveableWarship : IMoveableObjectcs
{
/// <summary>
/// Gле-объект класса DrawingWarship или его наследника
/// </summary>
private DrawingWarship? _warship = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="warship"></param>
public MoveableWarship(DrawingWarship warship)
{
_warship = warship;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_warship == null || _warship.EntityWarship == null || !_warship.GetPosX.HasValue || !_warship.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_warship.GetPosX.Value, _warship.GetPosY.Value, _warship.GetWidth, _warship.GetHeight);
}
}
public int GetStep => (int)(_warship?.EntityWarship?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_warship == null || _warship.EntityWarship == null)
{
return false;
}
return _warship.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,27 @@
namespace Battleship.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,72 @@
namespace Battleship.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координата Х
/// </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 ObjectMiddleHorizontall => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="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,22 @@
namespace Battleship.MovementStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotIInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}