Compare commits

..

8 Commits
main ... Laba08

Author SHA1 Message Date
dc6c31f382 Laba08 2023-12-22 13:51:04 +04:00
4d7de3bca3 Laba07 2023-12-22 13:47:31 +04:00
3e6e60a533 Laba06 2023-12-22 13:40:17 +04:00
689ec4a5ce Laba05 2023-12-06 18:54:22 +04:00
aa766d5f54 Laba04 2023-12-06 18:47:21 +04:00
5c698b6514 Laba03 2023-12-06 13:45:35 +04:00
bc9b12c8fe Лаба02 2023-11-13 13:26:03 +04:00
95a9f6f733 Лаба01 2023-10-23 10:18:44 +04:00
42 changed files with 3656 additions and 78 deletions

View File

@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectContainerShip.Direction;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectContainerShip.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int
height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ContainerShip.Generics;
using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip.MovementStrategy;
namespace ProjectContainerShip.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class ContainerGenericCollection<T, U>
where T : DrawningShip
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetShip => _collection.GetShip();
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 200;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public ContainerGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool operator +(ContainerGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return false;
}
return collect?._collection.Insert(obj, new DrawningContainerShipEqutables()) ?? false;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T operator -(ContainerGenericCollection<T, U> collect, int
pos)
{
T obj = collect._collection[pos];
if (obj != null)
{
collect?._collection.Remove(pos);
}
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowContainer()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 2);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth , j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
///
private void DrawObjects(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
foreach (var contShip in _collection.GetShip())
{
if (contShip != null)
{
T? ship = _collection[i];
if (ship == null)
continue;
int row = height - 1 - (i / width);
int col = width - 1 - (i % width);
ship.SetPosition(col * _placeSizeWidth, row * _placeSizeHeight + 25);
ship.DrawTransport(g);
}
}
}
}
}

View File

@ -0,0 +1,191 @@
using ContainerShip.Exceptions;
using ContainerShip.Generics;
using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip.Generics;
using ProjectContainerShip.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class ContainerGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<ContainerShipCollectionInfo, ContainerGenericCollection<DrawningShip,
DrawningObjectShip>> _shipStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<ContainerShipCollectionInfo> Keys => _shipStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public ContainerGenericStorage(int pictureWidth, int pictureHeight)
{
_shipStorages = new Dictionary<ContainerShipCollectionInfo, ContainerGenericCollection<DrawningShip,
DrawningObjectShip>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (!_shipStorages.ContainsKey(new ContainerShipCollectionInfo(name, string.Empty)))
{
var lincornCollection = new ContainerGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight);
_shipStorages.Add(new ContainerShipCollectionInfo(name, string.Empty), lincornCollection);
}
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_shipStorages.ContainsKey(new ContainerShipCollectionInfo(name, string.Empty)))
{
_shipStorages.Remove(new ContainerShipCollectionInfo(name, string.Empty));
}
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public ContainerGenericCollection<DrawningShip, DrawningObjectShip>? this[string ind]
{
get
{
ContainerShipCollectionInfo indObj = new ContainerShipCollectionInfo(ind, string.Empty);
if (_shipStorages.ContainsKey(indObj))
{
return _shipStorages[indObj];
}
return null;
}
}
/// <summary>
/// Сохранение информации в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<ContainerShipCollectionInfo, ContainerGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
{
StringBuilder records = new();
foreach (DrawningShip? elem in record.Value.GetShip)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"shipStorage{Environment.NewLine}{data}");
}
}
/// <summary>
/// Загрузка информации в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string cheker = reader.ReadLine();
if (cheker == null)
{
throw new Exception("Нет данных для загрузки");
}
if (!cheker.StartsWith("shipStorage"))
{
throw new Exception("Неверный формат ввода");
}
_shipStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
{
throw new Exception("Нет данных для загрузки");
}
if (strs == null)
{
break;
}
firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0];
ContainerGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
{
DrawningShip? ship =
data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null)
{
try { _ = collection + ship; }
catch (ContainerShipNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
_shipStorages.Add(new ContainerShipCollectionInfo(name, string.Empty), collection);
}
}
}
}
}

View File

@ -8,4 +8,33 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip.Generics
{
internal class ContainerShipCollectionInfo : IEquatable<ContainerShipCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public ContainerShipCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(ContainerShipCollectionInfo? other)
{
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,47 @@
using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectContainerShip.Entities;
namespace ContainerShip.Generics
{
internal class ContainerShipCompareByColor : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityShip == null)
throw new ArgumentNullException(nameof(y));
if (x.EntityShip.BodyColor.Name != y.EntityShip.BodyColor.Name)
{
return x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
}
if (x.GetType().Name != y.GetType().Name)
{
if (x is EntityShip)
return -1;
else
return 1;
}
if (x.GetType().Name == y.GetType().Name && x is EntityContainerShip)
{
EntityContainerShip EntityX = (EntityContainerShip)x.EntityShip;
EntityContainerShip EntityY = (EntityContainerShip)y.EntityShip;
if (EntityX.AdditionalColor.Name != EntityY.AdditionalColor.Name)
{
return EntityX.AdditionalColor.Name.CompareTo(EntityY.AdditionalColor.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

@ -0,0 +1,28 @@
using ProjectContainerShip.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip.Generics
{
internal class ContainerShipCompareByType : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityShip == null)
throw new ArgumentNullException(nameof(y));
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip.Exceptions
{
[Serializable] internal class ContainerShipNotFoundException : ApplicationException
{
public ContainerShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public ContainerShipNotFoundException() : base() { }
public ContainerShipNotFoundException(string message) : base(message) { }
public ContainerShipNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ContainerShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

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

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectContainerShip.Direction;
using ProjectContainerShip.Entities;
using System.Net.NetworkInformation;
namespace ProjectContainerShip.DrawningObjects
{
public class DrawningContainerShip : DrawningShip
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет палубы</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="crane">Признак наличия крана</param>
/// <param name="container">Признак наличия контейнеров</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningContainerShip(int speed, double weight, Color bodyColor, Color additionalColor, bool crane, bool container, int width, int height) :
base(speed, weight, bodyColor, width, height, 200, 30)
{
if (EntityShip != null)
{
EntityShip = new EntityContainerShip(speed, weight, bodyColor, additionalColor, crane, container);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityShip is not EntityContainerShip containerShip)
{
return;
}
Brush additionalBrush = new SolidBrush(containerShip.AdditionalColor);
if (containerShip.Container)
{
g.FillRectangle(additionalBrush, _startPosX + 55, _startPosY + 7, 35, 5);
}
//кран
if (containerShip.Crane)
{
Brush brBl = new SolidBrush(Color.Black);
g.FillRectangle(brBl, _startPosX + 110, _startPosY + 0, 3, 12);
g.FillRectangle(brBl, _startPosX + 105, _startPosY + 1, 20, 2);
}
// несколько контенеров
if (containerShip.Container)
{
g.FillRectangle(additionalBrush, _startPosX + 55, _startPosY + 2, 35, 5);
g.FillRectangle(additionalBrush, _startPosX + 135, _startPosY + 7, 35, 5);
g.FillRectangle(additionalBrush, _startPosX + 135, _startPosY + 2, 35, 5);
}
base.DrawTransport(g);
}
}
}

View File

@ -0,0 +1,59 @@
using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectContainerShip.Entities;
namespace ContainerShip.Generics
{
internal class DrawningContainerShipEqutables : IEqualityComparer<DrawningShip?>
{
public bool Equals(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityShip == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityShip.Speed != y.EntityShip.Speed)
{
return false;
}
if (x.EntityShip.Weight != y.EntityShip.Weight)
{
return false;
}
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
{
return false;
}
if (x is EntityContainerShip && y is EntityContainerShip)
{
EntityContainerShip EntityX = (EntityContainerShip)x.EntityShip;
EntityContainerShip EntityY = (EntityContainerShip)y.EntityShip;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
if (EntityX.Crane != EntityY.Crane)
return false;
if (EntityX.Container != EntityY.Container)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectContainerShip.DrawningObjects;
using static ProjectContainerShip.Direction;
namespace ProjectContainerShip.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IMoveableObject для работы с объектом DrawningShip
/// </summary>
public class DrawningObjectShip : IMoveableObject
{
private readonly DrawningShip? _drawningShip = null;
public DrawningObjectShip (DrawningShip drawningShip)
{
_drawningShip = drawningShip;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningShip == null || _drawningShip.EntityShip == null)
{
return null;
}
return new ObjectParameters(_drawningShip.GetPosX, _drawningShip.GetPosY, _drawningShip.GetWidth, _drawningShip.GetHeight);
}
}
public int GetStep => (int)(_drawningShip?.EntityShip?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawningShip?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawningShip?.MoveTransport(direction);
public void SetPosition(int x, int y)
{
if (_drawningShip != null)
{
_drawningShip.SetPosition(x, y);
}
}
public void Draw(Graphics g)
{
if (_drawningShip != null)
{
_drawningShip.DrawTransport(g);
}
}
}
}

View File

@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectContainerShip;
using ProjectContainerShip.Entities;
using ProjectContainerShip.MovementStrategy;
using static ProjectContainerShip.Direction;
namespace ProjectContainerShip.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningShip
{
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningShip
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectShip(this);
/// <summary>
/// Класс-сущность
/// </summary>
public EntityShip? EntityShip { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки корабля
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки корабля
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки корабля
/// </summary>
protected readonly int _shipWidth = 200;
/// <summary>
/// Высота прорисовки корабля
/// </summary>
protected readonly int _shipHeight = 30;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningShip(int speed, double weight, Color bodyColor, int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
EntityShip = new EntityShip(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="shipWidth">Ширина прорисовки корабля</param>
/// <param name="shipHeight">Высота прорисовки корабля</param>
protected DrawningShip(int speed, double weight, Color bodyColor, int width, int height, int shipWidth, int shipHeight)
{
if (width > _shipWidth && height > _shipHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_shipWidth = shipWidth;
_shipHeight = shipHeight;
EntityShip = new EntityShip(speed, weight, bodyColor);
}
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if ((x > 0) && (x < _pictureWidth))
_startPosX = x;
else _startPosX = 0;
if ((y > 0) && (y < _pictureHeight))
_startPosY = y;
else _startPosY = 0;
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _shipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _shipHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityShip == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityShip.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityShip.Step > 0,
// вправо
DirectionType.Right => _startPosX + _shipWidth + EntityShip.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _shipHeight + EntityShip.Step < _pictureHeight,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityShip == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityShip.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityShip.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityShip.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityShip.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityShip == null)
{
return;
}
Brush bodyColor = new SolidBrush(EntityShip.BodyColor);
//границы корабля
Brush brRd = new SolidBrush(Color.Red);
Point point1 = new Point(_startPosX, _startPosY + 12);
Point point2 = new Point(_startPosX + 25, _startPosY + 35);
Point point3 = new Point(_startPosX + 175, _startPosY + 35);
Point point4 = new Point(_startPosX + 200, _startPosY + 12);
Point[] curvePoints1 = { point1, point2, point3, point4 };
g.FillPolygon(bodyColor, curvePoints1);
//граница палубы
Brush brBlue = new SolidBrush(Color.Blue);
g.FillRectangle(bodyColor, _startPosX + 35, _startPosY + 0, 16, 12);
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.Entities
{
internal class EntityContainerShip : EntityShip
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия крана
/// </summary>
public bool Crane { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительных контейнеров
/// </summary>
public bool Container { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса контейнеровоза
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес </param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="crane">Признак наличия крана</param>
/// <param name="container">Признак наличия контейнеров</param>
public EntityContainerShip(int speed, double weight, Color bodyColor, Color additionalColor, bool crane, bool container) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Crane = crane;
Container = container;
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip
{
public class EntityShip
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения корабля
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес корабля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityShip(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectContainerShip.Entities;
namespace ProjectContainerShip.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityShip
/// </summary>
public static class ExtentionDrawningContainer
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningShip? CreateDrawningShip(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
else if (strs.Length == 6)
{
return new DrawningContainerShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningShip">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningShip drawningShip, char separatorForObject)
{
var ship = drawningShip.EntityShip;
if (ship == null)
{
return string.Empty;
}
var str = $"{ship.Speed}{separatorForObject}{ship.Weight}{separatorForObject}{ship.BodyColor.Name}";
if (ship is not EntityContainerShip dopShip)
{
return str;
}
return $"{str}{separatorForObject}{dopShip.AdditionalColor.Name}{separatorForObject}{dopShip.Crane}{separatorForObject}{dopShip.Container}";
}
}
}

View File

@ -1,39 +0,0 @@
namespace ContainerShip
{
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

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

View File

@ -0,0 +1,272 @@
namespace ProjectContainerShip
{
partial class FormContainerCollection
{
/// <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()
{
pictureBoxCollection = new PictureBox();
maskedTextBoxNumber = new MaskedTextBox();
buttonAddEx = new Button();
buttonRemoveEx = new Button();
buttonRefreshCollection = new Button();
groupBox1 = new GroupBox();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
groupBox2 = new GroupBox();
textBoxStorageName = new TextBox();
buttonDelObject = new Button();
listBoxStorages = new ListBox();
buttonAddObject = new Button();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout();
menuStrip.SuspendLayout();
groupBox2.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(932, 503);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(19, 404);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(95, 27);
maskedTextBoxNumber.TabIndex = 1;
//
// buttonAddEx
//
buttonAddEx.Location = new Point(19, 371);
buttonAddEx.Name = "buttonAddEx";
buttonAddEx.Size = new Size(95, 27);
buttonAddEx.TabIndex = 2;
buttonAddEx.Text = "Добавить";
buttonAddEx.UseVisualStyleBackColor = true;
buttonAddEx.Click += ButtonAddShip_Click;
//
// buttonRemoveEx
//
buttonRemoveEx.Location = new Point(19, 437);
buttonRemoveEx.Name = "buttonRemoveEx";
buttonRemoveEx.Size = new Size(95, 27);
buttonRemoveEx.TabIndex = 3;
buttonRemoveEx.Text = "Удалить";
buttonRemoveEx.UseVisualStyleBackColor = true;
buttonRemoveEx.Click += ButtonRemoveShip_Click;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(19, 470);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(95, 27);
buttonRefreshCollection.TabIndex = 4;
buttonRefreshCollection.Text = "Обновить";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// groupBox1
//
groupBox1.Controls.Add(ButtonSortByColor);
groupBox1.Controls.Add(ButtonSortByType);
groupBox1.Controls.Add(menuStrip);
groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(buttonAddEx);
groupBox1.Controls.Add(buttonRefreshCollection);
groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(buttonRemoveEx);
groupBox1.Location = new Point(812, 0);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(120, 503);
groupBox1.TabIndex = 5;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(6, 116);
ButtonSortByColor.Margin = new Padding(3, 4, 3, 4);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(110, 51);
ButtonSortByColor.TabIndex = 11;
ButtonSortByColor.Text = "Сортировка по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(6, 57);
ButtonSortByType.Margin = new Padding(3, 4, 3, 4);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(108, 51);
ButtonSortByType.TabIndex = 10;
ButtonSortByType.Text = "Сортировка по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(3, 23);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(7, 3, 0, 3);
menuStrip.Size = new Size(114, 30);
menuStrip.TabIndex = 8;
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(177, 26);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click_1;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(177, 26);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// groupBox2
//
groupBox2.Controls.Add(textBoxStorageName);
groupBox2.Controls.Add(buttonDelObject);
groupBox2.Controls.Add(listBoxStorages);
groupBox2.Controls.Add(buttonAddObject);
groupBox2.Location = new Point(6, 174);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(116, 191);
groupBox2.TabIndex = 5;
groupBox2.TabStop = false;
groupBox2.Text = "Наборы";
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(13, 26);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(95, 27);
textBoxStorageName.TabIndex = 6;
//
// buttonDelObject
//
buttonDelObject.Location = new Point(13, 158);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(95, 27);
buttonDelObject.TabIndex = 8;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += ButtonDelObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(13, 92);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(95, 64);
listBoxStorages.TabIndex = 6;
listBoxStorages.Click += ListBoxObjects_SelectedIndexChanged;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(13, 59);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(95, 27);
buttonAddObject.TabIndex = 7;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
saveFileDialog.Title = "Выберите текстовый файл";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
openFileDialog.Title = "Сохранить текстовый файл";
//
// FormContainerCollection
//
ClientSize = new Size(932, 503);
Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection);
Name = "FormContainerCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCollection;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonAddEx;
private Button buttonRemoveEx;
private Button buttonRefreshCollection;
private GroupBox groupBox1;
private GroupBox groupBox2;
private TextBox textBoxStorageName;
private Button buttonDelObject;
private ListBox listBoxStorages;
private Button buttonAddObject;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@ -0,0 +1,270 @@
using ProjectContainerShip;
using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip.Generics;
using ProjectContainerShip.MovementStrategy;
using Microsoft.Extensions.Logging;
using ContainerShip.Exceptions;
using ContainerShip.Generics;
namespace ProjectContainerShip
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningShip
/// </summary>
public partial class FormContainerCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly ContainerGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormContainerCollection(ILogger<FormContainerCollection> logger)
{
InitializeComponent();
_storage = new ContainerGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Пустое название набора");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowContainer();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление невыбранного набора");
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var form = new FormContainerConfig();
form.AddEvent(ship =>
{
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
_ = obj + ship;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowContainer();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
});
form.Show();
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowContainer();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (ContainerShipNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowContainer();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить наборы с ошибкой: {ex.Message}");
}
}
}
private void CompareContainerShip(IComparer<DrawningShip?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowContainer();
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareContainerShip(new ContainerShipCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareContainerShip(new ContainerShipCompareByColor());
}
}

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>259, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,387 @@
namespace ProjectContainerShip
{
partial class FormContainerConfig
{
/// <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()
{
groupBox1 = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
groupBox2 = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxContainer = new CheckBox();
checkBoxCrane = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
label2 = new Label();
label1 = new Label();
panelColor = new Panel();
labelDopColor = new Label();
labelBaseColor = new Label();
pictureBoxObject = new PictureBox();
ButtonOk = new Button();
buttonCancel = new Button();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(labelModifiedObject);
groupBox1.Controls.Add(labelSimpleObject);
groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(checkBoxContainer);
groupBox1.Controls.Add(checkBoxCrane);
groupBox1.Controls.Add(numericUpDownWeight);
groupBox1.Controls.Add(numericUpDownSpeed);
groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(label1);
groupBox1.Location = new Point(14, 16);
groupBox1.Margin = new Padding(3, 4, 3, 4);
groupBox1.Name = "groupBox1";
groupBox1.Padding = new Padding(3, 4, 3, 4);
groupBox1.Size = new Size(519, 304);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(358, 195);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(110, 35);
labelModifiedObject.TabIndex = 8;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(246, 195);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(99, 35);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// groupBox2
//
groupBox2.Controls.Add(panelPurple);
groupBox2.Controls.Add(panelYellow);
groupBox2.Controls.Add(panelBlack);
groupBox2.Controls.Add(panelBlue);
groupBox2.Controls.Add(panelGray);
groupBox2.Controls.Add(panelGreen);
groupBox2.Controls.Add(panelWhite);
groupBox2.Controls.Add(panelRed);
groupBox2.Location = new Point(246, 43);
groupBox2.Margin = new Padding(3, 4, 3, 4);
groupBox2.Name = "groupBox2";
groupBox2.Padding = new Padding(3, 4, 3, 4);
groupBox2.Size = new Size(211, 141);
groupBox2.TabIndex = 6;
groupBox2.TabStop = false;
groupBox2.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.FromArgb(192, 0, 192);
panelPurple.Location = new Point(159, 84);
panelPurple.Margin = new Padding(3, 4, 3, 4);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(40, 40);
panelPurple.TabIndex = 7;
panelPurple.MouseDown += panelColor_MouseDown;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(159, 29);
panelYellow.Margin = new Padding(3, 4, 3, 4);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(40, 40);
panelYellow.TabIndex = 3;
panelYellow.MouseDown += panelColor_MouseDown;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(112, 84);
panelBlack.Margin = new Padding(3, 4, 3, 4);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(40, 40);
panelBlack.TabIndex = 6;
panelBlack.MouseDown += panelColor_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(112, 29);
panelBlue.Margin = new Padding(3, 4, 3, 4);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(40, 40);
panelBlue.TabIndex = 2;
panelBlue.MouseDown += panelColor_MouseDown;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(65, 84);
panelGray.Margin = new Padding(3, 4, 3, 4);
panelGray.Name = "panelGray";
panelGray.Size = new Size(40, 40);
panelGray.TabIndex = 5;
panelGray.MouseDown += panelColor_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.FromArgb(0, 192, 0);
panelGreen.Location = new Point(65, 29);
panelGreen.Margin = new Padding(3, 4, 3, 4);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(40, 40);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += panelColor_MouseDown;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(18, 84);
panelWhite.Margin = new Padding(3, 4, 3, 4);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(40, 40);
panelWhite.TabIndex = 4;
panelWhite.MouseDown += panelColor_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(18, 29);
panelRed.Margin = new Padding(3, 4, 3, 4);
panelRed.Name = "panelRed";
panelRed.Size = new Size(40, 40);
panelRed.TabIndex = 0;
panelRed.MouseDown += panelColor_MouseDown;
//
// checkBoxContainer
//
checkBoxContainer.AutoSize = true;
checkBoxContainer.Location = new Point(11, 229);
checkBoxContainer.Margin = new Padding(3, 4, 3, 4);
checkBoxContainer.Name = "checkBoxContainer";
checkBoxContainer.Size = new Size(199, 24);
checkBoxContainer.TabIndex = 5;
checkBoxContainer.Text = "Признак наличия крана";
checkBoxContainer.UseVisualStyleBackColor = true;
//
// checkBoxCrane
//
checkBoxCrane.AutoSize = true;
checkBoxCrane.Location = new Point(11, 261);
checkBoxCrane.Margin = new Padding(3, 4, 3, 4);
checkBoxCrane.Name = "checkBoxCrane";
checkBoxCrane.Size = new Size(249, 24);
checkBoxCrane.TabIndex = 4;
checkBoxCrane.Text = "Признак наличия котнейнеров";
checkBoxCrane.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(87, 80);
numericUpDownWeight.Margin = new Padding(3, 4, 3, 4);
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(83, 27);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(87, 41);
numericUpDownSpeed.Margin = new Padding(3, 4, 3, 4);
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(83, 27);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(11, 83);
label2.Name = "label2";
label2.Size = new Size(36, 20);
label2.TabIndex = 1;
label2.Text = "Вес:";
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(11, 44);
label1.Name = "label1";
label1.Size = new Size(76, 20);
label1.TabIndex = 0;
label1.Text = "Скорость:";
//
// panelColor
//
panelColor.AllowDrop = true;
panelColor.Controls.Add(labelDopColor);
panelColor.Controls.Add(labelBaseColor);
panelColor.Controls.Add(pictureBoxObject);
panelColor.Location = new Point(539, 16);
panelColor.Margin = new Padding(3, 4, 3, 4);
panelColor.Name = "panelColor";
panelColor.Size = new Size(315, 245);
panelColor.TabIndex = 1;
panelColor.DragDrop += PanelObject_DragDrop;
panelColor.DragEnter += PanelObject_DragEnter;
//
// labelDopColor
//
labelDopColor.AllowDrop = true;
labelDopColor.BorderStyle = BorderStyle.FixedSingle;
labelDopColor.Location = new Point(187, 13);
labelDopColor.Name = "labelDopColor";
labelDopColor.Size = new Size(114, 38);
labelDopColor.TabIndex = 2;
labelDopColor.Text = "Доп. цвет";
labelDopColor.TextAlign = ContentAlignment.MiddleCenter;
labelDopColor.DragDrop += LabelDopColor_DragDrop;
labelDopColor.DragEnter += LabelColor_DragEnter;
labelDopColor.MouseDown += LabelObject_MouseDown;
//
// labelBaseColor
//
labelBaseColor.AllowDrop = true;
labelBaseColor.BorderStyle = BorderStyle.FixedSingle;
labelBaseColor.Location = new Point(14, 13);
labelBaseColor.Name = "labelBaseColor";
labelBaseColor.Size = new Size(114, 38);
labelBaseColor.TabIndex = 2;
labelBaseColor.Text = "Цвет";
labelBaseColor.TextAlign = ContentAlignment.MiddleCenter;
labelBaseColor.DragDrop += LabelBaseColor_DragDrop;
labelBaseColor.DragEnter += LabelColor_DragEnter;
labelBaseColor.MouseDown += LabelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(14, 61);
pictureBoxObject.Margin = new Padding(3, 4, 3, 4);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(288, 169);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// ButtonOk
//
ButtonOk.Location = new Point(553, 277);
ButtonOk.Margin = new Padding(3, 4, 3, 4);
ButtonOk.Name = "ButtonOk";
ButtonOk.Size = new Size(114, 43);
ButtonOk.TabIndex = 2;
ButtonOk.Text = "Добавить";
ButtonOk.UseVisualStyleBackColor = true;
ButtonOk.Click += ButtonOk_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(727, 277);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(114, 43);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormContainerConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(914, 336);
Controls.Add(buttonCancel);
Controls.Add(ButtonOk);
Controls.Add(panelColor);
Controls.Add(groupBox1);
Margin = new Padding(3, 4, 3, 4);
Name = "FormContainerConfig";
Text = "FormSelfPropelledArtilleryUnitConfig";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBox1;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label label2;
private Label label1;
private GroupBox groupBox2;
private CheckBox checkBoxContainer;
private CheckBox checkBoxCrane;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private Label labelSimpleObject;
private Label labelModifiedObject;
private Panel panelColor;
private PictureBox pictureBoxObject;
private Label labelDopColor;
private Label labelBaseColor;
private Button ButtonOk;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,170 @@
using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip.Entities;
using ProjectContainerShip;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectContainerShip
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormContainerConfig : Form
{
/// <summary>
/// Переменная-выбранный корабль
/// </summary>
DrawningShip? _ship = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningShip> EventAddShip;
/// <summary>
/// Конструктор
/// </summary>
public FormContainerConfig()
{
InitializeComponent();
panelBlack.MouseDown += panelColor_MouseDown;
panelPurple.MouseDown += panelColor_MouseDown;
panelGray.MouseDown += panelColor_MouseDown;
panelGreen.MouseDown += panelColor_MouseDown;
panelRed.MouseDown += panelColor_MouseDown;
panelWhite.MouseDown += panelColor_MouseDown;
panelYellow.MouseDown += panelColor_MouseDown;
panelBlue.MouseDown += panelColor_MouseDown;
// TODO buttonCancel.Click with lambda
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Отрисовать контейнеровоз
/// </summary>
private void DrawShip()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_ship?.SetPosition(5, 5);
_ship?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawningShip> ev)
{
if (EventAddShip == null)
{
EventAddShip = new Action<DrawningShip>(ev);
}
else
{
EventAddShip += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_ship = new DrawningShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_ship = new DrawningContainerShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxContainer.Checked,
checkBoxCrane.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
DrawShip();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship != null)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
_ship.EntityShip.BodyColor = (Color)e.Data.GetData(typeof(Color));
}
DrawShip();
}
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (_ship != null && _ship.EntityShip is EntityContainerShip entityustabat)
{
labelDopColor.AllowDrop = true;
}
else
labelDopColor.AllowDrop = false;
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship != null && _ship.EntityShip is EntityContainerShip entityContainerShip)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
entityContainerShip.AdditionalColor = (Color)e.Data.GetData(typeof(Color));
}
DrawShip();
}
}
/// <summary>
/// Добавление корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddShip?.Invoke(_ship);
Close();
}
}
}

View File

@ -0,0 +1,193 @@
namespace ProjectContainerShip
{
partial class FormContainerShip
{
/// <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(FormContainerShip));
pictureBoxContainerShip = new PictureBox();
buttonCreate = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonLeft = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonCreateDeckShip = new Button();
buttonSelectShip = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxContainerShip).BeginInit();
SuspendLayout();
//
// pictureBoxContainerShip
//
pictureBoxContainerShip.Dock = DockStyle.Fill;
pictureBoxContainerShip.Location = new Point(0, 0);
pictureBoxContainerShip.Margin = new Padding(3, 4, 3, 4);
pictureBoxContainerShip.Name = "pictureBoxContainerShip";
pictureBoxContainerShip.Size = new Size(1010, 615);
pictureBoxContainerShip.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxContainerShip.TabIndex = 0;
pictureBoxContainerShip.TabStop = false;
//
// buttonCreate
//
buttonCreate.Location = new Point(225, 564);
buttonCreate.Margin = new Padding(3, 4, 3, 4);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(86, 31);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
// buttonRight
//
buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage");
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(962, 559);
buttonRight.Margin = new Padding(3, 4, 3, 4);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(34, 40);
buttonRight.TabIndex = 2;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage");
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(921, 511);
buttonUp.Margin = new Padding(3, 4, 3, 4);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(34, 40);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(921, 559);
buttonDown.Margin = new Padding(3, 4, 3, 4);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(34, 40);
buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(880, 559);
buttonLeft.Margin = new Padding(3, 4, 3, 4);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(34, 40);
buttonLeft.TabIndex = 5;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Location = new Point(858, 16);
comboBoxStrategy.Margin = new Padding(3, 4, 3, 4);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(138, 28);
comboBoxStrategy.TabIndex = 6;
//
// buttonStep
//
buttonStep.Location = new Point(898, 55);
buttonStep.Margin = new Padding(3, 4, 3, 4);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(86, 31);
buttonStep.TabIndex = 7;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// buttonCreateDeckShip
//
buttonCreateDeckShip.Location = new Point(14, 564);
buttonCreateDeckShip.Margin = new Padding(3, 4, 3, 4);
buttonCreateDeckShip.Name = "buttonCreateDeckShip";
buttonCreateDeckShip.Size = new Size(205, 31);
buttonCreateDeckShip.TabIndex = 8;
buttonCreateDeckShip.Text = "Создать контейнеровоз";
buttonCreateDeckShip.UseVisualStyleBackColor = true;
buttonCreateDeckShip.Click += buttonCreateDeckShip_Click;
//
// buttonSelectShip
//
buttonSelectShip.Location = new Point(317, 564);
buttonSelectShip.Margin = new Padding(3, 4, 3, 4);
buttonSelectShip.Name = "buttonSelectShip";
buttonSelectShip.Size = new Size(86, 31);
buttonSelectShip.TabIndex = 9;
buttonSelectShip.Text = "Выбрать";
buttonSelectShip.UseVisualStyleBackColor = true;
buttonSelectShip.Click += buttonSelectShip_Click;
//
// FormContainerShip
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1010, 615);
Controls.Add(buttonSelectShip);
Controls.Add(buttonCreateDeckShip);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxContainerShip);
Margin = new Padding(3, 4, 3, 4);
Name = "FormContainerShip";
StartPosition = FormStartPosition.CenterScreen;
((System.ComponentModel.ISupportInitialize)pictureBoxContainerShip).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxContainerShip;
private Button buttonCreate;
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
private Button buttonLeft;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonCreateDeckShip;
private Button buttonSelectShip;
}
}

View File

@ -0,0 +1,166 @@
using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip.MovementStrategy;
using static ProjectContainerShip.Direction;
namespace ProjectContainerShip
{
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Êîíòåéíåðîâîç"
/// </summary>
public partial class FormContainerShip : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningShip? _drawingContainerShip;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
public DrawningShip? SelectedShip { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormContainerShip()
{
InitializeComponent();
_abstractStrategy = null;
_drawingContainerShip = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè
/// </summary>
private void Draw()
{
if (_drawingContainerShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxContainerShip.Width, pictureBoxContainerShip.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingContainerShip.DrawTransport(gr);
pictureBoxContainerShip.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawingContainerShip = new DrawningShip(random.Next(100, 300), random.Next(1000, 3000), color,
pictureBoxContainerShip.Width, pictureBoxContainerShip.Height);
_drawingContainerShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü êîðàáëü ñ êîíòåéíåðàìè"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateDeckShip_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO âûáîð îñíîâíîãî öâåòà
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO âûáîð äîïîëíèòåëüíîãî öâåòà
ColorDialog dialog2 = new();
if (dialog2.ShowDialog() == DialogResult.OK)
{
dopColor = dialog2.Color;
}
_drawingContainerShip = new DrawningContainerShip(random.Next(100, 300), random.Next(1000, 3000),
color, dopColor, Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxContainerShip.Width, pictureBoxContainerShip.Height);
_drawingContainerShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Èçìåíåíèå ïîëîæåíèÿ êîðàáëÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingContainerShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingContainerShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingContainerShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingContainerShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingContainerShip.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawingContainerShip == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawningObjectShip(_drawingContainerShip), pictureBoxContainerShip.Width, pictureBoxContainerShip.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void buttonSelectShip_Click(object sender, EventArgs e)
{
SelectedShip = _drawingContainerShip;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,201 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="buttonRight.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAABGdBTUEAALGPC/xhBQAAAG9QTFRF////
AAAAWVlZ8fHx9PT0REREtLS0Ojo6+Pj4a2trp6enj4+P3t7eXl5efX1919fXh4eHw8PD6+vrdXV10dHR
5ubmDAwMy8vLTU1NlZWVvLy8iIiINjY2nJycFhYWYWFhJycnUVFRHR0dr6+vKioqoesKnwAAAAlwSFlz
AAAOvAAADrwBlbxySQAAAipJREFUeF7t3NlS20AQRmEJGzAgL+ybIQTy/s8YOfyawtJtZIWT891QVleB
u6iWZnpmVEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmS9F3N8hOqWdb13WqeT0BP9aebfMa5TYJ1fZ4rNKvk
17rOJZjjpLdzirzjnCa7P+6IxXiU5AJYjN2ttLPKdZAfSa3zwCvGs6TWeV8nwPGS1IqTBDjuk1mxSYDj
du+Z0XrADVMX/WJ8axLheExqxVMCHJfJrHhOgKPZJrXOcpEIxqKdCu/Z8orxOakVlwlw9Eep9WMCHM1b
Uuuc4Ypx/jOpdbZXiXBsklpxnwDHSTIrXhLgWL8ntQ6vRzX72p/aAfaovjQZP/GK8SOZFbwe1U0yK3g9
qll/WnzMK8brpFbwGsbnyaz4SIBj0KPiFePVoBh5S6n9YerriA3j9ero8Jb9if+IxXiRPzC9kYpxcF+b
0EW+0181e81v/yeMMSseDKImNUaHajAtndQYDSr+/3COr0P+vfQ/eB5WVbPJOOOQDjmmmcghx6VTwM8t
8PND/Byf3qfB99rw/VJ8z5u+boFfe1r35zG09UP8GjB9HR+/FwO/nwa/J4q+r23RO12C25uI31+K3yNM
3+c92Kv/C1aCw/MWsBLEn5nBn3vCn13Dnz/knyHlnwPee04gz3Lzz+Pz36nAfy8G/90m7bywfSKi30+z
g7zDSJIkSZIkSZIkSZIkSZIkSZIkSZIkSZK+q6r6DXB6GOTqATe4AAAAAElFTkSuQmCC
</value>
</data>
<data name="buttonUp.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAABGdBTUEAALGPC/xhBQAAAG9QTFRF////
AAAAWVlZ8fHx9PT0REREtLS0Ojo6+Pj4a2trp6enj4+P3t7eXl5efX1919fXh4eHw8PD6+vrdXV10dHR
5ubmDAwMy8vLTU1NlZWVvLy8iIiINjY2nJycFhYWYWFhJycnUVFRHR0dr6+vKioqoesKnwAAAAlwSFlz
AAAOvAAADrwBlbxySQAAA01JREFUeF7t3dluo0AURVHwEGdO7DjznPT/f2PHcAgULsD90FKd0l5P7jKR
2FF0jYuWXQAAAAAAAAAAAAAAAADA/7JZP643epyls3LnTP/K0GUVWJaX+nd2vhVYlt9aycyV8nautJaV
xZvqdt4WWs3JUnG1pVYz0kyZRnbTpp0yjcymzVZZXVs9l4W5okJzPZuDcMo0Mpo2/SnTyGbanCpo36mO
MHevnJh7HWMtPmUaOUyblVriVjrK2I1ShtzoOFuvChn2qiNNjU2ZhvW02ShinPHGzfGLGirXF3pQlhfX
elB5Odbxfk6UUFkVncJwwp7oeDuPCqhtipkeleWs9/f7qJ8ws9bp137mSbewN4PW+hkr5zr52u4KNCjs
Xa2eVz9jJZwy1et6WBheCxhOm3as/KivzXqF4bS5qJaMPOvEa/X1db8wvCZ/rtZsPOm0a9qR6Rf2dm+e
6kUP4ZRpdtX2Cns7cEbTZvGhc6787lXsF4b7G398ps2DTrnS7jdFCsM9qgctJi+46Pxq38XHCufduxnl
tVYTd6TTrXXuMsUKgztSZXmk1aQNn3K0cPgXkqr5l861EvzZxQsH/6hTFUyZTy3WBgqLT61Wkp82wfj/
CO+DDhUOvLikafQNw1Bh5G1IssYvwwYL4xd5KZrf6Rwre5fSw4XhhfpdutNm4u3QSGHnuR/JboRPvaUd
K4y8YU7P5LbEWKHDtAmnTGxrabSwt3GV4LRZ6NRq0e3B8cLe5mN6/6UoeKmPb/FOFIYbyOm98HdfKFbx
t7JThcfdWXynxWQEu0q3WuyZKixu9XQluRdFndfO0O2yycJgI1xL6Wj3RwdveU4Xdm6ovmslHb+vZ8M3
kg4obKdNghtvunoe+d0fUli810ckuXl6e7lczcbO7KDC4mm2Wl4OzKrUHVbojEJ/FPqj0B+F/ij0R6E/
Cv1R6I9CfxT6o9Afhf4o9EehPwr9UeiPQn8U+qPQH4X+KPRHoT8K/VHoj0J/FPqj0B+F/ij0R6E/Cv1R
6I9CfxT6o9Afhf4o9EehPwr9UeiPQn/tBw+afDL5P2s/6dvwG0kOU39pddZfW326+xT9t0y+9TBuvj3a
5vhlxwAAAAAAAAAAAAAAAACSUBR/Aa2bGOTQ6k1jAAAAAElFTkSuQmCC
</value>
</data>
<data name="buttonDown.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAABGdBTUEAALGPC/xhBQAAAG9QTFRF////
AAAAWVlZ8fHx9PT0REREtLS0Ojo6+Pj4a2trp6enj4+P3t7eXl5efX1919fXh4eHw8PD6+vrdXV10dHR
5ubmDAwMy8vLTU1NlZWVvLy8iIiINjY2nJycFhYWYWFhJycnUVFRHR0dr6+vKioqoesKnwAAAAlwSFlz
AAAOvAAADrwBlbxySQAAA2JJREFUeF7t3dtyolAQheHgIZqTicacMznO+z/jBFgoLRtwLqame9f/XUnj
xV6W1UBTBScAAAAAAAAAAAAAAAAA8K/MtqfbqT5n6fytKIq3c21l6OInX+lC29m5VMCiuFYlNzfKVxQr
VXIzUb6imKiSGxLGR8L4SBgfCeMjYXwkjI+E8ZEwPhLGR8L4SBgfCeMjYXwkjI+E8ZEwPhLGR8L4SBgf
CeMjYXwkjI+E8ZEwPhLGR8L4SBgfCeMjYXwkjI+E8ZEwPhLGR8L4SBgfCeMjYXwkjI+E8ZEwPhK6d7ea
LybP2kg5LuHzZDFf3WnDled68e/aTDgq4Xv9jaFf6j/ZParsTIWuYxKe6RvFpQp+6Lf/8UuVjiMS/tIX
iuJKFT+0sNKDSofGEz5of0klN6ZaV6WnT4wmvNPuirsHSN5rYaXFUkVrLOFyod2lexX9WGlllXS3GUu4
6zIlfw8enGlltSdVjZGET9pZm6nqyFZLq61VbRtOuNa+2lZVV861uFrieDaYcP/oz5LTh7jeanmV1263
GUq4fNWuyq2q7rR7YSLFUMIr7aksVPRn2j5kFC+q7gwkfNGOyr3jZynbbnN49tyfUGft4rLLNAa7TW/C
EF2mYQ78H/ag1pdw9qFyxf0zhh+10MqnirW+hJ+qVh5V9Gv6paVWblSt9CTcPyL6x1eAJ7Zfa621U1VL
6YSnqtVCPOm7d8nJhP0/iGPmb/e2/9ulEg78qT0z3WauYjrhXJWK/y7TWP7Wkiu79p9IOHRwcc0ewr9V
7Sb81nbN33htQPI0rJNw+CTPOXMqranSYUIzveqeqHuXuBw6TGgutvzNR8ckLmkPEo5dMLvXvWCwCUeH
Hv7Z0dLDQcL2eDs9uArAjgc3JuFGn2rJ4WMEZsS7aDWfK9tl+m9XeWe7zU0roTl1jdhlGva/2Gejb4dk
+0la3824IPa3PPv03lCNwhzXE9yOt49numaH3/H28ez59aEAg6dxQ90meJdp2DPQtmzehGhmFS0ZvULP
zJt29jOq+NLdJosu07ATmZrrm2h/z07VSs0ELhuH3SbDF3XabpNTl2nMyncBN94CjbeP177LlOnrcvfd
Jrsu02i6TYZdplG/tjrbl1aXNuundeixDAAAAAAAAAAAAAAAAADPTk7+AFMOGOSa0d0UAAAAAElFTkSu
QmCC
</value>
</data>
<data name="buttonLeft.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAABGdBTUEAALGPC/xhBQAAAG9QTFRF////
AAAAWVlZ8fHx9PT0REREtLS0Ojo6+Pj4a2trp6enj4+P3t7eXl5efX1919fXh4eHw8PD6+vrdXV10dHR
5ubmDAwMy8vLTU1NlZWVvLy8iIiINjY2nJycFhYWYWFhJycnUVFRHR0dr6+vKioqoesKnwAAAAlwSFlz
AAAOvAAADrwBlbxySQAAAkFJREFUeF7t3GtT2zAQhWErF5JAnIQQSrmFW///b+wCR6LY/Vg3nqP3+cJE
O5Nhh1kjrSQ3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAACMyVQ/Tc02P1J6WuuToUP6dKfPds6VYErXGjFz
pfTCRkNWpgtl926uQSeHeMR8WWjUyFcJfpho2MdGmWVuD9PpTyWWPSngYvuqxLKVAi7OlFfxqICLnfIq
bhQwseyW4MJsOrP+pcSy1VIRE3fKq7hVwMW98iouFTCxbJVX9mC2Llw/KLFsYlaCl8qruFfAxa3yKsxm
osuV8sqezUpw3y3Bl5kiJm6UV7FTwMWj8irOFHDxR7/pw3GrgIlv/aZ3c7Med68E3dqGnX5TSm8KuOj2
m9JBARPTufLKFmYlmHddiisFXLwpr+JcARe9EjTrN816JbhXxMT2qMQyt4lorwRT207+v91gK7ReCZ7M
hX6jf+xCXz8Ggzy/9/ryUTgOsdLudZxOaohpYq/ldFJDLLb9/4bjqsNB5vr2z9IK/h+OZk6zGbDlZT8v
rWBtEdzXh8F+jV9Bn6aCXltw75cG+553BfsWFew9he7+4avZ/mGw3wOuYB+/grMYFZynCe5nooL9uba/
nE1szc4mVnC+NLifEQ7257yjGJ+VWuZ2Vr9pZu73LYL7nZlgf++pgrtrFdw/DN0eleGFfPt7wBXc5e70
qBzv4wf3dyoE+/diVPBuE72fpvVbJ37j1wMHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFSiaX4DkC8Y5EW8
SJQAAAAASUVORK5CYII=
</value>
</data>
</root>

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectContainerShip.Direction;
namespace ProjectContainerShip.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
void SetPosition(int x, int y);
void Draw(Graphics g);
}
}

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectRightBorder <= FieldWidth &&
objParams.ObjectRightBorder + GetStep() >= FieldWidth &&
objParams.ObjectDownBorder <= FieldHeight &&
objParams.ObjectDownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectRightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectDownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2
&& objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2
&& objParams.ObjectMiddleVertical <= FieldHeight / 2
&& objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Правая граница
/// </summary>
public int ObjectRightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int ObjectDownBorder => _y + _height;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -1,4 +1,11 @@
namespace ContainerShip
using ProjectContainerShip;
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectContainerShip
{
internal static class Program
{
@ -11,8 +18,31 @@ namespace ContainerShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormContainerCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormContainerCollection>().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}appsettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ContainerShip.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("ContainerShip.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap angle_arrow_down_icon_icons_com_73683 {
get {
object obj = ResourceManager.GetObject("angle-arrow-down_icon-icons.com_73683", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap keyboard_left_arrow_button_icon_icons_com_72692 {
get {
object obj = ResourceManager.GetObject("keyboard-left-arrow-button_icon-icons.com_72692", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap keyboard_right_arrow_button_1_icon_icons_com_72690 {
get {
object obj = ResourceManager.GetObject("keyboard-right-arrow-button-1_icon-icons.com_72690", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap up_arrow_icon_icons_com_73351 {
get {
object obj = ResourceManager.GetObject("up-arrow_icon-icons.com_73351", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,133 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="keyboard-right-arrow-button-1_icon-icons.com_72690" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\keyboard-right-arrow-button-1_icon-icons.com_72690.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="angle-arrow-down_icon-icons.com_73683" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\angle-arrow-down_icon-icons.com_73683.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="keyboard-left-arrow-button_icon-icons.com_72692" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\keyboard-left-arrow-button_icon-icons.com_72692.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="up-arrow_icon-icons.com_73351" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\up-arrow_icon-icons.com_73351.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 674 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 516 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 750 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 667 B

View File

@ -0,0 +1,119 @@
using ContainerShip.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="ship">Добавляемый контейнеровоз</param>
/// <returns></returns>
public bool Insert(T ship, IEqualityComparer<T>? equal = null)
{
Insert(ship, 0, equal);
return true;
}
public bool Insert(T ship, int position, IEqualityComparer<T>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new ContainerShipNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(position);
if (equal != null)
{
if (_places.Contains(ship, equal))
throw new ArgumentException(nameof(ship));
}
_places.Insert(position, ship);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position > _maxCount || position >= Count)
throw new ContainerShipNotFoundException();
if (_places[position] == null)
{
throw new ContainerShipNotFoundException();
}
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (position < 0 || position > _maxCount)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetShip(int? maxShip = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxShip.HasValue && i == maxShip.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.MovementStrategy
{
public enum Status
{
NotInit,InProgress, Finish
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip.Exceptions
{
[Serializable] internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithShipName", "WithThreadId" ],
"Properties": {
"Application": "ContainerShip"
}
}
}