Compare commits
15 Commits
Author | SHA1 | Date | |
---|---|---|---|
2c9a539e25 | |||
1fe1d75be5 | |||
44f2614f95 | |||
88fde22201 | |||
1641bff131 | |||
d4b74a7d92 | |||
ceb90e2be8 | |||
5a4f260e9d | |||
713f348d06 | |||
3df532a330 | |||
a79f90b41b | |||
83a063cde7 | |||
03402dd7cf | |||
eb93d49c6b | |||
791544be65 |
125
ProjectBattleship/ProjectBattleship/AbstractStrategy.cs
Normal file
125
ProjectBattleship/ProjectBattleship/AbstractStrategy.cs
Normal file
@ -0,0 +1,125 @@
|
||||
namespace ProjectBattleship.MovementStrategy;
|
||||
/// <summary>
|
||||
/// Класс-стратегия перемещения объекта
|
||||
/// </summary>
|
||||
public abstract class AbstractStrategy
|
||||
{
|
||||
/// <summary>
|
||||
/// Перемещаемый объект
|
||||
/// </summary>
|
||||
private IMoveableObject? _moveableObject;
|
||||
/// <summary>
|
||||
/// Статус перемещения
|
||||
/// </summary>
|
||||
private StrategyStatus _state = StrategyStatus.NotInit;
|
||||
/// <summary>
|
||||
/// Ширина поля
|
||||
/// </summary>
|
||||
protected int FieldWidth { get; private set; }
|
||||
/// <summary>
|
||||
/// Высота поля
|
||||
/// </summary>
|
||||
protected int FieldHeight { get; private set; }
|
||||
/// <summary>
|
||||
/// Статус перемещения
|
||||
/// </summary>
|
||||
public StrategyStatus 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 = StrategyStatus.NotInit;
|
||||
return;
|
||||
}
|
||||
_state = StrategyStatus.InProgress;
|
||||
_moveableObject = moveableObject;
|
||||
FieldWidth = width;
|
||||
FieldHeight = height;
|
||||
}
|
||||
/// <summary>
|
||||
/// Шаг перемещения
|
||||
/// </summary>
|
||||
public void MakeStep()
|
||||
{
|
||||
if (_state != StrategyStatus.InProgress)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (IsTargetDestinaion())
|
||||
{
|
||||
_state = StrategyStatus.Finish;
|
||||
return;
|
||||
}
|
||||
MoveToTarget();
|
||||
}
|
||||
/// <summary>
|
||||
/// Перемещение влево
|
||||
/// </summary>
|
||||
/// <returns>Результат перемещения (true - удалось переместиться, false -
|
||||
///неудача)</returns>
|
||||
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
|
||||
/// <summary>
|
||||
/// Перемещение вправо
|
||||
/// </summary>
|
||||
/// <returns>Результат перемещения (true - удалось переместиться, false -
|
||||
///неудача)</returns>
|
||||
protected bool MoveRight() => MoveTo(MovementDirection.Right);
|
||||
/// <summary>
|
||||
/// Перемещение вверх
|
||||
/// </summary>
|
||||
/// <returns>Результат перемещения (true - удалось переместиться, false -
|
||||
///неудача)</returns>
|
||||
protected bool MoveUp() => MoveTo(MovementDirection.Up);
|
||||
/// <summary>
|
||||
/// Перемещение вниз
|
||||
/// </summary>
|
||||
/// <returns>Результат перемещения (true - удалось переместиться, false -
|
||||
///неудача)</returns>
|
||||
protected bool MoveDown() => MoveTo(MovementDirection.Down);
|
||||
/// <summary>
|
||||
/// Параметры объекта
|
||||
/// </summary>
|
||||
protected ObjectParameters? GetObjectParameters =>
|
||||
_moveableObject?.GetObjectPosition;
|
||||
/// <summary>
|
||||
/// Шаг объекта
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected int? GetStep()
|
||||
{
|
||||
if (_state != StrategyStatus.InProgress)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return _moveableObject?.GetStep;
|
||||
}
|
||||
/// <summary>
|
||||
/// Перемещение к цели
|
||||
/// </summary>
|
||||
protected abstract void MoveToTarget();
|
||||
/// <summary>
|
||||
/// Достигнута ли цель
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected abstract bool IsTargetDestinaion();
|
||||
/// <summary>
|
||||
/// Попытка перемещения в требуемом направлении
|
||||
/// </summary>
|
||||
/// <param name="movementDirection">Направление</param>
|
||||
/// <returns>Результат попытки (true - удалось переместиться, false -
|
||||
///неудача)</returns>
|
||||
private bool MoveTo(MovementDirection movementDirection)
|
||||
{
|
||||
if (_state != StrategyStatus.InProgress)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
|
||||
}
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using ProjectBattleship.Exceptions;
|
||||
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Абстракция компании, хранящий коллекцию автомобилей
|
||||
/// </summary>
|
||||
public abstract class AbstractCompany
|
||||
{
|
||||
/// <summary>
|
||||
/// Размер места (ширина)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeWidth = 210;
|
||||
/// <summary>
|
||||
/// Размер места (высота)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeHeight = 80;
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureWidth;
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureHeight;
|
||||
/// <summary>
|
||||
/// Коллекция кораблей
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawingWarship>? _collection = null;
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно
|
||||
/// разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth">Ширина окна</param>
|
||||
/// <param name="picHeight">Высота окна</param>
|
||||
/// <param name="collection">Коллекция автомобилей</param>
|
||||
public AbstractCompany(int picWidth, int picHeight,
|
||||
ICollectionGenericObjects<DrawingWarship> collection)
|
||||
{
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_collection = collection;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
/// <summary>
|
||||
/// Перегрузка оператора сложения для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="warship">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company,
|
||||
DrawingWarship warship)
|
||||
{
|
||||
return company._collection?.Insert(warship) ?? 0;
|
||||
}
|
||||
/// <summary>
|
||||
/// Перегрузка оператора удаления для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="position">Номер удаляемого объекта</param>
|
||||
/// <returns></returns>
|
||||
public static DrawingWarship? operator -(AbstractCompany company,
|
||||
int position)
|
||||
{
|
||||
return company._collection?.Remove(position);
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение случайного объекта из коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public DrawingWarship? GetRandomObject()
|
||||
{
|
||||
Random rnd = new();
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
/// <summary>
|
||||
/// Вывод всей коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Bitmap? Show()
|
||||
{
|
||||
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
|
||||
Graphics graphics = Graphics.FromImage(bitmap);
|
||||
DrawBackground(graphics);
|
||||
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
try
|
||||
{
|
||||
DrawingWarship? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException e)
|
||||
{ }
|
||||
catch (PositionOutOfCollectionException e)
|
||||
{ }
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackground(Graphics g);
|
||||
/// <summary>
|
||||
/// Расстановка объектов
|
||||
/// </summary>
|
||||
protected abstract void SetObjectsPosition();
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Тип коллекции
|
||||
/// </summary>
|
||||
public enum CollectionType
|
||||
{
|
||||
/// <summary>
|
||||
/// Неопределено
|
||||
/// </summary>
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// Массив
|
||||
/// </summary>
|
||||
Massive = 1,
|
||||
/// <summary>
|
||||
/// Список
|
||||
/// </summary>
|
||||
List = 2
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using ProjectBattleship.Exceptions;
|
||||
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Реализация абстрактной компании - доки
|
||||
/// </summary>
|
||||
public class Docks : AbstractCompany
|
||||
{
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth"></param>
|
||||
/// <param name="picHeight"></param>
|
||||
/// <param name="collection"></param>
|
||||
public Docks(int picWidth, int picHeight,
|
||||
ICollectionGenericObjects<DrawingWarship> collection) :
|
||||
base(picWidth, picHeight, collection)
|
||||
{
|
||||
}
|
||||
protected override void DrawBackground(Graphics g)
|
||||
{
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
Brush brush = new SolidBrush(Color.Black);
|
||||
for (int i = 0; i < width; ++i)
|
||||
{
|
||||
for (int j = 0; j < height; ++j)
|
||||
{
|
||||
g.FillRectangle(brush, i * _placeSizeWidth,
|
||||
j * _placeSizeHeight, 200, 5);
|
||||
g.FillRectangle(brush, i * _placeSizeWidth,
|
||||
j * _placeSizeHeight, 5, 80);
|
||||
}
|
||||
}
|
||||
for (int j = 0; j < height - 4; ++j)
|
||||
{
|
||||
g.FillRectangle(brush, j * _placeSizeWidth,
|
||||
height * _placeSizeHeight, 200, 5);
|
||||
}
|
||||
}
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int curWidth = width - 1;
|
||||
int curHeight = 0;
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
|
||||
}
|
||||
catch (ObjectNotFoundException) { }
|
||||
catch (PositionOutOfCollectionException e) { }
|
||||
if (curWidth > 0)
|
||||
curWidth--;
|
||||
else
|
||||
{
|
||||
curWidth = width - 1;
|
||||
curHeight++;
|
||||
}
|
||||
|
||||
if (curHeight >= height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
namespace ProjectBattleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Интерфейс описания действий для набора хранимых объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public interface ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Количество объектов в коллекции
|
||||
/// </summary>
|
||||
int Count { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Установка максимального количества элементов
|
||||
/// </summary>
|
||||
int MaxCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj);
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию на конкретную позицию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj, int position);
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта из коллекции с конкретной позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
|
||||
T? Remove(int position);
|
||||
|
||||
/// <summary>
|
||||
/// Получение объекта по позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>Объект</returns>
|
||||
T? Get(int position);
|
||||
|
||||
/// <summary>
|
||||
/// Получение типа коллекции
|
||||
/// </summary>
|
||||
CollectionType GetCollectionType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Получение объектов коллекции по одному
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
using ProjectBattleship.CollectionGenericObjects;
|
||||
using ProjectBattleship.Exceptions;
|
||||
|
||||
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int MaxCount
|
||||
{
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
get
|
||||
{
|
||||
|
||||
return Count;
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public ListGenericObjects()
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
public T Get(int position)
|
||||
{
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < Count; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,138 @@
|
||||
using ProjectBattleship.Exceptions;
|
||||
using ProjectBattleship.CollectionGenericObjects;
|
||||
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
public int Count => _collection.Length;
|
||||
/// <summary>
|
||||
/// Установка максимального кол-ва объектов
|
||||
/// </summary>
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
if (_collection.Length > 0)
|
||||
{
|
||||
Array.Resize(ref _collection, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_collection = new T?[value];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public MassiveGenericObjects()
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение объекта по позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция (индекс)</param>
|
||||
/// <returns></returns>
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// вставка в свободное место набора
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (_collection[position] != null)
|
||||
{
|
||||
bool pushed = false;
|
||||
for (int index = position + 1; index < Count; index++)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
position = index;
|
||||
pushed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pushed)
|
||||
{
|
||||
for (int index = position - 1; index >= 0; index--)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
position = index;
|
||||
pushed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!pushed)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
}
|
||||
|
||||
// вставка
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
|
||||
T? temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return temp;
|
||||
}
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,204 @@
|
||||
using ProjectBattleship.CollectionGenericObjects;
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using ProjectBattleship.Exceptions;
|
||||
|
||||
namespace Battleship.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Класс-хранилище коллекций
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class StorageCollection<T> where T : DrawingWarship
|
||||
{
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
|
||||
return;
|
||||
switch (collectionType)
|
||||
{
|
||||
case CollectionType.List:
|
||||
_storages.Add(name, new ListGenericObjects<T>());
|
||||
break;
|
||||
case CollectionType.Massive:
|
||||
_storages.Add(name, new MassiveGenericObjects<T>());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
if (_storages.ContainsKey(name)) { _storages.Remove(name); }
|
||||
}
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
|
||||
return value;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Сохранение информации по самолетам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
using StreamWriter streamWriter = new StreamWriter(fs);
|
||||
streamWriter.Write(_collectionKey);
|
||||
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
streamWriter.Write(Environment.NewLine);
|
||||
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
streamWriter.Write(value.Key);
|
||||
streamWriter.Write(_separatorForKeyValue);
|
||||
streamWriter.Write(value.Value.GetCollectionType);
|
||||
streamWriter.Write(_separatorForKeyValue);
|
||||
streamWriter.Write(value.Value.MaxCount);
|
||||
streamWriter.Write(_separatorForKeyValue);
|
||||
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
streamWriter.Write(data);
|
||||
streamWriter.Write(_separatorItems);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по кораблям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader sr = new StreamReader(filename))
|
||||
{
|
||||
string? str;
|
||||
str = sr.ReadLine();
|
||||
if (str != _collectionKey.ToString())
|
||||
throw new FormatException("В файле неверные данные");
|
||||
_storages.Clear();
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
{
|
||||
string[] record = str.Split(_separatorForKeyValue);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawingWarship() is T Warship)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(Warship) == -1)
|
||||
{
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) => collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
namespace ProjectBattleship.DrawingObject;
|
||||
/// <summary>
|
||||
/// Направление перемещения
|
||||
/// </summary>
|
||||
public enum DirectionType
|
||||
{
|
||||
/// <summary>
|
||||
/// Неизвестное направление
|
||||
/// </summary>
|
||||
Unknow = -1,
|
||||
/// <summary>
|
||||
/// Вверх
|
||||
/// </summary>
|
||||
Up = 1,
|
||||
/// <summary>
|
||||
/// Вниз
|
||||
/// </summary>
|
||||
Down = 2,
|
||||
/// <summary>
|
||||
/// Влево
|
||||
/// </summary>
|
||||
Left = 3,
|
||||
/// <summary>
|
||||
/// Вправо
|
||||
/// </summary>
|
||||
Right = 4
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
using ProjectBattleship.Entities;
|
||||
namespace ProjectBattleship.DrawingObject;
|
||||
/// <summary>
|
||||
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
|
||||
/// </summary>
|
||||
public class DrawingBattleship : DrawingWarship
|
||||
{
|
||||
public DrawingBattleship(EntityWarship warship) : base(150, 50)
|
||||
{
|
||||
EntityWarship = warship;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="speed">Скорость</param>
|
||||
/// <param name="weight">Вес</param>
|
||||
/// <param name="bodyColor">Основной цвет</param>
|
||||
/// <param name="additionalColor">Дополнительный цвет</param>
|
||||
/// <param name="turret">Признак наличия обвеса</param>
|
||||
/// <param name="rocketCompartment">Признак наличия антикрыла</param>
|
||||
public DrawingBattleship(int speed, double weight, Color bodyColor, Color
|
||||
additionalColor, bool turret, bool rocketCompartment) : base(150, 50)
|
||||
{
|
||||
EntityWarship = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketCompartment);
|
||||
}
|
||||
|
||||
public override void DrawTransport(Graphics g)
|
||||
{
|
||||
if (EntityWarship == null || EntityWarship is not EntityBattleship battleship ||
|
||||
!_startPosX.HasValue || !_startPosY.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Pen pen = new(Color.Black);
|
||||
Brush additionalBrush = new SolidBrush(battleship.AdditionalColor);
|
||||
base.DrawTransport(g);
|
||||
//отсек под ракеты
|
||||
if (battleship.RocketCompartment)
|
||||
{
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 14,
|
||||
_startPosY.Value + 14, 10, 10);
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 26,
|
||||
_startPosY.Value + 14, 10, 10);
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 14,
|
||||
_startPosY.Value + 26, 10, 10);
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 26,
|
||||
_startPosY.Value + 26, 10, 10);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 14,
|
||||
_startPosY.Value + 14, 10, 10);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 26,
|
||||
_startPosY.Value + 14, 10, 10);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 14,
|
||||
_startPosY.Value + 26, 10, 10);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 26,
|
||||
_startPosY.Value + 26, 10, 10);
|
||||
}
|
||||
//орудийная башня
|
||||
if (battleship.Turret)
|
||||
{
|
||||
Point[] turret = new Point[] {new Point(_startPosX.Value + 112,
|
||||
_startPosY.Value + 19), new Point(_startPosX.Value + 112,
|
||||
_startPosY.Value + 31), new Point(_startPosX.Value + 119,
|
||||
_startPosY.Value + 28), new Point(_startPosX.Value + 119,
|
||||
_startPosY.Value + 22)};
|
||||
g.FillPolygon(additionalBrush, turret);
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 119,
|
||||
_startPosY.Value + 24, 12, 2);
|
||||
g.DrawPolygon(pen, turret);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 119,
|
||||
_startPosY.Value + 24, 12, 2);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,230 @@
|
||||
using ProjectBattleship.Entities;
|
||||
namespace ProjectBattleship.DrawingObject;
|
||||
/// <summary>
|
||||
/// Класс, отвечающий за прорисовку и перемещение базового объекта-сущности
|
||||
/// </summary>
|
||||
public class DrawingWarship
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс-сущность
|
||||
/// </summary>
|
||||
public EntityWarship? EntityWarship { get; protected set; }
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
private int? _pictureWidth;
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
private int? _pictureHeight;
|
||||
/// <summary>
|
||||
/// Левая координата прорисовки военного корабля
|
||||
/// </summary>
|
||||
protected int? _startPosX;
|
||||
/// <summary>
|
||||
/// Верхняя кооридната прорисовки военного корабля
|
||||
/// </summary>
|
||||
protected int? _startPosY;
|
||||
private EntityWarship warship;
|
||||
|
||||
/// <summary>
|
||||
/// Ширина прорисовки военного корабля
|
||||
/// </summary>
|
||||
private readonly int _drawingWarshipWidth = 150;
|
||||
/// <summary>
|
||||
/// Высота прорисовки военного корабля
|
||||
/// </summary>
|
||||
private readonly int _drawingWarshipHeight = 50;
|
||||
/// <summary>
|
||||
/// Пустой конструктор
|
||||
/// </summary>
|
||||
private DrawingWarship()
|
||||
{
|
||||
_pictureWidth = null;
|
||||
_pictureHeight = null;
|
||||
_startPosX = null;
|
||||
_startPosY = null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="speed">Скорость</param>
|
||||
/// <param name="weight">Вес</param>
|
||||
/// <param name="bodyColor">Основной цвет</param>
|
||||
public DrawingWarship(int speed, double weight, Color bodyColor) : this()
|
||||
{
|
||||
EntityWarship = new EntityWarship(speed, weight, bodyColor);
|
||||
}
|
||||
/// <summary>
|
||||
/// Конструктор для наследников
|
||||
/// </summary>
|
||||
/// <param name="drawingWarshipWidth">Ширина прорисовки военного корабля</param>
|
||||
/// <param name="drawingWarshipHeight">Высота прорисовки военного корабля</param>
|
||||
protected DrawingWarship(int drawingWarshipWidth, int drawingWarshipHeight) : this()
|
||||
{
|
||||
_drawingWarshipWidth = drawingWarshipWidth;
|
||||
_pictureHeight = drawingWarshipHeight;
|
||||
}
|
||||
|
||||
public DrawingWarship(EntityWarship warship)
|
||||
{
|
||||
EntityWarship = warship;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Установка границ поля
|
||||
/// </summary>
|
||||
/// <param name="width">Ширина поля</param>
|
||||
/// <param name="height">Высота поля</param>
|
||||
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя
|
||||
//разместить объект в этих размерах</returns>
|
||||
public bool SetPictureSize(int width, int height)
|
||||
{
|
||||
if (_drawingWarshipWidth < width && _drawingWarshipHeight < height)
|
||||
{
|
||||
_pictureWidth = width;
|
||||
_pictureHeight = height;
|
||||
if (_startPosX.HasValue && _startPosY.HasValue)
|
||||
{
|
||||
SetPosition(_startPosX.Value, _startPosY.Value);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Установка позиции
|
||||
/// </summary>
|
||||
/// <param name="x">Координата X</param>
|
||||
/// <param name="y">Координата Y</param>
|
||||
public void SetPosition(int x, int y)
|
||||
{
|
||||
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (x > 0 && y > 0 && x + _drawingWarshipWidth < _pictureWidth
|
||||
&& y + _drawingWarshipHeight < _pictureHeight)
|
||||
{
|
||||
_startPosX = x;
|
||||
_startPosY = y;
|
||||
}
|
||||
else
|
||||
{
|
||||
Random rnd = new();
|
||||
_startPosX = rnd.Next(0, _pictureWidth.Value -
|
||||
_drawingWarshipWidth);
|
||||
_startPosY = rnd.Next(0, _pictureHeight.Value -
|
||||
_drawingWarshipHeight);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Изменение направления перемещения
|
||||
/// </summary>
|
||||
/// <param name="direction">Направление</param>
|
||||
/// <returns>true - перемещене выполнено, false - перемещение
|
||||
///невозможно</returns>
|
||||
public bool MoveTransport(DirectionType direction)
|
||||
{
|
||||
if (EntityWarship == null || !_startPosX.HasValue ||
|
||||
!_startPosY.HasValue)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
switch (direction)
|
||||
{
|
||||
//влево
|
||||
case DirectionType.Left:
|
||||
if (_startPosX.Value - EntityWarship.Step > 0)
|
||||
{
|
||||
_startPosX -= (int)EntityWarship.Step;
|
||||
}
|
||||
return true;
|
||||
//вверх
|
||||
case DirectionType.Up:
|
||||
if (_startPosY.Value - EntityWarship.Step > 0)
|
||||
{
|
||||
_startPosY -= (int)EntityWarship.Step;
|
||||
}
|
||||
return true;
|
||||
//вправо
|
||||
case DirectionType.Right:
|
||||
if (_startPosX + _drawingWarshipWidth + EntityWarship.Step < _pictureWidth)
|
||||
{
|
||||
_startPosX += (int)EntityWarship.Step;
|
||||
}
|
||||
return true;
|
||||
//вниз
|
||||
case DirectionType.Down:
|
||||
if (_startPosY + _drawingWarshipHeight + EntityWarship.Step < _pictureHeight)
|
||||
{
|
||||
_startPosY += (int)EntityWarship.Step;
|
||||
}
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Прорисовка объекта
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
public virtual void DrawTransport(Graphics g)
|
||||
{
|
||||
if (EntityWarship == null || !_startPosX.HasValue ||
|
||||
!_startPosY.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Pen pen = new(Color.Black);
|
||||
Brush bodyBrush = new SolidBrush(EntityWarship.BodyColor);
|
||||
//основная часть
|
||||
Point[] body = new Point[] {new Point(_startPosX.Value + 5,
|
||||
_startPosY.Value), new Point(_startPosX.Value + 100,
|
||||
_startPosY.Value), new Point(_startPosX.Value + 150,
|
||||
_startPosY.Value + 25), new Point(_startPosX.Value + 100,
|
||||
_startPosY.Value + 50), new Point(_startPosX.Value + 5,
|
||||
_startPosY.Value + 50)};
|
||||
g.FillPolygon(bodyBrush, body);
|
||||
g.DrawPolygon(pen, body);
|
||||
Brush brBlack = new SolidBrush(Color.Black);
|
||||
g.FillRectangle(brBlack, _startPosX.Value,
|
||||
_startPosY.Value + 6, 5, 13);
|
||||
g.FillRectangle(brBlack, _startPosX.Value,
|
||||
_startPosY.Value + 31, 5, 13);
|
||||
Brush brDark = new SolidBrush(Color.DarkGray);
|
||||
g.FillRectangle(brDark, _startPosX.Value + 39,
|
||||
_startPosY.Value + 20, 40, 10);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 39,
|
||||
_startPosY.Value + 20, 40, 10);
|
||||
g.FillRectangle(brDark, _startPosX.Value + 70,
|
||||
_startPosY.Value + 12, 18, 26);
|
||||
g.DrawRectangle(pen, _startPosX.Value + 70,
|
||||
_startPosY.Value + 12, 18, 26);
|
||||
g.FillEllipse(brBlack, _startPosX.Value + 94,
|
||||
_startPosY.Value + 19, 12, 12);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Координата X объекта
|
||||
/// </summary>
|
||||
public int? GetPosX => _startPosX;
|
||||
/// <summary>
|
||||
/// Координата Y объекта
|
||||
/// </summary>
|
||||
public int? GetPosY => _startPosY;
|
||||
/// <summary>
|
||||
/// Ширина объекта
|
||||
/// </summary>
|
||||
public int GetWidth => _drawingWarshipWidth;
|
||||
/// <summary>
|
||||
/// Высота объекта
|
||||
/// </summary>
|
||||
public int GetHeight => _drawingWarshipHeight;
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
using ProjectBattleship.Entities;
|
||||
namespace ProjectBattleship.DrawingObject;
|
||||
/// <summary>
|
||||
/// Расширение для класса EntityWarship
|
||||
/// </summary>
|
||||
public static class ExtentionDrawingWarship
|
||||
{
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly string _separatorForObject = ":";
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="info">Строка с данными для создания объекта</param>
|
||||
/// <returns>Объект</returns>
|
||||
public static DrawingWarship? CreateDrawingWarship(this string info)
|
||||
{
|
||||
string[] strs = info.Split(_separatorForObject);
|
||||
EntityWarship? warship = EntityBattleship.CreateEntityBattleship(strs);
|
||||
if (warship != null)
|
||||
{
|
||||
return new DrawingBattleship(warship);
|
||||
}
|
||||
warship = EntityWarship.CreateEntityWarship(strs);
|
||||
if (warship != null)
|
||||
{
|
||||
return new DrawingWarship(warship);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение данных для сохранения в файл
|
||||
/// </summary>
|
||||
/// <param name="drawingWarship">Сохраняемый объект</param>
|
||||
/// <returns>Строка с данными по объекту</returns>
|
||||
public static string GetDataForSave(this DrawingWarship drawingWarship)
|
||||
{
|
||||
string[]? array = drawingWarship?.EntityWarship?.GetStringRepresentation();
|
||||
if (array == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Join(_separatorForObject, array);
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace ProjectBattleship.Entities;
|
||||
/// <summary>
|
||||
/// Класс-сущность "Линкор"
|
||||
/// </summary>
|
||||
public class EntityBattleship : EntityWarship
|
||||
{
|
||||
public Color AdditionalColor { get; private set; }
|
||||
public void SetAdditionalColor(Color color)
|
||||
{
|
||||
AdditionalColor = color;
|
||||
}
|
||||
public bool Turret { get; private set; }
|
||||
public bool RocketCompartment { get; private set; }
|
||||
public EntityBattleship(int speed, double weight, Color bodyColor,
|
||||
Color additionalColor, bool turret, bool rocketCompartment) :
|
||||
base(speed, weight, bodyColor)
|
||||
{
|
||||
AdditionalColor = additionalColor;
|
||||
Turret = turret;
|
||||
RocketCompartment = rocketCompartment;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение строк со значениями свойств объекта класса-сущности
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(),
|
||||
BodyColor.Name, AdditionalColor.Name, RocketCompartment.ToString(), Turret.ToString() };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityWarship? CreateEntityBattleship(string[] strs)
|
||||
{
|
||||
if (strs.Length != 7 || strs[0] != nameof(EntityBattleship))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new EntityBattleship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
|
||||
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
namespace ProjectBattleship.Entities;
|
||||
/// <summary>
|
||||
/// Класс-сущность "Военный корабль"
|
||||
/// </summary>
|
||||
public class EntityWarship
|
||||
{
|
||||
public int Speed { get; private set; }
|
||||
public double Weight { get; private set; }
|
||||
public Color BodyColor { get; private set; }
|
||||
public void SetBodyColor(Color color)
|
||||
{
|
||||
BodyColor = color;
|
||||
}
|
||||
public double Step => Speed * 100 / Weight;
|
||||
public EntityWarship(int speed, double weight, Color bodyColor)
|
||||
{
|
||||
Speed = speed;
|
||||
Weight = weight;
|
||||
BodyColor = bodyColor;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение строк со значениями свойств объекта класса-сущности
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityWarship), Speed.ToString(),
|
||||
Weight.ToString(), BodyColor.Name };
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityWarship? CreateEntityWarship(string[] strs)
|
||||
{
|
||||
if (strs.Length != 4 || strs[0] != nameof(EntityWarship))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new EntityWarship(Convert.ToInt32(strs[1]),
|
||||
Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class CollectionOverflowException : ApplicationException
|
||||
{
|
||||
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
|
||||
public CollectionOverflowException() : base() { }
|
||||
public CollectionOverflowException(string message) : base(message) { }
|
||||
public CollectionOverflowException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected CollectionOverflowException(SerializationInfo info,
|
||||
StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
|
||||
internal class ObjectNotFoundException : ApplicationException
|
||||
{
|
||||
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
|
||||
|
||||
public ObjectNotFoundException() : base() { }
|
||||
|
||||
public ObjectNotFoundException(string message) : base(message) { }
|
||||
|
||||
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
|
||||
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace ProjectBattleship.Exceptions;
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class PositionOutOfCollectionException : ApplicationException
|
||||
{
|
||||
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
|
||||
public PositionOutOfCollectionException() : base() { }
|
||||
public PositionOutOfCollectionException(string message) : base(message) { }
|
||||
public PositionOutOfCollectionException(string message, Exception
|
||||
exception) : base(message, exception) { }
|
||||
protected PositionOutOfCollectionException(SerializationInfo info,
|
||||
StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
partial class Form1
|
||||
{
|
||||
/// <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.components = new System.ComponentModel.Container();
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(800, 450);
|
||||
this.Text = "Form1";
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
public partial class Form1 : Form
|
||||
{
|
||||
public Form1()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
155
ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs
generated
Normal file
155
ProjectBattleship/ProjectBattleship/FormBattleship.Designer.cs
generated
Normal file
@ -0,0 +1,155 @@
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
partial class FormBattleship
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
pictureBoxBattleship = new PictureBox();
|
||||
buttonLeft = new Button();
|
||||
buttonDown = new Button();
|
||||
buttonRight = new Button();
|
||||
buttonUp = new Button();
|
||||
comboBoxStrategy = new ComboBox();
|
||||
buttonStrategyStep = new Button();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).BeginInit();
|
||||
SuspendLayout();
|
||||
//
|
||||
// pictureBoxBattleship
|
||||
//
|
||||
pictureBoxBattleship.Dock = DockStyle.Fill;
|
||||
pictureBoxBattleship.Location = new Point(0, 0);
|
||||
pictureBoxBattleship.Margin = new Padding(2);
|
||||
pictureBoxBattleship.Name = "pictureBoxBattleship";
|
||||
pictureBoxBattleship.Size = new Size(876, 436);
|
||||
pictureBoxBattleship.TabIndex = 0;
|
||||
pictureBoxBattleship.TabStop = false;
|
||||
//
|
||||
// buttonLeft
|
||||
//
|
||||
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
|
||||
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
|
||||
buttonLeft.Location = new Point(739, 389);
|
||||
buttonLeft.Margin = new Padding(2);
|
||||
buttonLeft.Name = "buttonLeft";
|
||||
buttonLeft.Size = new Size(35, 35);
|
||||
buttonLeft.TabIndex = 2;
|
||||
buttonLeft.UseVisualStyleBackColor = true;
|
||||
buttonLeft.Click += ButtonMove_Click;
|
||||
//
|
||||
// buttonDown
|
||||
//
|
||||
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
|
||||
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
|
||||
buttonDown.Location = new Point(780, 389);
|
||||
buttonDown.Margin = new Padding(2);
|
||||
buttonDown.Name = "buttonDown";
|
||||
buttonDown.Size = new Size(35, 35);
|
||||
buttonDown.TabIndex = 3;
|
||||
buttonDown.UseVisualStyleBackColor = true;
|
||||
buttonDown.Click += ButtonMove_Click;
|
||||
//
|
||||
// buttonRight
|
||||
//
|
||||
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
|
||||
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
|
||||
buttonRight.Location = new Point(821, 389);
|
||||
buttonRight.Margin = new Padding(2);
|
||||
buttonRight.Name = "buttonRight";
|
||||
buttonRight.Size = new Size(35, 35);
|
||||
buttonRight.TabIndex = 4;
|
||||
buttonRight.UseVisualStyleBackColor = true;
|
||||
buttonRight.Click += ButtonMove_Click;
|
||||
//
|
||||
// buttonUp
|
||||
//
|
||||
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
|
||||
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
|
||||
buttonUp.Location = new Point(780, 348);
|
||||
buttonUp.Margin = new Padding(2);
|
||||
buttonUp.Name = "buttonUp";
|
||||
buttonUp.Size = new Size(35, 35);
|
||||
buttonUp.TabIndex = 5;
|
||||
buttonUp.UseVisualStyleBackColor = true;
|
||||
buttonUp.Click += ButtonMove_Click;
|
||||
//
|
||||
// comboBoxStrategy
|
||||
//
|
||||
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||
comboBoxStrategy.FormattingEnabled = true;
|
||||
comboBoxStrategy.Items.AddRange(new object[] { "К центру ", "К краю" });
|
||||
comboBoxStrategy.Location = new Point(652, 12);
|
||||
comboBoxStrategy.Name = "comboBoxStrategy";
|
||||
comboBoxStrategy.Size = new Size(212, 38);
|
||||
comboBoxStrategy.TabIndex = 6;
|
||||
//
|
||||
// button1
|
||||
//
|
||||
buttonStrategyStep.Location = new Point(752, 72);
|
||||
buttonStrategyStep.Name = "button1";
|
||||
buttonStrategyStep.Size = new Size(104, 43);
|
||||
buttonStrategyStep.TabIndex = 7;
|
||||
buttonStrategyStep.Text = "шаг";
|
||||
buttonStrategyStep.TextAlign = ContentAlignment.TopCenter;
|
||||
buttonStrategyStep.UseVisualStyleBackColor = true;
|
||||
buttonStrategyStep.Click += ButtonStrategyStep_Click;
|
||||
//
|
||||
// FormBattleship
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(12F, 30F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(876, 436);
|
||||
Controls.Add(buttonStrategyStep);
|
||||
Controls.Add(comboBoxStrategy);
|
||||
Controls.Add(buttonUp);
|
||||
Controls.Add(buttonRight);
|
||||
Controls.Add(buttonDown);
|
||||
Controls.Add(buttonLeft);
|
||||
Controls.Add(pictureBoxBattleship);
|
||||
Margin = new Padding(2);
|
||||
Name = "FormBattleship";
|
||||
StartPosition = FormStartPosition.CenterScreen;
|
||||
Text = "Линкор";
|
||||
TopMost = true;
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).EndInit();
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private PictureBox pictureBoxBattleship;
|
||||
private Button buttonLeft;
|
||||
private Button buttonDown;
|
||||
private Button buttonRight;
|
||||
private Button buttonUp;
|
||||
private ComboBox comboBoxStrategy;
|
||||
private Button buttonStrategyStep;
|
||||
}
|
||||
}
|
127
ProjectBattleship/ProjectBattleship/FormBattleship.cs
Normal file
127
ProjectBattleship/ProjectBattleship/FormBattleship.cs
Normal file
@ -0,0 +1,127 @@
|
||||
using ProjectBattleship.MovementStrategy;
|
||||
using ProjectBattleship.DrawingObject;
|
||||
namespace ProjectBattleship;
|
||||
/// <summary>
|
||||
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Ñïîðòèâíûé àâòîìîáèëü"
|
||||
/// </summary>
|
||||
public partial class FormBattleship : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
|
||||
/// </summary>
|
||||
private DrawingWarship? _drawingWarship;
|
||||
/// <summary>
|
||||
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
|
||||
/// </summary>
|
||||
private AbstractStrategy? _strategy;
|
||||
/// <summary>
|
||||
/// Ïîëó÷åíèå îáúåêòà
|
||||
/// </summary>
|
||||
public DrawingWarship SetWarship
|
||||
{
|
||||
set
|
||||
{
|
||||
_drawingWarship = value;
|
||||
_drawingWarship.SetPictureSize(pictureBoxBattleship.Width,
|
||||
pictureBoxBattleship.Height);
|
||||
comboBoxStrategy.Enabled = true;
|
||||
_strategy = null;
|
||||
Draw();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Êîíñòðóêòîð ôîðìû
|
||||
/// </summary>
|
||||
public FormBattleship()
|
||||
{
|
||||
InitializeComponent();
|
||||
_strategy = null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Ìåòîä ïðîðèñîâêè âîåííîãî êîðàáëÿ
|
||||
/// </summary>
|
||||
private void Draw()
|
||||
{
|
||||
if (_drawingWarship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Bitmap bmp = new(pictureBoxBattleship.Width,
|
||||
pictureBoxBattleship.Height);
|
||||
Graphics gr = Graphics.FromImage(bmp);
|
||||
_drawingWarship.DrawTransport(gr);
|
||||
pictureBoxBattleship.Image = bmp;
|
||||
}
|
||||
/// <summary>
|
||||
/// Ïåðåìåùåíèå îáúåêòà ïî ôîðìå (íàæàòèå êíîïîê íàâèãàöèè)
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonMove_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_drawingWarship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
string name = ((Button)sender)?.Name ?? string.Empty;
|
||||
bool result = false;
|
||||
switch (name)
|
||||
{
|
||||
case "buttonUp":
|
||||
result = _drawingWarship.MoveTransport(DirectionType.Up);
|
||||
break;
|
||||
case "buttonDown":
|
||||
result = _drawingWarship.MoveTransport(DirectionType.Down);
|
||||
break;
|
||||
case "buttonLeft":
|
||||
result = _drawingWarship.MoveTransport(DirectionType.Left);
|
||||
break;
|
||||
case "buttonRight":
|
||||
result = _drawingWarship.MoveTransport(DirectionType.Right);
|
||||
break;
|
||||
}
|
||||
if (result)
|
||||
{
|
||||
Draw();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonStrategyStep_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_drawingWarship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (comboBoxStrategy.Enabled)
|
||||
{
|
||||
_strategy = comboBoxStrategy.SelectedIndex switch
|
||||
{
|
||||
0 => new MoveToCenter(),
|
||||
1 => new MoveToBorder(),
|
||||
_ => null,
|
||||
};
|
||||
if (_strategy == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_strategy.SetData(new MoveableWarship(_drawingWarship),
|
||||
pictureBoxBattleship.Width, pictureBoxBattleship.Height);
|
||||
}
|
||||
if (_strategy == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
comboBoxStrategy.Enabled = false;
|
||||
_strategy.MakeStep();
|
||||
Draw();
|
||||
if (_strategy.GetStatus() == StrategyStatus.Finish)
|
||||
{
|
||||
comboBoxStrategy.Enabled = true;
|
||||
_strategy = null;
|
||||
}
|
||||
}
|
||||
}
|
@ -18,7 +18,7 @@
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
354
ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs
generated
Normal file
354
ProjectBattleship/ProjectBattleship/FormWarshipCollection.Designer.cs
generated
Normal file
@ -0,0 +1,354 @@
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
partial class FormWarshipCollection
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
groupBoxCollectionTools = new GroupBox();
|
||||
panelCompanyTools = new Panel();
|
||||
buttonRefresh = new Button();
|
||||
buttonAddBattleship = new Button();
|
||||
maskedTextBoxPosition = new MaskedTextBox();
|
||||
buttonAddWarship = new Button();
|
||||
buttonGoToCheck = new Button();
|
||||
buttonRemoveWarship = new Button();
|
||||
buttonCreateCompany = new Button();
|
||||
comboBoxSelectorCompany = new ComboBox();
|
||||
panelCollection = new Panel();
|
||||
buttonCollectionDel = new Button();
|
||||
listBoxCollection = new ListBox();
|
||||
buttonCollectionAdd = new Button();
|
||||
radioButtonList = new RadioButton();
|
||||
radioButtonMassive = new RadioButton();
|
||||
textBoxCollectionName = new TextBox();
|
||||
labelCollection = new Label();
|
||||
pictureBox = new PictureBox();
|
||||
menuStrip = new MenuStrip();
|
||||
файлToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveToolStripMenuItem = new ToolStripMenuItem();
|
||||
loadToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
groupBoxCollectionTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelCollection.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
||||
menuStrip.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
// groupBoxCollectionTools
|
||||
//
|
||||
groupBoxCollectionTools.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
groupBoxCollectionTools.Controls.Add(panelCompanyTools);
|
||||
groupBoxCollectionTools.Controls.Add(buttonCreateCompany);
|
||||
groupBoxCollectionTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxCollectionTools.Controls.Add(panelCollection);
|
||||
groupBoxCollectionTools.Location = new Point(699, 27);
|
||||
groupBoxCollectionTools.Name = "groupBoxCollectionTools";
|
||||
groupBoxCollectionTools.Size = new Size(279, 618);
|
||||
groupBoxCollectionTools.TabIndex = 1;
|
||||
groupBoxCollectionTools.TabStop = false;
|
||||
groupBoxCollectionTools.Text = "Инструменты";
|
||||
//
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
panelCompanyTools.Controls.Add(buttonAddBattleship);
|
||||
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
|
||||
panelCompanyTools.Controls.Add(buttonAddWarship);
|
||||
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
||||
panelCompanyTools.Controls.Add(buttonRemoveWarship);
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Location = new Point(6, 354);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(267, 234);
|
||||
panelCompanyTools.TabIndex = 11;
|
||||
//
|
||||
// buttonRefresh
|
||||
//
|
||||
buttonRefresh.Location = new Point(8, 203);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(251, 34);
|
||||
buttonRefresh.TabIndex = 7;
|
||||
buttonRefresh.Text = "Обновить";
|
||||
buttonRefresh.UseVisualStyleBackColor = true;
|
||||
buttonRefresh.Click += ButtonRefresh_Click;
|
||||
//
|
||||
// buttonAddBattleship
|
||||
//
|
||||
buttonAddBattleship.Location = new Point(8, 46);
|
||||
buttonAddBattleship.Name = "buttonAddBattleship";
|
||||
buttonAddBattleship.Size = new Size(251, 34);
|
||||
buttonAddBattleship.TabIndex = 3;
|
||||
buttonAddBattleship.Text = "Добавить линкор";
|
||||
buttonAddBattleship.UseVisualStyleBackColor = true;
|
||||
buttonAddBattleship.Click += ButtonAddBattleship_Click;
|
||||
//
|
||||
// maskedTextBoxPosition
|
||||
//
|
||||
maskedTextBoxPosition.Location = new Point(8, 86);
|
||||
maskedTextBoxPosition.Mask = "00";
|
||||
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
|
||||
maskedTextBoxPosition.Size = new Size(251, 31);
|
||||
maskedTextBoxPosition.TabIndex = 8;
|
||||
maskedTextBoxPosition.ValidatingType = typeof(int);
|
||||
//
|
||||
// buttonAddWarship
|
||||
//
|
||||
buttonAddWarship.Location = new Point(8, 6);
|
||||
buttonAddWarship.Name = "buttonAddWarship";
|
||||
buttonAddWarship.Size = new Size(251, 34);
|
||||
buttonAddWarship.TabIndex = 2;
|
||||
buttonAddWarship.Text = "Добавить военный корабль";
|
||||
buttonAddWarship.UseVisualStyleBackColor = true;
|
||||
buttonAddWarship.Click += ButtonAddWarship_Click;
|
||||
//
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Location = new Point(8, 163);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(251, 34);
|
||||
buttonGoToCheck.TabIndex = 6;
|
||||
buttonGoToCheck.Text = "Передать на тесты";
|
||||
buttonGoToCheck.UseVisualStyleBackColor = true;
|
||||
buttonGoToCheck.Click += ButtonGoToCheck_Click;
|
||||
//
|
||||
// buttonRemoveWarship
|
||||
//
|
||||
buttonRemoveWarship.Location = new Point(8, 123);
|
||||
buttonRemoveWarship.Name = "buttonRemoveWarship";
|
||||
buttonRemoveWarship.Size = new Size(251, 34);
|
||||
buttonRemoveWarship.TabIndex = 5;
|
||||
buttonRemoveWarship.Text = "Удалить военный корабль";
|
||||
buttonRemoveWarship.UseVisualStyleBackColor = true;
|
||||
buttonRemoveWarship.Click += ButtonRemoveWarship_Click;
|
||||
//
|
||||
// buttonCreateCompany
|
||||
//
|
||||
buttonCreateCompany.Location = new Point(14, 320);
|
||||
buttonCreateCompany.Name = "buttonCreateCompany";
|
||||
buttonCreateCompany.Size = new Size(251, 34);
|
||||
buttonCreateCompany.TabIndex = 10;
|
||||
buttonCreateCompany.Text = "Создать компанию";
|
||||
buttonCreateCompany.UseVisualStyleBackColor = true;
|
||||
buttonCreateCompany.Click += ButtonCreateCompany_Click;
|
||||
//
|
||||
// comboBoxSelectorCompany
|
||||
//
|
||||
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||
comboBoxSelectorCompany.FormattingEnabled = true;
|
||||
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
|
||||
comboBoxSelectorCompany.Location = new Point(14, 281);
|
||||
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
|
||||
comboBoxSelectorCompany.Size = new Size(251, 33);
|
||||
comboBoxSelectorCompany.TabIndex = 0;
|
||||
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
|
||||
//
|
||||
// panelCollection
|
||||
//
|
||||
panelCollection.Controls.Add(buttonCollectionDel);
|
||||
panelCollection.Controls.Add(listBoxCollection);
|
||||
panelCollection.Controls.Add(buttonCollectionAdd);
|
||||
panelCollection.Controls.Add(radioButtonList);
|
||||
panelCollection.Controls.Add(radioButtonMassive);
|
||||
panelCollection.Controls.Add(textBoxCollectionName);
|
||||
panelCollection.Controls.Add(labelCollection);
|
||||
panelCollection.Location = new Point(6, 30);
|
||||
panelCollection.Name = "panelCollection";
|
||||
panelCollection.Size = new Size(267, 246);
|
||||
panelCollection.TabIndex = 9;
|
||||
//
|
||||
// buttonCollectionDel
|
||||
//
|
||||
buttonCollectionDel.Location = new Point(8, 210);
|
||||
buttonCollectionDel.Name = "buttonCollectionDel";
|
||||
buttonCollectionDel.Size = new Size(251, 34);
|
||||
buttonCollectionDel.TabIndex = 7;
|
||||
buttonCollectionDel.Text = "Удалить коллекцию";
|
||||
buttonCollectionDel.UseVisualStyleBackColor = true;
|
||||
buttonCollectionDel.Click += ButtonCollectionDel_Click;
|
||||
//
|
||||
// listBoxCollection
|
||||
//
|
||||
listBoxCollection.FormattingEnabled = true;
|
||||
listBoxCollection.ItemHeight = 25;
|
||||
listBoxCollection.Location = new Point(8, 125);
|
||||
listBoxCollection.Name = "listBoxCollection";
|
||||
listBoxCollection.Size = new Size(251, 79);
|
||||
listBoxCollection.TabIndex = 6;
|
||||
//
|
||||
// buttonCollectionAdd
|
||||
//
|
||||
buttonCollectionAdd.Location = new Point(8, 85);
|
||||
buttonCollectionAdd.Name = "buttonCollectionAdd";
|
||||
buttonCollectionAdd.Size = new Size(251, 34);
|
||||
buttonCollectionAdd.TabIndex = 5;
|
||||
buttonCollectionAdd.Text = "Добавить коллекцию";
|
||||
buttonCollectionAdd.UseVisualStyleBackColor = true;
|
||||
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
|
||||
//
|
||||
// radioButtonList
|
||||
//
|
||||
radioButtonList.AutoSize = true;
|
||||
radioButtonList.Location = new Point(150, 58);
|
||||
radioButtonList.Name = "radioButtonList";
|
||||
radioButtonList.Size = new Size(96, 29);
|
||||
radioButtonList.TabIndex = 4;
|
||||
radioButtonList.TabStop = true;
|
||||
radioButtonList.Text = "Список";
|
||||
radioButtonList.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// radioButtonMassive
|
||||
//
|
||||
radioButtonMassive.AutoSize = true;
|
||||
radioButtonMassive.Location = new Point(19, 58);
|
||||
radioButtonMassive.Name = "radioButtonMassive";
|
||||
radioButtonMassive.Size = new Size(98, 29);
|
||||
radioButtonMassive.TabIndex = 3;
|
||||
radioButtonMassive.TabStop = true;
|
||||
radioButtonMassive.Text = "Массив";
|
||||
radioButtonMassive.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// textBoxCollectionName
|
||||
//
|
||||
textBoxCollectionName.Location = new Point(8, 26);
|
||||
textBoxCollectionName.Name = "textBoxCollectionName";
|
||||
textBoxCollectionName.Size = new Size(251, 31);
|
||||
textBoxCollectionName.TabIndex = 2;
|
||||
//
|
||||
// labelCollection
|
||||
//
|
||||
labelCollection.AutoSize = true;
|
||||
labelCollection.Location = new Point(44, 1);
|
||||
labelCollection.Name = "labelCollection";
|
||||
labelCollection.Size = new Size(186, 25);
|
||||
labelCollection.TabIndex = 1;
|
||||
labelCollection.Text = "Название коллекции:";
|
||||
//
|
||||
// pictureBox
|
||||
//
|
||||
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
|
||||
pictureBox.Location = new Point(0, 51);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(688, 567);
|
||||
pictureBox.TabIndex = 2;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
// menuStrip
|
||||
//
|
||||
menuStrip.ImageScalingSize = new Size(24, 24);
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(978, 33);
|
||||
menuStrip.TabIndex = 3;
|
||||
menuStrip.Text = "menuStrip";
|
||||
//
|
||||
// файлToolStripMenuItem
|
||||
//
|
||||
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
|
||||
файлToolStripMenuItem.Name = "файлToolStripMenuItem";
|
||||
файлToolStripMenuItem.Size = new Size(69, 29);
|
||||
файлToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// saveToolStripMenuItem
|
||||
//
|
||||
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
|
||||
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
|
||||
saveToolStripMenuItem.Size = new Size(278, 34);
|
||||
saveToolStripMenuItem.Text = "Сохранение ";
|
||||
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
|
||||
//
|
||||
// loadToolStripMenuItem
|
||||
//
|
||||
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
|
||||
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
|
||||
loadToolStripMenuItem.Size = new Size(278, 34);
|
||||
loadToolStripMenuItem.Text = "Загрузка";
|
||||
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
|
||||
//
|
||||
// saveFileDialog
|
||||
//
|
||||
saveFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// openFileDialog
|
||||
//
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// FormWarshipCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(10F, 25F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(978, 618);
|
||||
Controls.Add(groupBoxCollectionTools);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(menuStrip);
|
||||
MainMenuStrip = menuStrip;
|
||||
Name = "FormWarshipCollection";
|
||||
Text = "Коллекция военных кораблей";
|
||||
groupBoxCollectionTools.ResumeLayout(false);
|
||||
panelCompanyTools.ResumeLayout(false);
|
||||
panelCompanyTools.PerformLayout();
|
||||
panelCollection.ResumeLayout(false);
|
||||
panelCollection.PerformLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
|
||||
menuStrip.ResumeLayout(false);
|
||||
menuStrip.PerformLayout();
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
private GroupBox groupBoxCollectionTools;
|
||||
private Button buttonAddBattleship;
|
||||
private Button buttonAddWarship;
|
||||
private ComboBox comboBoxSelectorCompany;
|
||||
private Button buttonRefresh;
|
||||
private Button buttonGoToCheck;
|
||||
private Button buttonRemoveWarship;
|
||||
private MaskedTextBox maskedTextBoxPosition;
|
||||
private PictureBox pictureBox;
|
||||
private Panel panelCollection;
|
||||
private TextBox textBoxCollectionName;
|
||||
private Label labelCollection;
|
||||
private Button buttonCollectionAdd;
|
||||
private RadioButton radioButtonList;
|
||||
private RadioButton radioButtonMassive;
|
||||
private Button buttonCreateCompany;
|
||||
private Button buttonCollectionDel;
|
||||
private ListBox listBoxCollection;
|
||||
private Panel panelCompanyTools;
|
||||
private MenuStrip menuStrip;
|
||||
private ToolStripMenuItem файлToolStripMenuItem;
|
||||
private ToolStripMenuItem saveToolStripMenuItem;
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
}
|
||||
}
|
369
ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs
Normal file
369
ProjectBattleship/ProjectBattleship/FormWarshipCollection.cs
Normal file
@ -0,0 +1,369 @@
|
||||
using Battleship.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectBattleship.CollectionGenericObjects;
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectBattleship;
|
||||
/// <summary>
|
||||
/// Форма работы с компанией и ее коллекцией
|
||||
/// </summary>
|
||||
public partial class FormWarshipCollection : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Хранилише коллекций
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawingWarship> _storageCollection;
|
||||
/// <summary>
|
||||
/// Компания
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор компании
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender,
|
||||
EventArgs e)
|
||||
{
|
||||
panelCompanyTools.Enabled = false;
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление военного корабля
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddWarship_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormWarshipConfig form = new();
|
||||
form.Show();
|
||||
form.AddEvent(SetWarship);
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление военного корабля в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="Warship"></param>
|
||||
private void SetWarship(DrawingWarship warship)
|
||||
{
|
||||
if (_company == null || warship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
var res = _company + warship;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Объект добавлен под индексом {res}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление линкора
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddBattleship_Click(object sender, EventArgs e) =>
|
||||
CreateObject(nameof(DrawingBattleship));
|
||||
/// <summary>
|
||||
/// Создание объекта класса-перемещения
|
||||
/// </summary>
|
||||
/// <param name="type">Тип создаваемого объекта</param>
|
||||
private void CreateObject(string type)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Random random = new();
|
||||
DrawingWarship drawingWarship;
|
||||
switch (type)
|
||||
{
|
||||
case nameof(DrawingWarship):
|
||||
drawingWarship = new DrawingWarship(random.Next(100, 300),
|
||||
random.Next(1000, 3000), GetColor(random));
|
||||
break;
|
||||
case nameof(DrawingBattleship):
|
||||
drawingWarship = new DrawingBattleship(random.Next(100, 300),
|
||||
random.Next(1000, 3000),
|
||||
GetColor(random), GetColor(random),
|
||||
Convert.ToBoolean(random.Next(0, 2)),
|
||||
Convert.ToBoolean(random.Next(0, 2)));
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
if (_company + drawingWarship != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение цвета
|
||||
/// </summary>
|
||||
/// <param name="random">Генератор случайных чисел</param>
|
||||
/// <returns></returns>
|
||||
private static Color GetColor(Random random)
|
||||
{
|
||||
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;
|
||||
}
|
||||
return color;
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление объекта
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveWarship_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)
|
||||
|| _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
try
|
||||
{
|
||||
var res = _company - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Передача объекта в другую форму
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
DrawingWarship? warship = null;
|
||||
int counter = 100;
|
||||
while (warship == null)
|
||||
{
|
||||
warship = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (warship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormBattleship form = new()
|
||||
{
|
||||
SetWarship = warship
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
|
||||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation("Добавление коллекции");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
|
||||
DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation("Коллекция удалена");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
private void RerfreshListBoxItems()
|
||||
{
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
{
|
||||
listBoxCollection.Items.Add(colName);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание компании
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCreateCompany_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 ||
|
||||
listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
ICollectionGenericObjects<DrawingWarship>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
}
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new Docks(pictureBox.Width,
|
||||
pictureBox.Height, collection);
|
||||
break;
|
||||
}
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Сохранение"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", 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
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
RerfreshListBoxItems();
|
||||
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
129
ProjectBattleship/ProjectBattleship/FormWarshipCollection.resx
Normal file
129
ProjectBattleship/ProjectBattleship/FormWarshipCollection.resx
Normal file
@ -0,0 +1,129 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<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="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>163, 17</value>
|
||||
</metadata>
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>351, 17</value>
|
||||
</metadata>
|
||||
</root>
|
360
ProjectBattleship/ProjectBattleship/FormWarshipConfig.Designer.cs
generated
Normal file
360
ProjectBattleship/ProjectBattleship/FormWarshipConfig.Designer.cs
generated
Normal file
@ -0,0 +1,360 @@
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
partial class FormWarshipConfig
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
groupBoxConfig = new GroupBox();
|
||||
groupBoxColors = new GroupBox();
|
||||
panelPurple = new Panel();
|
||||
panelBlack = new Panel();
|
||||
panelGray = new Panel();
|
||||
panelWhite = new Panel();
|
||||
panelYellow = new Panel();
|
||||
panelBlue = new Panel();
|
||||
panelGreen = new Panel();
|
||||
panelRed = new Panel();
|
||||
checkBoxRocketCompartment = new CheckBox();
|
||||
checkBoxTurret = new CheckBox();
|
||||
numericUpDownWeight = new NumericUpDown();
|
||||
labelWeight = new Label();
|
||||
numericUpDownSpeed = new NumericUpDown();
|
||||
labelSpeed = new Label();
|
||||
labelModifiedObject = new Label();
|
||||
labelSimpleObject = new Label();
|
||||
pictureBoxObject = new PictureBox();
|
||||
buttonAdd = new Button();
|
||||
buttonCancel = new Button();
|
||||
panelObject = new Panel();
|
||||
labelAdditionalColor = new Label();
|
||||
labelBodyColor = new Label();
|
||||
groupBoxConfig.SuspendLayout();
|
||||
groupBoxColors.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
|
||||
panelObject.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
// groupBoxConfig
|
||||
//
|
||||
groupBoxConfig.Controls.Add(groupBoxColors);
|
||||
groupBoxConfig.Controls.Add(checkBoxRocketCompartment);
|
||||
groupBoxConfig.Controls.Add(checkBoxTurret);
|
||||
groupBoxConfig.Controls.Add(numericUpDownWeight);
|
||||
groupBoxConfig.Controls.Add(labelWeight);
|
||||
groupBoxConfig.Controls.Add(numericUpDownSpeed);
|
||||
groupBoxConfig.Controls.Add(labelSpeed);
|
||||
groupBoxConfig.Controls.Add(labelModifiedObject);
|
||||
groupBoxConfig.Controls.Add(labelSimpleObject);
|
||||
groupBoxConfig.Dock = DockStyle.Left;
|
||||
groupBoxConfig.Location = new Point(0, 0);
|
||||
groupBoxConfig.Name = "groupBoxConfig";
|
||||
groupBoxConfig.Size = new Size(671, 379);
|
||||
groupBoxConfig.TabIndex = 0;
|
||||
groupBoxConfig.TabStop = false;
|
||||
groupBoxConfig.Text = "Параметры";
|
||||
//
|
||||
// groupBoxColors
|
||||
//
|
||||
groupBoxColors.Controls.Add(panelPurple);
|
||||
groupBoxColors.Controls.Add(panelBlack);
|
||||
groupBoxColors.Controls.Add(panelGray);
|
||||
groupBoxColors.Controls.Add(panelWhite);
|
||||
groupBoxColors.Controls.Add(panelYellow);
|
||||
groupBoxColors.Controls.Add(panelBlue);
|
||||
groupBoxColors.Controls.Add(panelGreen);
|
||||
groupBoxColors.Controls.Add(panelRed);
|
||||
groupBoxColors.Location = new Point(300, 30);
|
||||
groupBoxColors.Name = "groupBoxColors";
|
||||
groupBoxColors.Size = new Size(345, 195);
|
||||
groupBoxColors.TabIndex = 8;
|
||||
groupBoxColors.TabStop = false;
|
||||
groupBoxColors.Text = "Цвета";
|
||||
//
|
||||
// panelPurple
|
||||
//
|
||||
panelPurple.BackColor = Color.MediumPurple;
|
||||
panelPurple.Location = new Point(271, 112);
|
||||
panelPurple.Name = "panelPurple";
|
||||
panelPurple.Size = new Size(62, 56);
|
||||
panelPurple.TabIndex = 7;
|
||||
//
|
||||
// panelBlack
|
||||
//
|
||||
panelBlack.BackColor = Color.Black;
|
||||
panelBlack.Location = new Point(182, 112);
|
||||
panelBlack.Name = "panelBlack";
|
||||
panelBlack.Size = new Size(62, 56);
|
||||
panelBlack.TabIndex = 6;
|
||||
//
|
||||
// panelGray
|
||||
//
|
||||
panelGray.BackColor = Color.LightGray;
|
||||
panelGray.Location = new Point(94, 112);
|
||||
panelGray.Name = "panelGray";
|
||||
panelGray.Size = new Size(62, 56);
|
||||
panelGray.TabIndex = 5;
|
||||
//
|
||||
// panelWhite
|
||||
//
|
||||
panelWhite.BackColor = Color.White;
|
||||
panelWhite.Location = new Point(7, 112);
|
||||
panelWhite.Name = "panelWhite";
|
||||
panelWhite.Size = new Size(62, 56);
|
||||
panelWhite.TabIndex = 4;
|
||||
//
|
||||
// panelYellow
|
||||
//
|
||||
panelYellow.BackColor = Color.Yellow;
|
||||
panelYellow.Location = new Point(271, 30);
|
||||
panelYellow.Name = "panelYellow";
|
||||
panelYellow.Size = new Size(62, 56);
|
||||
panelYellow.TabIndex = 3;
|
||||
//
|
||||
// panelBlue
|
||||
//
|
||||
panelBlue.BackColor = Color.Blue;
|
||||
panelBlue.Location = new Point(182, 30);
|
||||
panelBlue.Name = "panelBlue";
|
||||
panelBlue.Size = new Size(62, 56);
|
||||
panelBlue.TabIndex = 2;
|
||||
//
|
||||
// panelGreen
|
||||
//
|
||||
panelGreen.BackColor = Color.Green;
|
||||
panelGreen.Location = new Point(94, 30);
|
||||
panelGreen.Name = "panelGreen";
|
||||
panelGreen.Size = new Size(62, 56);
|
||||
panelGreen.TabIndex = 1;
|
||||
//
|
||||
// panelRed
|
||||
//
|
||||
panelRed.BackColor = Color.Red;
|
||||
panelRed.Location = new Point(7, 30);
|
||||
panelRed.Name = "panelRed";
|
||||
panelRed.Size = new Size(62, 56);
|
||||
panelRed.TabIndex = 0;
|
||||
//
|
||||
// checkBoxRocketCompartment
|
||||
//
|
||||
checkBoxRocketCompartment.AutoSize = true;
|
||||
checkBoxRocketCompartment.Location = new Point(14, 277);
|
||||
checkBoxRocketCompartment.Name = "checkBoxRocketCompartment";
|
||||
checkBoxRocketCompartment.Size = new Size(337, 29);
|
||||
checkBoxRocketCompartment.TabIndex = 7;
|
||||
checkBoxRocketCompartment.Text = "Признак наличия отсека под ракеты";
|
||||
checkBoxRocketCompartment.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// checkBoxTurret
|
||||
//
|
||||
checkBoxTurret.AutoSize = true;
|
||||
checkBoxTurret.Location = new Point(14, 231);
|
||||
checkBoxTurret.Name = "checkBoxTurret";
|
||||
checkBoxTurret.Size = new Size(335, 29);
|
||||
checkBoxTurret.TabIndex = 6;
|
||||
checkBoxTurret.Text = "Признак наличия орудийной башни";
|
||||
checkBoxTurret.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// numericUpDownWeight
|
||||
//
|
||||
numericUpDownWeight.Location = new Point(111, 82);
|
||||
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
|
||||
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
|
||||
numericUpDownWeight.Name = "numericUpDownWeight";
|
||||
numericUpDownWeight.Size = new Size(120, 31);
|
||||
numericUpDownWeight.TabIndex = 5;
|
||||
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
|
||||
//
|
||||
// labelWeight
|
||||
//
|
||||
labelWeight.AutoSize = true;
|
||||
labelWeight.Location = new Point(12, 82);
|
||||
labelWeight.Name = "labelWeight";
|
||||
labelWeight.Size = new Size(43, 25);
|
||||
labelWeight.TabIndex = 4;
|
||||
labelWeight.Text = "Вес:";
|
||||
//
|
||||
// numericUpDownSpeed
|
||||
//
|
||||
numericUpDownSpeed.Location = new Point(111, 30);
|
||||
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
|
||||
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
|
||||
numericUpDownSpeed.Name = "numericUpDownSpeed";
|
||||
numericUpDownSpeed.Size = new Size(120, 31);
|
||||
numericUpDownSpeed.TabIndex = 3;
|
||||
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
|
||||
//
|
||||
// labelSpeed
|
||||
//
|
||||
labelSpeed.AutoSize = true;
|
||||
labelSpeed.Location = new Point(12, 32);
|
||||
labelSpeed.Name = "labelSpeed";
|
||||
labelSpeed.Size = new Size(93, 25);
|
||||
labelSpeed.TabIndex = 2;
|
||||
labelSpeed.Text = "Скорость:";
|
||||
//
|
||||
// labelModifiedObject
|
||||
//
|
||||
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
|
||||
labelModifiedObject.Location = new Point(482, 319);
|
||||
labelModifiedObject.Name = "labelModifiedObject";
|
||||
labelModifiedObject.Size = new Size(163, 38);
|
||||
labelModifiedObject.TabIndex = 1;
|
||||
labelModifiedObject.Text = "Продвинутый";
|
||||
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
|
||||
labelModifiedObject.MouseDown += LabelObject_MouseDown;
|
||||
//
|
||||
// labelSimpleObject
|
||||
//
|
||||
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
|
||||
labelSimpleObject.Location = new Point(300, 319);
|
||||
labelSimpleObject.Name = "labelSimpleObject";
|
||||
labelSimpleObject.Size = new Size(162, 38);
|
||||
labelSimpleObject.TabIndex = 0;
|
||||
labelSimpleObject.Text = "Простой";
|
||||
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
|
||||
labelSimpleObject.MouseDown += LabelObject_MouseDown;
|
||||
//
|
||||
// pictureBoxObject
|
||||
//
|
||||
pictureBoxObject.Location = new Point(46, 92);
|
||||
pictureBoxObject.Name = "pictureBoxObject";
|
||||
pictureBoxObject.Size = new Size(252, 175);
|
||||
pictureBoxObject.TabIndex = 1;
|
||||
pictureBoxObject.TabStop = false;
|
||||
//
|
||||
// buttonAdd
|
||||
//
|
||||
buttonAdd.Location = new Point(707, 323);
|
||||
buttonAdd.Name = "buttonAdd";
|
||||
buttonAdd.Size = new Size(112, 34);
|
||||
buttonAdd.TabIndex = 2;
|
||||
buttonAdd.Text = "Добавить";
|
||||
buttonAdd.UseVisualStyleBackColor = true;
|
||||
buttonAdd.Click += ButtonAdd_Click;
|
||||
//
|
||||
// buttonCancel
|
||||
//
|
||||
buttonCancel.Location = new Point(911, 323);
|
||||
buttonCancel.Name = "buttonCancel";
|
||||
buttonCancel.Size = new Size(112, 34);
|
||||
buttonCancel.TabIndex = 3;
|
||||
buttonCancel.Text = "Отмена";
|
||||
buttonCancel.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// panelObject
|
||||
//
|
||||
panelObject.AllowDrop = true;
|
||||
panelObject.Controls.Add(labelAdditionalColor);
|
||||
panelObject.Controls.Add(labelBodyColor);
|
||||
panelObject.Controls.Add(pictureBoxObject);
|
||||
panelObject.Location = new Point(691, 12);
|
||||
panelObject.Name = "panelObject";
|
||||
panelObject.Size = new Size(343, 294);
|
||||
panelObject.TabIndex = 0;
|
||||
panelObject.DragDrop += PanelObject_DragDrop;
|
||||
panelObject.DragEnter += PanelObject_DragEnter;
|
||||
//
|
||||
// labelAdditionalColor
|
||||
//
|
||||
labelAdditionalColor.AllowDrop = true;
|
||||
labelAdditionalColor.AutoSize = true;
|
||||
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
|
||||
labelAdditionalColor.Location = new Point(220, 18);
|
||||
labelAdditionalColor.Name = "labelAdditionalColor";
|
||||
labelAdditionalColor.Size = new Size(93, 27);
|
||||
labelAdditionalColor.TabIndex = 3;
|
||||
labelAdditionalColor.Text = "Доп. цвет";
|
||||
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
|
||||
labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
|
||||
labelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
|
||||
//
|
||||
// labelBodyColor
|
||||
//
|
||||
labelBodyColor.AllowDrop = true;
|
||||
labelBodyColor.AutoSize = true;
|
||||
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
|
||||
labelBodyColor.Location = new Point(46, 22);
|
||||
labelBodyColor.Name = "labelBodyColor";
|
||||
labelBodyColor.Size = new Size(53, 27);
|
||||
labelBodyColor.TabIndex = 2;
|
||||
labelBodyColor.Text = "Цвет";
|
||||
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
|
||||
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
|
||||
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
|
||||
//
|
||||
// FormWarshipConfig
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(10F, 25F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1046, 379);
|
||||
Controls.Add(panelObject);
|
||||
Controls.Add(buttonCancel);
|
||||
Controls.Add(buttonAdd);
|
||||
Controls.Add(groupBoxConfig);
|
||||
Name = "FormWarshipConfig";
|
||||
Text = "Создание объекта";
|
||||
groupBoxConfig.ResumeLayout(false);
|
||||
groupBoxConfig.PerformLayout();
|
||||
groupBoxColors.ResumeLayout(false);
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
|
||||
panelObject.ResumeLayout(false);
|
||||
panelObject.PerformLayout();
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private GroupBox groupBoxConfig;
|
||||
private Label labelSimpleObject;
|
||||
private Label labelSpeed;
|
||||
private Label labelModifiedObject;
|
||||
private Label labelWeight;
|
||||
private NumericUpDown numericUpDownSpeed;
|
||||
private NumericUpDown numericUpDownWeight;
|
||||
private CheckBox checkBoxTurret;
|
||||
private CheckBox checkBoxRocketCompartment;
|
||||
private GroupBox groupBoxColors;
|
||||
private Panel panelRed;
|
||||
private Panel panelPurple;
|
||||
private Panel panelBlack;
|
||||
private Panel panelGray;
|
||||
private Panel panelWhite;
|
||||
private Panel panelYellow;
|
||||
private Panel panelBlue;
|
||||
private Panel panelGreen;
|
||||
private PictureBox pictureBoxObject;
|
||||
private Button buttonAdd;
|
||||
private Button buttonCancel;
|
||||
private Panel panelObject;
|
||||
private Label labelAdditionalColor;
|
||||
private Label labelBodyColor;
|
||||
}
|
||||
}
|
178
ProjectBattleship/ProjectBattleship/FormWarshipConfig.cs
Normal file
178
ProjectBattleship/ProjectBattleship/FormWarshipConfig.cs
Normal file
@ -0,0 +1,178 @@
|
||||
using ProjectBattleship.DrawingObject;
|
||||
using ProjectBattleship.Entities;
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
/// <summary>
|
||||
/// Форма конфигурации объекта
|
||||
/// </summary>
|
||||
public partial class FormWarshipConfig : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Объект - прорисовка
|
||||
/// </summary>
|
||||
private DrawingWarship? _warship;
|
||||
/// <summary>
|
||||
/// Событие для передачи объекта
|
||||
/// </summary>
|
||||
private event Action<DrawingWarship>? WarshipDelegate;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormWarshipConfig()
|
||||
{
|
||||
InitializeComponent();
|
||||
panelRed.MouseDown += Panel_MouseDown;
|
||||
panelGreen.MouseDown += Panel_MouseDown;
|
||||
panelBlue.MouseDown += Panel_MouseDown;
|
||||
panelYellow.MouseDown += Panel_MouseDown;
|
||||
panelWhite.MouseDown += Panel_MouseDown;
|
||||
panelGray.MouseDown += Panel_MouseDown;
|
||||
panelBlack.MouseDown += Panel_MouseDown;
|
||||
panelPurple.MouseDown += Panel_MouseDown;
|
||||
|
||||
buttonCancel.Click += (sender, e) => Close();
|
||||
}
|
||||
/// <summary>
|
||||
/// Привязка внешнего метода к событию
|
||||
/// </summary>
|
||||
/// <param name="WarshipDelegate"></param>
|
||||
public void AddEvent(Action<DrawingWarship> warshipDelegate)
|
||||
{
|
||||
if (WarshipDelegate != null)
|
||||
{
|
||||
WarshipDelegate = warshipDelegate;
|
||||
}
|
||||
else
|
||||
{
|
||||
WarshipDelegate += warshipDelegate;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Прорисовка объекта
|
||||
/// </summary>
|
||||
private void DrawObject()
|
||||
{
|
||||
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
|
||||
Graphics gr = Graphics.FromImage(bmp);
|
||||
_warship?.SetPictureSize(pictureBoxObject.Width,
|
||||
pictureBoxObject.Height);
|
||||
_warship?.SetPosition(15, 15);
|
||||
_warship?.DrawTransport(gr);
|
||||
pictureBoxObject.Image = bmp;
|
||||
}
|
||||
/// <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 ??
|
||||
string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
|
||||
}
|
||||
/// <summary>
|
||||
/// Проверка получаемой информации (ее типа на соответствие требуемому)
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void PanelObject_DragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ?
|
||||
DragDropEffects.Copy : 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":
|
||||
_warship = new DrawingWarship((int)numericUpDownSpeed.Value,
|
||||
(double)numericUpDownWeight.Value, Color.White);
|
||||
break;
|
||||
case "labelModifiedObject":
|
||||
_warship = new
|
||||
DrawingBattleship((int)numericUpDownSpeed.Value,
|
||||
(double)numericUpDownWeight.Value,
|
||||
Color.White, Color.Black, checkBoxTurret.Checked,
|
||||
checkBoxRocketCompartment.Checked);
|
||||
break;
|
||||
}
|
||||
DrawObject();
|
||||
}
|
||||
/// <summary>
|
||||
/// Передаем информацию при нажатии на Panel
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void Panel_MouseDown(object? sender, MouseEventArgs e)
|
||||
{
|
||||
(sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
|
||||
|
||||
}
|
||||
|
||||
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
|
||||
{
|
||||
e.Effect = DragDropEffects.Copy;
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Effect = DragDropEffects.None;
|
||||
}
|
||||
}
|
||||
|
||||
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
if (_warship != null)
|
||||
{
|
||||
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
|
||||
{
|
||||
_warship.EntityWarship.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
|
||||
}
|
||||
DrawObject();
|
||||
}
|
||||
}
|
||||
|
||||
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
if (_warship != null && _warship is DrawingBattleship)
|
||||
{
|
||||
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
|
||||
{
|
||||
e.Effect = DragDropEffects.Copy;
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Effect = DragDropEffects.None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
if (_warship != null && _warship.EntityWarship is EntityBattleship _battleship)
|
||||
{
|
||||
if (e.Data.GetDataPresent(typeof(Color)))
|
||||
{
|
||||
_battleship.SetAdditionalColor((Color)e.Data.GetData(typeof(Color)));
|
||||
|
||||
}
|
||||
DrawObject();
|
||||
}
|
||||
}
|
||||
|
||||
private void ButtonAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_warship != null)
|
||||
{
|
||||
WarshipDelegate?.Invoke(_warship);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
120
ProjectBattleship/ProjectBattleship/FormWarshipConfig.resx
Normal file
120
ProjectBattleship/ProjectBattleship/FormWarshipConfig.resx
Normal file
@ -0,0 +1,120 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<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>
|
22
ProjectBattleship/ProjectBattleship/IMoveableObject.cs
Normal file
22
ProjectBattleship/ProjectBattleship/IMoveableObject.cs
Normal file
@ -0,0 +1,22 @@
|
||||
namespace ProjectBattleship.MovementStrategy;
|
||||
/// <summary>
|
||||
/// Интерфейс для работы с перемещаемым объектом
|
||||
/// </summary>
|
||||
public interface IMoveableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Получение координаты объекта
|
||||
/// </summary>
|
||||
ObjectParameters? GetObjectPosition { get; }
|
||||
/// <summary>
|
||||
/// Шаг объекта
|
||||
/// </summary>
|
||||
int GetStep { get; }
|
||||
/// <summary>
|
||||
/// Попытка переместить объект в указанном направлении
|
||||
/// </summary>
|
||||
/// <param name="direction">Направление</param>
|
||||
/// <returns>true - объект перемещен, false - перемещение
|
||||
///невозможно</returns>
|
||||
bool TryMoveObject(MovementDirection direction);
|
||||
}
|
53
ProjectBattleship/ProjectBattleship/MoveToBorder.cs
Normal file
53
ProjectBattleship/ProjectBattleship/MoveToBorder.cs
Normal file
@ -0,0 +1,53 @@
|
||||
namespace ProjectBattleship.MovementStrategy
|
||||
{
|
||||
/// <summary>
|
||||
/// Стратегия перемещения объекта к краю экрана
|
||||
/// </summary>
|
||||
internal class MoveToBorder : AbstractStrategy
|
||||
{
|
||||
protected override bool IsTargetDestinaion()
|
||||
{
|
||||
ObjectParameters? objParams = GetObjectParameters;
|
||||
if (objParams == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return objParams.RightBorder - GetStep() <= FieldWidth
|
||||
&& objParams.RightBorder + GetStep() >= FieldWidth &&
|
||||
objParams.DownBorder - GetStep() <= FieldHeight
|
||||
&& objParams.DownBorder + GetStep() >= FieldHeight;
|
||||
}
|
||||
protected override void MoveToTarget()
|
||||
{
|
||||
ObjectParameters? objParams = GetObjectParameters;
|
||||
if (objParams == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int diffX = objParams.RightBorder - FieldWidth;
|
||||
if (Math.Abs(diffX) > GetStep())
|
||||
{
|
||||
if (diffX > 0)
|
||||
{
|
||||
MoveLeft();
|
||||
}
|
||||
else
|
||||
{
|
||||
MoveRight();
|
||||
}
|
||||
}
|
||||
int diffY = objParams.DownBorder - FieldHeight;
|
||||
if (Math.Abs(diffY) > GetStep())
|
||||
{
|
||||
if (diffY > 0)
|
||||
{
|
||||
MoveUp();
|
||||
}
|
||||
else
|
||||
{
|
||||
MoveDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
51
ProjectBattleship/ProjectBattleship/MoveToCenter.cs
Normal file
51
ProjectBattleship/ProjectBattleship/MoveToCenter.cs
Normal file
@ -0,0 +1,51 @@
|
||||
namespace ProjectBattleship.MovementStrategy;
|
||||
/// <summary>
|
||||
/// Стратегия перемещения объекта в центр экрана
|
||||
/// </summary>
|
||||
public class MoveToCenter : AbstractStrategy
|
||||
{
|
||||
protected override bool IsTargetDestinaion()
|
||||
{
|
||||
ObjectParameters? objParams = GetObjectParameters;
|
||||
if (objParams == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2
|
||||
&& objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
|
||||
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2
|
||||
&& objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
|
||||
}
|
||||
protected override void MoveToTarget()
|
||||
{
|
||||
ObjectParameters? objParams = GetObjectParameters;
|
||||
if (objParams == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
|
||||
if (Math.Abs(diffX) > GetStep())
|
||||
{
|
||||
if (diffX > 0)
|
||||
{
|
||||
MoveLeft();
|
||||
}
|
||||
else
|
||||
{
|
||||
MoveRight();
|
||||
}
|
||||
}
|
||||
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
|
||||
if (Math.Abs(diffY) > GetStep())
|
||||
{
|
||||
if (diffY > 0)
|
||||
{
|
||||
MoveUp();
|
||||
}
|
||||
else
|
||||
{
|
||||
MoveDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
58
ProjectBattleship/ProjectBattleship/MoveableWarship.cs
Normal file
58
ProjectBattleship/ProjectBattleship/MoveableWarship.cs
Normal file
@ -0,0 +1,58 @@
|
||||
using ProjectBattleship.DrawingObject;
|
||||
namespace ProjectBattleship.MovementStrategy;
|
||||
/// <summary>
|
||||
/// Класс-реализация IMoveableObject с использованием DrawingWarship
|
||||
/// </summary>
|
||||
public class MoveableWarship : IMoveableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Поле-объект класса DrawingWarship или его наследника
|
||||
/// </summary>
|
||||
private readonly DrawingWarship? _warship = null;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="warship">Объект класса DrawingWarship</param>
|
||||
public MoveableWarship(DrawingWarship warship)
|
||||
{
|
||||
_warship = warship;
|
||||
}
|
||||
public ObjectParameters? GetObjectPosition
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_warship == null || _warship.EntityWarship == null ||
|
||||
!_warship.GetPosX.HasValue || !_warship.GetPosY.HasValue)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new ObjectParameters(_warship.GetPosX.Value,
|
||||
_warship.GetPosY.Value, _warship.GetWidth, _warship.GetHeight);
|
||||
}
|
||||
}
|
||||
public int GetStep => (int)(_warship?.EntityWarship?.Step ?? 0);
|
||||
public bool TryMoveObject(MovementDirection direction)
|
||||
{
|
||||
if (_warship == null || _warship.EntityWarship == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return _warship.MoveTransport(GetDirectionType(direction));
|
||||
}
|
||||
/// <summary>
|
||||
/// Конвертация из MovementDirection в DirectionType
|
||||
/// </summary>
|
||||
/// <param name="direction">MovementDirection</param>
|
||||
/// <returns>DirectionType</returns>
|
||||
private static DirectionType GetDirectionType(MovementDirection direction)
|
||||
{
|
||||
return direction switch
|
||||
{
|
||||
MovementDirection.Left => DirectionType.Left,
|
||||
MovementDirection.Right => DirectionType.Right,
|
||||
MovementDirection.Up => DirectionType.Up,
|
||||
MovementDirection.Down => DirectionType.Down,
|
||||
_ => DirectionType.Unknow,
|
||||
};
|
||||
}
|
||||
}
|
23
ProjectBattleship/ProjectBattleship/MovementDirection.cs
Normal file
23
ProjectBattleship/ProjectBattleship/MovementDirection.cs
Normal file
@ -0,0 +1,23 @@
|
||||
namespace ProjectBattleship.MovementStrategy;
|
||||
/// <summary>
|
||||
/// Направление перемещения
|
||||
/// </summary>
|
||||
public enum MovementDirection
|
||||
{
|
||||
/// <summary>
|
||||
/// Вверх
|
||||
/// </summary>
|
||||
Up = 1,
|
||||
/// <summary>
|
||||
/// Вниз
|
||||
/// </summary>
|
||||
Down = 2,
|
||||
/// <summary>
|
||||
/// Влево
|
||||
/// </summary>
|
||||
Left = 3,
|
||||
/// <summary>
|
||||
/// Вправо
|
||||
/// </summary>
|
||||
Right = 4
|
||||
}
|
61
ProjectBattleship/ProjectBattleship/ObjectParameters.cs
Normal file
61
ProjectBattleship/ProjectBattleship/ObjectParameters.cs
Normal file
@ -0,0 +1,61 @@
|
||||
namespace ProjectBattleship.MovementStrategy;
|
||||
/// <summary>
|
||||
/// Параметры-координаты объекта
|
||||
/// </summary>
|
||||
public class ObjectParameters
|
||||
{
|
||||
/// <summary>
|
||||
/// Координата X
|
||||
/// </summary>
|
||||
private readonly int _x;
|
||||
/// <summary>
|
||||
/// Координата Y
|
||||
/// </summary>
|
||||
private readonly int _y;
|
||||
/// <summary>
|
||||
/// Ширина объекта
|
||||
/// </summary>
|
||||
private readonly int _width;
|
||||
/// <summary>
|
||||
/// Высота объекта
|
||||
/// </summary>
|
||||
private readonly int _height;
|
||||
/// <summary>
|
||||
/// Левая граница
|
||||
/// </summary>
|
||||
public int LeftBorder => _x;
|
||||
/// <summary>
|
||||
/// Верхняя граница
|
||||
/// </summary>
|
||||
public int TopBorder => _y;
|
||||
/// <summary>
|
||||
/// Правая граница
|
||||
/// </summary>
|
||||
public int RightBorder => _x + _width;
|
||||
/// <summary>
|
||||
/// Нижняя граница
|
||||
/// </summary>
|
||||
public int DownBorder => _y + _height;
|
||||
/// <summary>
|
||||
/// Середина объекта
|
||||
/// </summary>
|
||||
public int 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,11 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
using System.Drawing;
|
||||
using System;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectBattleship
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +19,34 @@ namespace ProjectBattleship
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new Form1());
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider =
|
||||
services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormWarshipCollection>());
|
||||
}
|
||||
/// <summary>
|
||||
/// Êîíôèãóðàöèÿ ñåðâèñà DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormWarshipCollection>().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}serilogConfig.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,4 +8,35 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Update="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilogConfig.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
113
ProjectBattleship/ProjectBattleship/Properties/Resources.Designer.cs
generated
Normal file
113
ProjectBattleship/ProjectBattleship/Properties/Resources.Designer.cs
generated
Normal file
@ -0,0 +1,113 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// Этот код создан программой.
|
||||
// Исполняемая версия:4.0.30319.42000
|
||||
//
|
||||
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
|
||||
// повторной генерации кода.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace ProjectBattleship.Properties {
|
||||
using System;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
|
||||
/// </summary>
|
||||
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
|
||||
// с помощью такого средства, как ResGen или Visual Studio.
|
||||
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
|
||||
// с параметром /str или перестройте свой проект VS.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class Resources {
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal Resources() {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
get {
|
||||
if (object.ReferenceEquals(resourceMan, null)) {
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectBattleship.Properties.Resources", typeof(Resources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
|
||||
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
get {
|
||||
return resourceCulture;
|
||||
}
|
||||
set {
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap arrowDown {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowDown", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap arrowLeft {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowLeft", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap arrowLeft1 {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowLeft1", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap arrowRight {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowRight", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap arrowUp {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowUp", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
136
ProjectBattleship/ProjectBattleship/Properties/Resources.resx
Normal file
136
ProjectBattleship/ProjectBattleship/Properties/Resources.resx
Normal file
@ -0,0 +1,136 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<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>
|
||||
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
|
||||
<data name="arrowLeft" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\Resources\arrowLeft.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
<data name="arrowDown" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\Resources\arrowDown.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
<data name="arrowLeft1" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\Resources\arrowLeft1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
<data name="arrowRight" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\Resources\arrowRight.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
<data name="arrowUp" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\Resources\arrowUp.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
</root>
|
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowDown.png
Normal file
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowDown.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 24 KiB |
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowLeft.png
Normal file
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowLeft.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 7.0 KiB |
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowLeft1.png
Normal file
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowLeft1.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 7.0 KiB |
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowRight.png
Normal file
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowRight.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 24 KiB |
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowUp.png
Normal file
BIN
ProjectBattleship/ProjectBattleship/Resources/arrowUp.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 24 KiB |
19
ProjectBattleship/ProjectBattleship/StrategyStatus.cs
Normal file
19
ProjectBattleship/ProjectBattleship/StrategyStatus.cs
Normal file
@ -0,0 +1,19 @@
|
||||
namespace ProjectBattleship.MovementStrategy;
|
||||
/// <summary>
|
||||
/// Статус выполнения операции перемещения
|
||||
/// </summary>
|
||||
public enum StrategyStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// Все готово к началу
|
||||
/// </summary>
|
||||
NotInit,
|
||||
/// <summary>
|
||||
/// Выполняется
|
||||
/// </summary>
|
||||
InProgress,
|
||||
/// <summary>
|
||||
/// Завершено
|
||||
/// </summary>
|
||||
Finish
|
||||
}
|
20
ProjectBattleship/ProjectBattleship/serilogConfig.json
Normal file
20
ProjectBattleship/ProjectBattleship/serilogConfig.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"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user