Compare commits

..

1 Commits

21 changed files with 265 additions and 1369 deletions

View File

@ -1,138 +0,0 @@
using Battleship.MovementStrategy;
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
{
/// <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?.GetObjectParametrs;
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

@ -1,6 +1,6 @@
namespace Battleship
{
partial class FormBattleship
partial class Battleship
{
/// <summary>
/// Required designer variable.
@ -34,10 +34,6 @@
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonCreateAdd = new System.Windows.Forms.Button();
this.buttonStep = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonSelectShip = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxBattleship)).BeginInit();
this.SuspendLayout();
//
@ -55,9 +51,9 @@
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(12, 415);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(114, 23);
this.buttonCreate.Size = new System.Drawing.Size(75, 23);
this.buttonCreate.TabIndex = 6;
this.buttonCreate.Text = "Создать корабль";
this.buttonCreate.Text = "Создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
@ -109,67 +105,18 @@
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonCreateAdd
//
this.buttonCreateAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateAdd.Location = new System.Drawing.Point(132, 415);
this.buttonCreateAdd.Name = "buttonCreateAdd";
this.buttonCreateAdd.Size = new System.Drawing.Size(159, 23);
this.buttonCreateAdd.TabIndex = 11;
this.buttonCreateAdd.Text = "Создать военный корабль";
this.buttonCreateAdd.UseVisualStyleBackColor = true;
this.buttonCreateAdd.Click += new System.EventHandler(this.buttonCreateAdd_Click);
//
// buttonStep
//
this.buttonStep.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonStep.Location = new System.Drawing.Point(713, 48);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(75, 23);
this.buttonStep.TabIndex = 12;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"В центр",
"К границе"});
this.comboBoxStrategy.Location = new System.Drawing.Point(667, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(121, 23);
this.comboBoxStrategy.TabIndex = 13;
//
// buttonSelectShip
//
this.buttonSelectShip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonSelectShip.Location = new System.Drawing.Point(297, 415);
this.buttonSelectShip.Name = "buttonSelectShip";
this.buttonSelectShip.Size = new System.Drawing.Size(118, 23);
this.buttonSelectShip.TabIndex = 14;
this.buttonSelectShip.Text = "Выбрать корабль";
this.buttonSelectShip.UseVisualStyleBackColor = true;
this.buttonSelectShip.Click += new System.EventHandler(this.buttonSelectShip_Click);
//
// FormBattleship
// Battleship
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonSelectShip);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.buttonCreateAdd);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.pictureBoxBattleship);
this.Name = "FormBattleship";
this.Name = "Battleship";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxBattleship)).EndInit();
this.ResumeLayout(false);
@ -183,9 +130,5 @@
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateAdd;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button buttonSelectShip;
}
}

View File

@ -0,0 +1,72 @@
namespace Battleship
{
public partial class Battleship : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningBattleship? _drawningBattleship;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public Battleship()
{
InitializeComponent();
}
/// Ìåòîä ïðîðèñîâêè
/// </summary>
private void Draw()
{
if (_drawningBattleship == null)
{
return;
}
Bitmap bmp = new(pictureBoxBattleship.Width,
pictureBoxBattleship.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningBattleship.DrawTransport(gr);
pictureBoxBattleship.Image = bmp;
}
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawningBattleship = new DrawningBattleship();
_drawningBattleship.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)),
pictureBoxBattleship.Width, pictureBoxBattleship.Height);
_drawningBattleship.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningBattleship == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningBattleship.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningBattleship.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningBattleship.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningBattleship.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
}
}

View File

@ -1,52 +1,195 @@
using Battleship;
using Battleship.Entities;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.DrawningObjects
namespace Battleship
{
public class DrawningBattleship : DrawningShip
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningBattleship
{
public DrawningBattleship(int speed, double weight, Color bodyColor, Color
additionalColor, bool tower, bool section, int width, int height)
: base(speed, weight, bodyColor, width, height, 175, 80)
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBattleship? EntityBattleship { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки
/// </summary>
private readonly int _buttleshipWidth = 175;
/// <summary>
/// Высота прорисовки
/// </summary>
private readonly int _buttleshipHeight = 80;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет основы</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="tower">Признак наличия орудийной башни</param>
/// <param name="section">Признак наличия отсека под ракеты</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена,
///нельзя создать объект в этих размерах</retu rns>
public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool tower, bool section, int width, int height)
{
if(EntityShip != null)
if (width < _buttleshipWidth || height < _buttleshipHeight)
{
EntityShip = new EntityBattleship(speed, weight, bodyColor, additionalColor, tower, section);
return false;
}
_pictureWidth = width;
_pictureHeight = height;
EntityBattleship = new EntityBattleship();
EntityBattleship.Init(speed, weight, bodyColor, additionalColor,
tower, section);
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x >= 0 && x + _buttleshipWidth <= _pictureWidth && y >= 0 && y + _buttleshipHeight <= _pictureHeight)
{
_startPosX = x;
_startPosY = y;
}
}
public override void DrawTransport(Graphics g)
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityShip is not EntityBattleship battleShip)
if (EntityBattleship == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX - EntityBattleship.Step > 0)
{
_startPosX -= (int)EntityBattleship.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityBattleship.Step > 0)
{
_startPosY -= (int)EntityBattleship.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + _buttleshipWidth + EntityBattleship.Step < _pictureWidth)
{
_startPosX += (int)EntityBattleship.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _buttleshipHeight + EntityBattleship.Step < _pictureHeight)
{
_startPosY += (int)EntityBattleship.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntityBattleship == null)
{
return;
}
Pen pen = new(Color.Black, 2);
Brush additionalBrush = new
SolidBrush(battleShip.AdditionalColor);
base.DrawTransport(g);
SolidBrush(EntityBattleship.AdditionalColor);
//основа
Brush mainBrush = new SolidBrush(EntityBattleship.BodyColor);
Point[] hull = new Point[]
{
new Point(_startPosX + 5, _startPosY + 0),
new Point(_startPosX + 120, _startPosY + 0),
new Point(_startPosX + 160, _startPosY + 35),
new Point(_startPosX + 120, _startPosY + 70),
new Point(_startPosX + 5, _startPosY + 70),
};
g.FillPolygon(mainBrush, hull);
g.DrawPolygon(pen, hull);
//блоки
Brush blockBrush = new
SolidBrush(Color.DimGray);
g.FillRectangle(blockBrush, _startPosX + 70, _startPosY + 15, 20, 40);
g.DrawRectangle(pen, _startPosX + 70, _startPosY + 15, 20, 40);
g.FillRectangle(additionalBrush, _startPosX + 40, _startPosY + 25, 30, 20);
g.DrawRectangle(pen, _startPosX + 40, _startPosY + 25, 30, 20);
g.FillEllipse(additionalBrush, _startPosX + 100, _startPosY + 20, 30, 30);
g.DrawEllipse(pen, _startPosX + 100, _startPosY + 20, 30, 30);
//для ускорения
Brush speedBrush = new
SolidBrush(Color.Gold);
g.FillRectangle(speedBrush, _startPosX + 0, _startPosY + 10, 5, 20);
g.DrawRectangle(pen, _startPosX + 0, _startPosY + 10, 5, 20);
g.FillRectangle(speedBrush, _startPosX + 0, _startPosY + 40, 5, 20);
g.DrawRectangle(pen, _startPosX + 0, _startPosY + 40, 5, 20);
//орудийная башня
if (battleShip.Tower)
if (EntityBattleship.Tower)
{
g.FillRectangle(additionalBrush, _startPosX + 108, _startPosY + 28, 15, 15);
Brush baseBrush = new SolidBrush(Color.White);
g.FillRectangle(baseBrush, _startPosX + 108, _startPosY + 28, 15, 15);
g.DrawRectangle(pen, _startPosX + 108, _startPosY + 28, 15, 15);
Brush gunBrush = new SolidBrush(Color.Black);
g.FillRectangle(gunBrush, _startPosX + 123, _startPosY + 32, 47, 6);
g.DrawRectangle(pen, _startPosX + 123, _startPosY + 32, 55, 6);
}
//отсеки под ракеты
if (battleShip.Section)
if (EntityBattleship.Section)
{
g.FillRectangle(additionalBrush, _startPosX + 20, _startPosY + 70, 40, 10);
Brush sectionBrush = new
SolidBrush(Color.Gray);
g.FillRectangle(sectionBrush, _startPosX + 20, _startPosY + 70, 40, 10);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 70, 40, 10);
g.FillRectangle(additionalBrush, _startPosX + 75, _startPosY + 70, 40, 10);
g.FillRectangle(sectionBrush, _startPosX + 75, _startPosY + 70, 40, 10);
g.DrawRectangle(pen, _startPosX + 75, _startPosY + 70, 40, 10);
}
}
}
}

View File

@ -1,41 +0,0 @@
using Battleship.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Battleship;
namespace Battleship.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningCar (паттерн 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

@ -1,231 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Battleship.Entities;
using Battleship.MovementStrategy;
namespace Battleship.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningShip
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityShip? EntityShip { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки
/// </summary>
protected readonly int _buttleshipWidth = 175;
/// <summary>
/// Высота прорисовки
/// </summary>
protected readonly int _buttleshipHeight = 80;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет основы</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена,
///нельзя создать объект в этих размерах</retu rns>
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectShip(this);
public DrawningShip(int speed, double weight, Color bodyColor, int width, int height)
{
if (width < _buttleshipWidth || height < _buttleshipHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
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="buttleshipWidth">Ширина прорисовки автомобиля</param>
/// <param name="buttleshipHeight">Высота прорисовки автомобиля</param>
protected DrawningShip(int speed, double weight, Color bodyColor, int
width, int height, int buttleshipWidth, int buttleshipHeight)
{
if (width <= _buttleshipWidth || height <= _buttleshipHeight)
return;
_pictureWidth = width;
_pictureHeight = height;
_buttleshipWidth = buttleshipWidth;
_buttleshipHeight = buttleshipHeight;
EntityShip = new EntityShip(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x >= 0 && x + _buttleshipWidth <= _pictureWidth && y >= 0 && y + _buttleshipHeight <= _pictureHeight)
{
_startPosX = x;
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityShip == null)
{
return;
}
Pen pen = new(Color.Black, 2);
//основа
Brush mainBrush = new SolidBrush(EntityShip.BodyColor);
Point[] hull = new Point[]
{
new Point(_startPosX + 5, _startPosY + 0),
new Point(_startPosX + 120, _startPosY + 0),
new Point(_startPosX + 160, _startPosY + 35),
new Point(_startPosX + 120, _startPosY + 70),
new Point(_startPosX + 5, _startPosY + 70),
};
g.FillPolygon(mainBrush, hull);
g.DrawPolygon(pen, hull);
//блоки
Brush blockBrush = new
SolidBrush(Color.DimGray);
g.FillRectangle(blockBrush, _startPosX + 70, _startPosY + 15, 20, 40);
g.DrawRectangle(pen, _startPosX + 70, _startPosY + 15, 20, 40);
g.FillRectangle(blockBrush, _startPosX + 40, _startPosY + 25, 30, 20);
g.DrawRectangle(pen, _startPosX + 40, _startPosY + 25, 30, 20);
g.FillEllipse(blockBrush, _startPosX + 100, _startPosY + 20, 30, 30);
g.DrawEllipse(pen, _startPosX + 100, _startPosY + 20, 30, 30);
//для ускорения
Brush speedBrush = new
SolidBrush(Color.Gold);
g.FillRectangle(speedBrush, _startPosX + 0, _startPosY + 10, 5, 20);
g.DrawRectangle(pen, _startPosX + 0, _startPosY + 10, 5, 20);
g.FillRectangle(speedBrush, _startPosX + 0, _startPosY + 40, 5, 20);
g.DrawRectangle(pen, _startPosX + 0, _startPosY + 40, 5, 20);
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// /// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _buttleshipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _buttleshipHeight;
/// <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 + EntityShip.Step + _buttleshipWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityShip.Step + _buttleshipHeight < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityShip == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityShip.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityShip.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityShip.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityShip.Step;
break;
}
}
}
}

View File

@ -1,15 +1,28 @@
using Battleship.Entities;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Entities
namespace Battleship
{
internal class EntityBattleship: EntityShip
public class EntityBattleship
{
/// <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>
/// Признак (опция) наличия башни
@ -22,7 +35,7 @@ namespace Battleship.Entities
/// <summary>
/// Шаг перемещения
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
@ -32,10 +45,13 @@ namespace Battleship.Entities
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="tower">Признак наличия орудийной башни</param>
/// <param name="section">Признак наличия отсека под ракеты</param>
public EntityBattleship(int speed, double weight, Color bodyColor, Color
additionalColor, bool tower, bool section) : base(speed, weight, bodyColor)
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool tower, bool section)
{
AdditionalColor = additionalColor;
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Tower = tower;
Section = section;
}

View File

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

@ -1,161 +0,0 @@
using Battleship.DrawningObjects;
using Battleship.MovementStrategy;
using System.Drawing;
namespace Battleship
{
public partial class FormBattleship : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningShip? _drawningShip;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âûáðàííûé êîðàáëü
/// </summary>
public DrawningShip? SelectedShip { get; private set; }
public FormBattleship()
{
InitializeComponent();
_abstractStrategy = null;
SelectedShip = null;
}
/// Ìåòîä ïðîðèñîâêè
/// </summary>
private void Draw()
{
if (_drawningShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxBattleship.Width,
pictureBoxBattleship.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningShip.DrawTransport(gr);
pictureBoxBattleship.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü ïðîñòîé êîðàáëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawningShip = new DrawningShip(random.Next(100, 300),
random.Next(1000, 3000), color,
pictureBoxBattleship.Width, pictureBoxBattleship.Height);
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü âîåííûé êîðàáëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAdd_Click(object sender, EventArgs e)
{
Random random = new();
Color bodyColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
bodyColor = dialog.Color;
}
Color addColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
if (dialog.ShowDialog() == DialogResult.OK)
{
addColor = dialog.Color;
}
_drawningShip = new DrawningBattleship(random.Next(100, 300),
random.Next(1000, 3000), bodyColor,
addColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxBattleship.Width, pictureBoxBattleship.Height);
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningShip.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
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), pictureBoxBattleship.Width,
pictureBoxBattleship.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void buttonSelectShip_Click(object sender, EventArgs e)
{
SelectedShip = _drawningShip;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -1,129 +0,0 @@
namespace Battleship
{
partial class FormShipCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxBattleShip = new System.Windows.Forms.GroupBox();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.buttonRefreshCollection = new System.Windows.Forms.Button();
this.buttonRemoveShip = new System.Windows.Forms.Button();
this.buttonAddShip = new System.Windows.Forms.Button();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBoxBattleShip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.SuspendLayout();
//
// groupBoxBattleShip
//
this.groupBoxBattleShip.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxBattleShip.Controls.Add(this.maskedTextBoxNumber);
this.groupBoxBattleShip.Controls.Add(this.buttonRefreshCollection);
this.groupBoxBattleShip.Controls.Add(this.buttonRemoveShip);
this.groupBoxBattleShip.Controls.Add(this.buttonAddShip);
this.groupBoxBattleShip.Location = new System.Drawing.Point(618, 1);
this.groupBoxBattleShip.Name = "groupBoxBattleShip";
this.groupBoxBattleShip.Size = new System.Drawing.Size(183, 450);
this.groupBoxBattleShip.TabIndex = 0;
this.groupBoxBattleShip.TabStop = false;
this.groupBoxBattleShip.Text = "Инструменты";
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(22, 152);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(147, 23);
this.maskedTextBoxNumber.TabIndex = 3;
//
// buttonRefreshCollection
//
this.buttonRefreshCollection.Location = new System.Drawing.Point(22, 265);
this.buttonRefreshCollection.Name = "buttonRefreshCollection";
this.buttonRefreshCollection.Size = new System.Drawing.Size(147, 33);
this.buttonRefreshCollection.TabIndex = 2;
this.buttonRefreshCollection.Text = "Обновить коллекцию";
this.buttonRefreshCollection.UseVisualStyleBackColor = true;
this.buttonRefreshCollection.Click += new System.EventHandler(this.buttonRefreshCollection_Click);
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(22, 217);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(147, 33);
this.buttonRemoveShip.TabIndex = 1;
this.buttonRemoveShip.Text = "Удалить корабль";
this.buttonRemoveShip.UseVisualStyleBackColor = true;
this.buttonRemoveShip.Click += new System.EventHandler(this.buttonRemoveShip_Click);
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(22, 22);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(147, 33);
this.buttonAddShip.TabIndex = 0;
this.buttonAddShip.Text = "Добавить корабль";
this.buttonAddShip.UseVisualStyleBackColor = true;
this.buttonAddShip.Click += new System.EventHandler(this.buttonAddShip_Click);
//
// pictureBoxCollection
//
this.pictureBoxCollection.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBoxCollection.Location = new System.Drawing.Point(-1, 1);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(613, 450);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// FormShipCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.groupBoxBattleShip);
this.Name = "FormShipCollection";
this.Text = "FormShipCollection";
this.groupBoxBattleShip.ResumeLayout(false);
this.groupBoxBattleShip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxBattleShip;
private Button buttonRefreshCollection;
private Button buttonRemoveShip;
private Button buttonAddShip;
private PictureBox pictureBoxCollection;
private MaskedTextBox maskedTextBoxNumber;
}
}

View File

@ -1,77 +0,0 @@
using Battleship.DrawningObjects;
using Battleship.Generics;
using Battleship.MovementStrategy;
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;
namespace Battleship
{
public partial class FormShipCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly ShipGenericCollection<DrawningShip,DrawningObjectShip> _ships;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
{
InitializeComponent();
_ships = new ShipGenericCollection<DrawningShip, DrawningObjectShip>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddShip_Click(object sender, EventArgs e)
{
FormBattleship form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_ships + form.SelectedShip != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _ships.ShowShips();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
private void buttonRemoveShip_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_ships - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _ships.ShowShips();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _ships.ShowShips();
}
}
}

View File

@ -1,60 +0,0 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

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

@ -1,58 +0,0 @@
using Battleship.MovementStrategy;
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 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

@ -1,57 +0,0 @@
using Battleship.MovementStrategy;
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 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

@ -1,57 +0,0 @@
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;
/// <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

@ -11,7 +11,7 @@ namespace Battleship
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormShipCollection());
Application.Run(new Battleship());
}
}
}

View File

@ -1,88 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Generics
{
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T ship)
{
if (_places[Count - 1] != null)
return -1;
return Insert(ship,0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// /// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T ship, int position)
{
if (!(position >= 0 && position < Count))
return -1;
if (_places[position] != null)
{
int ind = position;
while (ind < Count && _places[ind] != null)
ind++;
if (ind == Count)
return -1;
for (int i = ind - 1; i >= position; i--)
_places[i + 1] = _places[i];
}
_places[position] = ship;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (!(position >= 0 && position < Count) || _places[position] == null)
return false;
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
}
}

View File

@ -1,86 +0,0 @@
using Battleship.DrawningObjects;
using Battleship.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Generics
{
internal class ShipGenericCollection<T, U>
where T : DrawningShip
where U : IMoveableObject
{
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 185;
private readonly int _placeSizeHeight = 90;
private readonly SetGeneric<T> _collection;
public ShipGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static int operator +(ShipGenericCollection<T, U>? collect, T? obj)
{
if (obj != null && collect != null)
return collect._collection.Insert(obj);
return -1;
}
public static bool operator -(ShipGenericCollection<T, U>? collect, int pos)
{
T? obj = collect?._collection.Get(pos);
if (obj != null && collect != null)
{
return collect._collection.Remove(pos);
}
return false;
}
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
public Bitmap ShowShips()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void DrawObjects(Graphics g)
{
for (int i = 0; i < _collection.Count; i++)
{
DrawningShip? ship = _collection.Get(i);
if(ship != null)
{
int inRow = _pictureWidth / _placeSizeWidth;
ship.SetPosition(i % inRow * _placeSizeWidth, (_collection.Count / inRow - 1 - i / inRow) * _placeSizeHeight + 5);
ship.DrawTransport(g);
}
}
}
}
}

View File

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}