Compare commits

..

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

42 changed files with 84 additions and 3417 deletions

View File

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

@ -1,50 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
using Sailboat.Entities;
namespace Sailboat.Generics
{
internal class BoatCompareByColor : IComparer<DrawingBoat?>
{
public int Compare(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
var bodyColorCompare = x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x.EntityBoat is EntitySailboat xEntitySailboat && y.EntityBoat is EntitySailboat yEntitySailboat)
{
var dumpBoxColorCompare = xEntitySailboat.BodyColor.Name.CompareTo(yEntitySailboat.BodyColor.Name);
if (dumpBoxColorCompare != 0)
{
return dumpBoxColorCompare;
}
var tentColorCompare = xEntitySailboat.AdditionalColor.Name.CompareTo(yEntitySailboat.AdditionalColor.Name);
if (tentColorCompare != 0)
{
return tentColorCompare;
}
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}
}

View File

@ -1,35 +0,0 @@
using Sailboat.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.Generics
{
internal class BoatCompareByType : IComparer<DrawingBoat?>
{
public int Compare(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare =
x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}
}

View File

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

View File

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

View File

@ -1,144 +0,0 @@
using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawingBoat
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class BoatsGenericCollection<T, U>
where T : DrawingBoat
where U : IMoveableObject
{
/// <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 = 170;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetBoats => _collection.GetBoats();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public BoatsGenericCollection(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 +(BoatsGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return false;
}
return (bool)collect?._collection.Insert(obj, new DrawingBoatEqutables());
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(BoatsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
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 ShowBoats()
{
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, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int i = 0;
foreach (var boat in _collection.GetBoats())
{
if (boat != null)
{
int width = _pictureWidth / _placeSizeWidth;
boat._pictureWidth = _pictureWidth;
boat._pictureHeight = _pictureHeight;
boat.SetPosition(i % width * _placeSizeWidth, i / width * _placeSizeHeight);
boat.DrawTransport(g);
}
i++;
}
}
}
}

View File

@ -1,180 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy;
using Sailboat.Exceptions;
namespace Sailboat.Generics
{
internal class BoatsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<BoatsCollectionInfo> Keys => _boatStorages.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 BoatsGenericStorage(int pictureWidth, int pictureHeight)
{
_boatStorages = new Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_boatStorages.ContainsKey(new BoatsCollectionInfo(name, string.Empty)))
return;
_boatStorages.Remove(new BoatsCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>? this[string ind]
{
get
{
BoatsCollectionInfo indObj = new BoatsCollectionInfo(ind, string.Empty);
if (_boatStorages.ContainsKey(indObj))
return _boatStorages[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<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{
StringBuilder records = new();
foreach (DrawingBoat? elem in record.Value.GetBoats)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new InvalidOperationException("Файл не найден, невалидная операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine("BoatStorage");
writer.Write(data.ToString());
}
}
/// <summary>
/// Загрузка информации по лодкам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка призагрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string checker = reader.ReadLine();
if (checker == null)
throw new NullReferenceException("Нет данных для загрузки");
if (!checker.StartsWith("BoatStorage"))
{
//если нет такой записи, то это не те данные
throw new FormatException("Неверный формат данных");
}
_boatStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
throw new NullReferenceException("Нет данных для загрузки");
if (strs == null)
break;
firstinit = false;
string name = strs.Split('|')[0];
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split('|')[1].Split(';'))
{
DrawingBoat? vehicle = data?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (vehicle != null)
{
try
{
_ = collection + vehicle;
}
catch (BoatNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
_boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), collection);
}
}
}
}
}

View File

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

View File

@ -1,153 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.Entities;
using Sailboat.MovementStrategy;
namespace Sailboat.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingBoat
{
public EntityBoat? EntityBoat { get; protected set; }
public int _pictureWidth;
public int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
private readonly int _boatWidth = 185;
private readonly int _boatHeight = 160;
public int GetPosX => _startPosX;
char separator = '|';
public int GetPosY => _startPosY;
public int GetWidth => _boatWidth;
public int GetHeight => _boatHeight;
public IMoveableObject GetMoveableObject => new DrawingObjectBoat(this);
public DrawingBoat(int speed, double weight, Color bodyColor, int width, int height)
{
if (width < _boatWidth || height < _boatHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityBoat = new EntityBoat(speed, weight, bodyColor);
}
protected DrawingBoat(int speed, double weight, Color bodyColor, int width, int height, int boatWidth, int boatHeight)
{
if (width < _boatWidth || height < _boatHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_boatWidth = boatWidth;
_boatHeight = boatHeight;
EntityBoat = new EntityBoat(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)
{
if (x < 0 || x + _boatWidth > _pictureWidth)
{
x = 0;
}
if (y < 0 || y + _boatHeight > _pictureHeight)
{
y = 0;
}
_startPosX = x;
_startPosY = y;
}
public bool CanMove(DirectionType direction)
{
if (EntityBoat == null)
{
return false;
}
return direction switch
{
DirectionType.Left => _startPosX - EntityBoat.Step > 0,
DirectionType.Up => _startPosY - EntityBoat.Step > 0,
DirectionType.Right => _startPosX + EntityBoat.Step < _pictureWidth,
DirectionType.Down => _startPosY + EntityBoat.Step < _pictureHeight,
_ => false
};
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityBoat == null)
{
return;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX - EntityBoat.Step > 0)
{
_startPosX -= (int)EntityBoat.Step;
}
break;
case DirectionType.Up:
if (_startPosY - EntityBoat.Step > 0)
{
_startPosY -= (int)EntityBoat.Step;
}
break;
case DirectionType.Right:
if (_startPosX + EntityBoat.Step + _boatWidth < _pictureWidth)
{
_startPosX += (int)EntityBoat.Step;
}
break;
case DirectionType.Down:
if (_startPosY + EntityBoat.Step + _boatHeight < _pictureHeight)
{
_startPosY += (int)EntityBoat.Step;
}
break;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityBoat == null)
{
return;
}
Pen pen = new(Color.Black);
// Основной корпус парусника
Brush Brush = new
SolidBrush(EntityBoat.BodyColor);
Point[] hull = new Point[]
{
new Point(_startPosX + 5, _startPosY + 90),
new Point(_startPosX + 120, _startPosY + 90),
new Point(_startPosX + 180, _startPosY + 120),
new Point(_startPosX + 120, _startPosY + 150),
new Point(_startPosX + 5, _startPosY + 150)
};
g.FillPolygon(Brush, hull);
g.DrawPolygon(pen, hull);
Brush addBrush = new
SolidBrush(Color.Green);
g.FillEllipse(addBrush, _startPosX + 20, _startPosY + 100, 100, 40);
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 100, 100, 40);
}
}
}

View File

@ -1,59 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
using Sailboat.Entities;
namespace Sailboat.Generics
{
internal class DrawingBoatEqutables : IEqualityComparer<DrawingBoat?>
{
public bool Equals(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x.EntityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBoat.Speed != y.EntityBoat.Speed)
{
return false;
}
if (x.EntityBoat.Weight != y.EntityBoat.Weight)
{
return false;
}
if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor)
{
return false;
}
if (x is DrawingSailboat && y is DrawingSailboat)
{
EntitySailboat EntityX = (EntitySailboat)x.EntityBoat;
EntitySailboat EntityY = (EntitySailboat)y.EntityBoat;
if (EntityX.Sail != EntityY.Sail)
return false;
if (EntityX.Hull != EntityY.Hull)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingBoat obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -1,40 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
namespace Sailboat.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningBoat (паттерн Adapter)
/// </summary>
public class DrawingObjectBoat : IMoveableObject
{
private readonly DrawingBoat? _drawingBoat = null;
public DrawingObjectBoat(DrawingBoat drawingBoat)
{
_drawingBoat = drawingBoat;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingBoat == null || _drawingBoat.EntityBoat ==
null)
{
return null;
}
return new ObjectParameters(_drawingBoat.GetPosX, _drawingBoat.GetPosY, _drawingBoat.GetWidth, _drawingBoat.GetHeight);
}
}
public int GetStep => (int)(_drawingBoat?.EntityBoat?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawingBoat?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawingBoat?.MoveTransport(direction);
}
}

View File

@ -1,82 +0,0 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.Entities;
namespace Sailboat.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingSailboat : DrawingBoat
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="hull">Признак наличия усиленного корпуса</param>
/// <param name="sail">Признак наличия паруса</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingSailboat(int speed, double weight, Color bodyColor, Color additionalColor, bool hull, bool sail, int width, int height) :
base(speed, weight, bodyColor, width, height, 200, 160)
{
if (EntityBoat != null)
{
EntityBoat = new EntitySailboat(speed, weight, bodyColor,
additionalColor, hull, sail);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityBoat is not EntitySailboat sailboat)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new
SolidBrush(sailboat.AdditionalColor);
// Усиленный корпус парусника
if (sailboat.Hull)
{
Point[] hullCooler = new Point[]
{
new Point(_startPosX, _startPosY + 80),
new Point(_startPosX + 125, _startPosY + 80),
new Point(_startPosX + 190, _startPosY + 120),
new Point(_startPosX + 125, _startPosY + 160),
new Point(_startPosX, _startPosY + 160)
};
g.FillPolygon(additionalBrush, hullCooler);
g.DrawPolygon(pen, hullCooler);
}
base.DrawTransport(g);
// Парус
if (sailboat.Sail)
{
Brush sailBrush = new
SolidBrush(sailboat.AdditionalColor);
Point[] sail = new Point[]
{
new Point(_startPosX + 65, _startPosY),
new Point(_startPosX + 130, _startPosY + 120),
new Point(_startPosX + 15, _startPosY + 120)
};
g.FillPolygon(sailBrush, sail);
g.DrawPolygon(pen, sail);
g.DrawLine(pen, new Point(_startPosX + 65, _startPosY + 120), new Point(_startPosX + 65, _startPosY));
}
}
}
}

View File

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

View File

@ -1,50 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.Entities
{
/// <summary>
/// Класс-сущность "Парусная лодка"
/// </summary>
public class EntitySailboat : EntityBoat
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия усиленного корпуса
/// </summary>
public bool Hull { get; private set; }
/// <summary>
/// Признак (опция) наличия паруса
/// </summary>
public bool Sail { get; private set; }
public void ChangeAddColor(Color color)
{
AdditionalColor = color;
}
/// <summary>
/// Инициализация полей объекта-класса парусной лодки
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес лодки</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="hull">Признак наличия усиленного корпуса</param>
/// <param name="sail">Признак наличия паруса</param>
public EntitySailboat(int speed, double weight, Color bodyColor, Color
additionalColor, bool hull, bool sail) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Hull = hull;
Sail = sail;
}
}
}

View File

@ -1,66 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic.Logging;
using Sailboat.Entities;
namespace Sailboat.DrawingObjects
{
public static class ExtentionDrawingBoat
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingBoat? CreateDrawingBoat(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingSailboat(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="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingBoat drawingBoat, char separatorForObject)
{
var boat = drawingBoat.EntityBoat;
if (boat == null)
{
return string.Empty;
}
var str = $"{boat.Speed}{separatorForObject}{boat.Weight}{separatorForObject}{boat.BodyColor.Name}";
if (boat is not EntitySailboat sailboat)
{
return str;
}
return $"{str}{separatorForObject}{sailboat.AdditionalColor.Name}{separatorForObject}{sailboat.Hull}{separatorForObject}{sailboat.Sail}";
}
}
}

39
Sailboat/Sailboat/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,39 @@
namespace Sailboat
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

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

View File

@ -1,17 +1,17 @@
<?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
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>
@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -1,271 +0,0 @@
namespace Sailboat
{
partial class FormBoatCollection
{
/// <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();
buttonAddBoat = new Button();
buttonRemoveBoat = new Button();
buttonRefreshCollection = new Button();
maskedTextBoxNumber = new MaskedTextBox();
groupBoxTools = new GroupBox();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxCollection = new GroupBox();
textBoxStorageName = new TextBox();
listBoxStorages = new ListBox();
buttonDelObject = new Button();
buttonAddObject = new Button();
menuStrip = new MenuStrip();
ToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBoxTools.SuspendLayout();
groupBoxCollection.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(750, 600);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// buttonAddBoat
//
buttonAddBoat.Location = new Point(5, 402);
buttonAddBoat.Name = "buttonAddBoat";
buttonAddBoat.Size = new Size(197, 45);
buttonAddBoat.TabIndex = 1;
buttonAddBoat.Text = "Добавить лодку";
buttonAddBoat.UseVisualStyleBackColor = true;
buttonAddBoat.Click += buttonAddBoat_Click;
//
// buttonRemoveBoat
//
buttonRemoveBoat.Location = new Point(5, 486);
buttonRemoveBoat.Name = "buttonRemoveBoat";
buttonRemoveBoat.Size = new Size(197, 45);
buttonRemoveBoat.TabIndex = 2;
buttonRemoveBoat.Text = "Удалить лодку";
buttonRemoveBoat.UseVisualStyleBackColor = true;
buttonRemoveBoat.Click += buttonRemoveBoat_Click;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(6, 537);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(197, 45);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(39, 453);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(138, 27);
maskedTextBoxNumber.TabIndex = 4;
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonSortByColor);
groupBoxTools.Controls.Add(buttonSortByType);
groupBoxTools.Controls.Add(groupBoxCollection);
groupBoxTools.Controls.Add(buttonAddBoat);
groupBoxTools.Controls.Add(buttonRefreshCollection);
groupBoxTools.Controls.Add(maskedTextBoxNumber);
groupBoxTools.Controls.Add(buttonRemoveBoat);
groupBoxTools.Controls.Add(menuStrip);
groupBoxTools.Location = new Point(756, 12);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(209, 588);
groupBoxTools.TabIndex = 2;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(12, 367);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(184, 29);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(12, 335);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(184, 29);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// groupBoxCollection
//
groupBoxCollection.Controls.Add(textBoxStorageName);
groupBoxCollection.Controls.Add(listBoxStorages);
groupBoxCollection.Controls.Add(buttonDelObject);
groupBoxCollection.Controls.Add(buttonAddObject);
groupBoxCollection.Location = new Point(6, 54);
groupBoxCollection.Name = "groupBoxCollection";
groupBoxCollection.Size = new Size(196, 275);
groupBoxCollection.TabIndex = 5;
groupBoxCollection.TabStop = false;
groupBoxCollection.Text = "Наборы";
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(6, 26);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(184, 27);
textBoxStorageName.TabIndex = 3;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(21, 101);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(150, 124);
listBoxStorages.TabIndex = 2;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// buttonDelObject
//
buttonDelObject.Location = new Point(6, 231);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(184, 37);
buttonDelObject.TabIndex = 1;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += buttonDelObject_Click;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(6, 59);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(184, 36);
buttonAddObject.TabIndex = 0;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += buttonAddObject_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { ToolStripMenuItem });
menuStrip.Location = new Point(3, 23);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(203, 28);
menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip";
//
// ToolStripMenuItem
//
ToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
ToolStripMenuItem.Name = "ToolStripMenuItem";
ToolStripMenuItem.Size = new Size(59, 24);
ToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(177, 26);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(177, 26);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormBoatCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(970, 606);
Controls.Add(groupBoxTools);
Controls.Add(pictureBoxCollection);
Name = "FormBoatCollection";
Text = "FormBoatCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
groupBoxCollection.ResumeLayout(false);
groupBoxCollection.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private Button buttonAddBoat;
private Button buttonRemoveBoat;
private Button buttonRefreshCollection;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBoxTools;
private GroupBox groupBoxCollection;
private ListBox listBoxStorages;
private Button buttonDelObject;
private Button buttonAddObject;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -1,247 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using Sailboat.DrawingObjects;
using Sailboat.Generics;
using Sailboat.MovementStrategy;
using Sailboat.Exceptions;
namespace Sailboat
{
public partial class FormBoatCollection : Form
{
private readonly BoatsGenericStorage _storage;
private readonly ILogger _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
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;
}
}
private void buttonAddBoat_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Коллекция не выбрана");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
var formBoatConfig = new FormBoatConfig();
formBoatConfig.AddEvent(AddBoat);
formBoatConfig.Show();
}
private void AddBoat(DrawingBoat drawingBoat)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
if (obj + drawingBoat)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"Объект {obj.GetType()} добавлен");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonRemoveBoat_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции {pos}");
pictureBoxCollection.Image = obj.ShowBoats();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (BoatNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
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.ShowBoats();
}
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}");
}
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBoats();
}
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($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
_logger.LogWarning("Отмена удаления набора");
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
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.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByType());
private void CompareBoats(IComparer<DrawingBoat?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowBoats();
}
private void buttonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor());
}
}

View File

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

View File

@ -1,352 +0,0 @@
namespace Sailboat
{
partial class FormBoatConfig
{
/// <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()
{
groupBoxParameters = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
groupBoxColors = new GroupBox();
panelGray = new Panel();
panelBlack = new Panel();
panelPurple = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
panelBlue = new Panel();
panelYellow = new Panel();
panelGreen = new Panel();
checkBoxSail = new CheckBox();
checkBoxHull = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
pictureBoxObject = new PictureBox();
PanelObject = new Panel();
labelAddColor = new Label();
labelColor = new Label();
buttonOk = new Button();
buttonCancel = new Button();
groupBoxParameters.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
PanelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxParameters
//
groupBoxParameters.Controls.Add(labelModifiedObject);
groupBoxParameters.Controls.Add(labelSimpleObject);
groupBoxParameters.Controls.Add(groupBoxColors);
groupBoxParameters.Controls.Add(checkBoxSail);
groupBoxParameters.Controls.Add(checkBoxHull);
groupBoxParameters.Controls.Add(numericUpDownWeight);
groupBoxParameters.Controls.Add(numericUpDownSpeed);
groupBoxParameters.Controls.Add(labelWeight);
groupBoxParameters.Controls.Add(labelSpeed);
groupBoxParameters.Location = new Point(12, 0);
groupBoxParameters.Name = "groupBoxParameters";
groupBoxParameters.Size = new Size(620, 283);
groupBoxParameters.TabIndex = 0;
groupBoxParameters.TabStop = false;
groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(484, 219);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(109, 29);
labelModifiedObject.TabIndex = 8;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.MouseDown += LableObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(375, 219);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(72, 29);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.MouseDown += LableObject_MouseDown;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Location = new Point(332, 35);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(282, 172);
groupBoxColors.TabIndex = 6;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelGray
//
panelGray.BackColor = Color.Silver;
panelGray.Location = new Point(91, 102);
panelGray.Name = "panelGray";
panelGray.Size = new Size(40, 40);
panelGray.TabIndex = 0;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(156, 102);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(40, 40);
panelBlack.TabIndex = 0;
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(225, 102);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(40, 40);
panelPurple.TabIndex = 0;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(19, 102);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(40, 40);
panelWhite.TabIndex = 15;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(19, 34);
panelRed.Name = "panelRed";
panelRed.Size = new Size(40, 40);
panelRed.TabIndex = 0;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(156, 34);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(40, 40);
panelBlue.TabIndex = 14;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(225, 34);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(40, 40);
panelYellow.TabIndex = 0;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(89, 34);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(40, 40);
panelGreen.TabIndex = 0;
//
// checkBoxSail
//
checkBoxSail.AutoSize = true;
checkBoxSail.Location = new Point(17, 203);
checkBoxSail.Name = "checkBoxSail";
checkBoxSail.Size = new Size(206, 24);
checkBoxSail.TabIndex = 5;
checkBoxSail.Text = "Признак наличия паруса";
checkBoxSail.UseVisualStyleBackColor = true;
//
// checkBoxHull
//
checkBoxHull.AutoSize = true;
checkBoxHull.Location = new Point(17, 173);
checkBoxHull.Name = "checkBoxHull";
checkBoxHull.Size = new Size(299, 24);
checkBoxHull.TabIndex = 4;
checkBoxHull.Text = "Признак наличия усиленного корпуса";
checkBoxHull.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(137, 112);
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(150, 27);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(137, 71);
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(150, 27);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(42, 114);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(42, 73);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(14, 37);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(213, 191);
pictureBoxObject.TabIndex = 9;
pictureBoxObject.TabStop = false;
//
// PanelObject
//
PanelObject.AllowDrop = true;
PanelObject.Controls.Add(labelAddColor);
PanelObject.Controls.Add(labelColor);
PanelObject.Controls.Add(pictureBoxObject);
PanelObject.Location = new Point(638, 12);
PanelObject.Name = "PanelObject";
PanelObject.Size = new Size(239, 236);
PanelObject.TabIndex = 9;
PanelObject.DragDrop += PanelObject_DragDrop;
PanelObject.DragEnter += PanelObject_DragEnter;
//
// labelAddColor
//
labelAddColor.AllowDrop = true;
labelAddColor.BorderStyle = BorderStyle.FixedSingle;
labelAddColor.Location = new Point(133, 9);
labelAddColor.Name = "labelAddColor";
labelAddColor.Size = new Size(86, 25);
labelAddColor.TabIndex = 11;
labelAddColor.Text = "Доп. цвет";
labelAddColor.DragDrop += addColorLabel_DragDrop;
labelAddColor.DragEnter += LabelColor_DragEnter;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(41, 9);
labelColor.Name = "labelColor";
labelColor.Size = new Size(48, 25);
labelColor.TabIndex = 10;
labelColor.Text = "Цвет";
labelColor.DragDrop += LabelColor_DragDrop;
labelColor.DragEnter += LabelColor_DragEnter;
//
// buttonOk
//
buttonOk.Location = new Point(652, 254);
buttonOk.Name = "buttonOk";
buttonOk.Size = new Size(94, 29);
buttonOk.TabIndex = 12;
buttonOk.Text = "Добавить";
buttonOk.UseVisualStyleBackColor = true;
buttonOk.Click += buttonOk_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(763, 254);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 13;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormBoatConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(887, 298);
Controls.Add(buttonOk);
Controls.Add(buttonCancel);
Controls.Add(PanelObject);
Controls.Add(groupBoxParameters);
Name = "FormBoatConfig";
Text = "Создание объекта";
groupBoxParameters.ResumeLayout(false);
groupBoxParameters.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
PanelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private CheckBox checkBoxSail;
private CheckBox checkBoxHull;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private GroupBox groupBoxColors;
private Label labelModifiedObject;
private Label labelSimpleObject;
private PictureBox pictureBoxObject;
private Panel PanelObject;
private Label labelAddColor;
private Label labelColor;
private Button buttonOk;
private Button buttonCancel;
private Panel panelGray;
private Panel panelBlack;
private Panel panelPurple;
private Panel panelWhite;
private Panel panelRed;
private Panel panelBlue;
private Panel panelYellow;
private Panel panelGreen;
}
}

View File

@ -1,130 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sailboat.DrawingObjects;
using Sailboat.Generics;
using Sailboat.MovementStrategy;
using Sailboat.Entities;
namespace Sailboat
{
public partial class FormBoatConfig : Form
{
DrawingBoat? _boat = null;
private event Action<DrawingBoat>? EventAddBoat;
public FormBoatConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
private void DrawBoat()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_boat?.SetPosition(5, 5);
_boat?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
internal void AddEvent(Action<DrawingBoat> ev)
{
if (EventAddBoat == null)
{
EventAddBoat = ev;
}
else
{
EventAddBoat += ev;
}
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void LableObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_boat = new DrawingBoat((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_boat = new DrawingSailboat((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxHull.Checked,
checkBoxSail.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawBoat();
}
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_boat?.EntityBoat == null)
return;
Color bodyColor = (Color)e.Data.GetData(typeof(Color));
_boat.EntityBoat.ChangeColor(bodyColor);
DrawBoat();
}
private void addColorLabel_DragDrop(object sender, DragEventArgs e)
{
if ((_boat?.EntityBoat == null) || (_boat is DrawingSailboat == false))
return;
((EntitySailboat)_boat.EntityBoat).ChangeAddColor((Color)e.Data.GetData(typeof(Color)));
DrawBoat();
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void buttonOk_Click(object sender, EventArgs e)
{
EventAddBoat?.Invoke(_boat);
Close();
}
}
}

View File

@ -1,190 +0,0 @@
namespace Sailboat
{
partial class FormSailboat
{
/// <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()
{
pictureBoxSailboat = new PictureBox();
buttonUp = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonCreateBoat = new Button();
buttonCreateSailboat = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonSelectBoat = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).BeginInit();
SuspendLayout();
//
// pictureBoxSailboat
//
pictureBoxSailboat.Dock = DockStyle.Fill;
pictureBoxSailboat.Location = new Point(0, 0);
pictureBoxSailboat.Name = "pictureBoxSailboat";
pictureBoxSailboat.Size = new Size(882, 453);
pictureBoxSailboat.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxSailboat.TabIndex = 0;
pictureBoxSailboat.TabStop = false;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.up;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(804, 340);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 1;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.right;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(840, 376);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 2;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.down;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(804, 411);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.left;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(768, 376);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonCreateBoat
//
buttonCreateBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBoat.Location = new Point(149, 391);
buttonCreateBoat.Name = "buttonCreateBoat";
buttonCreateBoat.Size = new Size(131, 50);
buttonCreateBoat.TabIndex = 5;
buttonCreateBoat.Text = "Создать лодку";
buttonCreateBoat.UseVisualStyleBackColor = true;
buttonCreateBoat.Click += buttonCreateBoat_Click;
//
// buttonCreateSailboat
//
buttonCreateSailboat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateSailboat.Location = new Point(12, 391);
buttonCreateSailboat.Name = "buttonCreateSailboat";
buttonCreateSailboat.Size = new Size(131, 50);
buttonCreateSailboat.TabIndex = 6;
buttonCreateSailboat.Text = "Создать парусную лодку";
buttonCreateSailboat.UseVisualStyleBackColor = true;
buttonCreateSailboat.Click += buttonCreateSailboat_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "До центра", "До края" });
comboBoxStrategy.Location = new Point(719, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Location = new Point(776, 46);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(94, 29);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonSelectBoat
//
buttonSelectBoat.Location = new Point(618, 399);
buttonSelectBoat.Name = "buttonSelectBoat";
buttonSelectBoat.Size = new Size(122, 35);
buttonSelectBoat.TabIndex = 9;
buttonSelectBoat.Text = "Выбрать лодку";
buttonSelectBoat.UseVisualStyleBackColor = true;
buttonSelectBoat.Click += buttonSelectBoat_Click;
//
// FormSailboat
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(buttonSelectBoat);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateSailboat);
Controls.Add(buttonCreateBoat);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(pictureBoxSailboat);
Name = "FormSailboat";
StartPosition = FormStartPosition.CenterScreen;
Text = "FormSailboat";
((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxSailboat;
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonLeft;
private Button buttonCreateBoat;
private Button buttonCreateSailboat;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectBoat;
}
}

View File

@ -1,147 +0,0 @@
using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sailboat
{
public partial class FormSailboat : Form
{
private DrawingBoat? _drawingBoat;
private AbstractStrategy? _abstractStrategy;
public DrawingBoat? SelectedBoat { get; private set; }
public FormSailboat()
{
InitializeComponent();
_abstractStrategy = null;
SelectedBoat = null;
}
private void Draw()
{
if (_drawingBoat == null)
{
return;
}
Bitmap bmp = new(pictureBoxSailboat.Width,
pictureBoxSailboat.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingBoat.DrawTransport(gr);
pictureBoxSailboat.Image = bmp;
}
private void buttonCreateBoat_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;
}
_drawingBoat = new DrawingBoat(random.Next(100, 300), random.Next(1000, 3000), color, pictureBoxSailboat.Width, pictureBoxSailboat.Height);
_drawingBoat.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonCreateSailboat_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;
}
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
if (dialog.ShowDialog() == DialogResult.OK)
{
dopColor = dialog.Color;
}
_drawingBoat = new DrawingSailboat(random.Next(100, 300),
random.Next(1000, 3000), color, dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxSailboat.Width, pictureBoxSailboat.Height);
_drawingBoat.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingBoat == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingBoat.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingBoat.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingBoat.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingBoat.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingBoat == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectBoat(_drawingBoat), pictureBoxSailboat.Width,
pictureBoxSailboat.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void buttonSelectBoat_Click(object sender, EventArgs e)
{
SelectedBoat = _drawingBoat;
DialogResult = DialogResult.OK;
}
}
}

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

@ -1,103 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sailboat.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("Sailboat.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 down {
get {
object obj = ResourceManager.GetObject("down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap left {
get {
object obj = ResourceManager.GetObject("left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right {
get {
object obj = ResourceManager.GetObject("right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap up {
get {
object obj = ResourceManager.GetObject("up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

View File

@ -1,35 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<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>
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

View File

@ -1,117 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.Exceptions;
namespace Sailboat.Generics
{
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;
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="boat">Добавляемая лодка</param>
/// <returns></returns>
public bool Insert(T boat, IEqualityComparer<T?>? equal = null)
{
return Insert(boat, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="boat">Добавляемая лодка</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T boat, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new BoatNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (equal != null && _places.Contains(boat, equal))
throw new ArgumentException("Данный объект уже есть в коллекции");
_places.Insert(0, boat);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position > _maxCount || position >= Count)
throw new BoatNotFoundException(position);
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
return;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetBoats(int? maxBoats = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxBoats.HasValue && i == maxBoats.Value)
{
yield break;
}
}
}
}
}

View File

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

View File

@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.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

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