Compare commits

..

No commits in common. "Lab_8" and "main" have entirely different histories.
Lab_8 ... main

45 changed files with 52 additions and 5618 deletions

View File

@ -1,123 +0,0 @@
using ProjectBattleship.Drawnings;
using System;
using Battleship.Drawnings;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию кораблей
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 100;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция кораблей
/// </summary>
protected ICollectionGenericObjects<DrawingShip>? _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<DrawingShip> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawingShip ship)
{
return company._collection.Insert(ship, new DrawningShipEqutables());
}
public void Sort(IComparer<DrawingShip?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawingShip? operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawingShip? 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
{
DrawingShip? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException) { };
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackground(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@ -1,73 +0,0 @@
using ProjectBattleship.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -1,22 +0,0 @@
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
/// Тип коллекции
/// </summary>
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// Список
/// </summary>
List = 2
}

View File

@ -1,61 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBattleship.CollectionGenericObjects
{
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, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <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();
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@ -1,89 +0,0 @@
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
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
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
if (position < 0 || position >= _collection.Count)
throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count + 1 <= _maxCount)
{
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException();
_collection.Add(obj);
return Count - 1;
}
throw new CollectionOverflowException(MaxCount);
}
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Count + 1 > MaxCount)
throw new CollectionOverflowException(MaxCount);
if (position < 0 || position >= MaxCount)
throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException();
_collection.Insert(position, obj);
return true;
}
public T Remove(int position)
{
if (position < 0 || position >= _collection.Count)
throw new PositionOutOfCollectionException(position);
T temp = _collection[position];
_collection.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,133 +0,0 @@
using ProjectBattleship.Drawnings;
using ProjectBattleship.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.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 >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
int index = Array.IndexOf(_collection, null);
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException(index);
if (index >= 0)
{
_collection[index] = obj;
return index;
}
throw new CollectionOverflowException(_collection.Length);
}
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= _collection.Length) // проверка позиции
throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
throw new ObjectExistsException(position);
if (_collection[position] == null) // Попытка вставить на указанную позицию
{
_collection[position] = obj;
return true;
}
for (int i = position; i < _collection.Length; i++) // попытка вставить объект на позицию после указанной
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
for (int i = 0; i < position; i++) // попытка вставить объект на позицию до указанной
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
throw new CollectionOverflowException(_collection.Length);
}
public T Remove(int position)
{
if (position < 0 || position >= _collection.Length) // проверка позиции
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];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
}

View File

@ -1,73 +0,0 @@
using ProjectBattleship.Drawnings;
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using Battleship.Exceptions;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - доки с кораблями
/// </summary>
public class ShipDocks : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public ShipDocks(int picWidth, int picHeight, ICollectionGenericObjects<DrawingShip> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
}
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)),
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
}
}
protected override void SetObjectsPosition()
{
int n = 0;
for (int j = _pictureHeight / _placeSizeHeight - 1; j >= 0; j--)
{
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
try
{
DrawingShip? drawingTrans = _collection?.Get(n);
if (drawingTrans != null)
{
drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight);
drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
catch (ObjectNotFoundException e)
{
}
catch (PositionOutOfCollectionException e)
{
}
n++;
}
}
}
}

View File

@ -1,181 +0,0 @@
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Drawnings;
using System.Text;
using Battleship.Exceptions;
using Microsoft.AspNetCore.Http;
using Battleship.CollectionGenericObjects;
namespace ProjectBattleship.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawingShip
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
public StorageCollection()
{
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
CollectionInfo tempInfo = new(name, collectionType, string.Empty);
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(tempInfo))
return;
switch (collectionType)
{
case CollectionType.List:
_storages.Add(tempInfo, new ListGenericObjects<T>());
break;
case CollectionType.Massive:
_storages.Add(tempInfo, new MassiveGenericObjects<T>());
break;
default:
break;
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
CollectionInfo tempInfo = new(name, CollectionType.None, string.Empty);
if (tempInfo.Name != null && _storages.ContainsKey(tempInfo))
_storages.Remove(tempInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
CollectionInfo tempInfo = new(name, CollectionType.None, string.Empty);
if (tempInfo == null || !_storages.ContainsKey(tempInfo)) { return null; }
return _storages[tempInfo];
}
}
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
continue;
sb.Append(data);
sb.Append(_separatorItems);
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
}
}
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 != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningShip() is T ship)
{
try
{
if (collection.Insert(ship) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -1,11 +0,0 @@
namespace ProjectBattleship.Drawnings
{
public enum DirectionType
{
Unknow = -1,
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
}

View File

@ -1,46 +0,0 @@
using ProjectBattleship.Entities;
namespace ProjectBattleship.Drawnings;
public class DrawingBattleship : DrawingShip
{
public DrawingBattleship(EntityShip ship) : base(143, 75)
{
EntityShip = ship;
}
public DrawingBattleship(int speed, double weight, Color bodycolor, Color additionalcolor, bool turret, bool rocketLauncher) : base(143, 75)
{
EntityShip = new EntityBattleship(speed, weight, bodycolor, additionalcolor, turret, rocketLauncher);
}
public override void DrawTransport(Graphics g)
{
if (EntityShip == null || EntityShip 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.Turret)
{
Point[] shield = 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, shield);
g.FillRectangle(additionalBrush, _startPosX.Value + 119, _startPosY.Value + 24, 12, 2);
g.DrawPolygon(pen, shield);
g.DrawRectangle(pen, _startPosX.Value + 119, _startPosY.Value + 24, 12, 2);
}
//ячейки для ракет
if (battleship.RocketLauncher)
{
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);
}
}
}

View File

@ -1,148 +0,0 @@
using ProjectBattleship.Entities;
namespace ProjectBattleship.Drawnings;
public class DrawingShip
{
public EntityShip? EntityShip { get; protected set; }
private int? _pictureWidth;
private int? _pictureHeight;
protected int? _startPosX;
protected int? _startPosY;
private readonly int _shipWidth = 150;
private readonly int _shipHeight = 50;
public int? GetPosX => _startPosX;
public int? GetPosY => _startPosY;
public int GetWidth => _shipWidth;
public int GetHeight => _shipHeight;
private DrawingShip()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
public DrawingShip(int speed, double weight, Color bodycolor) : this()
{
EntityShip = new EntityShip(speed, weight, bodycolor);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
protected DrawingShip(int shipWidth, int shipHeight) : this()
{
_shipWidth = shipWidth;
_shipHeight = shipHeight;
}
public DrawingShip(EntityShip ship) : this()
{
EntityShip = ship;
}
public bool SetPictureSize(int width, int height)
{
if (width >= _shipWidth || height >= _shipHeight)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null && _startPosY != null)
{
SetPosition(_startPosX.Value, _startPosY.Value);
}
return true;
}
return false;
}
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x < 0)
{
x = 0;
}
else if (x > _pictureWidth - _shipWidth)
{
x = _pictureWidth.Value - _shipWidth;
}
if (y < 0)
{
y = 0;
}
else if (y > _pictureHeight - _shipHeight)
{
y = _pictureHeight.Value - _shipHeight;
}
_startPosX = x;
_startPosY = y;
}
public bool MoveTransport(DirectionType direction)
{
if (EntityShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
// Влево
case DirectionType.Left:
if (_startPosX.Value - EntityShip.Step > 0)
{
_startPosX -= (int)EntityShip.Step;
}
return true;
//Вверх
case DirectionType.Up:
if (_startPosY.Value - EntityShip.Step > 0)
{
_startPosY -= (int)EntityShip.Step;
}
return true;
//Вправо
case DirectionType.Right:
{
if (_startPosX.Value + _shipWidth + EntityShip.Step < _pictureWidth)
{
_startPosX += (int)EntityShip.Step;
}
}
return true;
//Вниз
case DirectionType.Down:
{
if (_startPosY.Value + _shipHeight + EntityShip.Step < _pictureHeight)
{
_startPosY += (int)EntityShip.Step;
}
}
return true;
default:
return false;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush bodyBrush = new SolidBrush(EntityShip.BodyColor);
//корпус
Point[] hull = 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, hull);
g.DrawPolygon(pen, hull);
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);
}
}

View File

@ -1,36 +0,0 @@
using ProjectBattleship.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Drawnings;
public class DrawningCompareByColor : IComparer<DrawingShip?>
{
public int Compare(DrawingShip? x, DrawingShip? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityShip == null)
{
return -1;
}
if (y == null || y.EntityShip == null)
{
return 1;
}
if (x.EntityShip.BodyColor.Name != y.EntityShip.BodyColor.Name)
{
return x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -1,36 +0,0 @@
using ProjectBattleship.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Drawnings;
public class DrawningCompareByType : IComparer<DrawingShip?>
{
public int Compare(DrawingShip? x, DrawingShip? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityShip == null)
{
return -1;
}
if (y == null || y.EntityShip == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -1,62 +0,0 @@
using ProjectBattleship.Entities;
using ProjectBattleship.Drawnings;
using ProjectBattleship.Entities;
using System.Diagnostics.CodeAnalysis;
namespace Battleship.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningShipEqutables : IEqualityComparer<DrawingShip?>
{
public bool Equals(DrawingShip? x, DrawingShip? y)
{
if (x == null || x.EntityShip == null)
{
return false;
}
if (y == null || y.EntityShip == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityShip.Speed != y.EntityShip.Speed)
{
return false;
}
if (x.EntityShip.Weight != y.EntityShip.Weight)
{
return false;
}
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
{
return false;
}
if (x is DrawingBattleship && y is DrawingBattleship)
{
EntityBattleship EntityX = (EntityBattleship)x.EntityShip;
EntityBattleship EntityY = (EntityBattleship)y.EntityShip;
if (EntityX.RocketLauncher != EntityY.RocketLauncher)
{
return false;
}
if (EntityX.Turret != EntityY.Turret)
{
return false;
}
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingShip obj)
{
return obj.GetHashCode();
}
}

View File

@ -1,53 +0,0 @@
using ProjectBattleship.Entities;
using ProjectBattleship.Drawnings;
using ProjectBattleship.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBattleship.Drawnings;
public static class ExtentionDrawingShip
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawingShip? CreateDrawningShip(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityShip? ship = EntityBattleship.CreateEntityBattleship(strs);
if (ship != null)
{
return new DrawingBattleship(ship);
}
ship = EntityShip.CreateEntityShip(strs);
if (ship != null)
{
return new DrawingShip(ship);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningShip">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingShip drawningShip)
{
string[]? array = drawningShip?.EntityShip?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -1,37 +0,0 @@
using System.Net.Sockets;
namespace ProjectBattleship.Entities;
public class EntityBattleship : EntityShip
{
public Color AdditionalColor { get; private set; }
public bool Turret { get; private set; }
public bool RocketLauncher { get; private set; }
public double Step => (double)Speed * 100 / Weight;
public EntityBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool turret, bool rocketLauncher) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Turret = turret;
RocketLauncher = rocketLauncher;
}
public void ChangeAddColor(Color? addColor)
{
AdditionalColor = addColor ?? AdditionalColor;
}
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Turret.ToString(), RocketLauncher.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBattleship? 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]));
}
}

View File

@ -1,36 +0,0 @@
namespace ProjectBattleship.Entities;
public class EntityShip
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public double Step => Speed * 100 / Weight;
public EntityShip(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
public void ChangeColor(Color? color)
{
BodyColor = color ?? BodyColor;
}
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityShip), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityShip? CreateEntityShip(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityShip))
{
return null;
}
return new EntityShip(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -1,20 +0,0 @@
using System.Runtime.Serialization;
namespace Battleship.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) { }
}

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class ObjectExistsException : ApplicationException
{
public ObjectExistsException(int count) : base("Вставка существующего объекта") { }
public ObjectExistsException() : base() { }
public ObjectExistsException(string message) : base(message) { }
public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
protected ObjectExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -1,20 +0,0 @@
using System.Runtime.Serialization;
namespace Battleship.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) { }
}

View File

@ -1,20 +0,0 @@
using System.Runtime.Serialization;
namespace Battleship.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) { }
}

View File

@ -0,0 +1,39 @@
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
}
}

View File

@ -0,0 +1,10 @@
namespace ProjectBattleship
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -1,150 +0,0 @@
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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBattleship));
pictureBoxBattleship = new PictureBox();
buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = 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(3, 4, 3, 4);
pictureBoxBattleship.Name = "pictureBoxBattleship";
pictureBoxBattleship.Size = new Size(922, 598);
pictureBoxBattleship.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxBattleship.TabIndex = 0;
pictureBoxBattleship.TabStop = false;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(734, 525);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(39, 37);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage");
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(794, 471);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(39, 37);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(794, 525);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(39, 37);
buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage");
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(854, 525);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(39, 37);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(742, 24);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 8;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(799, 74);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 10;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormBattleship
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(922, 598);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxBattleship);
Name = "FormBattleship";
Text = "Линкор";
((System.ComponentModel.ISupportInitialize)pictureBoxBattleship).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxBattleship;
private Button buttonLeft;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -1,103 +0,0 @@
using ProjectBattleship.Drawnings;
using ProjectBattleship.MovementStrategy;
namespace ProjectBattleship
{
public partial class FormBattleship : Form
{
private DrawingShip? _drawingShip;
private AbstractStrategy? _strategy;
public FormBattleship()
{
InitializeComponent();
_strategy = null;
}
public DrawingShip SetShip
{
set
{
_drawingShip = value;
_drawingShip.SetPictureSize(pictureBoxBattleship.Width, pictureBoxBattleship.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
private void Draw()
{
if (_drawingShip == null)
{
return;
}
Bitmap bmp = new Bitmap(pictureBoxBattleship.Width, pictureBoxBattleship.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingShip.DrawTransport(gr);
pictureBoxBattleship.Image = bmp;
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result =
_drawingShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawingShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawingShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawingShip.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawingShip == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableShip(_drawingShip), pictureBoxBattleship.Width, pictureBoxBattleship.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,375 +0,0 @@
namespace ProjectBattleship
{
partial class FormShipCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
pictureBox = new PictureBox();
groupBoxTools = new GroupBox();
buttonCreateCompany = new Button();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonRemoveShip = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddShip = new Button();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
panelCompanyTools = new Panel();
buttonSortByType = new Button();
buttonSortByColor = new Button();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
groupBoxTools.SuspendLayout();
menuStrip.SuspendLayout();
panelCompanyTools.SuspendLayout();
SuspendLayout();
//
// pictureBox
//
pictureBox.Dock = DockStyle.Left;
pictureBox.Location = new Point(0, 30);
pictureBox.Margin = new Padding(3, 4, 3, 4);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(895, 836);
pictureBox.TabIndex = 0;
pictureBox.TabStop = false;
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonSortByColor);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonSortByType);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(buttonCollectionDel);
groupBoxTools.Controls.Add(listBoxCollection);
groupBoxTools.Controls.Add(buttonCollectionAdd);
groupBoxTools.Controls.Add(radioButtonList);
groupBoxTools.Controls.Add(radioButtonMassive);
groupBoxTools.Controls.Add(textBoxCollectionName);
groupBoxTools.Controls.Add(labelCollectionName);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(897, 30);
groupBoxTools.Margin = new Padding(3, 4, 3, 4);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 4, 3, 4);
groupBoxTools.Size = new Size(203, 836);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(9, 384);
buttonCreateCompany.Margin = new Padding(3, 4, 3, 4);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(189, 31);
buttonCreateCompany.TabIndex = 14;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(8, 309);
buttonCollectionDel.Margin = new Padding(3, 4, 3, 4);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(191, 31);
buttonCollectionDel.TabIndex = 13;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += buttonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(8, 157);
listBoxCollection.Margin = new Padding(3, 4, 3, 4);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(190, 144);
listBoxCollection.TabIndex = 12;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(8, 120);
buttonCollectionAdd.Margin = new Padding(3, 4, 3, 4);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(191, 31);
buttonCollectionAdd.TabIndex = 11;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += buttonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(117, 85);
radioButtonList.Margin = new Padding(3, 4, 3, 4);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 10;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(23, 85);
radioButtonMassive.Margin = new Padding(3, 4, 3, 4);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 9;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(8, 48);
textBoxCollectionName.Margin = new Padding(3, 4, 3, 4);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(190, 27);
textBoxCollectionName.TabIndex = 8;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(35, 24);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(158, 20);
labelCollectionName.TabIndex = 7;
labelCollectionName.Text = "Название коллекции:";
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(10, 348);
comboBoxSelectorCompany.Margin = new Padding(3, 4, 3, 4);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(189, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(9, 277);
buttonRefresh.Margin = new Padding(3, 4, 3, 4);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(187, 53);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(9, 216);
buttonGoToCheck.Margin = new Padding(3, 4, 3, 4);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(187, 53);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRemoveShip
//
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(9, 155);
buttonRemoveShip.Margin = new Padding(3, 4, 3, 4);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(187, 53);
buttonRemoveShip.TabIndex = 4;
buttonRemoveShip.Text = "Удалить корабль";
buttonRemoveShip.UseVisualStyleBackColor = true;
buttonRemoveShip.Click += ButtonRemoveShip_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(9, 116);
maskedTextBoxPosition.Margin = new Padding(3, 4, 3, 4);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(187, 27);
maskedTextBoxPosition.TabIndex = 3;
//
// buttonAddShip
//
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(9, 55);
buttonAddShip.Margin = new Padding(3, 4, 3, 4);
buttonAddShip.Name = "buttonAddShip";
buttonAddShip.Size = new Size(187, 53);
buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавление корабля";
buttonAddShip.UseVisualStyleBackColor = true;
buttonAddShip.Click += ButtonAddShip_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(6, 3, 0, 3);
menuStrip.Size = new Size(1100, 30);
menuStrip.TabIndex = 1;
menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(59, 24);
fileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(166, 26);
saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.Size = new Size(166, 26);
loadToolStripMenuItem.Text = "Загрузить";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "Ships";
//
// saveFileDialog
//
saveFileDialog.FileName = "Ships";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRemoveShip);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 507);
panelCompanyTools.Margin = new Padding(3, 4, 3, 4);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(203, 329);
panelCompanyTools.TabIndex = 15;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(9, 423);
buttonSortByType.Margin = new Padding(3, 4, 3, 4);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(189, 31);
buttonSortByType.TabIndex = 15;
buttonSortByType.Text = "Сортировать по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(10, 462);
buttonSortByColor.Margin = new Padding(3, 4, 3, 4);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(189, 31);
buttonSortByColor.TabIndex = 16;
buttonSortByColor.Text = "Сортировать по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1100, 866);
Controls.Add(groupBoxTools);
Controls.Add(pictureBox);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 4, 3, 4);
Name = "FormShipCollection";
Text = "Коллекция кораблей";
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBox;
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddShip;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Button buttonRemoveShip;
private ListBox listBoxCollection;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private Button buttonCollectionDel;
private Button buttonCreateCompany;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Panel panelCompanyTools;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -1,294 +0,0 @@
using Battleship;
using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Drawnings;
using System.Windows.Forms;
using Battleship.Exceptions;
using Microsoft.Extensions.Logging;
using Battleship.Drawnings;
namespace ProjectBattleship
{
public partial class FormShipCollection : Form
{
private readonly StorageCollection<DrawingShip> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new ShipDocks(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawingShip>());
break;
}
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление обычного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
FormShipConfig form = new();
form.Show();
form.AddEvent(SetShip);
}
private void SetShip(DrawingShip? ship)
{
if (_company == null || ship == null)
return;
try
{
var res = _company + ship;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
catch (CollectionOverflowException ex)
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
catch (ObjectExistsException ex)
{
MessageBox.Show("Такой объект есть в коллекции");
_logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
}
}
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удаление корабля по индексу {pos}", pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось удалить корабль из коллекции по индексу {pos}", pos);
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
_logger.LogError("Ошибка: {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;
}
DrawingShip? car = null;
int counter = 100;
while (car == null)
{
car = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (car == null)
{
return;
}
FormBattleship form = new()
{
SetShip = car
};
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();
}
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawingShip>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new ShipDocks(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
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("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
RerfreshListBoxItems();
}
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);
}
}
}
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);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareShips(new DrawningCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareShips(new DrawningCompareByColor());
}
private void CompareShips(IComparer<DrawingShip?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}
}

View File

@ -1,132 +0,0 @@
<?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="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>307, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -1,357 +0,0 @@
namespace Battleship
{
partial class FormShipConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColors = new GroupBox();
panelGray = new Panel();
panelOrange = new Panel();
panelPink = new Panel();
panelPurple = new Panel();
panelBlue = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxRockets = new CheckBox();
checkBoxWeapon = 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(checkBoxRockets);
groupBoxConfig.Controls.Add(checkBoxWeapon);
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(996, 436);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelOrange);
groupBoxColors.Controls.Add(panelPink);
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(499, 52);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(471, 249);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(359, 135);
panelGray.Name = "panelGray";
panelGray.Size = new Size(76, 71);
panelGray.TabIndex = 3;
//
// panelOrange
//
panelOrange.BackColor = Color.Orange;
panelOrange.Location = new Point(359, 38);
panelOrange.Name = "panelOrange";
panelOrange.Size = new Size(76, 71);
panelOrange.TabIndex = 1;
//
// panelPink
//
panelPink.BackColor = Color.HotPink;
panelPink.Location = new Point(254, 135);
panelPink.Name = "panelPink";
panelPink.Size = new Size(76, 71);
panelPink.TabIndex = 4;
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(148, 135);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(76, 71);
panelPurple.TabIndex = 5;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(254, 38);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(76, 71);
panelBlue.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(44, 135);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(76, 71);
panelWhite.TabIndex = 2;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(148, 38);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(76, 71);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(44, 38);
panelRed.Name = "panelRed";
panelRed.Size = new Size(76, 71);
panelRed.TabIndex = 0;
//
// checkBoxRockets
//
checkBoxRockets.AutoSize = true;
checkBoxRockets.Location = new Point(12, 265);
checkBoxRockets.Name = "checkBoxRockets";
checkBoxRockets.Size = new Size(374, 36);
checkBoxRockets.TabIndex = 7;
checkBoxRockets.Text = "Наличие рокетных установок";
checkBoxRockets.UseVisualStyleBackColor = true;
//
// checkBoxWeapon
//
checkBoxWeapon.AutoSize = true;
checkBoxWeapon.Location = new Point(12, 207);
checkBoxWeapon.Name = "checkBoxWeapon";
checkBoxWeapon.Size = new Size(343, 36);
checkBoxWeapon.TabIndex = 6;
checkBoxWeapon.Text = "Наличие оруженой башни";
checkBoxWeapon.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(150, 124);
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(240, 39);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 124);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(57, 32);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(150, 52);
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(240, 39);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 52);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(121, 32);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(757, 326);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(169, 65);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(499, 326);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(169, 65);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(41, 97);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(379, 249);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(1028, 378);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(150, 46);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(1327, 378);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(150, 46);
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(1028, 12);
panelObject.Name = "panelObject";
panelObject.Size = new Size(449, 360);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(251, 26);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(169, 65);
labelAdditionalColor.TabIndex = 10;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(41, 26);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(169, 65);
labelBodyColor.TabIndex = 9;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += LabelBodyColor_DragDrop;
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
//
// FormShipConfig
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1501, 436);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormShipConfig";
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);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelSimpleObject;
private Label labelSpeed;
private Label labelModifiedObject;
private CheckBox checkBoxRockets;
private CheckBox checkBoxWeapon;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private GroupBox groupBoxColors;
private Panel panelGray;
private Panel panelOrange;
private Panel panelPink;
private Panel panelPurple;
private Panel panelBlue;
private Panel panelWhite;
private Panel panelGreen;
private Panel panelRed;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@ -1,155 +0,0 @@
using ProjectBattleship.Drawnings;
using ProjectBattleship.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Battleship;
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormShipConfig : Form
{
/// <summary>
/// Объект-прорисовка
/// </summary>
private DrawingShip? _ship;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawingShip?> EventAddShip;
/// <summary>
/// Конструктор
/// </summary>labelModifiedObject
public FormShipConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelPink.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelOrange.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
public void AddEvent(Action<DrawingShip> action)
{
EventAddShip += action;
}
// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_ship?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_ship?.SetPosition(15, 15);
_ship?.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)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_ship = new DrawingShip((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_ship = new DrawingBattleship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxWeapon.Checked, checkBoxRockets.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);
}
/// <summary>
/// Проверка полчаемой в LabelBodyColor информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _ship != null)
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
/// <summary>
/// Проверка полчаемой в LabelAdditionalColor информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _ship != null && _ship is DrawingBattleship)
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void LabelBodyColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e?.Data?.GetData(typeof(Color));
_ship?.EntityShip?.ChangeColor(color);
DrawObject();
}
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e?.Data?.GetData(typeof(Color));
if (_ship is DrawingBattleship)
{
((EntityBattleship?)_ship.EntityShip)?.ChangeAddColor(color);
DrawObject();
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
EventAddShip?.Invoke(_ship);
Close();
}
}

View File

@ -1,120 +0,0 @@
<?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>

View File

@ -1,57 +0,0 @@
namespace ProjectBattleship.MovementStrategy;
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private StrategyStatus _state = StrategyStatus.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public StrategyStatus GetStatus() { return _state; }
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;
}
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
protected bool MoveRight() => MoveTo(MovementDirection.Right);
protected bool MoveUp() => MoveTo(MovementDirection.Up);
protected bool MoveDown() => MoveTo(MovementDirection.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestinaion();
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -1,7 +0,0 @@
namespace ProjectBattleship.MovementStrategy;
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
bool TryMoveObject(MovementDirection direction);
}

View File

@ -1,25 +0,0 @@
namespace ProjectBattleship.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.LeftBorder - GetStep() <= 0 || objParams.RightBorder + GetStep() >= FieldWidth || objParams.TopBorder - GetStep() <= 0 || objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int x = objParams.RightBorder;
if (x + GetStep() < FieldWidth) MoveRight();
int y = objParams.DownBorder;
if (y + GetStep() < FieldHeight) MoveDown();
}
}

View File

@ -1,46 +0,0 @@
namespace ProjectBattleship.MovementStrategy;
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();
}
}
}
}

View File

@ -1,42 +0,0 @@
using ProjectBattleship.Drawnings;
namespace ProjectBattleship.MovementStrategy;
public class MoveableShip : IMoveableObject
{
private readonly DrawingShip? _ship = null;
public MoveableShip(DrawingShip ship)
{
_ship = ship;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_ship == null || _ship.EntityShip == null || !_ship.GetPosX.HasValue || !_ship.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_ship.GetPosX.Value, _ship.GetPosY.Value, _ship.GetWidth, _ship.GetHeight);
}
}
public int GetStep => (int)(_ship?.EntityShip?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_ship == null || _ship.EntityShip == null)
{
return false;
}
return _ship.MoveTransport(GetDirectionType(direction));
}
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -1,8 +0,0 @@
namespace ProjectBattleship.MovementStrategy;
public enum MovementDirection
{
Up = 1,
Down = 2,
Left = 3,
Right = 4
}

View File

@ -1,21 +0,0 @@
namespace ProjectBattleship.MovementStrategy;
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
public int LeftBorder => _x;
public int TopBorder => _y;
public int RightBorder => _x + _width;
public int DownBorder => _y + _height;
public int ObjectMiddleHorizontal => _x + _width / 2;
public int ObjectMiddleVertical => _y + _height / 2;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@ -1,9 +0,0 @@
namespace ProjectBattleship.MovementStrategy
{
public enum StrategyStatus
{
NotInit,
InProgress,
Finish
}
}

View File

@ -1,9 +1,3 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using Battleship;
namespace ProjectBattleship
{
internal static class Program
@ -17,35 +11,7 @@ namespace ProjectBattleship
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormShipCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
Application.Run(new Form1());
}
}
}

View File

@ -8,29 +8,4 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<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>
</Project>

View File

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

View File

@ -1,120 +0,0 @@
<?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>

View File

@ -1,20 +0,0 @@
{
"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"
}
}
}