15 Commits
main ... laba_8

50 changed files with 4185 additions and 77 deletions

View File

@@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Drawings;
using Linkor_8.Drawnings;
namespace Linkor_8.CollectionGenericObjects;
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 400;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 140;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция автомобилей
/// </summary>
protected ICollectionGenericObjects<DrawningLinkorSimple>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => (int)(_pictureWidth / _placeSizeWidth) * (int)(_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция автомобилей</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningLinkorSimple> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="linkor">Добавляемый объект</param>
/// <returns></returns>
public static bool operator +(AbstractCompany company, DrawningLinkorSimple linkor)
{
return company._collection?.Insert(linkor, new DrawningLinkorEqutables()) ?? false;
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static bool operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position) ?? false;
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningLinkorSimple? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningLinkorSimple? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;
}
public void Sort(IComparer<DrawningLinkorSimple?> comparer)
{
_collection?.CollectionSort(comparer);
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.CollectionGenericObjects;
using Linkor_8.Drawnings;
namespace Linkor_8.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3) return null;
return new CollectionInfo(
strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType), strs[1]),
strs.Length > 2 ? strs[2] : string.Empty
);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.CollectionGenericObjects;
/// <summary>
/// Тип коллекции
/// </summary>
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// Список
/// </summary>
List = 2
}

View File

@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Drawings;
namespace Linkor_8.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj, IEqualityComparer<T>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
bool Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
}

View File

@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Drawings;
namespace Linkor_8.CollectionGenericObjects;
public class LinkorSharingService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public LinkorSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningLinkorSimple> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black, 3);
int widthCount = _pictureWidth / _placeSizeWidth;
int heightCount = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < widthCount; i++)
{
for (int j = 0; j < heightCount; j++)
{
Point[] p =
{
new Point(i*_placeSizeWidth + 10, j*_placeSizeHeight + 5),
new Point(i*_placeSizeWidth + _placeSizeWidth - 20, j*_placeSizeHeight + 5),
new Point(i*_placeSizeWidth + _placeSizeWidth - 20, j*_placeSizeHeight + _placeSizeHeight - 10),
new Point(i*_placeSizeWidth + 10, j*_placeSizeHeight + _placeSizeHeight - 10),
};
g.DrawLines(pen, p);
}
}
}
protected override void SetObjectsPosition()
{
int x = 0;
int y = 0;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x + 15, y + 15);
y += _placeSizeHeight;
if (y >= _pictureHeight - _placeSizeHeight)
{
y = 0;
x += _placeSizeWidth;
}
if (x >= _pictureWidth - _placeSizeWidth)
{
break;
}
}
}
}

View File

@@ -0,0 +1,139 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Drawings;
using Linkor_8.Exceptions;
namespace Linkor_8.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
private bool IsPositionValid(int position) => position >= 0 && position < _collection.Count;
public T? Get(int position)
{
if (!IsPositionValid(position))
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position];
}
public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (obj == null)
return false;
if (_collection.Count >= _maxCount)
{
throw new CollectionOverflowException(_maxCount);
}
if (comparer != null)
{
if (_collection.Contains(obj, comparer)) throw new InsertException("Такой объект уже присутствует в коллекции");
}
_collection.Add(obj);
return true;
}
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (obj == null)
return false;
if (_collection.Count >= _maxCount)
{
throw new CollectionOverflowException(_maxCount);
}
if (position < 0 || position > _collection.Count)
{
throw new PositionOutOfCollectionException(position);
}
if (comparer != null)
{
if (_collection.Contains(obj, comparer)) throw new InsertException("Такой объект уже присутствует в коллекции");
}
_collection.Insert(position, obj);
return true;
}
public bool Remove(int position)
{
if (!IsPositionValid(position))
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
_collection.RemoveAt(position);
return true;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Drawings;
using Linkor_8.Exceptions;
namespace Linkor_8.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
private bool IsPositionValid(int position) => position >= 0 && position < _collection.Length;
public T? Get(int position)
{
if (!IsPositionValid(position))
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
return null;
}
return _collection[position];
}
public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
return Insert(obj, 0, comparer);
}
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (!IsPositionValid(position))
throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
foreach (var item in _collection)
{
if (item != null && comparer.Equals(item, obj))
{
throw new InsertException("Такой объект уже присутствует в коллекции");
}
}
}
if (obj == null)
return false;
if (_collection[position] == null)
{
_collection[position] = obj;
return true;
}
for (int i = position + 1; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
for (int i = position - 1; i >= 0; i--)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
throw new CollectionOverflowException(_collection.Length);
}
public bool Remove(int position)
{
if (!IsPositionValid(position))
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
_collection[position] = null;
return true;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Drawings;
using Linkor_8.Exceptions;
namespace Linkor_8.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : DrawningLinkorSimple
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
if (_storages == null || _storages.ContainsKey(collectionInfo)) return;
switch (collectionType)
{
case CollectionType.Massive:
_storages.Add(collectionInfo, new MassiveGenericObjects<T>());
break;
case CollectionType.List:
_storages.Add(collectionInfo, new ListGenericObjects<T>());
break;
default: return;
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (name == null) return;
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (_storages != null && _storages.ContainsKey(collectionInfo)) _storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
var key = _storages.Keys.FirstOrDefault(k => k.Name == name);
return key != null ? _storages[key] : null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0) throw new("Отсутсвует коллекция для сохранения");
if (File.Exists(filename))
{
File.Delete(filename);
}
StreamWriter writer = new StreamWriter(filename);
writer.WriteLine(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new StringBuilder();
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data)) continue;
sb.Append(data);
sb.Append(_separatorItems);
}
writer.WriteLine(sb.ToString());
}
writer.Close();
}
public void LoadData(string filename)
{
if (!File.Exists(filename)) throw new FileNotFoundException("Файл не существует");
StreamReader reader = new StreamReader(filename);
if (reader.EndOfStream) throw new FormatException("Файл пуст");
if (!reader.ReadLine()?.Equals(_collectionKey) ?? true) throw new FormatException("Неверные данные в файле");
_storages.Clear();
while (!reader.EndOfStream)
{
string[] record = reader.ReadLine()?.Trim().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries) ?? new string[] { };
if (record.Length != 3) continue;
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null) throw new PositionOutOfCollectionException("Неудалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string el in set)
{
if (el?.CreateDrawningLinkorSimple() is T linkor)
{
try
{
if (!collection.Insert(linkor)) throw new Exception("Неудалось вставить элемент");
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException(collection.MaxCount);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

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

View File

@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Entities;
namespace Linkor_8.Drawings;
public class DrawningLinkor : DrawningLinkorSimple
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="mainColor">Основной цвет</param>
/// <param name="secondColor">Дополнительный цвет</param>
/// <param name="flag">Признак наличия обвеса</param>
/// <param name="stripes">Признак наличия антикрыла</param>
/// <param name="helicopterLandingSite">Признак наличия гоночной полосы</param>
public DrawningLinkor(int speed, double weight, Color mainColor, Color secondColor, bool flag, bool stripes, bool helicopterLandingSite) : base(340, 100)
{
Entity_Linkor_Simple = new Entity_Linkor(speed, weight, mainColor, secondColor, flag, stripes, helicopterLandingSite);
}
public DrawningLinkor(Entity_Linkor linkor) : base(linkor)
{
Entity_Linkor_Simple = linkor;
}
public override void DrawTransport(Graphics g)
{
_startPosX += 5;
_startPosY += 5;
base.DrawTransport(g);
_startPosX -= 5;
_startPosY -= 5;
if (Entity_Linkor_Simple == null || Entity_Linkor_Simple is not Entity_Linkor Linkor || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
//вертолетная площадка
if (Linkor.HelicopterLandingSite)
{
Pen penHelicopter = new Pen(Color.Red, 3);
g.DrawEllipse(penHelicopter, _startPosX.Value + 15, _startPosY.Value + 10, 90, 90);
g.DrawLine(penHelicopter, _startPosX.Value + 30, _startPosY.Value + 22, _startPosX.Value + 30, _startPosY.Value + 90);
g.DrawLine(penHelicopter, _startPosX.Value + 30, _startPosY.Value + 56, _startPosX.Value + 90, _startPosY.Value + 56);
g.DrawLine(penHelicopter, _startPosX.Value + 90, _startPosY.Value + 22, _startPosX.Value + 90, _startPosY.Value + 90);
}
//полоски
if (Linkor.Stripes)
{
Pen penStripes1 = new Pen(Color.White, 10);
g.DrawLine(penStripes1, _startPosX.Value + 120, _startPosY.Value + 105, _startPosX.Value + 120, _startPosY.Value + 5);
Pen penStripes2 = new Pen(Color.DarkBlue, 10);
g.DrawLine(penStripes2, _startPosX.Value + 130, _startPosY.Value + 105, _startPosX.Value + 130, _startPosY.Value + 5);
Pen penStripes3 = new Pen(Color.Red, 10);
g.DrawLine(penStripes3, _startPosX.Value + 140, _startPosY.Value + 105, _startPosX.Value + 140, _startPosY.Value + 5);
}
//флаг
if (Linkor.Flag)
{
Brush additionalBrush = new SolidBrush(Linkor.SecondColor);
Pen pen = new Pen(Color.Black, 3);
g.DrawRectangle(pen, _startPosX.Value + 250, _startPosY.Value, 40, 20);
g.DrawLine(pen, _startPosX.Value + 250, _startPosY.Value, _startPosX.Value + 250, _startPosY.Value + 60);
g.FillRectangle(additionalBrush, _startPosX.Value + 250, _startPosY.Value, 40, 20);
}
}
}

View File

@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Drawings;
using Linkor_8.Entities;
namespace Linkor_8.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningLinkorEqutables : IEqualityComparer<DrawningLinkorSimple?>
{
public bool Equals(DrawningLinkorSimple? x, DrawningLinkorSimple? y)
{
if (x == null || x.Entity_Linkor_Simple == null) return false;
if (y == null || y.Entity_Linkor_Simple == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.Entity_Linkor_Simple.Speed != y.Entity_Linkor_Simple.Speed) return false;
if (x.Entity_Linkor_Simple.Weight != y.Entity_Linkor_Simple.Weight) return false;
if (x.Entity_Linkor_Simple.MainColor != y.Entity_Linkor_Simple.MainColor) return false;
if (
x is DrawningLinkor xAdvanced &&
y is DrawningLinkor yAdvanced
)
{
Entity_Linkor? xAdvancedEntity = xAdvanced.Entity_Linkor_Simple as Entity_Linkor;
Entity_Linkor? yAdvancedEntity = yAdvanced.Entity_Linkor_Simple as Entity_Linkor;
if (xAdvancedEntity.SecondColor != yAdvancedEntity.SecondColor) return false;
if (xAdvancedEntity.Flag != yAdvancedEntity.Flag) return false;
if (xAdvancedEntity.HelicopterLandingSite != yAdvancedEntity.HelicopterLandingSite) return false;
if (xAdvancedEntity.Stripes != yAdvancedEntity.Stripes) return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningLinkorSimple? obj)
{
return obj.GetHashCode();
}
}

View File

@@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Entities;
namespace Linkor_8.Drawings;
public class DrawningLinkorSimple
{
/// <summary>
/// Класс-сущность
/// </summary>
public Entity_Linkor_Simple? Entity_Linkor_Simple { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки линкора
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки линкора
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки линкора
/// </summary>
private readonly int _drawningLinkorWidth = 340;
/// <summary>
/// Высота прорисовки линкора
/// </summary>
private readonly int _drawningLinkorHeight = 100;
/// <summary>
/// Координата X
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningLinkorWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningLinkorHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
public DrawningLinkorSimple()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
public DrawningLinkorSimple(Entity_Linkor_Simple linkor)
{
Entity_Linkor_Simple = linkor;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="mainColor">Основной цвет</param>
public DrawningLinkorSimple(int speed, double weight, Color mainColor) : this()
{
Entity_Linkor_Simple = new Entity_Linkor_Simple(speed, weight, mainColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningLinkorWidth">Ширина прорисовки линкора</param>
/// <param name="drawningLinkorHeight">Высота прорисовки линкора</param>
protected DrawningLinkorSimple(int drawningLinkorWidth, int drawningLinkorHeight) : this()
{
_drawningLinkorWidth = drawningLinkorWidth;
_pictureHeight = drawningLinkorHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
if (height < _drawningLinkorHeight || width < _drawningLinkorWidth)
{
return false;
}
else
{
_pictureWidth = width;
_pictureHeight = height;
return true;
}
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x + _drawningLinkorWidth >= _pictureWidth && y + _drawningLinkorHeight >= _pictureHeight)
{
_startPosX = _pictureWidth - _drawningLinkorWidth;
_startPosY = _pictureHeight - _drawningLinkorHeight;
}
else if (x + _drawningLinkorWidth >= _pictureWidth)
{
_startPosX = _pictureWidth - _drawningLinkorWidth;
_startPosY = y;
}
else if (y + _drawningLinkorHeight >= _pictureHeight)
{
_startPosX = x;
_startPosY = _pictureHeight - _drawningLinkorHeight;
}
else
{
_startPosX = x;
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (Entity_Linkor_Simple == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - Entity_Linkor_Simple.Step > 0)
{
_startPosX -= (int)Entity_Linkor_Simple.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - Entity_Linkor_Simple.Step > 0)
{
_startPosY -= (int)Entity_Linkor_Simple.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + Entity_Linkor_Simple.Step + _drawningLinkorWidth < _pictureWidth)
{
_startPosX += (int)Entity_Linkor_Simple.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + Entity_Linkor_Simple.Step + _drawningLinkorHeight < _pictureHeight)
{
_startPosY += (int)Entity_Linkor_Simple.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (Entity_Linkor_Simple == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
//границы линкора
Brush Brushlinkor = new SolidBrush(Entity_Linkor_Simple.MainColor);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 300, 100);
g.FillRectangle(Brushlinkor, _startPosX.Value, _startPosY.Value, 300, 100);
g.DrawLine(pen, _startPosX.Value + 300, _startPosY.Value, _startPosX.Value + 340, _startPosY.Value + 50);
g.DrawLine(pen, _startPosX.Value + 300, _startPosY.Value + 100, _startPosX.Value + 340, _startPosY.Value + 50);
Point point1 = new Point(_startPosX.Value + 300, _startPosY.Value + 100);
Point point2 = new Point(_startPosX.Value + 300, _startPosY.Value);
Point point3 = new Point(_startPosX.Value + 340, _startPosY.Value + 50);
Point[] points = { point1, point2, point3 };
g.FillPolygon(Brushlinkor, points);
//стекло
Brush GlassBrush = new SolidBrush(Color.LightBlue);
g.DrawEllipse(pen, _startPosX.Value + 240, _startPosY.Value + 10, 50, 70);
g.FillEllipse(GlassBrush, _startPosX.Value + 240, _startPosY.Value + 10, 50, 70);
//башня с пушками
Brush BrushGun = new SolidBrush(Color.LightGray);
//пушки
g.DrawRectangle(pen, _startPosX.Value + 170, _startPosY.Value + 10, 50, 10);
g.DrawRectangle(pen, _startPosX.Value + 170, _startPosY.Value + 40, 50, 10);
g.DrawRectangle(pen, _startPosX.Value + 170, _startPosY.Value + 70, 50, 10);
g.FillRectangle(BrushGun, _startPosX.Value + 170, _startPosY.Value + 10, 50, 10);
g.FillRectangle(BrushGun, _startPosX.Value + 170, _startPosY.Value + 40, 50, 10);
g.FillRectangle(BrushGun, _startPosX.Value + 170, _startPosY.Value + 70, 50, 10);
//башня
Brush BrushGun1 = new SolidBrush(Color.Gray);
g.DrawRectangle(pen, _startPosX.Value + 220, _startPosY.Value, 50, 90);
g.FillRectangle(BrushGun1, _startPosX.Value + 220, _startPosY.Value, 50, 90);
//отсеки для ракет
Brush bombbrush = new SolidBrush(Color.Black);
g.FillRectangle(bombbrush, _startPosX.Value - 10, _startPosY.Value + 10, 10, 20);
g.FillRectangle(bombbrush, _startPosX.Value - 10, _startPosY.Value + 60, 10, 20);
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Linkor_8.Entities;
namespace Linkor_8.Drawings;
public static class ExtentionDrawningLinkor
{
// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningLinkorSimple? CreateDrawningLinkorSimple(this string info)
{
string[] strs = info.Split(_separatorForObject);
Entity_Linkor_Simple? linkor = Entity_Linkor.CreateEntityLinkor(strs);
if (linkor != null)
{
return new DrawningLinkor((Entity_Linkor)linkor);
}
linkor = Entity_Linkor_Simple.CreateEntityLinkorSimple(strs);
if (linkor != null)
{
return new DrawningLinkorSimple(linkor);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningLinkorSimple">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningLinkorSimple drawningLinkorSimple)
{
string[]? array = drawningLinkorSimple?.Entity_Linkor_Simple?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.Drawings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class LinkorCompareByColor : IComparer<DrawningLinkorSimple?>
{
public int Compare(DrawningLinkorSimple? x, DrawningLinkorSimple? y)
{
if (x == null && y == null) return 0;
if (x == null) return -1;
if (y == null) return 1;
if (x.Entity_Linkor_Simple == null && y.Entity_Linkor_Simple == null) return 0;
if (x.Entity_Linkor_Simple == null) return -1;
if (y.Entity_Linkor_Simple == null) return 1;
int colorCompare = x.Entity_Linkor_Simple.MainColor.Name.CompareTo(y.Entity_Linkor_Simple.MainColor.Name);
if (colorCompare != 0) return colorCompare;
int speedCompare = x.Entity_Linkor_Simple.Speed.CompareTo(y.Entity_Linkor_Simple.Speed);
if (speedCompare != 0) return speedCompare;
return x.Entity_Linkor_Simple.Weight.CompareTo(y.Entity_Linkor_Simple.Weight);
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.Drawings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class LinkorCompareByType : IComparer<DrawningLinkorSimple?>
{
public int Compare(DrawningLinkorSimple? x, DrawningLinkorSimple? y)
{
if (x == null && y == null) return 0;
if (x == null) return -1;
if (y == null) return 1;
if (x.Entity_Linkor_Simple == null && y.Entity_Linkor_Simple == null) return 0;
if (x.Entity_Linkor_Simple == null) return -1;
if (y.Entity_Linkor_Simple == null) return 1;
int typeCompare = x.GetType().Name.CompareTo(y.GetType().Name);
if (typeCompare != 0) return typeCompare;
int speedCompare = x.Entity_Linkor_Simple.Speed.CompareTo(y.Entity_Linkor_Simple.Speed);
if (speedCompare != 0) return speedCompare;
return x.Entity_Linkor_Simple.Weight.CompareTo(y.Entity_Linkor_Simple.Weight);
}
}

View File

@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.Entities;
public class Entity_Linkor : Entity_Linkor_Simple
{
public Color SecondColor { get; private set; }
/// <summary>
/// Есть ли флаг
/// </summary>
public bool Flag { get; private set; }
/// <summary>
/// Имеются ли полоски на борту
/// </summary>
public bool Stripes { get; private set; }
/// <summary>
/// Новая ли модель
/// </summary>
public bool HelicopterLandingSite { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="mainColor"></param>
/// <param name="secondColor"></param>
/// <param name="flag"></param>
/// <param name="stripes"></param>
/// <param name="helicopterLandingSite"></param>
public Entity_Linkor(int speed, double weight, Color mainColor, Color secondColor, bool flag, bool stripes, bool helicopterLandingSite) : base(speed, weight, mainColor)
{
SecondColor = secondColor;
Flag = flag;
Stripes = stripes;
HelicopterLandingSite = helicopterLandingSite;
}
/// <summary>
/// Сеттеры
/// </summary>
/// <param name="color"></param>
public void SetSecondColor(Color color)
{
SecondColor = color;
}
public override string[] GetStringRepresentation()
{
return new string[] { nameof(Entity_Linkor), Speed.ToString(), Weight.ToString(), MainColor.Name, SecondColor.Name,
Flag.ToString(), Stripes.ToString(), HelicopterLandingSite.ToString() };
}
public static Entity_Linkor? CreateEntityLinkor(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(Entity_Linkor))
{
return null;
}
return new Entity_Linkor(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
}

View File

@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
namespace Linkor_8.Entities;
/// <summary>
/// Класс-сущность "Простой линкор"
/// </summary>
public class Entity_Linkor_Simple
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color MainColor { get; private set; }
/// <summary>
/// Шаг перемещения линкора
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="mainColor"></param>
public Entity_Linkor_Simple(int speed, double weight, Color mainColor)
{
Speed = speed;
Weight = weight;
MainColor = mainColor;
}
public void SetMainColor(Color color)
{
MainColor = color;
}
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(Entity_Linkor_Simple), Speed.ToString(), Weight.ToString(), MainColor.Name };
}
public static Entity_Linkor_Simple? CreateEntityLinkorSimple(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(Entity_Linkor_Simple))
{
return null;
}
return new Entity_Linkor_Simple(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

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

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.Exceptions;
[Serializable]
internal class InsertException : Exception
{
public InsertException() : base() { }
public InsertException(string message) : base(message) { }
public InsertException(string message, Exception ex) : base(message, ex) { }
protected InsertException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

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

View File

@@ -1,39 +0,0 @@
namespace Linkor_8
{
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 Linkor_8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

152
Linkor_8/Linkor_8/FormLinkor.Designer.cs generated Normal file
View File

@@ -0,0 +1,152 @@

namespace Linkor_8
{
partial class FormLinkor
{
/// <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()
{
PictureBoxLinkor = new PictureBox();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonLeft = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)PictureBoxLinkor).BeginInit();
SuspendLayout();
//
// PictureBoxLinkor
//
PictureBoxLinkor.Dock = DockStyle.Fill;
PictureBoxLinkor.Location = new Point(0, 0);
PictureBoxLinkor.Name = "PictureBoxLinkor";
PictureBoxLinkor.Size = new Size(1902, 1033);
PictureBoxLinkor.TabIndex = 0;
PictureBoxLinkor.TabStop = false;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.up_arrow;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(1814, 945);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 2;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.bottom_arrow;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(1814, 986);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.right_arrow;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(1855, 986);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.left_arrow;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(1773, 986);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 5;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(1739, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(1796, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormLinkor
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1902, 1033);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonLeft);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(PictureBoxLinkor);
Name = "FormLinkor";
Text = "Линкор";
((System.ComponentModel.ISupportInitialize)PictureBoxLinkor).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox PictureBoxLinkor;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private Button buttonLeft;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@@ -0,0 +1,131 @@
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 Linkor_8.Drawings;
using Linkor_8.MovingStrategy;
namespace Linkor_8
{
public partial class FormLinkor : Form
{
private DrawningLinkorSimple? _drawningLinkorSimple;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
public FormLinkor()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
{
if (_drawningLinkorSimple == null)
{
return;
}
Bitmap bmp = new(PictureBoxLinkor.Width, PictureBoxLinkor.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningLinkorSimple.DrawTransport(gr);
PictureBoxLinkor.Image = bmp;
}
public DrawningLinkorSimple SetLinkor
{
set
{
_drawningLinkorSimple = value;
_drawningLinkorSimple.SetPictureSize(PictureBoxLinkor.Width, PictureBoxLinkor.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningLinkorSimple == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningLinkorSimple.MoveTransport(DirectionType.Up); break;
case "buttonDown":
result = _drawningLinkorSimple.MoveTransport(DirectionType.Down); break;
case "buttonRight":
result = _drawningLinkorSimple.MoveTransport(DirectionType.Right); break;
case "buttonLeft":
result = _drawningLinkorSimple.MoveTransport(DirectionType.Left); break;
}
if (result)
{
Draw();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningLinkorSimple == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableLinkor(_drawningLinkorSimple), PictureBoxLinkor.Width, PictureBoxLinkor.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

View File

@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
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

@@ -0,0 +1,396 @@
namespace Linkor_8
{
partial class FormLinkorCollection
{
/// <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()
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddLinkorSimple = new Button();
buttonGoToCheck = new Button();
buttonDelLinkor = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1444, 24);
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(220, 751);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddLinkorSimple);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonDelLinkor);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 379);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(214, 370);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(7, 313);
buttonSortByColor.Margin = new Padding(3, 2, 3, 2);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(203, 42);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(7, 266);
buttonSortByType.Margin = new Padding(3, 2, 3, 2);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(203, 42);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddLinkorSimple
//
buttonAddLinkorSimple.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddLinkorSimple.Location = new Point(5, 9);
buttonAddLinkorSimple.Margin = new Padding(3, 2, 3, 2);
buttonAddLinkorSimple.Name = "buttonAddLinkorSimple";
buttonAddLinkorSimple.Size = new Size(200, 42);
buttonAddLinkorSimple.TabIndex = 1;
buttonAddLinkorSimple.Text = "Добавление линкора без обвесов";
buttonAddLinkorSimple.UseVisualStyleBackColor = true;
buttonAddLinkorSimple.Click += ButtonAddLinkorSimple_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(7, 127);
buttonGoToCheck.Margin = new Padding(3, 2, 3, 2);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(203, 42);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonDelLinkor
//
buttonDelLinkor.Location = new Point(7, 220);
buttonDelLinkor.Margin = new Padding(3, 2, 3, 2);
buttonDelLinkor.Name = "buttonDelLinkor";
buttonDelLinkor.Size = new Size(203, 42);
buttonDelLinkor.TabIndex = 4;
buttonDelLinkor.Text = "Удаление линкора";
buttonDelLinkor.UseVisualStyleBackColor = true;
buttonDelLinkor.Click += buttonDelLinkor_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(5, 102);
maskedTextBoxPosition.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(205, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonRefresh
//
buttonRefresh.Location = new Point(7, 173);
buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(203, 42);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(8, 329);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(210, 22);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создание компании";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 18);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(214, 308);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(5, 197);
buttonCollectionDel.Margin = new Padding(3, 2, 3, 2);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(210, 22);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(7, 100);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(201, 94);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 71);
buttonCollectionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(210, 22);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(104, 49);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(15, 49);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(1, 17);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(212, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(38, 0);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(122, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(10, 356);
comboBoxSelectorCompany.Margin = new Padding(3, 2, 3, 2);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(205, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Margin = new Padding(3, 2, 3, 2);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1444, 751);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(1664, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file|*.txt";
//
// FormLinkorCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1664, 775);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "FormLinkorCollection";
Text = "Коллекция линкоров";
groupBoxTools.ResumeLayout(false);
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
private void ButtonAddLinkor_Click1(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddLinkorSimple;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonDelLinkor;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Panel panelStorage;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private Button buttonCollectionAdd;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -0,0 +1,307 @@
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 Linkor_8.Drawings;
using Linkor_8.Drawnings;
using Linkor_8.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using Linkor_8.Exceptions;
namespace Linkor_8;
public partial class FormLinkorCollection : Form
{
/// <summary>
/// Хранилише коллекций
/// </summary>
private readonly StorageCollection<DrawningLinkorSimple> _storageCollection;
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
public FormLinkorCollection(ILogger<FormLinkorCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
private void SetLinkor(DrawningLinkorSimple? linkor)
{
if (_company == null)
{
MessageBox.Show("_company == null");
return;
}
if (linkor == null)
{
MessageBox.Show("linkor == null");
return;
}
try
{
if (_company + linkor)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Объект " + string.Join(";", linkor.Entity_Linkor_Simple.GetStringRepresentation()) + " добавлен");
pictureBox.Image = _company.Show();
}
}
catch (Exception ex)
{
_logger.LogError($"Ошибка: {ex.Message}");
MessageBox.Show(ex.Message);
}
}
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
private void ButtonAddLinkorSimple_Click(object sender, EventArgs e)
{
FormLinkorConfig form = new();
form.AddEvent(SetLinkor);
form.Show();
}
private void buttonDelLinkor_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_company - pos)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("объект " + pos + " удален");
pictureBox.Image = _company.Show();
}
}
catch (Exception ex)
{
_logger.LogError($"Ошибка: {ex.Message}");
MessageBox.Show(ex.Message);
}
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
private void buttonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningLinkorSimple? linkor = null;
int counter = 100;
while (linkor == null)
{
linkor = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (linkor == null)
{
return;
}
FormLinkor form = new()
{
SetLinkor = linkor
};
form.ShowDialog();
}
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RerfreshListBoxItems();
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItems.Count == 0)
{
MessageBox.Show("Нет выбранных элементов");
return;
}
if (MessageBox.Show("Подтвердите удаление коллекции" + listBoxCollection.SelectedItem?.ToString(), "", MessageBoxButtons.YesNo) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString());
_logger.LogInformation($"Удалена коллекция:");
RerfreshListBoxItems();
}
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Создание компании c невыбранной коллекции");
return;
}
ICollectionGenericObjects<DrawningLinkorSimple>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не удалось инициализировать коллекцию");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new LinkorSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Реузльтат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareLinkors(new LinkorCompareByColor());
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareLinkors(new LinkorCompareByType());
}
private void CompareLinkors(IComparer<DrawningLinkorSimple?> comparer)
{
if (comparer == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

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

View File

@@ -0,0 +1,399 @@
namespace Linkor_8
{
partial class FormLinkorConfig
{
/// <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()
{
groupBoxLinkorConfig = new GroupBox();
groupBoxColor = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelGrey = new Panel();
panelBlue = new Panel();
panelWhite = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxHelicopterLandingSite = new CheckBox();
checkBoxStripes = new CheckBox();
checkBoxFlag = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxLinkorConfig.SuspendLayout();
groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxLinkorConfig
//
groupBoxLinkorConfig.Controls.Add(groupBoxColor);
groupBoxLinkorConfig.Controls.Add(checkBoxHelicopterLandingSite);
groupBoxLinkorConfig.Controls.Add(checkBoxStripes);
groupBoxLinkorConfig.Controls.Add(checkBoxFlag);
groupBoxLinkorConfig.Controls.Add(numericUpDownWeight);
groupBoxLinkorConfig.Controls.Add(labelWeight);
groupBoxLinkorConfig.Controls.Add(numericUpDownSpeed);
groupBoxLinkorConfig.Controls.Add(labelSpeed);
groupBoxLinkorConfig.Controls.Add(labelModifiedObject);
groupBoxLinkorConfig.Controls.Add(labelSimpleObject);
groupBoxLinkorConfig.Dock = DockStyle.Left;
groupBoxLinkorConfig.Location = new Point(0, 0);
groupBoxLinkorConfig.Margin = new Padding(3, 2, 3, 2);
groupBoxLinkorConfig.Name = "groupBoxLinkorConfig";
groupBoxLinkorConfig.Padding = new Padding(3, 2, 3, 2);
groupBoxLinkorConfig.Size = new Size(536, 223);
groupBoxLinkorConfig.TabIndex = 0;
groupBoxLinkorConfig.TabStop = false;
groupBoxLinkorConfig.Text = "Параметры";
//
// groupBoxColor
//
groupBoxColor.Controls.Add(panelPurple);
groupBoxColor.Controls.Add(panelYellow);
groupBoxColor.Controls.Add(panelBlack);
groupBoxColor.Controls.Add(panelGrey);
groupBoxColor.Controls.Add(panelBlue);
groupBoxColor.Controls.Add(panelWhite);
groupBoxColor.Controls.Add(panelGreen);
groupBoxColor.Controls.Add(panelRed);
groupBoxColor.Location = new Point(263, 17);
groupBoxColor.Margin = new Padding(3, 2, 3, 2);
groupBoxColor.Name = "groupBoxColor";
groupBoxColor.Padding = new Padding(3, 2, 3, 2);
groupBoxColor.Size = new Size(241, 115);
groupBoxColor.TabIndex = 9;
groupBoxColor.TabStop = false;
groupBoxColor.Text = "Цвета";
//
// panelPurple
//
panelPurple.AllowDrop = true;
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(192, 76);
panelPurple.Margin = new Padding(3, 2, 3, 2);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(35, 30);
panelPurple.TabIndex = 7;
//
// panelYellow
//
panelYellow.AllowDrop = true;
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(192, 27);
panelYellow.Margin = new Padding(3, 2, 3, 2);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(35, 30);
panelYellow.TabIndex = 3;
//
// panelBlack
//
panelBlack.AllowDrop = true;
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(137, 76);
panelBlack.Margin = new Padding(3, 2, 3, 2);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(35, 30);
panelBlack.TabIndex = 6;
//
// panelGrey
//
panelGrey.AllowDrop = true;
panelGrey.BackColor = Color.Gray;
panelGrey.Location = new Point(82, 76);
panelGrey.Margin = new Padding(3, 2, 3, 2);
panelGrey.Name = "panelGrey";
panelGrey.Size = new Size(35, 30);
panelGrey.TabIndex = 5;
//
// panelBlue
//
panelBlue.AllowDrop = true;
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(137, 27);
panelBlue.Margin = new Padding(3, 2, 3, 2);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(35, 30);
panelBlue.TabIndex = 2;
//
// panelWhite
//
panelWhite.AllowDrop = true;
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(24, 76);
panelWhite.Margin = new Padding(3, 2, 3, 2);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(35, 30);
panelWhite.TabIndex = 4;
//
// panelGreen
//
panelGreen.AllowDrop = true;
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(82, 27);
panelGreen.Margin = new Padding(3, 2, 3, 2);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(35, 30);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(24, 27);
panelRed.Margin = new Padding(3, 2, 3, 2);
panelRed.Name = "panelRed";
panelRed.Size = new Size(35, 30);
panelRed.TabIndex = 0;
//
// checkBoxHelicopterLandingSite
//
checkBoxHelicopterLandingSite.AutoSize = true;
checkBoxHelicopterLandingSite.Location = new Point(5, 157);
checkBoxHelicopterLandingSite.Margin = new Padding(3, 2, 3, 2);
checkBoxHelicopterLandingSite.Name = "checkBoxHelicopterLandingSite";
checkBoxHelicopterLandingSite.Size = new Size(256, 19);
checkBoxHelicopterLandingSite.TabIndex = 8;
checkBoxHelicopterLandingSite.Text = "Признак наличия вертолетной площадки";
checkBoxHelicopterLandingSite.UseVisualStyleBackColor = true;
//
// checkBoxStripes
//
checkBoxStripes.AutoSize = true;
checkBoxStripes.Location = new Point(5, 122);
checkBoxStripes.Margin = new Padding(3, 2, 3, 2);
checkBoxStripes.Name = "checkBoxStripes";
checkBoxStripes.Size = new Size(173, 19);
checkBoxStripes.TabIndex = 7;
checkBoxStripes.Text = "Признак наличия полосок";
checkBoxStripes.UseVisualStyleBackColor = true;
//
// checkBoxFlag
//
checkBoxFlag.AutoSize = true;
checkBoxFlag.Location = new Point(5, 85);
checkBoxFlag.Margin = new Padding(3, 2, 3, 2);
checkBoxFlag.Name = "checkBoxFlag";
checkBoxFlag.Size = new Size(159, 19);
checkBoxFlag.TabIndex = 6;
checkBoxFlag.Text = "Признак наличия флага";
checkBoxFlag.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(77, 46);
numericUpDownWeight.Margin = new Padding(3, 2, 3, 2);
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(102, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(5, 46);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(77, 17);
numericUpDownSpeed.Margin = new Padding(3, 2, 3, 2);
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(102, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(5, 17);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(407, 154);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(97, 34);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += labelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(304, 154);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(97, 34);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += labelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(3, 45);
pictureBoxObject.Margin = new Padding(3, 2, 3, 2);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(363, 138);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(559, 190);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(142, 22);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(756, 190);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(142, 22);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(542, 1);
panelObject.Margin = new Padding(3, 2, 3, 2);
panelObject.Name = "panelObject";
panelObject.Size = new Size(369, 185);
panelObject.TabIndex = 4;
panelObject.DragDrop += panelObject_DragDrop;
panelObject.DragEnter += panelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(214, 6);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(97, 34);
labelAdditionalColor.TabIndex = 11;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(17, 6);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(97, 34);
labelBodyColor.TabIndex = 10;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelColor_DragDrop;
labelBodyColor.DragEnter += labelColor_DragEnter;
//
// FormLinkorConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(923, 223);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxLinkorConfig);
Margin = new Padding(3, 2, 3, 2);
Name = "FormLinkorConfig";
Text = "Создание объекта";
groupBoxLinkorConfig.ResumeLayout(false);
groupBoxLinkorConfig.PerformLayout();
groupBoxColor.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 groupBoxLinkorConfig;
private Label labelModifiedObject;
private Label labelSimpleObject;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private CheckBox checkBoxFlag;
private CheckBox checkBoxHelicopterLandingSite;
private CheckBox checkBoxStripes;
private GroupBox groupBoxColor;
private Panel panelRed;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelGrey;
private Panel panelBlue;
private Panel panelWhite;
private Panel panelGreen;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelBodyColor;
}
}

View File

@@ -0,0 +1,114 @@

using Linkor_8.Drawings;
using Linkor_8.Entities;
namespace Linkor_8;
public partial class FormLinkorConfig : Form
{
private DrawningLinkorSimple _linkor;
private event Action<DrawningLinkorSimple> _linkorDelegate;
public FormLinkorConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelGrey.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
public void AddEvent(Action<DrawningLinkorSimple> LinkorDelegate)
{
_linkorDelegate += LinkorDelegate;
}
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
if (sender is Panel p)
{
p?.DoDragDrop(p?.BackColor ?? Color.Transparent, DragDropEffects.Move | DragDropEffects.Copy);
}
}
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_linkor.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_linkor.SetPosition(15, 15);
_linkor.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, 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":
_linkor = new DrawningLinkorSimple((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_linkor = new DrawningLinkor((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxFlag.Checked, checkBoxStripes.Checked, checkBoxHelicopterLandingSite.Checked);
break;
}
DrawObject();
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(typeof(Color)) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_linkor == null || e?.Data == null) return;
var colorData = e.Data.GetData(typeof(Color));
if (colorData is not Color objColor) return;
switch ((sender as Label)?.Name)
{
case "labelBodyColor":
_linkor.Entity_Linkor_Simple?.SetMainColor(objColor);
break;
case "labelAdditionalColor":
(_linkor.Entity_Linkor_Simple as Entity_Linkor)?.SetSecondColor(objColor);
break;
}
DrawObject();
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_linkor != null)
{
_linkorDelegate.Invoke(_linkor);
Close();
}
}
}

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,7 @@
using Linkor_8.Drawings;
namespace Linkor_8
{
public delegate void LinkorDelegate(DrawningLinkorSimple linkor);
}

View File

@@ -8,4 +8,38 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="9.0.5" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.4.0" />
<PackageReference Include="Serilog" Version="4.3.0" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.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,143 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.MovingStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

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

View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.MovingStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.DownBorder + GetStep() >= FieldHeight && objParams.RightBorder + GetStep() >= FieldWidth;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

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

View File

@@ -0,0 +1,71 @@
using Linkor_8.Drawings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.MovingStrategy;
/// <summary>
/// Класс - реализация IMoveableObject с использованием DrawningLinkorSimple
/// </summary>
public class MoveableLinkor : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCar или его наследника
/// </summary>
private readonly DrawningLinkorSimple? _linkor = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="car">Объект класса DrawningCar</param>
public MoveableLinkor(DrawningLinkorSimple linkor)
{
_linkor = linkor;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_linkor == null || _linkor.Entity_Linkor_Simple == null || !_linkor.GetPosX.HasValue || !_linkor.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_linkor.GetPosX.Value, _linkor.GetPosY.Value, _linkor.GetWidth, _linkor.GetHeight);
}
}
public int GetStep => (int)(_linkor?.Entity_Linkor_Simple?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_linkor == null || _linkor.Entity_Linkor_Simple == null)
{
return false;
}
return _linkor.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

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

View File

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

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linkor_8.MovingStrategy;
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@@ -1,3 +1,10 @@
using Linkor_8;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
namespace Linkor_8
{
internal static class Program
@@ -10,8 +17,23 @@ namespace Linkor_8
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ServiceCollection services = new();
ConfigureServices(services);
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormLinkorCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormLinkorCollection>()
.AddLogging(option => {
option.SetMinimumLevel(LogLevel.Debug);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("serilogconfig.json", optional: true, reloadOnChange: true).Build())
.CreateLogger());
});
}
}
}

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -0,0 +1,17 @@
{
"Serilog": {
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "loging/logger.txt",
"rollingInterval": "Day"
}
}
]
}
}