Pibd-12 ZagidulinGA Lab02 Simple #2

Closed
Grigorii_Zagidulin wants to merge 3 commits from Lab02 into Lab01
17 changed files with 730 additions and 186 deletions

View File

@ -1,126 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship;
// класс прорисовки и пермещения
public class DrawningBattleship
{
#region [Variables Initialization]
public EntityBattleship? EntityBattleship { get; private set; } //класс сущность
private int? _pictureWidth; //ширина окна
private int? _pictureHeight; //высота окна
private int? _startX; // Х начальной позиции
private int? _startY; // Y начальной позиции
private readonly int _drawningShipWidth = 143; // длина корабля
private readonly int _drawningShipHeight = 75; // высота корабля
#endregion
public void Init(EntityBattleship entityBattleship) //инициализация свойств корабля и параметров окна, позиции
{
EntityBattleship = entityBattleship;
_pictureWidth = null;
_pictureHeight = null;
_startX = null;
_startY = null;
}
public bool SetPictureSize(int width, int height) // установка размеров окна
{
if (width > _drawningShipWidth && height > _drawningShipHeight) //если размеры окна позволяют вместить корабль, то присваиваем
{
if (_startX.HasValue && _startY.HasValue)
{
if (_drawningShipHeight + _startY.Value > height)
{
_startY = height - _drawningShipHeight;
}
if (_drawningShipWidth + _startX.Value > width)
{
_startX = width - _drawningShipWidth;
}
}
_pictureWidth = width;
_pictureHeight = height;
return true;
}
return false;
}
public void SetPosition(int x, int y) // установка позиции корабля
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) // проверка инициализации размеров окна
return;
if (x < 0 || x + _drawningShipWidth > _pictureWidth) // если корабль не вмещается по Х - присваиваем 0
x = 0;
if (y < 0 || y + _drawningShipHeight > _pictureHeight) // если корабль не вмещается по Y - присваиваем 0
y = 0;
_startX = x;
_startY = y;
}
public bool MoveTransport(DirectionType direction) //метод движения корабля
{
if (EntityBattleship == null || !_startX.HasValue || !_startY.HasValue) //проверка наличия корабля и инициализации начальной позиции
return false;
switch (direction)
{
case DirectionType.Left: // Влево
if (_startX.Value - EntityBattleship.Step > 0) // Проверяем, есть ли место для шага (аналогично далее)
_startX -= (int)EntityBattleship.Step;
return true;
case DirectionType.Right: // Вправо
if (_startX.Value + EntityBattleship.Step + _drawningShipWidth < _pictureWidth)
_startX += (int)EntityBattleship.Step;
return true;
case DirectionType.Up: // Вверх
if (_startY.Value - EntityBattleship.Step > 0)
_startY -= (int)EntityBattleship.Step;
return true;
case DirectionType.Down: // Вниз
if (_startY.Value + _drawningShipHeight + EntityBattleship.Step < _pictureHeight)
_startY += (int)EntityBattleship.Step;
return true;
default: return false;
}
}
public void DrawTransport(Graphics g) //метод рисования корабля
{
if (EntityBattleship == null || !_startX.HasValue || !_startY.HasValue) //проверка наличия корабля и инициализации начальной позиции
return;
Pen pen = new(Color.Black, 3);
Brush addBr = new SolidBrush(EntityBattleship.AdditionalColor);
Brush br = new SolidBrush(EntityBattleship.BodyColor);
#region [Drawing]
// Гриницы Линкора
g.DrawLine(pen, _startX.Value + 3, _startY.Value + 15, _startX.Value + 93, _startY.Value + 15);
g.DrawLine(pen, _startX.Value + 93, _startY.Value + 15, _startX.Value + 143, _startY.Value + 15 + 30);
g.DrawLine(pen, _startX.Value + 143, _startY.Value + 15 + 30, _startX.Value + 93, _startY.Value + 15 + 60);
g.DrawLine(pen, _startX.Value + 93, _startY.Value + 15 + 60, _startX.Value + 3, _startY.Value + 15 + 60);
g.DrawLine(pen, _startX.Value + 3, _startY.Value + 15 + 60, _startX.Value + 3, _startY.Value + 15);
//Заливка
g.FillRectangle(br, _startX.Value + 3, _startY.Value + 15, 90, 60);
g.FillPolygon(br, new PointF[] { new PointF(_startX.Value + 93, _startY.Value + 15), new PointF(_startX.Value + 143, _startY.Value + 15 + 30), new PointF(_startX.Value + 93, _startY.Value + 15 + 60) });
//Элементы палубы
g.DrawEllipse(pen, _startX.Value + 83, _startY.Value + 15 + 20, 20, 20);
g.DrawRectangle(pen, _startX.Value + 63, _startY.Value + 15 + 15, 15, 30);
g.DrawRectangle(pen, _startX.Value + 43, _startY.Value + 15 + 25, 20, 10);
Brush brBlack = new SolidBrush(Color.Black);
g.FillRectangle(brBlack, _startX.Value, _startY.Value + 15 + 10, 3, 15);
g.FillRectangle(brBlack, _startX.Value, _startY.Value + 15 + 35, 3, 15);
// Орудийная башня
if (EntityBattleship.Weapon)
{
g.FillPie(addBr, _startX.Value + 8, _startY.Value + 15, 30, 25, 180, 180);
g.FillRectangle(addBr, _startX.Value + 18, _startY.Value, 10, 20);
}
//Ракеты
if (EntityBattleship.Rockets)
{
g.FillRectangle(addBr, _startX.Value + 8, _startY.Value + 15 + 20, 30, 35);
g.DrawRectangle(pen, _startX.Value + 8, _startY.Value + 15 + 20, 30, 35);
g.DrawEllipse(pen, _startX.Value + 13, _startY.Value + 15 + 25, 10, 10);
g.DrawEllipse(pen, _startX.Value + 23, _startY.Value + 15 + 25, 10, 10);
g.DrawEllipse(pen, _startX.Value + 23, _startY.Value + 15 + 40, 10, 10);
g.DrawEllipse(pen, _startX.Value + 13, _startY.Value + 15 + 40, 10, 10);
}
#endregion
}
}

View File

@ -3,11 +3,12 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship;
namespace Battleship.Drawnings;
public enum DirectionType
{
Unknown = -1, //Неизвестное направление
Up = 1, //Вверх
Down = 2,//Вниз
Right = 3,//Вправо
Left = 4 //Влево
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Battleship.Entities;
namespace Battleship.Drawnings;
// класс прорисовки и пермещения
public class DrawningBattleship : DrawningShip
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="entityBattleship">объект класса-сущности</param>
public DrawningBattleship(EntityBattleship entityBattleship) : base(143, 75)
{
EntityShip = entityBattleship;
}
public override void DrawTransport(Graphics g)
{
if (EntityShip == null || EntityShip is not EntityBattleship entityBattleship || !_startX.HasValue || !_startY.HasValue) //проверка наличия корабля и инициализации начальной позиции
return;
_startY += 15;
base.DrawTransport(g);
_startY -= 15;
#region Прорисовка доп. элеменетов
Pen pen = new(Color.Black, 3); //!!! ЗАДАТЬ ВОПРОС ПРО PEN
Brush addBr = new SolidBrush(entityBattleship.AdditionalColor);
// Орудийная башня
if (entityBattleship.Weapon)
{
g.FillPie(addBr, _startX.Value + 8, _startY.Value + 15, 30, 25, 180, 180);
g.FillRectangle(addBr, _startX.Value + 18, _startY.Value, 10, 20);
}
//Ракеты
if (entityBattleship.Rockets)
{
g.FillRectangle(addBr, _startX.Value + 8, _startY.Value + 15 + 20, 30, 35);
g.DrawRectangle(pen, _startX.Value + 8, _startY.Value + 15 + 20, 30, 35);
g.DrawEllipse(pen, _startX.Value + 13, _startY.Value + 15 + 25, 10, 10);
g.DrawEllipse(pen, _startX.Value + 23, _startY.Value + 15 + 25, 10, 10);
g.DrawEllipse(pen, _startX.Value + 23, _startY.Value + 15 + 40, 10, 10);
g.DrawEllipse(pen, _startX.Value + 13, _startY.Value + 15 + 40, 10, 10);
}
#endregion
}
}

View File

@ -0,0 +1,147 @@
using Battleship.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Drawnings;
public class DrawningShip
{
#region [Инициализация переменных]
public EntityShip? EntityShip { get; protected set; } //класс сущность
private int? _pictureWidth; //ширина окна
private int? _pictureHeight; //высота окна
protected int? _startX; // Х начальной позиции
protected int? _startY; // Y начальной позиции
private readonly int _drawningShipWidth = 143; // длина корабля
private readonly int _drawningShipHeight = 60; // высота корабля
#endregion
#region [Инициализация геттеров переменных]
/// <summary>
/// Getter координаты Х
/// </summary>
public int? GetPosX => _startX;
/// <summary>
/// Getter координаты Y
/// </summary>
public int? GetPosY => _startY;
/// <summary>
/// Getter ширины объекта
/// </summary>
public int GetWidth => _drawningShipWidth;
/// <summary>
/// Getter высоты объекта
/// </summary>
public int GetHeight => _drawningShipHeight;
#endregion
/// <summary>
/// Пустой конструктор
/// </summary>
public DrawningShip()
{
_pictureWidth = null;
_pictureHeight = null;
_startX = null;
_startY = null;
}
/// <summary>
/// Конструктор прорисовки
/// </summary>
/// <param name="entityShip">Объект класса-сущности</param>
public DrawningShip(EntityShip entityShip) : this()
{
EntityShip = entityShip;
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningShipWidth"></param>
/// <param name="drawningShipHeight"></param>
protected DrawningShip(int drawningShipWidth, int drawningShipHeight) : this()
{
_drawningShipHeight = drawningShipHeight;
_drawningShipWidth = drawningShipWidth;
}
public bool SetPictureSize(int width, int height) // установка размеров окна
{
if (width > _drawningShipWidth && height > _drawningShipHeight) //если размеры окна позволяют вместить корабль, то присваиваем
{
if (_startX.HasValue && _startY.HasValue)
{
if (_drawningShipHeight + _startY.Value > height)
{
_startY = height - _drawningShipHeight;
}
if (_drawningShipWidth + _startX.Value > width)
{
_startX = width - _drawningShipWidth;
}
}
_pictureWidth = width;
_pictureHeight = height;
return true;
}
return false;
}
public void SetPosition(int x, int y) // установка позиции корабля
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) // проверка инициализации размеров окна
return;
if (x < 0 || x + _drawningShipWidth > _pictureWidth) // если корабль не вмещается по Х - присваиваем 0
x = 0;
if (y < 0 || y + _drawningShipHeight > _pictureHeight) // если корабль не вмещается по Y - присваиваем 0
y = 0;
_startX = x;
_startY = y;
}
public bool MoveTransport(DirectionType direction) //метод движения корабля
{
if (EntityShip == null || !_startX.HasValue || !_startY.HasValue) //проверка наличия корабля и инициализации начальной позиции
return false;
switch (direction)
{
case DirectionType.Left: // Влево
if (_startX.Value - EntityShip.Step > 0) // Проверяем, есть ли место для шага (аналогично далее)
_startX -= (int)EntityShip.Step;
return true;
case DirectionType.Right: // Вправо
if (_startX.Value + EntityShip.Step + _drawningShipWidth < _pictureWidth)
_startX += (int)EntityShip.Step;
return true;
case DirectionType.Up: // Вверх
if (_startY.Value - EntityShip.Step > 0)
_startY -= (int)EntityShip.Step;
return true;
case DirectionType.Down: // Вниз
if (_startY.Value + _drawningShipHeight + EntityShip.Step < _pictureHeight)
_startY += (int)EntityShip.Step;
return true;
default: return false;
}
}
public virtual void DrawTransport(Graphics g) //метод рисования корабля
{
if (EntityShip == null || !_startX.HasValue || !_startY.HasValue) //проверка наличия корабля и инициализации начальной позиции
return;
Pen pen = new(Color.Black, 3);
Brush br = new SolidBrush(EntityShip.BodyColor);
#region [Drawing]
// Гриницы Линкора
g.DrawLine(pen, _startX.Value + 3, _startY.Value, _startX.Value + 93, _startY.Value);
g.DrawLine(pen, _startX.Value + 93, _startY.Value, _startX.Value + 143, _startY.Value + 30);
g.DrawLine(pen, _startX.Value + 143, _startY.Value + 30, _startX.Value + 93, _startY.Value + 60);
g.DrawLine(pen, _startX.Value + 93, _startY.Value + 60, _startX.Value + 3, _startY.Value + 60);
g.DrawLine(pen, _startX.Value + 3, _startY.Value + 60, _startX.Value + 3, _startY.Value);
//Заливка
g.FillRectangle(br, _startX.Value + 3, _startY.Value, 90, 60);
g.FillPolygon(br, new PointF[] { new PointF(_startX.Value + 93, _startY.Value), new PointF(_startX.Value + 143, _startY.Value + 30), new PointF(_startX.Value + 93, _startY.Value + 60) });
//Элементы палубы
g.DrawEllipse(pen, _startX.Value + 83, _startY.Value + 20, 20, 20);
g.DrawRectangle(pen, _startX.Value + 63, _startY.Value + 15, 15, 30);
g.DrawRectangle(pen, _startX.Value + 43, _startY.Value + 25, 20, 10);
Brush brBlack = new SolidBrush(Color.Black);
g.FillRectangle(brBlack, _startX.Value, _startY.Value + 10, 3, 15);
g.FillRectangle(brBlack, _startX.Value, _startY.Value + 35, 3, 15);
#endregion
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Entities;
// класс-сущность "Боевой корабль"
public class EntityBattleship : EntityShip
{
public Color AdditionalColor; // дополнительный цвет
public bool Weapon { get; private set; } // оружие
public bool Rockets { get; set; } // рокеты
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodycolor">Основной цвет</param>
/// <param name="additionalcolor">Дополнительный цвет</param>
/// <param name="weapon">Наличие оружейной башни</param>
/// <param name="rockets">Наличие рокет</param>
public EntityBattleship(int speed, double weight, Color bodycolor, Color additionalcolor, bool weapon, bool rockets) : base(speed, weight, bodycolor) // инициализация полей объекта-класса военного корабля
{
AdditionalColor = additionalcolor;
Weapon = weapon;
Rockets = rockets;
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Entities;
/// <summary>
/// Класс-сущность "Корабль"
/// </summary>
public class EntityShip
{
public int Speed; // скорость
public double Weight; //вес
public Color BodyColor; /*основной цвет*/
public double Step => 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

@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship;
// класс-сущность "Боевой корабль"
public class EntityBattleship
{
public int Speed; // скорость
public double Weight; //вес
public Color BodyColor; /*основной цвет*/
public Color AdditionalColor; // дополнительный цвет
public bool Weapon { get; private set; } // оружие
public bool Rockets { get; set; } // рокеты
public double Step => Speed * 100 / Weight; // шаг перемещения корабля
public void Init(int speed, double weight, Color bodycolor, Color additionalcolor, bool weapon, bool rockets) // инициализация полей объекта-класса военного корабля
{
Speed = speed;
Weight = weight;
BodyColor = bodycolor;
AdditionalColor = additionalcolor;
Weapon = weapon;
Rockets = rockets;
}
}

View File

@ -32,26 +32,29 @@
buttonDown = new Button();
buttonLeft = new Button();
buttonRight = new Button();
buttonCreateSimple = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit();
SuspendLayout();
//
// pictureBoxBattleship
//
pictureBoxBattleship.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
pictureBoxBattleship.Dock = DockStyle.Fill;
pictureBoxBattleship.Location = new Point(0, 0);
pictureBoxBattleship.Name = "pictureBoxBattleship";
pictureBoxBattleship.Size = new Size(1259, 803);
pictureBoxBattleship.Size = new Size(1496, 902);
pictureBoxBattleship.TabIndex = 0;
pictureBoxBattleship.TabStop = false;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 745);
buttonCreate.Location = new Point(12, 844);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(150, 46);
buttonCreate.Size = new Size(316, 46);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.Text = "Создать боевой корабль";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
@ -60,7 +63,7 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.right_arrow;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(1152, 699);
buttonUp.Location = new Point(1389, 798);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(40, 40);
buttonUp.TabIndex = 2;
@ -72,7 +75,7 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.right_arrow_2;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(1152, 745);
buttonDown.Location = new Point(1389, 844);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(40, 40);
buttonDown.TabIndex = 3;
@ -84,7 +87,7 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.right_arrow_4;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(1106, 745);
buttonLeft.Location = new Point(1343, 844);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(40, 40);
buttonLeft.TabIndex = 4;
@ -96,18 +99,54 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.right_arrow_3;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(1198, 745);
buttonRight.Location = new Point(1435, 844);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(40, 40);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonCreateSimple
//
buttonCreateSimple.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateSimple.Location = new Point(334, 844);
buttonCreateSimple.Name = "buttonCreateSimple";
buttonCreateSimple.Size = new Size(316, 46);
buttonCreateSimple.TabIndex = 6;
buttonCreateSimple.Text = "Создать корабль";
buttonCreateSimple.UseVisualStyleBackColor = true;
buttonCreateSimple.Click += buttonCreateSimple_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(1232, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(243, 40);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(1325, 70);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(150, 46);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormBattleship
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1259, 803);
ClientSize = new Size(1496, 902);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateSimple);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
@ -127,5 +166,8 @@
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private Button buttonCreateSimple;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -7,62 +7,116 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Battleship.Drawnings;
using Battleship.Entities;
using Battleship.MovementStrategy;
namespace Battleship
{
public partial class FormBattleship : Form
{
private DrawningBattleship? _drawningBattleship;
private DrawningShip? _drawningShip;
private EntityShip? _entityShip;
private EntityBattleship? _entityBattleship;
public FormBattleship()
private AbstractStrategy? _strategy;
public FormBattleship()
{
InitializeComponent();
}
_strategy = null;
}
private void Draw() // метод рисования корабля
{
if (_drawningBattleship == null)
if (_drawningShip == null)
return;
Bitmap bmp = new(pictureBoxBattleship.Width, pictureBoxBattleship.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningBattleship.DrawTransport(gr);
_drawningShip.DrawTransport(gr);
pictureBoxBattleship.Image = bmp;
}
private void buttonCreate_Click(object sender, EventArgs e) // обработка кнопки "создать"
private void CreateObject(string type)
{
Random random = new Random();
_drawningBattleship = new DrawningBattleship();
_entityBattleship = new EntityBattleship();
_entityBattleship.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)), Convert.ToBoolean(random.Next(0, 2)));
_drawningBattleship.Init(_entityBattleship);
_drawningBattleship.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height);
_drawningBattleship.SetPosition(random.Next(10, 100), random.Next(10, 100));
Random random = new();
switch (type)
{
case nameof(DrawningShip):
_entityShip = new EntityShip(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
_drawningShip = new DrawningShip(_entityShip);
break;
case nameof(DrawningBattleship):
_entityBattleship = new EntityBattleship(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)));
_drawningShip = new DrawningBattleship(_entityBattleship);
break;
default:
return;
}
_drawningShip.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height);
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
private void buttonCreate_Click(object sender, EventArgs e) // обработка кнопки "создать боевой корабль"
{
CreateObject(nameof(DrawningBattleship));
}
private void buttonCreateSimple_Click(object sender, EventArgs e) // обработка кнопки "создать корабль"
{
CreateObject(nameof(DrawningShip));
}
private void ButtonMove_Click(object sender, EventArgs e) // обработка кнопок движения
{
if (_drawningBattleship == null)
if (_drawningShip == null)
return;
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningBattleship.MoveTransport(DirectionType.Up);
result = _drawningShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningBattleship.MoveTransport(DirectionType.Down);
result = _drawningShip.MoveTransport(DirectionType.Down);
break;
case "buttonRight":
result = _drawningBattleship.MoveTransport(DirectionType.Right);
result = _drawningShip.MoveTransport(DirectionType.Right);
break;
case "buttonLeft":
result = _drawningBattleship.MoveTransport(DirectionType.Left);
result = _drawningShip.MoveTransport(DirectionType.Left);
break;
}
if (result)
Draw();
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningShip == null)
return;
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
return;
_strategy.SetData(new MoveableShip(_drawningShip), 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,103 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy;
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private StrategyStatus _state = StrategyStatus.NotInit;
protected int FieldWidth { get; private set;}
protected int FieldHeight { get; private set;}
public StrategyStatus GetStatus() => _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 (IsTargetDestination())
{
_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>true - достигнута, false - не достигнута</returns>
protected abstract bool IsTargetDestination();
/// <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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.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,37 @@
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()
{
ObjectParameters? objParameters = GetObjectParameters;
if (objParameters == null)
{
return false;
}
return (objParameters.RightBorder - GetStep() <= FieldWidth && objParameters.RightBorder + GetStep() >= FieldWidth &&
objParameters.BottomBorder - GetStep() <= FieldHeight && objParameters.BottomBorder + GetStep() >= FieldHeight);
}
protected override void MoveToTarget()
{
ObjectParameters? objParameters = GetObjectParameters;
if (objParameters == null)
{
return;
}
int diffx = FieldWidth - objParameters.RightBorder;
if (diffx > GetStep())
{
MoveRight();
}
int diffy = FieldHeight - objParameters.BottomBorder;
if (diffy > GetStep())
{
MoveDown();
}
}
}

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 MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParameters = GetObjectParameters;
if (objParameters == null){
return false;
}
return (objParameters.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParameters.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParameters.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParameters.ObjectMiddleVertical + GetStep() >= FieldHeight / 2);
}
protected override void MoveToTarget()
{
ObjectParameters? objParameters = GetObjectParameters;
if (objParameters == null) {
return;
}
int diffx = objParameters.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffx) > GetStep()){
if (diffx > 0)
MoveLeft();
else
MoveRight();
}
int diffy = objParameters.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffy) > GetStep())
{
if (diffy > 0)
MoveUp();
else
MoveDown();
}
}
}

View File

@ -0,0 +1,54 @@
using Battleship.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject с помощью DrawningShip
/// </summary>
public class MoveableShip : IMoveableObject
{
private readonly DrawningShip? _ship = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="drawningShip">Объект класса DrawningShip</param>
public MoveableShip(DrawningShip drawningShip)
{
_ship = drawningShip;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_ship == null || !_ship.GetPosX.HasValue || !_ship.GetPosY.HasValue)
return null;
return new ObjectParameters(_ship.GetPosX.Value, _ship.GetPosY.Value, _ship.GetWidth, _ship.GetHeight);
}
}
public int GetStep => (int)(_ship?.EntityShip?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_ship == null || _ship.EntityShip == null)
return false;
return _ship.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Преобразование из DrawningShip
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public 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.Unknown,
};
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy;
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Вправо
/// </summary>
Right = 3,
/// <summary>
/// Влево
/// </summary>
Left = 4
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy;
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
public int LeftBorder => _x;
public int TopBorder => _y;
public int RightBorder => _x + _width;
public int BottomBorder => _y + _height;
public int ObjectMiddleHorizontal => _x + _width / 2;
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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy;
/// <summary>
/// Статус выполнения операции пермещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Готов к началу
/// </summary>
NotInit,
/// <summary>
/// В процессе
/// </summary>
InProgress,
/// <summary>
/// Выполнено
/// </summary>
Finish
}