Compare commits
33 Commits
main
...
LabWork_08
Author | SHA1 | Date | |
---|---|---|---|
2ca0fb3639 | |||
4717ef7fcd | |||
536b1d422e | |||
83035ffc77 | |||
9f41ebdfdf | |||
2d91563ed9 | |||
d5982487e8 | |||
5461093319 | |||
42de83a5cd | |||
f631482c24 | |||
a55aef24c0 | |||
c8a60fa26f | |||
3afc6e4ab6 | |||
1c81aec3af | |||
f6b058b912 | |||
f9fa6794b5 | |||
8b4ed85f88 | |||
091db401f9 | |||
2b46380712 | |||
366d614e4a | |||
27b4633cdc | |||
1516f11c25 | |||
7eaadef863 | |||
7686622b37 | |||
6eb869fd5c | |||
596b0127e7 | |||
7f35155da4 | |||
1fdfd6ec66 | |||
b05fca00fe | |||
fa9a16f4f4 | |||
eff115d3da | |||
bc2493c8bc | |||
bccd917047 |
138
Battleship/Battleship/AbstractStrategy.cs
Normal file
138
Battleship/Battleship/AbstractStrategy.cs
Normal file
@ -0,0 +1,138 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
20
Battleship/Battleship/AppSetting.json
Normal file
20
Battleship/Battleship/AppSetting.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs/log_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "Battleship"
|
||||
}
|
||||
}
|
||||
}
|
@ -1,72 +0,0 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -8,6 +8,15 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -1,195 +1,52 @@
|
||||
using System;
|
||||
using Battleship;
|
||||
using Battleship.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Battleship
|
||||
namespace Battleship.DrawningObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
|
||||
/// </summary>
|
||||
public class DrawningBattleship
|
||||
public class DrawningBattleship : DrawningShip
|
||||
{
|
||||
/// <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)
|
||||
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)
|
||||
{
|
||||
if (width < _buttleshipWidth || height < _buttleshipHeight)
|
||||
if(EntityShip != null)
|
||||
{
|
||||
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;
|
||||
EntityShip = new EntityBattleship(speed, weight, bodyColor, additionalColor, tower, section);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Изменение направления перемещения
|
||||
/// </summary>
|
||||
/// <param name="direction">Направление</param>
|
||||
public void MoveTransport(DirectionType direction)
|
||||
public override void DrawTransport(Graphics g)
|
||||
{
|
||||
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)
|
||||
if (EntityShip is not EntityBattleship battleShip)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Pen pen = new(Color.Black, 2);
|
||||
Brush additionalBrush = new
|
||||
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);
|
||||
SolidBrush(battleShip.AdditionalColor);
|
||||
base.DrawTransport(g);
|
||||
|
||||
//орудийная башня
|
||||
if (EntityBattleship.Tower)
|
||||
if (battleShip.Tower)
|
||||
{
|
||||
Brush baseBrush = new SolidBrush(Color.White);
|
||||
g.FillRectangle(baseBrush, _startPosX + 108, _startPosY + 28, 15, 15);
|
||||
g.FillRectangle(additionalBrush, _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 (EntityBattleship.Section)
|
||||
if (battleShip.Section)
|
||||
{
|
||||
Brush sectionBrush = new
|
||||
SolidBrush(Color.Gray);
|
||||
g.FillRectangle(sectionBrush, _startPosX + 20, _startPosY + 70, 40, 10);
|
||||
g.FillRectangle(additionalBrush, _startPosX + 20, _startPosY + 70, 40, 10);
|
||||
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 70, 40, 10);
|
||||
g.FillRectangle(sectionBrush, _startPosX + 75, _startPosY + 70, 40, 10);
|
||||
g.FillRectangle(additionalBrush, _startPosX + 75, _startPosY + 70, 40, 10);
|
||||
g.DrawRectangle(pen, _startPosX + 75, _startPosY + 70, 40, 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
41
Battleship/Battleship/DrawningObjectShip.cs
Normal file
41
Battleship/Battleship/DrawningObjectShip.cs
Normal file
@ -0,0 +1,41 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
231
Battleship/Battleship/DrawningShip.cs
Normal file
231
Battleship/Battleship/DrawningShip.cs
Normal file
@ -0,0 +1,231 @@
|
||||
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>
|
||||
public int _pictureWidth;
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
60
Battleship/Battleship/DrawningShipEqutables.cs
Normal file
60
Battleship/Battleship/DrawningShipEqutables.cs
Normal file
@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Battleship.DrawningObjects;
|
||||
using Battleship.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Battleship.Generics
|
||||
{
|
||||
internal class DrawningShipEqutables: IEqualityComparer<DrawningShip?>
|
||||
{
|
||||
public bool Equals(DrawningShip? x, DrawningShip? y)
|
||||
{
|
||||
if (x == null || x.EntityShip == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(x));
|
||||
}
|
||||
if (y == null || y.EntityShip == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(y));
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityShip.Speed != y.EntityShip.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityShip.Weight != y.EntityShip.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x is DrawningBattleship && y is DrawningBattleship)
|
||||
{
|
||||
EntityBattleship EntityX = (EntityBattleship)x.EntityShip;
|
||||
EntityBattleship EntityY = (EntityBattleship)y.EntityShip;
|
||||
|
||||
if (EntityX.Tower != EntityY.Tower)
|
||||
return false;
|
||||
if(EntityX.Section != EntityY.Section)
|
||||
return false;
|
||||
if(EntityX.AdditionalColor != EntityY.AdditionalColor)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetHashCode([DisallowNull] DrawningShip obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,28 +1,15 @@
|
||||
using System;
|
||||
using Battleship.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Battleship
|
||||
namespace Battleship.Entities
|
||||
{
|
||||
public class EntityBattleship
|
||||
internal class EntityBattleship: 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 Color AdditionalColor { get; private set; }
|
||||
/// <summary>
|
||||
/// Признак (опция) наличия башни
|
||||
@ -35,7 +22,7 @@ namespace Battleship
|
||||
/// <summary>
|
||||
/// Шаг перемещения
|
||||
/// </summary>
|
||||
public double Step => (double)Speed * 100 / Weight;
|
||||
|
||||
/// <summary>
|
||||
/// Инициализация полей объекта-класса спортивного автомобиля
|
||||
/// </summary>
|
||||
@ -45,15 +32,17 @@ namespace Battleship
|
||||
/// <param name="additionalColor">Дополнительный цвет</param>
|
||||
/// <param name="tower">Признак наличия орудийной башни</param>
|
||||
/// <param name="section">Признак наличия отсека под ракеты</param>
|
||||
public void Init(int speed, double weight, Color bodyColor, Color
|
||||
additionalColor, bool tower, bool section)
|
||||
public EntityBattleship(int speed, double weight, Color bodyColor, Color
|
||||
additionalColor, bool tower, bool section) : base(speed, weight, bodyColor)
|
||||
{
|
||||
Speed = speed;
|
||||
Weight = weight;
|
||||
BodyColor = bodyColor;
|
||||
AdditionalColor = additionalColor;
|
||||
AdditionalColor = additionalColor;
|
||||
Tower = tower;
|
||||
Section = section;
|
||||
}
|
||||
|
||||
public void setAdditionalColor(Color color)
|
||||
{
|
||||
AdditionalColor = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
46
Battleship/Battleship/EntityShip.cs
Normal file
46
Battleship/Battleship/EntityShip.cs
Normal file
@ -0,0 +1,46 @@
|
||||
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;
|
||||
}
|
||||
|
||||
public void setBodyColor(Color color)
|
||||
{
|
||||
BodyColor = color;
|
||||
}
|
||||
}
|
||||
}
|
65
Battleship/Battleship/ExtentionDrawningShip.cs
Normal file
65
Battleship/Battleship/ExtentionDrawningShip.cs
Normal file
@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Battleship.Entities;
|
||||
|
||||
namespace Battleship.DrawningObjects
|
||||
{
|
||||
public static class ExtentionDrawningShip
|
||||
{
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="info">Строка с данными для создания объекта</param>
|
||||
/// <param name="separatorForObject">Разделитель даннных</param>
|
||||
/// <param name="width">Ширина</param>
|
||||
/// <param name="height">Высота</param>
|
||||
/// <returns>Объект</returns>
|
||||
public static DrawningShip? CreateDrawningShip(this string info, char
|
||||
separatorForObject, int width, int height)
|
||||
{
|
||||
string[] strs = info.Split(separatorForObject);
|
||||
if (strs.Length == 3)
|
||||
{
|
||||
return new DrawningShip(Convert.ToInt32(strs[0]),
|
||||
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
|
||||
}
|
||||
if (strs.Length == 6)
|
||||
{
|
||||
return new DrawningBattleship(Convert.ToInt32(strs[0]),
|
||||
Convert.ToInt32(strs[1]),
|
||||
Color.FromName(strs[2]),
|
||||
Color.FromName(strs[3]),
|
||||
Convert.ToBoolean(strs[4]),
|
||||
Convert.ToBoolean(strs[5]), width, height);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение данных для сохранения в файл
|
||||
/// </summary>
|
||||
/// <param name="drawningShip">Сохраняемый объект</param>
|
||||
/// <param name="separatorForObject">Разделитель даннных</param>
|
||||
/// <returns>Строка с данными по объекту</returns>
|
||||
public static string GetDataForSave(this DrawningShip drawningShip,
|
||||
char separatorForObject)
|
||||
{
|
||||
var ship = drawningShip.EntityShip;
|
||||
if (ship == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
var str = $"{ship.Speed}{separatorForObject}{ship.Weight}{separatorForObject}{ship.BodyColor.Name}";
|
||||
if (ship is not EntityBattleship battleship)
|
||||
{
|
||||
return str;
|
||||
}
|
||||
return $"{str}{separatorForObject}{battleship.AdditionalColor.Name}" +
|
||||
$"{separatorForObject}{battleship.Tower}{separatorForObject}{battleship.Section}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
namespace Battleship
|
||||
{
|
||||
partial class Battleship
|
||||
partial class FormBattleship
|
||||
{
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
@ -34,6 +34,10 @@
|
||||
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();
|
||||
//
|
||||
@ -51,9 +55,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(75, 23);
|
||||
this.buttonCreate.Size = new System.Drawing.Size(114, 23);
|
||||
this.buttonCreate.TabIndex = 6;
|
||||
this.buttonCreate.Text = "Создать";
|
||||
this.buttonCreate.Text = "Создать корабль";
|
||||
this.buttonCreate.UseVisualStyleBackColor = true;
|
||||
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
|
||||
//
|
||||
@ -105,18 +109,67 @@
|
||||
this.buttonRight.UseVisualStyleBackColor = true;
|
||||
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
|
||||
//
|
||||
// Battleship
|
||||
// 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
|
||||
//
|
||||
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 = "Battleship";
|
||||
this.Name = "FormBattleship";
|
||||
this.Text = "Form1";
|
||||
((System.ComponentModel.ISupportInitialize)(this.pictureBoxBattleship)).EndInit();
|
||||
this.ResumeLayout(false);
|
||||
@ -130,5 +183,9 @@
|
||||
private Button buttonLeft;
|
||||
private Button buttonDown;
|
||||
private Button buttonRight;
|
||||
private Button buttonCreateAdd;
|
||||
private Button buttonStep;
|
||||
private ComboBox comboBoxStrategy;
|
||||
private Button buttonSelectShip;
|
||||
}
|
||||
}
|
161
Battleship/Battleship/FormBattleship.cs
Normal file
161
Battleship/Battleship/FormBattleship.cs
Normal file
@ -0,0 +1,161 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
277
Battleship/Battleship/FormShipCollection.Designer.cs
generated
Normal file
277
Battleship/Battleship/FormShipCollection.Designer.cs
generated
Normal file
@ -0,0 +1,277 @@
|
||||
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.buttonSortByColor = new System.Windows.Forms.Button();
|
||||
this.buttonSortByType = new System.Windows.Forms.Button();
|
||||
this.groupBox1 = new System.Windows.Forms.GroupBox();
|
||||
this.textBoxStorageName = new System.Windows.Forms.TextBox();
|
||||
this.listBoxStorages = new System.Windows.Forms.ListBox();
|
||||
this.buttonAddObject = new System.Windows.Forms.Button();
|
||||
this.buttonDelObject = new System.Windows.Forms.Button();
|
||||
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.menuStrip1 = new System.Windows.Forms.MenuStrip();
|
||||
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
this.сохранениеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
this.загрузкаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
|
||||
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
|
||||
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
|
||||
this.groupBoxBattleShip.SuspendLayout();
|
||||
this.groupBox1.SuspendLayout();
|
||||
this.menuStrip1.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.buttonSortByColor);
|
||||
this.groupBoxBattleShip.Controls.Add(this.buttonSortByType);
|
||||
this.groupBoxBattleShip.Controls.Add(this.groupBox1);
|
||||
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.Controls.Add(this.menuStrip1);
|
||||
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 = "Инструменты";
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
this.buttonSortByColor.Location = new System.Drawing.Point(24, 267);
|
||||
this.buttonSortByColor.Name = "buttonSortByColor";
|
||||
this.buttonSortByColor.Size = new System.Drawing.Size(146, 23);
|
||||
this.buttonSortByColor.TabIndex = 6;
|
||||
this.buttonSortByColor.Text = "Сортировка по цвету";
|
||||
this.buttonSortByColor.UseVisualStyleBackColor = true;
|
||||
this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click);
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
this.buttonSortByType.Location = new System.Drawing.Point(24, 238);
|
||||
this.buttonSortByType.Name = "buttonSortByType";
|
||||
this.buttonSortByType.Size = new System.Drawing.Size(146, 23);
|
||||
this.buttonSortByType.TabIndex = 5;
|
||||
this.buttonSortByType.Text = "Сортировка по типу";
|
||||
this.buttonSortByType.UseVisualStyleBackColor = true;
|
||||
this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click);
|
||||
//
|
||||
// groupBox1
|
||||
//
|
||||
this.groupBox1.Controls.Add(this.textBoxStorageName);
|
||||
this.groupBox1.Controls.Add(this.listBoxStorages);
|
||||
this.groupBox1.Controls.Add(this.buttonAddObject);
|
||||
this.groupBox1.Controls.Add(this.buttonDelObject);
|
||||
this.groupBox1.Location = new System.Drawing.Point(6, 46);
|
||||
this.groupBox1.Name = "groupBox1";
|
||||
this.groupBox1.Size = new System.Drawing.Size(174, 186);
|
||||
this.groupBox1.TabIndex = 1;
|
||||
this.groupBox1.TabStop = false;
|
||||
this.groupBox1.Text = "Набор";
|
||||
//
|
||||
// textBoxStorageName
|
||||
//
|
||||
this.textBoxStorageName.Location = new System.Drawing.Point(17, 22);
|
||||
this.textBoxStorageName.Name = "textBoxStorageName";
|
||||
this.textBoxStorageName.Size = new System.Drawing.Size(147, 23);
|
||||
this.textBoxStorageName.TabIndex = 4;
|
||||
//
|
||||
// listBoxStorages
|
||||
//
|
||||
this.listBoxStorages.FormattingEnabled = true;
|
||||
this.listBoxStorages.ItemHeight = 15;
|
||||
this.listBoxStorages.Location = new System.Drawing.Point(18, 80);
|
||||
this.listBoxStorages.Name = "listBoxStorages";
|
||||
this.listBoxStorages.Size = new System.Drawing.Size(147, 64);
|
||||
this.listBoxStorages.TabIndex = 3;
|
||||
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.ListBoxObjects_SelectedIndexChanged);
|
||||
//
|
||||
// buttonAddObject
|
||||
//
|
||||
this.buttonAddObject.Location = new System.Drawing.Point(17, 51);
|
||||
this.buttonAddObject.Name = "buttonAddObject";
|
||||
this.buttonAddObject.Size = new System.Drawing.Size(147, 23);
|
||||
this.buttonAddObject.TabIndex = 2;
|
||||
this.buttonAddObject.Text = "Добавить набор";
|
||||
this.buttonAddObject.UseVisualStyleBackColor = true;
|
||||
this.buttonAddObject.Click += new System.EventHandler(this.buttonAddObject_Click);
|
||||
//
|
||||
// buttonDelObject
|
||||
//
|
||||
this.buttonDelObject.Location = new System.Drawing.Point(18, 150);
|
||||
this.buttonDelObject.Name = "buttonDelObject";
|
||||
this.buttonDelObject.Size = new System.Drawing.Size(147, 23);
|
||||
this.buttonDelObject.TabIndex = 1;
|
||||
this.buttonDelObject.Text = "Удалить набор";
|
||||
this.buttonDelObject.UseVisualStyleBackColor = true;
|
||||
this.buttonDelObject.Click += new System.EventHandler(this.buttonDelObject_Click);
|
||||
//
|
||||
// maskedTextBoxNumber
|
||||
//
|
||||
this.maskedTextBoxNumber.Location = new System.Drawing.Point(24, 345);
|
||||
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(23, 406);
|
||||
this.buttonRefreshCollection.Name = "buttonRefreshCollection";
|
||||
this.buttonRefreshCollection.Size = new System.Drawing.Size(147, 31);
|
||||
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(23, 374);
|
||||
this.buttonRemoveShip.Name = "buttonRemoveShip";
|
||||
this.buttonRemoveShip.Size = new System.Drawing.Size(147, 26);
|
||||
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(23, 309);
|
||||
this.buttonAddShip.Name = "buttonAddShip";
|
||||
this.buttonAddShip.Size = new System.Drawing.Size(147, 30);
|
||||
this.buttonAddShip.TabIndex = 0;
|
||||
this.buttonAddShip.Text = "Добавить корабль";
|
||||
this.buttonAddShip.UseVisualStyleBackColor = true;
|
||||
this.buttonAddShip.Click += new System.EventHandler(this.buttonAddShip_Click);
|
||||
//
|
||||
// menuStrip1
|
||||
//
|
||||
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
|
||||
this.файлToolStripMenuItem});
|
||||
this.menuStrip1.Location = new System.Drawing.Point(3, 19);
|
||||
this.menuStrip1.Name = "menuStrip1";
|
||||
this.menuStrip1.Size = new System.Drawing.Size(177, 24);
|
||||
this.menuStrip1.TabIndex = 4;
|
||||
this.menuStrip1.Text = "menuStrip1";
|
||||
//
|
||||
// файлToolStripMenuItem
|
||||
//
|
||||
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
|
||||
this.сохранениеToolStripMenuItem,
|
||||
this.загрузкаToolStripMenuItem});
|
||||
this.файлToolStripMenuItem.Name = "файлToolStripMenuItem";
|
||||
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
|
||||
this.файлToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// сохранениеToolStripMenuItem
|
||||
//
|
||||
this.сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
|
||||
this.сохранениеToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
|
||||
this.сохранениеToolStripMenuItem.Text = "Сохранение";
|
||||
this.сохранениеToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
|
||||
//
|
||||
// загрузкаToolStripMenuItem
|
||||
//
|
||||
this.загрузкаToolStripMenuItem.Name = "загрузкаToolStripMenuItem";
|
||||
this.загрузкаToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
|
||||
this.загрузкаToolStripMenuItem.Text = "Загрузка";
|
||||
this.загрузкаToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_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;
|
||||
//
|
||||
// openFileDialog
|
||||
//
|
||||
this.openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// saveFileDialog
|
||||
//
|
||||
this.saveFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// 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.MainMenuStrip = this.menuStrip1;
|
||||
this.Name = "FormShipCollection";
|
||||
this.Text = "FormShipCollection";
|
||||
this.groupBoxBattleShip.ResumeLayout(false);
|
||||
this.groupBoxBattleShip.PerformLayout();
|
||||
this.groupBox1.ResumeLayout(false);
|
||||
this.groupBox1.PerformLayout();
|
||||
this.menuStrip1.ResumeLayout(false);
|
||||
this.menuStrip1.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;
|
||||
private GroupBox groupBox1;
|
||||
private TextBox textBoxStorageName;
|
||||
private ListBox listBoxStorages;
|
||||
private Button buttonAddObject;
|
||||
private Button buttonDelObject;
|
||||
private MenuStrip menuStrip1;
|
||||
private ToolStripMenuItem файлToolStripMenuItem;
|
||||
private ToolStripMenuItem сохранениеToolStripMenuItem;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private ToolStripMenuItem загрузкаToolStripMenuItem;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
287
Battleship/Battleship/FormShipCollection.cs
Normal file
287
Battleship/Battleship/FormShipCollection.cs
Normal file
@ -0,0 +1,287 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Battleship.DrawningObjects;
|
||||
using Battleship.Exceptions;
|
||||
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 ShipsGenericStorage _storage;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormShipCollection(ILogger<FormShipCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Сохранение"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Загрузка"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if(openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
|
||||
}
|
||||
}
|
||||
ReloadObjects();
|
||||
}
|
||||
|
||||
private void ReloadObjects()
|
||||
{
|
||||
int index = listBoxStorages.SelectedIndex;
|
||||
listBoxStorages.Items.Clear();
|
||||
for (int i = 0; i < _storage.Keys.Count; i++)
|
||||
{
|
||||
listBoxStorages.Items.Add(_storage.Keys[i].Name);
|
||||
}
|
||||
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
|
||||
>= listBoxStorages.Items.Count))
|
||||
{
|
||||
listBoxStorages.SelectedIndex = 0;
|
||||
}
|
||||
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
|
||||
index < listBoxStorages.Items.Count)
|
||||
{
|
||||
listBoxStorages.SelectedIndex = index;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление набора в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void buttonAddObject_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxStorageName.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор набора
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
pictureBoxCollection.Image =
|
||||
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowShips();
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление набора
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void buttonDelObject_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
string nameSet = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
|
||||
if (MessageBox.Show($"Удалить объект {nameSet}?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(nameSet);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удален набор: {nameSet}");
|
||||
}
|
||||
_logger.LogWarning("Отмена удаления набора");
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление объекта в набор
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void buttonAddShip_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var FormShipConfig = new FormShipConfig();
|
||||
FormShipConfig.AddEvent(AddShip);
|
||||
FormShipConfig.Show();
|
||||
}
|
||||
private void AddShip(DrawningShip drawningShip)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning("Добавление пустого объекта");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (obj + drawningShip)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
_logger.LogInformation($"Объект {obj.GetType()} добавлен");
|
||||
}
|
||||
}
|
||||
catch(StorageOverflowException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonRemoveShip_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning("Удаление объекта из несуществующего набора");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
_logger.LogWarning("Отмена удаления объекта");
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
try
|
||||
{
|
||||
if (obj - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
}
|
||||
catch (ShipNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Нет объекта{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
_logger.LogWarning($"Было введено не число");
|
||||
MessageBox.Show("Введите число");
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonRefreshCollection_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
||||
string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
}
|
||||
|
||||
private void buttonSortByType_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByType());
|
||||
private void buttonSortByColor_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByColor());
|
||||
private void CompareShips(IComparer<DrawningShip?> comparer)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
||||
string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
obj.Sort(comparer);
|
||||
pictureBoxCollection.Image = obj.ShowShips();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
69
Battleship/Battleship/FormShipCollection.resx
Normal file
69
Battleship/Battleship/FormShipCollection.resx
Normal file
@ -0,0 +1,69 @@
|
||||
<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>
|
||||
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>132, 17</value>
|
||||
</metadata>
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>272, 17</value>
|
||||
</metadata>
|
||||
</root>
|
389
Battleship/Battleship/FormShipConfig.Designer.cs
generated
Normal file
389
Battleship/Battleship/FormShipConfig.Designer.cs
generated
Normal file
@ -0,0 +1,389 @@
|
||||
namespace Battleship
|
||||
{
|
||||
partial class FormShipConfig
|
||||
{
|
||||
/// <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.groupBoxParameters = new System.Windows.Forms.GroupBox();
|
||||
this.labelModifiedObject = new System.Windows.Forms.Label();
|
||||
this.labelSimpleObject = new System.Windows.Forms.Label();
|
||||
this.groupBoxColor = new System.Windows.Forms.GroupBox();
|
||||
this.panelPurple = new System.Windows.Forms.Panel();
|
||||
this.panelBlack = new System.Windows.Forms.Panel();
|
||||
this.panelGray = new System.Windows.Forms.Panel();
|
||||
this.panelWhite = new System.Windows.Forms.Panel();
|
||||
this.panelYellow = new System.Windows.Forms.Panel();
|
||||
this.panelBlue = new System.Windows.Forms.Panel();
|
||||
this.panelGreen = new System.Windows.Forms.Panel();
|
||||
this.panelRed = new System.Windows.Forms.Panel();
|
||||
this.checkBoxRocket = new System.Windows.Forms.CheckBox();
|
||||
this.checkBoxTower = new System.Windows.Forms.CheckBox();
|
||||
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
|
||||
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
|
||||
this.labelWeight = new System.Windows.Forms.Label();
|
||||
this.labelSpeed = new System.Windows.Forms.Label();
|
||||
this.panelPicture = new System.Windows.Forms.Panel();
|
||||
this.labelAddColor = new System.Windows.Forms.Label();
|
||||
this.labelBodyColor = new System.Windows.Forms.Label();
|
||||
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
|
||||
this.buttonAdd = new System.Windows.Forms.Button();
|
||||
this.buttonCancel = new System.Windows.Forms.Button();
|
||||
this.groupBoxParameters.SuspendLayout();
|
||||
this.groupBoxColor.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
|
||||
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
|
||||
this.panelPicture.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// groupBoxParameters
|
||||
//
|
||||
this.groupBoxParameters.Controls.Add(this.labelModifiedObject);
|
||||
this.groupBoxParameters.Controls.Add(this.labelSimpleObject);
|
||||
this.groupBoxParameters.Controls.Add(this.groupBoxColor);
|
||||
this.groupBoxParameters.Controls.Add(this.checkBoxRocket);
|
||||
this.groupBoxParameters.Controls.Add(this.checkBoxTower);
|
||||
this.groupBoxParameters.Controls.Add(this.numericUpDownWeight);
|
||||
this.groupBoxParameters.Controls.Add(this.numericUpDownSpeed);
|
||||
this.groupBoxParameters.Controls.Add(this.labelWeight);
|
||||
this.groupBoxParameters.Controls.Add(this.labelSpeed);
|
||||
this.groupBoxParameters.Location = new System.Drawing.Point(12, 1);
|
||||
this.groupBoxParameters.Name = "groupBoxParameters";
|
||||
this.groupBoxParameters.Size = new System.Drawing.Size(514, 287);
|
||||
this.groupBoxParameters.TabIndex = 0;
|
||||
this.groupBoxParameters.TabStop = false;
|
||||
this.groupBoxParameters.Text = "Параметры";
|
||||
//
|
||||
// labelModifiedObject
|
||||
//
|
||||
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
|
||||
this.labelModifiedObject.Location = new System.Drawing.Point(377, 208);
|
||||
this.labelModifiedObject.Name = "labelModifiedObject";
|
||||
this.labelModifiedObject.Size = new System.Drawing.Size(109, 38);
|
||||
this.labelModifiedObject.TabIndex = 8;
|
||||
this.labelModifiedObject.Text = "Продвинутый";
|
||||
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
|
||||
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
|
||||
//
|
||||
// labelSimpleObject
|
||||
//
|
||||
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
|
||||
this.labelSimpleObject.Location = new System.Drawing.Point(229, 208);
|
||||
this.labelSimpleObject.Name = "labelSimpleObject";
|
||||
this.labelSimpleObject.Size = new System.Drawing.Size(109, 38);
|
||||
this.labelSimpleObject.TabIndex = 7;
|
||||
this.labelSimpleObject.Text = "Простой";
|
||||
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
|
||||
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
|
||||
//
|
||||
// groupBoxColor
|
||||
//
|
||||
this.groupBoxColor.Controls.Add(this.panelPurple);
|
||||
this.groupBoxColor.Controls.Add(this.panelBlack);
|
||||
this.groupBoxColor.Controls.Add(this.panelGray);
|
||||
this.groupBoxColor.Controls.Add(this.panelWhite);
|
||||
this.groupBoxColor.Controls.Add(this.panelYellow);
|
||||
this.groupBoxColor.Controls.Add(this.panelBlue);
|
||||
this.groupBoxColor.Controls.Add(this.panelGreen);
|
||||
this.groupBoxColor.Controls.Add(this.panelRed);
|
||||
this.groupBoxColor.Location = new System.Drawing.Point(229, 22);
|
||||
this.groupBoxColor.Name = "groupBoxColor";
|
||||
this.groupBoxColor.Size = new System.Drawing.Size(257, 167);
|
||||
this.groupBoxColor.TabIndex = 6;
|
||||
this.groupBoxColor.TabStop = false;
|
||||
this.groupBoxColor.Text = "Цвета";
|
||||
//
|
||||
// panelPurple
|
||||
//
|
||||
this.panelPurple.BackColor = System.Drawing.Color.Plum;
|
||||
this.panelPurple.Location = new System.Drawing.Point(187, 78);
|
||||
this.panelPurple.Name = "panelPurple";
|
||||
this.panelPurple.Size = new System.Drawing.Size(50, 50);
|
||||
this.panelPurple.TabIndex = 0;
|
||||
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
|
||||
//
|
||||
// panelBlack
|
||||
//
|
||||
this.panelBlack.BackColor = System.Drawing.Color.Black;
|
||||
this.panelBlack.Location = new System.Drawing.Point(131, 78);
|
||||
this.panelBlack.Name = "panelBlack";
|
||||
this.panelBlack.Size = new System.Drawing.Size(50, 50);
|
||||
this.panelBlack.TabIndex = 0;
|
||||
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
|
||||
//
|
||||
// panelGray
|
||||
//
|
||||
this.panelGray.BackColor = System.Drawing.Color.Gray;
|
||||
this.panelGray.Location = new System.Drawing.Point(75, 78);
|
||||
this.panelGray.Name = "panelGray";
|
||||
this.panelGray.Size = new System.Drawing.Size(50, 50);
|
||||
this.panelGray.TabIndex = 7;
|
||||
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
|
||||
//
|
||||
// panelWhite
|
||||
//
|
||||
this.panelWhite.BackColor = System.Drawing.Color.White;
|
||||
this.panelWhite.Location = new System.Drawing.Point(19, 78);
|
||||
this.panelWhite.Name = "panelWhite";
|
||||
this.panelWhite.Size = new System.Drawing.Size(50, 50);
|
||||
this.panelWhite.TabIndex = 0;
|
||||
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
|
||||
//
|
||||
// panelYellow
|
||||
//
|
||||
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
|
||||
this.panelYellow.Location = new System.Drawing.Point(187, 22);
|
||||
this.panelYellow.Name = "panelYellow";
|
||||
this.panelYellow.Size = new System.Drawing.Size(50, 50);
|
||||
this.panelYellow.TabIndex = 0;
|
||||
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
|
||||
//
|
||||
// panelBlue
|
||||
//
|
||||
this.panelBlue.BackColor = System.Drawing.Color.SlateBlue;
|
||||
this.panelBlue.Location = new System.Drawing.Point(131, 22);
|
||||
this.panelBlue.Name = "panelBlue";
|
||||
this.panelBlue.Size = new System.Drawing.Size(50, 50);
|
||||
this.panelBlue.TabIndex = 0;
|
||||
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
|
||||
//
|
||||
// panelGreen
|
||||
//
|
||||
this.panelGreen.BackColor = System.Drawing.Color.OliveDrab;
|
||||
this.panelGreen.Location = new System.Drawing.Point(75, 22);
|
||||
this.panelGreen.Name = "panelGreen";
|
||||
this.panelGreen.Size = new System.Drawing.Size(50, 50);
|
||||
this.panelGreen.TabIndex = 0;
|
||||
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
|
||||
//
|
||||
// panelRed
|
||||
//
|
||||
this.panelRed.BackColor = System.Drawing.Color.Maroon;
|
||||
this.panelRed.Location = new System.Drawing.Point(19, 22);
|
||||
this.panelRed.Name = "panelRed";
|
||||
this.panelRed.Size = new System.Drawing.Size(50, 50);
|
||||
this.panelRed.TabIndex = 0;
|
||||
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
|
||||
//
|
||||
// checkBoxRocket
|
||||
//
|
||||
this.checkBoxRocket.AutoSize = true;
|
||||
this.checkBoxRocket.Location = new System.Drawing.Point(10, 208);
|
||||
this.checkBoxRocket.Name = "checkBoxRocket";
|
||||
this.checkBoxRocket.Size = new System.Drawing.Size(180, 19);
|
||||
this.checkBoxRocket.TabIndex = 5;
|
||||
this.checkBoxRocket.Text = "Наличие отсеков под ракет ";
|
||||
this.checkBoxRocket.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// checkBoxTower
|
||||
//
|
||||
this.checkBoxTower.AutoSize = true;
|
||||
this.checkBoxTower.Location = new System.Drawing.Point(10, 170);
|
||||
this.checkBoxTower.Name = "checkBoxTower";
|
||||
this.checkBoxTower.Size = new System.Drawing.Size(180, 19);
|
||||
this.checkBoxTower.TabIndex = 4;
|
||||
this.checkBoxTower.Text = "Наличие орудийной башни";
|
||||
this.checkBoxTower.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// numericUpDownWeight
|
||||
//
|
||||
this.numericUpDownWeight.Location = new System.Drawing.Point(81, 100);
|
||||
this.numericUpDownWeight.Maximum = new decimal(new int[] {
|
||||
1000,
|
||||
0,
|
||||
0,
|
||||
0});
|
||||
this.numericUpDownWeight.Minimum = new decimal(new int[] {
|
||||
100,
|
||||
0,
|
||||
0,
|
||||
0});
|
||||
this.numericUpDownWeight.Name = "numericUpDownWeight";
|
||||
this.numericUpDownWeight.Size = new System.Drawing.Size(120, 23);
|
||||
this.numericUpDownWeight.TabIndex = 3;
|
||||
this.numericUpDownWeight.Value = new decimal(new int[] {
|
||||
100,
|
||||
0,
|
||||
0,
|
||||
0});
|
||||
//
|
||||
// numericUpDownSpeed
|
||||
//
|
||||
this.numericUpDownSpeed.Location = new System.Drawing.Point(81, 44);
|
||||
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
|
||||
1000,
|
||||
0,
|
||||
0,
|
||||
0});
|
||||
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
|
||||
100,
|
||||
0,
|
||||
0,
|
||||
0});
|
||||
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
|
||||
this.numericUpDownSpeed.Size = new System.Drawing.Size(120, 23);
|
||||
this.numericUpDownSpeed.TabIndex = 2;
|
||||
this.numericUpDownSpeed.Value = new decimal(new int[] {
|
||||
100,
|
||||
0,
|
||||
0,
|
||||
0});
|
||||
//
|
||||
// labelWeight
|
||||
//
|
||||
this.labelWeight.AutoSize = true;
|
||||
this.labelWeight.Location = new System.Drawing.Point(10, 100);
|
||||
this.labelWeight.Name = "labelWeight";
|
||||
this.labelWeight.Size = new System.Drawing.Size(32, 15);
|
||||
this.labelWeight.TabIndex = 1;
|
||||
this.labelWeight.Text = "Вес :";
|
||||
//
|
||||
// labelSpeed
|
||||
//
|
||||
this.labelSpeed.AutoSize = true;
|
||||
this.labelSpeed.Location = new System.Drawing.Point(10, 41);
|
||||
this.labelSpeed.Name = "labelSpeed";
|
||||
this.labelSpeed.Size = new System.Drawing.Size(65, 15);
|
||||
this.labelSpeed.TabIndex = 0;
|
||||
this.labelSpeed.Text = "Скорость :";
|
||||
//
|
||||
// panelPicture
|
||||
//
|
||||
this.panelPicture.AllowDrop = true;
|
||||
this.panelPicture.Controls.Add(this.labelAddColor);
|
||||
this.panelPicture.Controls.Add(this.labelBodyColor);
|
||||
this.panelPicture.Controls.Add(this.pictureBoxObject);
|
||||
this.panelPicture.Location = new System.Drawing.Point(532, 12);
|
||||
this.panelPicture.Name = "panelPicture";
|
||||
this.panelPicture.Size = new System.Drawing.Size(256, 216);
|
||||
this.panelPicture.TabIndex = 9;
|
||||
this.panelPicture.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
|
||||
this.panelPicture.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
|
||||
//
|
||||
// labelAddColor
|
||||
//
|
||||
this.labelAddColor.AllowDrop = true;
|
||||
this.labelAddColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
|
||||
this.labelAddColor.Location = new System.Drawing.Point(145, 17);
|
||||
this.labelAddColor.Name = "labelAddColor";
|
||||
this.labelAddColor.Size = new System.Drawing.Size(97, 28);
|
||||
this.labelAddColor.TabIndex = 12;
|
||||
this.labelAddColor.Text = "Доп. цвет";
|
||||
this.labelAddColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
|
||||
this.labelAddColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelColor_dragDrop);
|
||||
this.labelAddColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_dragEnter);
|
||||
//
|
||||
// labelBodyColor
|
||||
//
|
||||
this.labelBodyColor.AllowDrop = true;
|
||||
this.labelBodyColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
|
||||
this.labelBodyColor.Location = new System.Drawing.Point(15, 17);
|
||||
this.labelBodyColor.Name = "labelBodyColor";
|
||||
this.labelBodyColor.Size = new System.Drawing.Size(97, 28);
|
||||
this.labelBodyColor.TabIndex = 11;
|
||||
this.labelBodyColor.Text = "Цвет";
|
||||
this.labelBodyColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
|
||||
this.labelBodyColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelColor_dragDrop);
|
||||
this.labelBodyColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_dragEnter);
|
||||
//
|
||||
// pictureBoxObject
|
||||
//
|
||||
this.pictureBoxObject.Location = new System.Drawing.Point(15, 58);
|
||||
this.pictureBoxObject.Name = "pictureBoxObject";
|
||||
this.pictureBoxObject.Size = new System.Drawing.Size(227, 139);
|
||||
this.pictureBoxObject.TabIndex = 10;
|
||||
this.pictureBoxObject.TabStop = false;
|
||||
//
|
||||
// buttonAdd
|
||||
//
|
||||
this.buttonAdd.Location = new System.Drawing.Point(547, 244);
|
||||
this.buttonAdd.Name = "buttonAdd";
|
||||
this.buttonAdd.Size = new System.Drawing.Size(97, 32);
|
||||
this.buttonAdd.TabIndex = 13;
|
||||
this.buttonAdd.Text = "Добавить";
|
||||
this.buttonAdd.UseVisualStyleBackColor = true;
|
||||
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click_1);
|
||||
//
|
||||
// buttonCancel
|
||||
//
|
||||
this.buttonCancel.Location = new System.Drawing.Point(677, 244);
|
||||
this.buttonCancel.Name = "buttonCancel";
|
||||
this.buttonCancel.Size = new System.Drawing.Size(97, 32);
|
||||
this.buttonCancel.TabIndex = 14;
|
||||
this.buttonCancel.Text = "Отменить";
|
||||
this.buttonCancel.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// FormShipConfig
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(800, 288);
|
||||
this.Controls.Add(this.buttonAdd);
|
||||
this.Controls.Add(this.buttonCancel);
|
||||
this.Controls.Add(this.panelPicture);
|
||||
this.Controls.Add(this.groupBoxParameters);
|
||||
this.Name = "FormShipConfig";
|
||||
this.Text = "FormShipConfig";
|
||||
this.groupBoxParameters.ResumeLayout(false);
|
||||
this.groupBoxParameters.PerformLayout();
|
||||
this.groupBoxColor.ResumeLayout(false);
|
||||
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
|
||||
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
|
||||
this.panelPicture.ResumeLayout(false);
|
||||
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
|
||||
this.ResumeLayout(false);
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private GroupBox groupBoxParameters;
|
||||
private Label labelWeight;
|
||||
private Label labelSpeed;
|
||||
private NumericUpDown numericUpDownWeight;
|
||||
private NumericUpDown numericUpDownSpeed;
|
||||
private Label labelModifiedObject;
|
||||
private Label labelSimpleObject;
|
||||
private GroupBox groupBoxColor;
|
||||
private Panel panelPurple;
|
||||
private Panel panelBlack;
|
||||
private Panel panelGray;
|
||||
private Panel panelWhite;
|
||||
private Panel panelYellow;
|
||||
private Panel panelBlue;
|
||||
private Panel panelGreen;
|
||||
private Panel panelRed;
|
||||
private CheckBox checkBoxRocket;
|
||||
private CheckBox checkBoxTower;
|
||||
private Panel panelPicture;
|
||||
private PictureBox pictureBoxObject;
|
||||
private Label labelAddColor;
|
||||
private Label labelBodyColor;
|
||||
private Button buttonAdd;
|
||||
private Button buttonCancel;
|
||||
}
|
||||
}
|
166
Battleship/Battleship/FormShipConfig.cs
Normal file
166
Battleship/Battleship/FormShipConfig.cs
Normal file
@ -0,0 +1,166 @@
|
||||
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;
|
||||
using Battleship.DrawningObjects;
|
||||
using Battleship.Entities;
|
||||
|
||||
namespace Battleship
|
||||
{
|
||||
public partial class FormShipConfig : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Переменная-выбранный корабль
|
||||
/// </summary>
|
||||
DrawningShip? _ship = null;
|
||||
/// <summary>
|
||||
/// Событие
|
||||
/// </summary>
|
||||
public event Action<DrawningShip>? EventAddShip;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormShipConfig()
|
||||
{
|
||||
InitializeComponent();
|
||||
panelBlack.MouseDown += PanelColor_MouseDown;
|
||||
panelPurple.MouseDown += PanelColor_MouseDown;
|
||||
panelGray.MouseDown += PanelColor_MouseDown;
|
||||
panelGreen.MouseDown += PanelColor_MouseDown;
|
||||
panelRed.MouseDown += PanelColor_MouseDown;
|
||||
panelWhite.MouseDown += PanelColor_MouseDown;
|
||||
panelYellow.MouseDown += PanelColor_MouseDown;
|
||||
panelBlue.MouseDown += PanelColor_MouseDown;
|
||||
|
||||
buttonCancel.Click += (s, e) => Close();
|
||||
}
|
||||
/// <summary>
|
||||
/// Отрисовать
|
||||
/// </summary>
|
||||
private void DrawShip()
|
||||
{
|
||||
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
|
||||
Graphics gr = Graphics.FromImage(bmp);
|
||||
_ship?.SetPosition(5, 5);
|
||||
_ship?.DrawTransport(gr);
|
||||
pictureBoxObject.Image = bmp;
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление события
|
||||
/// </summary>
|
||||
/// <param name="ev">Привязанный метод</param>
|
||||
public void AddEvent(Action<DrawningShip> ev)
|
||||
{
|
||||
if (EventAddShip == null)
|
||||
{
|
||||
EventAddShip = ev;
|
||||
}
|
||||
else
|
||||
{
|
||||
EventAddShip += ev;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Передаем информацию при нажатии на Label
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
|
||||
{
|
||||
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
|
||||
}
|
||||
/// <summary>
|
||||
/// Проверка получаемой информации (ее типа на соответствие требуемому)
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void PanelObject_DragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
|
||||
{
|
||||
e.Effect = DragDropEffects.Copy;
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Effect = DragDropEffects.None;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Действия при приеме перетаскиваемой информации
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void PanelObject_DragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
switch (e.Data?.GetData(DataFormats.Text).ToString())
|
||||
{
|
||||
case "labelSimpleObject":
|
||||
_ship = new DrawningShip((int)numericUpDownSpeed.Value,
|
||||
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
|
||||
break;
|
||||
case "labelModifiedObject":
|
||||
_ship = new DrawningBattleship((int)numericUpDownSpeed.Value,
|
||||
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxTower.Checked,
|
||||
checkBoxRocket.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
|
||||
break;
|
||||
}
|
||||
DrawShip();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
|
||||
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
|
||||
{
|
||||
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
|
||||
}
|
||||
private void labelColor_dragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
|
||||
{
|
||||
e.Effect = DragDropEffects.Copy;
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Effect = DragDropEffects.None;
|
||||
}
|
||||
}
|
||||
private void labelColor_dragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
if (_ship == null)
|
||||
return;
|
||||
switch (((Label)sender).Name)
|
||||
{
|
||||
case "labelBodyColor":
|
||||
_ship?.EntityShip?.setBodyColor((Color)e.Data.GetData(typeof(Color)));
|
||||
break;
|
||||
case "labelAddColor":
|
||||
if (!(_ship is DrawningBattleship))
|
||||
return;
|
||||
(_ship.EntityShip as EntityBattleship)?.setAdditionalColor(color: (Color)e.Data.GetData(typeof(Color)));
|
||||
break;
|
||||
}
|
||||
DrawShip();
|
||||
}
|
||||
|
||||
private void buttonAdd_Click_1(object sender, EventArgs e)
|
||||
{
|
||||
EventAddShip?.Invoke(_ship);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
60
Battleship/Battleship/FormShipConfig.resx
Normal file
60
Battleship/Battleship/FormShipConfig.resx
Normal file
@ -0,0 +1,60 @@
|
||||
<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>
|
36
Battleship/Battleship/IMoveableObject.cs
Normal file
36
Battleship/Battleship/IMoveableObject.cs
Normal file
@ -0,0 +1,36 @@
|
||||
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);
|
||||
}
|
||||
}
|
58
Battleship/Battleship/MoveToBorder.cs
Normal file
58
Battleship/Battleship/MoveToBorder.cs
Normal file
@ -0,0 +1,58 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
57
Battleship/Battleship/MoveToCenter.cs
Normal file
57
Battleship/Battleship/MoveToCenter.cs
Normal file
@ -0,0 +1,57 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
57
Battleship/Battleship/ObjectParameters.cs
Normal file
57
Battleship/Battleship/ObjectParameters.cs
Normal file
@ -0,0 +1,57 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace Battleship
|
||||
{
|
||||
internal static class Program
|
||||
@ -8,10 +13,31 @@ namespace Battleship
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new Battleship());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormShipCollection>().AddLogging(option =>
|
||||
{
|
||||
string[] path = Directory.GetCurrentDirectory().Split('\\');
|
||||
string pathNeed = "";
|
||||
for (int i = 0; i < path.Length - 3; i++)
|
||||
{
|
||||
pathNeed += path[i] + "\\";
|
||||
}
|
||||
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true).Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
81
Battleship/Battleship/SetGeneric.cs
Normal file
81
Battleship/Battleship/SetGeneric.cs
Normal file
@ -0,0 +1,81 @@
|
||||
using Battleship.Exceptions;
|
||||
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
|
||||
{
|
||||
private readonly List<T?> _places;
|
||||
public int Count => _places.Count;
|
||||
private readonly int _maxCount;
|
||||
|
||||
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
|
||||
public SetGeneric(int count)
|
||||
{
|
||||
_maxCount = count;
|
||||
_places = new List<T?>(_maxCount);
|
||||
}
|
||||
|
||||
public bool Insert(T ship, IEqualityComparer<T?>? equal = null)
|
||||
{
|
||||
return Insert(ship, 0, equal);
|
||||
}
|
||||
|
||||
public bool Insert(T ship, int position, IEqualityComparer<T>? equal = null)
|
||||
{
|
||||
if (position < 0 || position >= _maxCount)
|
||||
throw new ShipNotFoundException(position);
|
||||
|
||||
if (Count >= _maxCount)
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
|
||||
if (equal != null && _places.Contains(ship, equal))
|
||||
throw new ArgumentException("Данный объект уже есть в коллекции");
|
||||
_places.Insert(0, ship);
|
||||
return true;
|
||||
}
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if (position < 0 || position > _maxCount || position >= Count)
|
||||
throw new ShipNotFoundException(position);
|
||||
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
public T? this[int position]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
return null;
|
||||
return _places[position];
|
||||
|
||||
}
|
||||
set
|
||||
{
|
||||
if (position < 0 || position > _maxCount || Count == _maxCount)
|
||||
return;
|
||||
_places[position] = value;
|
||||
}
|
||||
|
||||
}
|
||||
public IEnumerable<T> GetShips(int? maxShips = null)
|
||||
{
|
||||
for (int i = 0; i < _places.Count; ++i)
|
||||
{
|
||||
yield return _places[i];
|
||||
if (maxShips.HasValue && i == maxShips.Value)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
49
Battleship/Battleship/ShipCompareByColor.cs
Normal file
49
Battleship/Battleship/ShipCompareByColor.cs
Normal file
@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Battleship.DrawningObjects;
|
||||
using Battleship.Entities;
|
||||
|
||||
namespace Battleship.Generics
|
||||
{
|
||||
internal class ShipCompareByColor: IComparer<DrawningShip?>
|
||||
{
|
||||
public int Compare(DrawningShip? x, DrawningShip? y)
|
||||
{
|
||||
if (x == null || x.EntityShip == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(x));
|
||||
}
|
||||
if (y == null || y.EntityShip == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(y));
|
||||
}
|
||||
var bodyColorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
|
||||
if (bodyColorCompare != 0)
|
||||
{
|
||||
return bodyColorCompare;
|
||||
}
|
||||
if (x.EntityShip is EntityBattleship xEntityBattleship && y.EntityShip is EntityBattleship yEntityBattleship)
|
||||
{
|
||||
var BodyColorCompare = xEntityBattleship.BodyColor.Name.CompareTo(yEntityBattleship.BodyColor.Name);
|
||||
if (BodyColorCompare != 0)
|
||||
{
|
||||
return BodyColorCompare;
|
||||
}
|
||||
var AdditionalColorCompare = xEntityBattleship.AdditionalColor.Name.CompareTo(yEntityBattleship.AdditionalColor.Name);
|
||||
if (AdditionalColorCompare != 0)
|
||||
{
|
||||
return AdditionalColorCompare;
|
||||
}
|
||||
}
|
||||
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
|
||||
}
|
||||
}
|
||||
}
|
36
Battleship/Battleship/ShipCompareByType.cs
Normal file
36
Battleship/Battleship/ShipCompareByType.cs
Normal file
@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Battleship.DrawningObjects;
|
||||
|
||||
|
||||
namespace Battleship.Generics
|
||||
{
|
||||
internal class ShipCompareByType: IComparer<DrawningShip?>
|
||||
{
|
||||
public int Compare(DrawningShip? x, DrawningShip? y)
|
||||
{
|
||||
if (x == null || x.EntityShip == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(x));
|
||||
}
|
||||
if (y == null || y.EntityShip == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(y));
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
var speedCompare =
|
||||
x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
|
||||
}
|
||||
}
|
||||
}
|
98
Battleship/Battleship/ShipGenericCollection.cs
Normal file
98
Battleship/Battleship/ShipGenericCollection.cs
Normal file
@ -0,0 +1,98 @@
|
||||
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;
|
||||
/// <summary>
|
||||
/// Получение объектов коллекции
|
||||
/// </summary>
|
||||
public IEnumerable<T?> GetShips => _collection.GetShips();
|
||||
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
|
||||
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 bool operator +(ShipGenericCollection<T, U>? collect, T? obj)
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return collect?._collection.Insert(obj, new DrawningShipEqutables()) ?? false;
|
||||
}
|
||||
|
||||
public static T? operator -(ShipGenericCollection<T, U>? collect, int pos)
|
||||
{
|
||||
T? obj = collect?._collection[pos];
|
||||
if (obj != null && collect != null)
|
||||
{
|
||||
collect._collection.Remove(pos);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
public U? GetU(int pos)
|
||||
{
|
||||
return (U?)_collection[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)
|
||||
{
|
||||
int width = _pictureWidth/ _placeSizeWidth;
|
||||
int i = 0;
|
||||
foreach(var ship in _collection.GetShips())
|
||||
{
|
||||
if(ship != null)
|
||||
{
|
||||
ship._pictureWidth = _pictureWidth;
|
||||
ship._pictureHeight = _pictureHeight;
|
||||
int inRow = _pictureWidth / _placeSizeWidth;
|
||||
ship.SetPosition(i % inRow * _placeSizeWidth, _pictureHeight - _pictureHeight % _placeSizeHeight - (i / inRow + 1) * _placeSizeHeight + 5);
|
||||
ship.DrawTransport(g);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
19
Battleship/Battleship/ShipNotFoundException.cs
Normal file
19
Battleship/Battleship/ShipNotFoundException.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Battleship.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class ShipNotFoundException : ApplicationException
|
||||
{
|
||||
public ShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public ShipNotFoundException() : base() { }
|
||||
public ShipNotFoundException(string message) : base(message) { }
|
||||
public ShipNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected ShipNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
30
Battleship/Battleship/ShipsCollectionInfo.cs
Normal file
30
Battleship/Battleship/ShipsCollectionInfo.cs
Normal file
@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Battleship.Generics
|
||||
{
|
||||
internal class ShipsCollectionInfo : IEquatable<ShipsCollectionInfo>
|
||||
{
|
||||
public string Name { get; private set; }
|
||||
public string Description { get; private set; }
|
||||
public ShipsCollectionInfo(string name, string description)
|
||||
{
|
||||
Name = name;
|
||||
Description = description;
|
||||
}
|
||||
public bool Equals(ShipsCollectionInfo? other)
|
||||
{
|
||||
if (Name == other?.Name)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Name.GetHashCode();
|
||||
}
|
||||
}
|
||||
}
|
163
Battleship/Battleship/ShipsGenericStorage.cs
Normal file
163
Battleship/Battleship/ShipsGenericStorage.cs
Normal file
@ -0,0 +1,163 @@
|
||||
using Battleship.DrawningObjects;
|
||||
using Battleship.Exceptions;
|
||||
using Battleship.MovementStrategy;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Battleship.Generics
|
||||
{
|
||||
internal class ShipsGenericStorage
|
||||
{
|
||||
readonly Dictionary<ShipsCollectionInfo, ShipGenericCollection<DrawningShip,
|
||||
DrawningObjectShip>> _shipStorages;
|
||||
|
||||
public List<ShipsCollectionInfo> Keys => _shipStorages.Keys.ToList();
|
||||
|
||||
private readonly int _pictureWidth;
|
||||
|
||||
private readonly int _pictureHeight;
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private static readonly char _separatorForKeyValue = '|';
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly char _separatorRecords = ';';
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly char _separatorForObject = ':';
|
||||
|
||||
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
|
||||
{
|
||||
_shipStorages = new Dictionary<ShipsCollectionInfo,
|
||||
ShipGenericCollection<DrawningShip, DrawningObjectShip>>();
|
||||
_pictureWidth = pictureWidth;
|
||||
_pictureHeight = pictureHeight;
|
||||
}
|
||||
|
||||
public void AddSet(string name)
|
||||
{
|
||||
if (!_shipStorages.ContainsKey(new ShipsCollectionInfo(name, string.Empty)))
|
||||
_shipStorages.Add(new ShipsCollectionInfo(name, string.Empty),
|
||||
new ShipGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight));
|
||||
}
|
||||
|
||||
public void DelSet(string name)
|
||||
{
|
||||
if (_shipStorages.ContainsKey(new ShipsCollectionInfo(name, string.Empty)))
|
||||
_shipStorages.Remove(new ShipsCollectionInfo(name, string.Empty));
|
||||
}
|
||||
|
||||
public ShipGenericCollection<DrawningShip, DrawningObjectShip>?
|
||||
this[string ind]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_shipStorages.ContainsKey(new ShipsCollectionInfo(ind, string.Empty)))
|
||||
return _shipStorages[new ShipsCollectionInfo(ind, string.Empty)];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
StringBuilder data = new();
|
||||
foreach (KeyValuePair<ShipsCollectionInfo, ShipGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
|
||||
{
|
||||
StringBuilder records = new();
|
||||
foreach (DrawningShip? elem in record.Value.GetShips)
|
||||
{
|
||||
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
|
||||
}
|
||||
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write($"ShipStorage{Environment.NewLine}{data}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по кораблям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException($"Файл {filename} не найден");
|
||||
}
|
||||
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
throw new NullReferenceException("Нет данных для загрузки");
|
||||
}
|
||||
if (!str.StartsWith("ShipStorage"))
|
||||
{
|
||||
throw new FormatException("Неверный формат данных");
|
||||
}
|
||||
|
||||
_shipStorages.Clear();
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
{
|
||||
if (strs == null)
|
||||
{
|
||||
throw new NullReferenceException("Нет данных для загрузки");
|
||||
}
|
||||
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ShipGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
|
||||
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
DrawningShip? plane = elem?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (plane != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = collection + plane;
|
||||
}
|
||||
catch (ShipNotFoundException e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
|
||||
catch (StorageOverflowException e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
_shipStorages.Add(new ShipsCollectionInfo(record[0], string.Empty), collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
18
Battleship/Battleship/Status.cs
Normal file
18
Battleship/Battleship/Status.cs
Normal file
@ -0,0 +1,18 @@
|
||||
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
|
||||
}
|
||||
}
|
19
Battleship/Battleship/StorageOverflowException.cs
Normal file
19
Battleship/Battleship/StorageOverflowException.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Battleship.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class StorageOverflowException : ApplicationException
|
||||
{
|
||||
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
|
||||
public StorageOverflowException() : base() { }
|
||||
public StorageOverflowException(string message) : base(message) { }
|
||||
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
|
||||
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user