Compare commits

...

22 Commits

Author SHA1 Message Date
a5cfd9fbe4 Исправление случайно полученных ошибок 2024-10-06 01:25:05 +04:00
2a71e707f2 Revert "Готовая_Lab_7" 2024-10-06 01:06:29 +04:00
fe86c6e6d0 Готовая_Lab_7 2024-10-06 00:59:01 +04:00
de37b98f5c Revert "Финальный этап"
This reverts commit ded89563f9.
2024-10-05 23:47:35 +04:00
ded89563f9 Финальный этап 2024-10-05 23:17:03 +04:00
8b8c908d41 Третий этап 2024-09-05 20:03:59 +04:00
1dda5914de Исправление ошибок / второй этап 2024-09-03 19:20:36 +04:00
96d343bc3c Первый этап 2024-08-30 00:30:37 +04:00
04ef6e203c Исправление Lab6 на Lab07 2024-07-31 21:18:53 +03:00
62a2bf7716 Полностью готовая Lab_6 2024-07-30 16:22:44 +03:00
daddb88352 Исправление ошибок 2024-07-29 21:03:31 +03:00
1d71499845 Lab_6 2024-05-05 22:45:24 +03:00
e0a52ea60c Готовая Lab_6 2024-05-05 18:52:43 +03:00
688a6b5333 Готовая Lab_5 2024-03-11 01:13:49 +03:00
bfb444524a Добавление новой формулы и цвета в EntitySailboat 2024-02-26 11:12:59 +04:00
a8887319a1 Добавление новой формулы и цвета 2024-02-26 10:50:03 +04:00
6d876a6736 Последние исправления формы и добавления случайно удалённых элементов в прошлом коммите.
Готовая полностью Lab_4
2024-01-18 01:04:43 +03:00
0f2fc1be54 Проктирование формы 2024-01-15 23:05:56 +03:00
375e66b131 Замена массива на список и добавление нового класса 2024-01-15 22:44:26 +03:00
1e10a3cb96 Готовая полностью Lab_3 2024-01-15 21:28:27 +03:00
ac9e6959f3 Готовая полностью Lab_2 2023-12-25 02:25:54 +04:00
d1ed841a1f Исправление ошибок 2023-12-19 00:39:32 +03:00
38 changed files with 4131 additions and 50 deletions

View File

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

View File

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

@ -0,0 +1,149 @@
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 = 170;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 180;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetBoats => _collection.GetBoats();
/// <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);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(BoatsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
}
collect._collection.Remove(pos);
return false;
}
/// <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

@ -0,0 +1,185 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy;
namespace Sailboat.Generics
{
internal class BoatsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> 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<string,
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (_boatStorages.ContainsKey(name))
{
return;
}
_boatStorages[name] = new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_boatStorages.ContainsKey(name))
{
return;
}
_boatStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>?
this[string ind]
{
get
{
if (_boatStorages.ContainsKey(ind))
{
return _boatStorages[ind];
}
return null;
}
}
/// <summary>
/// Сохранение информации по лодкам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, 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}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"SailboatStorage{Environment.NewLine}{data}");
}
return true;
}
/// <summary>
/// Загрузка информации по лодкам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("BoatStorage"))
{
//если нет такой записи, то это не те данные
throw new Exception("Неверный формат данных");
}
_boatStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
{
if (!(collection + boat))
{
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_boatStorages.Add(record[0], collection);
}
}
}
}

View File

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

@ -0,0 +1,149 @@
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
{
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 = 160;
private readonly int _boatHeight = 160;
public int GetPosX => _startPosX;
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 + 5;
_startPosY = y + 17;
}
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 additionalBrush = new
SolidBrush(EntityBoat.BodyColor);
//основной корпус парусника
Brush Brush = new
SolidBrush(EntityBoat.BodyColor);
Point[] hull = new Point[]
{
new Point(_startPosX + 10, _startPosY + 90),
new Point(_startPosX + 110, _startPosY + 90),
new Point(_startPosX + 140, _startPosY + 120),
new Point(_startPosX + 110, _startPosY + 150),
new Point(_startPosX + 10, _startPosY + 150)
};
g.FillPolygon(Brush, hull);
g.DrawPolygon(pen, hull);
Brush addBrush = new
SolidBrush(Color.Aqua);
g.FillEllipse(addBrush, _startPosX + 20, _startPosY + 100, 90, 40);
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 100, 90, 40);
}
}
}

View File

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

@ -0,0 +1,83 @@
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
{
public class DrawingSailboat : DrawingBoat
{
public DrawingSailboat(int speed, double weight, Color bodyColor, Color additionalColor, bool hull, bool sail, int width, int height) :
base(speed, weight, bodyColor, width, height, 160, 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.Aqua);
Brush additionalBrush = new
SolidBrush(sailboat.AdditionalColor);
//усиленный корпус парусника
if (sailboat.Hull)
{
Point[] hullCooler = new Point[]
{
new Point(_startPosX, _startPosY + 80),
new Point(_startPosX + 120, _startPosY + 80),
new Point(_startPosX + 160, _startPosY + 120),
new Point(_startPosX + 120, _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);
//Флаг
Brush addBrush = new
SolidBrush(Color.Aqua);
Brush flagBrush = new
SolidBrush(sailboat.AdditionalColor);
Point[] flag = new Point[]
{
new Point(_startPosX + 65, _startPosY - 15),
new Point(_startPosX + 65, _startPosY + 10),
new Point(_startPosX + 20, _startPosY + 10),
new Point(_startPosX + 20, _startPosY - 15),
};
g.FillPolygon(addBrush, flag);
g.DrawPolygon(pen, flag);
g.DrawLine(pen, new Point(_startPosX + 65, _startPosY + 130), new Point(_startPosX + 65, _startPosY - 15));
g.DrawLine(pen, new Point(_startPosX + 65, _startPosY + 120), new Point(_startPosX + 65, _startPosY));
}
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.Entities
{
public class EntityBoat
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public void setBodyColor(Color color) { BodyColor = color; }
public double Step => (double)Speed * 100 / Weight;
public void ChangeColor(Color color)
{
BodyColor = color;
}
/// <summary>
/// Конструктор с параметрами
/// </summary>
public EntityBoat(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.Entities
{
public class EntitySailboat : EntityBoat
{
public Color AdditionalColor { get; private set; }
public void setAdditionalColor(Color color) { AdditionalColor = color; }
public bool Hull { get; private set; }
public bool Sail { get; private set; }
public void ChangeAddColor(Color color)
{
AdditionalColor = color;
}
/// <summary>
/// Инициализация полей объекта-класса парусной лодки
/// </summary>
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

@ -0,0 +1,63 @@
using Sailboat.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
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="drawningBoat">Сохраняемый объект</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}";
}
}
}

View File

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

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

View File

@ -0,0 +1,264 @@

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();
panelTools = new Panel();
panelCollection = new Panel();
buttonDelObject = new Button();
listBoxStorages = new ListBox();
buttonAddObject = new Button();
textBoxStorageName = new TextBox();
maskedTextBoxNumber = new MaskedTextBox();
buttonRefreshCollection = new Button();
buttonRemoveBoat = new Button();
buttonAddBoat = new Button();
menuStrip = new MenuStrip();
toolStripMenuItem1 = new ToolStripMenuItem();
ToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
panelCollection.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Margin = new Padding(3, 2, 3, 2);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(750, 600);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// panelTools
//
panelTools.BackColor = SystemColors.ScrollBar;
panelTools.Controls.Add(panelCollection);
panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRefreshCollection);
panelTools.Controls.Add(buttonRemoveBoat);
panelTools.Controls.Add(buttonAddBoat);
panelTools.Controls.Add(menuStrip);
panelTools.Location = new Point(689, 0);
panelTools.Margin = new Padding(3, 2, 3, 2);
panelTools.Name = "panelTools";
panelTools.Size = new Size(183, 542);
panelTools.TabIndex = 1;
//
// panelCollection
//
panelCollection.BackColor = SystemColors.AppWorkspace;
panelCollection.Controls.Add(buttonDelObject);
panelCollection.Controls.Add(listBoxStorages);
panelCollection.Controls.Add(buttonAddObject);
panelCollection.Controls.Add(textBoxStorageName);
panelCollection.Location = new Point(18, 124);
panelCollection.Margin = new Padding(3, 2, 3, 2);
panelCollection.Name = "panelCollection";
panelCollection.Size = new Size(158, 215);
panelCollection.TabIndex = 4;
//
// buttonDelObject
//
buttonDelObject.Location = new Point(10, 172);
buttonDelObject.Margin = new Padding(3, 2, 3, 2);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(135, 26);
buttonDelObject.TabIndex = 5;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += buttonDelObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(10, 76);
listBoxStorages.Margin = new Padding(3, 2, 3, 2);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(135, 79);
listBoxStorages.TabIndex = 6;
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(10, 46);
buttonAddObject.Margin = new Padding(3, 2, 3, 2);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(135, 26);
buttonAddObject.TabIndex = 5;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += buttonAddObject_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(25, 22);
textBoxStorageName.Margin = new Padding(3, 2, 3, 2);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(110, 23);
textBoxStorageName.TabIndex = 0;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(43, 425);
maskedTextBoxNumber.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(110, 23);
maskedTextBoxNumber.TabIndex = 3;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(18, 512);
buttonRefreshCollection.Margin = new Padding(3, 2, 3, 2);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(158, 26);
buttonRefreshCollection.TabIndex = 2;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// buttonRemoveBoat
//
buttonRemoveBoat.Location = new Point(18, 465);
buttonRemoveBoat.Margin = new Padding(3, 2, 3, 2);
buttonRemoveBoat.Name = "buttonRemoveBoat";
buttonRemoveBoat.Size = new Size(158, 26);
buttonRemoveBoat.TabIndex = 1;
buttonRemoveBoat.Text = "Удалить лодку";
buttonRemoveBoat.UseVisualStyleBackColor = true;
buttonRemoveBoat.Click += buttonRemoveBoat_Click;
//
// buttonAddBoat
//
buttonAddBoat.Location = new Point(18, 368);
buttonAddBoat.Margin = new Padding(3, 2, 3, 2);
buttonAddBoat.Name = "buttonAddBoat";
buttonAddBoat.Size = new Size(158, 26);
buttonAddBoat.TabIndex = 0;
buttonAddBoat.Text = "Добавить лодку";
buttonAddBoat.UseVisualStyleBackColor = true;
buttonAddBoat.Click += buttonAddBoat_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem1, ToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(183, 24);
menuStrip.TabIndex = 5;
//
// toolStripMenuItem1
//
toolStripMenuItem1.Name = "toolStripMenuItem1";
toolStripMenuItem1.Size = new Size(12, 20);
//
// ToolStripMenuItem
//
ToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
ToolStripMenuItem.Name = "ToolStripMenuItem";
ToolStripMenuItem.Size = new Size(48, 20);
ToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(141, 22);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(141, 22);
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(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 546);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "FormBoatCollection";
Text = "FormBoatCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
panelCollection.ResumeLayout(false);
panelCollection.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panelTools;
private Button buttonRefreshCollection;
private Button buttonRemoveBoat;
private Button buttonAddBoat;
private MaskedTextBox maskedTextBoxNumber;
private Panel panelCollection;
private Button buttonDelObject;
private ListBox listBoxStorages;
private Button buttonAddObject;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem toolStripMenuItem1;
private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,226 @@
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.Exceptions;
using Sailboat.Generics;
using Sailboat.MovementStrategy;
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]);
}
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()}");
}
}
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 ListBoxObjects_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}");
}
}
}
}
}

View File

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

View File

@ -0,0 +1,389 @@
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()
{
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.groupBoxParameters = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.checkBoxSail = new System.Windows.Forms.CheckBox();
this.checkBoxHull = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.PanelObject = new System.Windows.Forms.Panel();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.labelAddColor = new System.Windows.Forms.Label();
this.labelColor = new System.Windows.Forms.Label();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxColors.SuspendLayout();
this.groupBoxParameters.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.PanelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(345, 26);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(284, 179);
this.groupBoxColors.TabIndex = 0;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(217, 101);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(50, 50);
this.panelPurple.TabIndex = 7;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(217, 35);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(50, 50);
this.panelYellow.TabIndex = 3;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(150, 101);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(50, 50);
this.panelBlack.TabIndex = 6;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(150, 35);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(50, 50);
this.panelBlue.TabIndex = 2;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(83, 101);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(50, 50);
this.panelGray.TabIndex = 5;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(16, 101);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(50, 50);
this.panelWhite.TabIndex = 4;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(83, 35);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(50, 50);
this.panelGreen.TabIndex = 1;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(16, 35);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(50, 50);
this.panelRed.TabIndex = 0;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// groupBoxParameters
//
this.groupBoxParameters.Controls.Add(this.labelModifiedObject);
this.groupBoxParameters.Controls.Add(this.labelSimpleObject);
this.groupBoxParameters.Controls.Add(this.checkBoxSail);
this.groupBoxParameters.Controls.Add(this.checkBoxHull);
this.groupBoxParameters.Controls.Add(this.numericUpDownWeight);
this.groupBoxParameters.Controls.Add(this.numericUpDownSpeed);
this.groupBoxParameters.Controls.Add(this.labelWeight);
this.groupBoxParameters.Controls.Add(this.labelSpeed);
this.groupBoxParameters.Controls.Add(this.groupBoxColors);
this.groupBoxParameters.Location = new System.Drawing.Point(12, 12);
this.groupBoxParameters.Name = "groupBoxParameters";
this.groupBoxParameters.Size = new System.Drawing.Size(640, 285);
this.groupBoxParameters.TabIndex = 1;
this.groupBoxParameters.TabStop = false;
this.groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(489, 225);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(140, 40);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(345, 225);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(140, 40);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// checkBoxSail
//
this.checkBoxSail.AutoSize = true;
this.checkBoxSail.Location = new System.Drawing.Point(6, 168);
this.checkBoxSail.Name = "checkBoxSail";
this.checkBoxSail.Size = new System.Drawing.Size(169, 24);
this.checkBoxSail.TabIndex = 6;
this.checkBoxSail.Text = "Наличие парусника";
this.checkBoxSail.UseVisualStyleBackColor = true;
//
// checkBoxHull
//
this.checkBoxHull.AutoSize = true;
this.checkBoxHull.Location = new System.Drawing.Point(6, 127);
this.checkBoxHull.Name = "checkBoxHull";
this.checkBoxHull.Size = new System.Drawing.Size(237, 24);
this.checkBoxHull.TabIndex = 5;
this.checkBoxHull.Text = "Наличие усиленного корпуса";
this.checkBoxHull.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(118, 77);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(141, 27);
this.numericUpDownWeight.TabIndex = 4;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(118, 34);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(141, 27);
this.numericUpDownSpeed.TabIndex = 3;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(25, 79);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(36, 20);
this.labelWeight.TabIndex = 2;
this.labelWeight.Text = "Вес:";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(25, 36);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(76, 20);
this.labelSpeed.TabIndex = 1;
this.labelSpeed.Text = "Скорость:";
//
// PanelObject
//
this.PanelObject.AllowDrop = true;
this.PanelObject.Controls.Add(this.pictureBoxObject);
this.PanelObject.Controls.Add(this.labelAddColor);
this.PanelObject.Controls.Add(this.labelColor);
this.PanelObject.Location = new System.Drawing.Point(658, 12);
this.PanelObject.Name = "PanelObject";
this.PanelObject.Size = new System.Drawing.Size(362, 330);
this.PanelObject.TabIndex = 2;
this.PanelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.PanelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(3, 61);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(356, 266);
this.pictureBoxObject.TabIndex = 11;
this.pictureBoxObject.TabStop = false;
//
// labelAddColor
//
this.labelAddColor.AllowDrop = true;
this.labelAddColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAddColor.Location = new System.Drawing.Point(182, 16);
this.labelAddColor.Name = "labelAddColor";
this.labelAddColor.Size = new System.Drawing.Size(140, 40);
this.labelAddColor.TabIndex = 10;
this.labelAddColor.Text = "Доп. цвет";
this.labelAddColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAddColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelAddColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelColor
//
this.labelColor.AllowDrop = true;
this.labelColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelColor.Location = new System.Drawing.Point(38, 16);
this.labelColor.Name = "labelColor";
this.labelColor.Size = new System.Drawing.Size(140, 40);
this.labelColor.TabIndex = 9;
this.labelColor.Text = "Цвет";
this.labelColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(694, 348);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(140, 40);
this.buttonOk.TabIndex = 3;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(840, 348);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(140, 40);
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormBoatConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1032, 394);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.PanelObject);
this.Controls.Add(this.groupBoxParameters);
this.Name = "FormBoatConfig";
this.Text = "Создание объекта";
this.groupBoxColors.ResumeLayout(false);
this.groupBoxParameters.ResumeLayout(false);
this.groupBoxParameters.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.PanelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxColors;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private GroupBox groupBoxParameters;
private Label labelModifiedObject;
private Label labelSimpleObject;
private CheckBox checkBoxSail;
private CheckBox checkBoxHull;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Panel PanelObject;
private PictureBox pictureBoxObject;
private Label labelAddColor;
private Label labelColor;
private Button buttonOk;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,132 @@
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 LabelObject_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 == null)
return;
switch (((Label)sender).Name)
{
case "labelColor":
_boat.EntityBoat.setBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "labelAddColor":
if (!(_boat is DrawingSailboat))
return;
(_boat.EntityBoat as EntitySailboat).setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
break;
}
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

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

231
Sailboat/Sailboat/FormSailboat.Designer.cs generated Normal file
View File

@ -0,0 +1,231 @@
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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormSailboat));
this.pictureBoxSailboat = new System.Windows.Forms.PictureBox();
this.buttonCreateBoat = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonCreateSailboat = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonStep = new System.Windows.Forms.Button();
this.buttonSelectBoat = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxSailboat)).BeginInit();
this.SuspendLayout();
pictureBoxSailboat = new PictureBox();
buttonCreateBoat = new Button();
buttonLeft = new Button();
buttonUp = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonCreateSailboat = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).BeginInit();
SuspendLayout();
//
// pictureBoxSailboat
//
pictureBoxSailboat.Dock = DockStyle.Fill;
pictureBoxSailboat.Location = new Point(0, 0);
pictureBoxSailboat.Margin = new Padding(3, 2, 3, 2);
pictureBoxSailboat.Name = "pictureBoxSailboat";
pictureBoxSailboat.Size = new Size(834, 461);
pictureBoxSailboat.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxSailboat.TabIndex = 0;
pictureBoxSailboat.TabStop = false;
//
// buttonCreateBoat
//
buttonCreateBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBoat.Location = new Point(12, 408);
buttonCreateBoat.Margin = new Padding(3, 2, 3, 2);
buttonCreateBoat.Name = "buttonCreateBoat";
buttonCreateBoat.Size = new Size(111, 42);
buttonCreateBoat.TabIndex = 1;
buttonCreateBoat.Text = "Создать лодку";
buttonCreateBoat.UseVisualStyleBackColor = true;
buttonCreateBoat.Click += buttonCreateBoat_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(673, 420);
buttonLeft.Margin = new Padding(3, 2, 3, 2);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage");
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(716, 386);
buttonUp.Margin = new Padding(3, 2, 3, 2);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage");
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(760, 420);
buttonRight.Margin = new Padding(3, 2, 3, 2);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(716, 420);
buttonDown.Margin = new Padding(3, 2, 3, 2);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonCreateSailboat
//
buttonCreateSailboat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateSailboat.Location = new Point(145, 408);
buttonCreateSailboat.Margin = new Padding(3, 2, 3, 2);
buttonCreateSailboat.Name = "buttonCreateSailboat";
buttonCreateSailboat.Size = new Size(111, 42);
buttonCreateSailboat.TabIndex = 6;
buttonCreateSailboat.Text = "Создать парусник";
buttonCreateSailboat.UseVisualStyleBackColor = true;
buttonCreateSailboat.Click += buttonCreateSailboat_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "До центра", "До края" });
comboBoxStrategy.Location = new Point(701, 0);
comboBoxStrategy.Margin = new Padding(3, 2, 3, 2);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(133, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(701, 27);
buttonStep.Margin = new Padding(3, 2, 3, 2);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(133, 23);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonSelectBoat
//
this.buttonSelectBoat.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonSelectBoat.Location = new System.Drawing.Point(688, 97);
this.buttonSelectBoat.Name = "buttonSelectBoat";
this.buttonSelectBoat.Size = new System.Drawing.Size(149, 33);
this.buttonSelectBoat.TabIndex = 9;
this.buttonSelectBoat.Text = "Выбрать лодку";
this.buttonSelectBoat.UseVisualStyleBackColor = true;
this.buttonSelectBoat.Click += new System.EventHandler(this.buttonSelectBoat_Click);
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(882, 453);
this.Controls.Add(this.buttonSelectBoat);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonCreateSailboat);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonCreateBoat);
this.Controls.Add(this.pictureBoxSailboat);
this.Name = "FormSailboat";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Парусник";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxSailboat)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(834, 461);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateSailboat);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonCreateBoat);
Controls.Add(pictureBoxSailboat);
Margin = new Padding(3, 2, 3, 2);
Name = "FormSailboat";
StartPosition = FormStartPosition.CenterScreen;
Text = "Парусник";
((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxSailboat;
private Button buttonCreateBoat;
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonCreateSailboat;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectBoat;
}
}

View File

@ -0,0 +1,135 @@
using Sailboat.Entities;
using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy;
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(_drawingBoat.GetMoveableObject, pictureBoxSailboat.Width,
pictureBoxSailboat.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_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;
}
}
}

File diff suppressed because it is too large Load Diff

View File

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

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.MovementStrategy
{
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.MovementStrategy
{
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,3 +1,10 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace Sailboat
{
internal static class Program
@ -11,7 +18,33 @@ namespace Sailboat
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
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);
option.AddNLog("nlog.config");
});
}
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

View File

@ -8,4 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<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>
</Project>

View File

@ -0,0 +1,120 @@
using System;
using Sailboat.Exceptions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
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;
/// <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)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
Insert(boat, 0);
return true;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="boat">Добавляемая лодка</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T boat, int position)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
{
return false;
}
_places.Insert(position, boat);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || 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

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

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

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