Compare commits

...

6 Commits
master ... lab8

Author SHA1 Message Date
82f8ca24b0 work lab8 2024-06-05 12:08:56 +04:00
9563a3d4e5 work lab6 2024-06-05 12:05:29 +04:00
3cfd932bc1 work lab5 2024-06-05 11:58:04 +04:00
ea5e9c0244 work lab4 2024-06-05 11:57:21 +04:00
9eb2688a38 work lab3 2024-06-05 11:56:17 +04:00
6d9b87416f work lab 2 2024-06-05 11:54:48 +04:00
43 changed files with 3481 additions and 390 deletions

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -0,0 +1,11 @@
using AccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus
{
public delegate void BusDelegate(DrawningBus bus);
}

View File

@ -0,0 +1,71 @@
using AccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public abstract class AbstractCompany
{
protected readonly int _placeSizeWidth = 180;
protected readonly int _placeSizeHeight = 60;
protected readonly int _pictureWidth;
protected readonly int _pictureHeight;
protected ICollectionGenericObjects<DrawningBus?> _collection = null;
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
public AbstractCompany(int picWidth, int picHeigth, ICollectionGenericObjects<DrawningBus> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeigth;
_collection = collection;
_collection.MaxCount = GetMaxCount - 3;
}
public static bool operator +(AbstractCompany company, DrawningBus bus)
{
return company._collection?.Insert(bus, new DrawningBusEqutables()) ?? false;
}
public static bool operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
}
public DrawningBus? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackground(graphics);
for (int i = 0; i < (_collection?.MaxCount ?? 0); i++)
{
DrawningBus? obj = _collection?.Get(i);
if (obj != null) obj.SetPictureSize(_pictureWidth, _pictureHeight);
SetObjectPosition(i, _collection?.MaxCount ?? 0, obj);
obj?.DrawTransport(graphics);
}
return bitmap;
}
public void Sort(IComparer<DrawningBus?> comparer) => _collection?.CollectionSort(comparer);
protected abstract void DrawBackground(Graphics g);
protected abstract void SetObjectPosition(int position, int MaxPos, DrawningBus? bus);
}
}

View File

@ -0,0 +1,47 @@
using AccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public class BusStation : AbstractCompany
{
public BusStation(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBus> collection) : base(picWidth, picHeight, collection)
{
}
Pen black = new Pen(Color.Black);
protected override void DrawBackground(Graphics g)
{
for (int i = _pictureHeight - 1; i >= 0; i -= _placeSizeHeight)
{
g.DrawLine(black, _pictureWidth - ((int)(_pictureWidth / _placeSizeWidth) * _placeSizeWidth), i, _pictureWidth, i);
for (int j = _pictureWidth - 1; j >= 0; j -= _placeSizeWidth)
{
g.DrawLine(black, j, i, j, i - _placeSizeHeight + 20);
}
}
}
protected override void SetObjectPosition(int position, int MaxPos, DrawningBus? bus)
{
if (bus == null) return;
int _levelOfPosition = 0;
int _countPositionInRange = _pictureWidth / _placeSizeWidth;
if (position >= _countPositionInRange)
{
_levelOfPosition = position / _countPositionInRange;
}
if (position >= _countPositionInRange) position %= _countPositionInRange;
bus.SetPosition(_pictureWidth - position * _placeSizeWidth - bus.GetWidth() - (_placeSizeWidth - bus.GetWidth()) / 2,
_pictureHeight - _levelOfPosition * _placeSizeHeight - bus.GetHeigth() - (_placeSizeHeight - bus.GetHeigth()) / 2);
}
}
}

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.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] : "");
}
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,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public enum CollectionType
{
None = 0,
Massive = 1,
List = 2
}
}

View File

@ -0,0 +1,64 @@
using AccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// кол-во элем
/// </summary>
int Count { get; }
/// <summary>
/// макс кол-во элем
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// вставить
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <returns></returns>
bool Insert(T obj, IEqualityComparer<DrawningBus?>? comparer = null);
/// <summary>
/// вставить по позиции
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <param name="position">индекс</param>
/// <returns></returns>
bool Insert(T obj, int position, IEqualityComparer<DrawningBus?>? comparer = null);
/// <summary>
/// удаление
/// </summary>
/// <param name="position">индекс</param>
/// <returns></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();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@ -0,0 +1,107 @@
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
private readonly List<T?> _collection;
private int _maxCount;
public int Count { get { return _collection.Count; } }
public int MaxCount
{
get
{
return _maxCount;
}
set
{
if (value > 0) _maxCount = value;
}
}
public CollectionType GetCollectionType => CollectionType.List;
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
if (position < 0 || position >= _collection.Count || _collection == null || _collection.Count == 0) return null;
return _collection[position];
}
public bool Insert(T obj, IEqualityComparer<DrawningBus?>? comparer = null)
{
if (_collection == null || _collection.Count == _maxCount) throw new CollectionOverflowException(Count);
foreach (var drawningBus in _collection)
{
if (obj is DrawningBus objdr && drawningBus is DrawningBus bus)
{
if (comparer.Equals(objdr, bus)) throw new ObjectExistsException();
}
else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa)
{
if (comparer.Equals(objdra, busa)) throw new ObjectExistsException();
}
}
_collection.Add(obj);
return true;
}
public bool Insert(T obj, int position, IEqualityComparer<DrawningBus?>? comparer = null)
{
if (_collection == null || position < 0 || position > _maxCount) return false;
foreach (var drawningBus in _collection)
{
if (obj is DrawningBus objdr && drawningBus is DrawningBus bus)
{
if (comparer.Equals(objdr, bus)) throw new ObjectExistsException();
}
else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa)
{
if (comparer.Equals(objdra, busa)) throw new ObjectExistsException();
}
}
_collection.Insert(position, obj);
return true;
}
public bool Remove(int position)
{
if (_collection == null || position < 0 || position >= _collection.Count) throw new PozitionOutOfCollectionException(position);
_collection[position] = null;
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,142 @@
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
private T?[] _collection;
public int Count { get { return _collection.Length; } }
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0 && _collection.Length == 0)
{
_collection = new T?[value];
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position < 0 || position >= _collection.Length)
{
throw new PozitionOutOfCollectionException(position);
}
return _collection[position];
}
public bool Insert(T obj, IEqualityComparer<DrawningBus?>? comparer = null)
{
foreach(var drawningBus in _collection)
{
if (obj is DrawningBus objdr && drawningBus is DrawningBus bus)
{
if (comparer.Equals(objdr, bus)) throw new ObjectExistsException();
}
else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa)
{
if (comparer.Equals(objdra, busa)) throw new ObjectExistsException();
}
}
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
throw new CollectionOverflowException(Count);
}
public bool Insert(T obj, int position, IEqualityComparer<DrawningBus?>? comparer = null)
{
if (position < 0 || position >= _collection.Length) throw new PozitionOutOfCollectionException(position);
foreach (var drawningBus in _collection)
{
if (obj is DrawningBus objdr && drawningBus is DrawningBus bus)
{
if (comparer.Equals(objdr, bus)) throw new ObjectExistsException();
}
else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa)
{
if (comparer.Equals(objdra, busa)) throw new ObjectExistsException();
}
}
if (_collection[position] == null)
{
_collection[position] = obj;
return true;
}
else
{
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(Count);
}
public bool Remove(int position)
{
if (position < 0 || position >= _collection.Length) throw new PozitionOutOfCollectionException(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,166 @@
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public class StorageCollection<T>
where T: DrawningBus
{
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storage;
public List<CollectionInfo> Keys => _storage.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItem = ";";
public StorageCollection()
{
_storage = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
public void AddCollection(string name, CollectionType collectionType)
{
CollectionInfo info = new CollectionInfo(name, collectionType, "");
if (_storage.ContainsKey(info) || info.Name == "") return;
_storage[info] = CreateCollection(info.CollectionType);
}
public void DelCollection(string name)
{
_storage.Remove(new CollectionInfo(name, CollectionType.None, ""));
}
public ICollectionGenericObjects<T>? this[string name]
{
get
{
if (!_storage.ContainsKey(new CollectionInfo(name, CollectionType.None, ""))) return null;
return _storage[new CollectionInfo(name, CollectionType.None, "")];
}
}
public void SaveData(string filename)
{
if (_storage.Count == 0)
{
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storage)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
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(_separatorItem);
}
writer.Write(sb);
}
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader reader = File.OpenText(filename))
{
string str = reader.ReadLine();
if (str == null || str.Length == 0)
{
throw new InvalidOperationException("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new InvalidOperationException("В файле не верные данные");
}
_storage.Clear();
string strs = "";
while ((strs = reader.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new InvalidOperationException("Не удалось определить информацию об коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBus() is T bus)
{
try
{
if (!collection.Insert(bus))
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[2]);
}
}
catch(ObjectExistsException ex)
{
throw new InvalidOperationException(ex.Message);
}
catch (CollectionOverflowException ex)
{
throw new InvalidOperationException("Коллекция переполнена", ex);
}
}
}
_storage.Add(collectionInfo, collection);
}
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}
}

View File

@ -1,284 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus
{
/// <summary>
/// Класс, отвечающий за перемещение и прорисовку объекта-сущности
/// </summary>
public class DrawningAccordionBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAccordionBus? EntityAccordionBus { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWeight;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки авто
/// </summary>
private int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки авто
/// </summary>
private int? _startPosY;
/// <summary>
/// Ширина прорисовки авто
/// </summary>
private readonly int _drawningBusWeight = 130;
/// <summary>
/// Высота прорисовки авто
/// </summary>
private readonly int _drawningBusHeight = 20;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="threeDoors"></param>
/// <param name="fourDoors"></param>
/// <param name="fiveDoors"></param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool onePart, bool fiveDoors)
{
EntityAccordionBus = new EntityAccordionBus();
EntityAccordionBus.Init(speed, weight, bodyColor, additionalColor, onePart, fiveDoors);
_pictureWeight = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="weight">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>true - границы заданы, false - проверка не пройдена</returns>
public bool SetPictureSize(int weight, int height)
{
if (weight < _drawningBusWeight || height < _drawningBusHeight)
{
return false;
}
_pictureWeight = weight;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosX.Value + _drawningBusWeight > _pictureWeight)
{
_startPosX -= _startPosX.Value + _drawningBusWeight - _pictureWeight;
}
else if (_startPosY.HasValue && _startPosY.Value + _drawningBusHeight > _pictureHeight)
{
_startPosY -= _startPosY.Value + _drawningBusHeight - _pictureHeight;
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWeight.HasValue)
{
return;
}
if (x + _drawningBusWeight > _pictureWeight)
{
_startPosX = x - ( x + _drawningBusWeight - _pictureWeight);
}
else if (x < 0)
{
_startPosX = 0;
}
else
{
_startPosX = x;
}
if (y + _drawningBusHeight > _pictureHeight)
{
_startPosY = y - ( y + _drawningBusHeight - _pictureHeight);
}
else if (y < 0)
{
_startPosY = 0;
}
else
{
_startPosY = y;
}
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещение выполнено, false - перемещение невозможнор</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityAccordionBus == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX.Value - EntityAccordionBus.Step > 0)
{
_startPosX -= (int)EntityAccordionBus.Step;
}
else
{
_startPosX = 0;
}
return true;
case DirectionType.Right:
if (_startPosX.Value + EntityAccordionBus.Step + _drawningBusWeight < _pictureWeight)
{
_startPosX += (int)EntityAccordionBus.Step;
}
else
{
_startPosX = _pictureWeight - _drawningBusWeight;
}
return true;
case DirectionType.Up:
if (_startPosY.Value - EntityAccordionBus.Step > 0)
{
_startPosY -= (int)EntityAccordionBus.Step;
}
else
{
_startPosY = 0;
}
return true;
case DirectionType.Down:
if (_startPosY.Value + EntityAccordionBus.Step + _drawningBusHeight < _pictureHeight)
{
_startPosY += (int)EntityAccordionBus.Step;
}
else
{
_startPosY = _pictureHeight - _drawningBusHeight;
}
return true;
default:
return false;
}
}
/// <summary>
/// Отрисовка транспорта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntityAccordionBus == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityAccordionBus.AdditionalColor);
//корпус
Brush br = new SolidBrush(EntityAccordionBus.BodyColor);
g.FillRectangle(br, _startPosX.Value, _startPosY.Value, 60, 15);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 60, 15);
//колёса
Brush brWhite = new SolidBrush(Color.White);
g.FillEllipse(brWhite, _startPosX.Value + 5, _startPosY.Value + 10, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 40, _startPosY.Value + 10, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 40, _startPosY.Value + 10, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 10, 10, 10);
//стёкла
Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBlue, _startPosX.Value + 2, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 2, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 12, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 12, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 32, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 32, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 42, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 42, _startPosY.Value + 3, 5, 5);
//дверь
g.FillRectangle(additionalBrush, _startPosX.Value + 20, _startPosY.Value + 5, 5, 10);
g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 5, 5, 10);
if (!EntityAccordionBus.OnePart)
{
//корпус
g.FillRectangle(br, _startPosX.Value + 70, _startPosY.Value, 60, 15);
g.DrawRectangle(pen, _startPosX.Value + 70, _startPosY.Value, 60, 15);
//колёса
g.FillEllipse(brWhite, _startPosX.Value + 75, _startPosY.Value + 10, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 110, _startPosY.Value + 10, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 110, _startPosY.Value + 10, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 75, _startPosY.Value + 10, 10, 10);
//стёкла
g.FillRectangle(brBlue, _startPosX.Value + 72, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 72, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 82, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 82, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 92, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 92, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 102, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 102, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 112, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 112, _startPosY.Value + 3, 5, 5);
//гормошка
g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value, _startPosX.Value + 62, _startPosY.Value + 3);
g.DrawLine(pen, _startPosX.Value + 62, _startPosY.Value + 3, _startPosX.Value + 65, _startPosY.Value);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value, _startPosX.Value + 67, _startPosY.Value + 3);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value + 3, _startPosX.Value + 70, _startPosY.Value);
g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 15, _startPosX.Value + 62, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 62, _startPosY.Value + 12, _startPosX.Value + 65, _startPosY.Value + 15);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value + 15, _startPosX.Value + 67, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value + 12, _startPosX.Value + 70, _startPosY.Value + 15);
g.DrawLine(pen, _startPosX.Value + 62, _startPosY.Value + 3, _startPosX.Value + 62, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value + 3, _startPosX.Value + 67, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value, _startPosX.Value + 65, _startPosY.Value + 15);
//двери
g.FillRectangle(additionalBrush, _startPosX.Value + 123, _startPosY.Value + 5, 5, 10);
g.DrawRectangle(pen, _startPosX.Value + 123, _startPosY.Value + 5, 5, 10);
if (EntityAccordionBus.FiveDoors)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 87, _startPosY.Value + 9, 21, 5);
g.DrawRectangle(pen, _startPosX.Value + 87, _startPosY.Value + 9, 21, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 53, _startPosY.Value + 5, 5, 10);
g.DrawRectangle(pen, _startPosX.Value + 53, _startPosY.Value + 5, 5, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 27, _startPosY.Value + 9, 11, 5);
g.DrawRectangle(pen, _startPosX.Value + 27, _startPosY.Value + 9, 11, 5);
}
}
}
}
}

View File

@ -4,13 +4,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus
namespace AccordionBus.Drawnings
{
/// <summary>
/// Направление премещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Entities;
namespace AccordionBus.Drawnings
{
/// <summary>
/// Класс, отвечающий за перемещение и прорисовку объекта-сущности
/// </summary>
public class DrawningAccordionBus : DrawningBus
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="hatch"></param>
/// <param name="fiveDoors"></param>
public DrawningAccordionBus(int speed, double weight, Color bodyColor, Color
additionalColor, bool hatch, bool fiveDoors): base(130, 20)
{
EntityBus = new EntityAccordionBus(speed, weight, bodyColor, additionalColor, hatch, fiveDoors);
}
public DrawningAccordionBus(EntityAccordionBus bus) : base(130, 20)
{
EntityBus = bus;
}
/// <summary>
/// Отрисовка транспорта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityBus == null || EntityBus is not EntityAccordionBus accordionBus || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
base.DrawTransport(g);
Pen pen = new(Color.Black);
Brush brWhite = new SolidBrush(Color.White);
Brush br = new SolidBrush(accordionBus.BodyColor);
Brush brBlue = new SolidBrush(Color.LightBlue);
Brush additionalBrush = new SolidBrush(accordionBus.AdditionalColor);
//корпус
g.FillRectangle(br, _startPosX.Value + 70, _startPosY.Value, 60, 15);
g.DrawRectangle(pen, _startPosX.Value + 70, _startPosY.Value, 60, 15);
//колёса
g.FillEllipse(brWhite, _startPosX.Value + 75, _startPosY.Value + 10, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 110, _startPosY.Value + 10, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 110, _startPosY.Value + 10, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 75, _startPosY.Value + 10, 10, 10);
//стёкла
g.FillRectangle(brBlue, _startPosX.Value + 72, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 72, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 82, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 82, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 92, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 92, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 102, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 102, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 112, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 112, _startPosY.Value + 3, 5, 5);
//гормошка
g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value, _startPosX.Value + 62, _startPosY.Value + 3);
g.DrawLine(pen, _startPosX.Value + 62, _startPosY.Value + 3, _startPosX.Value + 65, _startPosY.Value);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value, _startPosX.Value + 67, _startPosY.Value + 3);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value + 3, _startPosX.Value + 70, _startPosY.Value);
g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 15, _startPosX.Value + 62, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 62, _startPosY.Value + 12, _startPosX.Value + 65, _startPosY.Value + 15);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value + 15, _startPosX.Value + 67, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value + 12, _startPosX.Value + 70, _startPosY.Value + 15);
g.DrawLine(pen, _startPosX.Value + 62, _startPosY.Value + 3, _startPosX.Value + 62, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value + 3, _startPosX.Value + 67, _startPosY.Value + 12);
g.DrawLine(pen, _startPosX.Value + 65, _startPosY.Value, _startPosX.Value + 65, _startPosY.Value + 15);
//двери
g.FillRectangle(additionalBrush, _startPosX.Value + 123, _startPosY.Value + 5, 5, 10);
g.DrawRectangle(pen, _startPosX.Value + 123, _startPosY.Value + 5, 5, 10);
if (accordionBus.FiveDoors)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 87, _startPosY.Value + 9, 21, 5);
g.DrawRectangle(pen, _startPosX.Value + 87, _startPosY.Value + 9, 21, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 53, _startPosY.Value + 5, 5, 10);
g.DrawRectangle(pen, _startPosX.Value + 53, _startPosY.Value + 5, 5, 10);
g.FillRectangle(additionalBrush, _startPosX.Value + 27, _startPosY.Value + 9, 11, 5);
g.DrawRectangle(pen, _startPosX.Value + 27, _startPosY.Value + 9, 11, 5);
}
//люки
if (accordionBus.Hatch)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 10, _startPosY.Value - 3, 10, 3);
g.FillRectangle(additionalBrush, _startPosX.Value + 90, _startPosY.Value - 3, 10, 3);
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value - 3, 10, 3);
g.DrawRectangle(pen, _startPosX.Value + 90, _startPosY.Value - 3, 10, 3);
}
}
}
}

View File

@ -0,0 +1,271 @@
using AccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawnings
{
public class DrawningBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBus? EntityBus { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWeight;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeigth;
/// <summary>
/// Левая координата прорисовки авто
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя координата прорисовки авто
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки авто
/// </summary>
private readonly int _drawningBusWeight = 60;
/// <summary>
/// Высота прорисовки авто
/// </summary>
private readonly int _drawningBusHeigth = 20;
/// <summary>
/// Координата Х объекта
/// </summary>
/// <returns></returns>
public int? GetPosX() => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
/// <returns></returns>
public int? GetPosY() => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
/// <returns></returns>
public int GetWidth() => _drawningBusWeight;
/// <summary>
/// Высота объекта
/// </summary>
/// <returns></returns>
public int GetHeigth() => _drawningBusHeigth;
/// <summary>
/// Пустой конструктор
/// </summary>
public DrawningBus()
{
_pictureWeight = null;
_pictureHeigth = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор границ объекта
/// </summary>
/// <param name="drawningBusWeight">Ширина</param>
/// <param name="drawningBusHeight">Высота</param>
protected DrawningBus(int drawningBusWeight, int drawningBusHeight) : this()
{
_drawningBusWeight = drawningBusWeight;
_drawningBusHeigth = drawningBusHeight;
}
/// <summary>
/// Конструктор пораметров
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningBus(int speed, double weight, Color bodyColor) : this()
{
EntityBus = new EntityBus(speed, weight, bodyColor);
}
public DrawningBus(EntityBus bus)
{
EntityBus = bus;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина</param>
/// <param name="heigth">Высота</param>
/// <returns>true - границы заданы, false - проверка не пройдена</returns>
public bool SetPictureSize(int width, int heigth)
{
if (width < _drawningBusWeight || heigth < _drawningBusHeigth)
{
return false;
}
_pictureWeight = width;
_pictureHeigth = heigth;
if (_startPosX.HasValue && _startPosX.Value + _drawningBusWeight > _pictureWeight)
{
_startPosX -= _startPosX.Value + _drawningBusWeight - _pictureWeight;
}
else if (_startPosY.HasValue && _startPosY.Value + _drawningBusHeigth > _pictureHeigth)
{
_startPosY -= _startPosY.Value + _drawningBusHeigth - _pictureHeigth;
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeigth.HasValue || !_pictureWeight.HasValue)
{
return;
}
if (x + _drawningBusWeight > _pictureWeight)
{
_startPosX = x - (x + _drawningBusWeight - _pictureWeight);
}
else if (x < 0)
{
_startPosX = 0;
}
else
{
_startPosX = x;
}
if (y + _drawningBusHeigth > _pictureHeigth)
{
_startPosY = y - (y + _drawningBusHeigth - _pictureHeigth);
}
else if (y < 0)
{
_startPosY = 0;
}
else
{
_startPosY = y;
}
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещение выполнено, false - перемещение невозможнор</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityBus == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX.Value - EntityBus.Step > 0)
{
_startPosX -= (int)EntityBus.Step;
}
else
{
_startPosX = 0;
}
return true;
case DirectionType.Right:
if (_startPosX.Value + EntityBus.Step + _drawningBusWeight < _pictureWeight)
{
_startPosX += (int)EntityBus.Step;
}
else
{
_startPosX = _pictureWeight - _drawningBusWeight;
}
return true;
case DirectionType.Up:
if (_startPosY.Value - EntityBus.Step > 0)
{
_startPosY -= (int)EntityBus.Step;
}
else
{
_startPosY = 0;
}
return true;
case DirectionType.Down:
if (_startPosY.Value + EntityBus.Step + _drawningBusHeigth < _pictureHeigth)
{
_startPosY += (int)EntityBus.Step;
}
else
{
_startPosY = _pictureHeigth - _drawningBusHeigth;
}
return true;
default:
return false;
}
}
/// <summary>
/// Отрисовка транспорта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityBus == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush brDoor = new SolidBrush(Color.Gray);
//корпус
Brush br = new SolidBrush(EntityBus.BodyColor);
g.FillRectangle(br, _startPosX.Value, _startPosY.Value, 60, 15);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 60, 15);
//колёса
Brush brWhite = new SolidBrush(Color.White);
g.FillEllipse(brWhite, _startPosX.Value + 5, _startPosY.Value + 10, 10, 10);
g.FillEllipse(brWhite, _startPosX.Value + 40, _startPosY.Value + 10, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 40, _startPosY.Value + 10, 10, 10);
g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 10, 10, 10);
//стёкла
Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBlue, _startPosX.Value + 2, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 2, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 12, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 12, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 32, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 32, _startPosY.Value + 3, 5, 5);
g.FillRectangle(brBlue, _startPosX.Value + 42, _startPosY.Value + 3, 5, 5);
g.DrawRectangle(pen, _startPosX.Value + 42, _startPosY.Value + 3, 5, 5);
//дверь
g.FillRectangle(brDoor, _startPosX.Value + 20, _startPosY.Value + 5, 5, 10);
g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 5, 5, 10);
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawnings
{
public class DrawningBusCompareByColor : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityBus == null) return 1;
if (y == null || y.EntityBus == null) return -1;
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
var redCompare = x.EntityBus.BodyColor.R.CompareTo(y.EntityBus.BodyColor.R);
if (redCompare != 0) return redCompare;
var blueCompare = x.EntityBus.BodyColor.B.CompareTo(y.EntityBus.BodyColor.B);
if (blueCompare != 0) return blueCompare;
return x.EntityBus.BodyColor.G.CompareTo(y.EntityBus.BodyColor.G);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0) return speedCompare;
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawnings
{
public class DrawningBusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityBus == null) return 1;
if (y == null || y.EntityBus == null) return -1;
if (x.GetType().Name != y.GetType().Name) return x.GetType().Name.CompareTo(y.GetType().Name);
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0) return speedCompare;
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}
}

View File

@ -0,0 +1,47 @@
using AccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawnings
{
public class DrawningBusEqutables : IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null) return false;
if (y == null || y.EntityBus == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.EntityBus.Speed != y.EntityBus.Speed) return false;
if (x.EntityBus.Weight != y.EntityBus.Weight) return false;
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor) return false;
if (x is DrawningAccordionBus xa && y is DrawningAccordionBus ya)
{
if (xa.EntityBus is EntityAccordionBus ex && ya.EntityBus is EntityAccordionBus ey)
{
if (ex.AdditionalColor != ey.AdditionalColor) return false;
if (ex.FiveDoors != ey.FiveDoors) return false;
if (ex.Hatch != ey.Hatch) return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus? obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,51 @@
using AccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawnings
{
public static class ExtentionDrawningBus
{
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строк характеристик
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningBus? CreateDrawningBus(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityBus? bus = EntityAccordionBus.CreateEntityAccordionBus(strs);
if (bus != null && bus is EntityAccordionBus busA)
{
return new DrawningAccordionBus(busA);
}
bus = EntityBus.CreateEntityBus(strs);
if (bus != null)
{
return new DrawningBus(bus);
}
return null;
}
/// <summary>
/// Подготовка данных для сохранения в файл
/// </summary>
/// <param name="drawningBus"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningBus drawningBus)
{
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
if (array == null) { return string.Empty; }
return string.Join(_separatorForObject, array);
}
}
}

View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Entities
{
/// <summary>
/// класс-сущность "автобус с гормошкой"
/// </summary>
public class EntityAccordionBus : EntityBus
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Одна часть
/// </summary>
public bool Hatch { get; set; }
/// <summary>
/// 5 дверей
/// </summary>
public bool FiveDoors { get; set; }
/// <summary>
/// инициализация полей объекта-класса
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="hatch">1 часть</param>
/// <param name="fiveDoors">5 дверей</param>
public EntityAccordionBus(int speed, double weight, Color bodyColor,
Color additionalColor, bool hatch, bool fiveDoors) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Hatch = hatch;
FiveDoors = fiveDoors;
}
/// <summary>
/// Новый дополнительный цвет
/// </summary>
/// <param name="color"></param>
public void SetAdditionalColor(Color color) { AdditionalColor = color; }
/// <summary>
/// Получение строк характеристик
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAccordionBus), Speed.ToString(), Weight.ToString(), BodyColor.Name,
AdditionalColor.Name, Hatch.ToString(), FiveDoors.ToString() };
}
/// <summary>
/// Создание объекта по строкам характеристик
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAccordionBus? CreateEntityAccordionBus(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAccordionBus)) { return null; }
return new EntityAccordionBus(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]),
Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}
}

View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Entities
{
/// <summary>
/// класс-сущность "Автобус"
/// </summary>
public class EntityBus
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityBus(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Новый основной цвет
/// </summary>
/// <param name="color"></param>
public void SetBodyColor(Color color) { BodyColor = color; }
/// <summary>
/// Получение строк характеристик
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityBus), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта по строкам характеристик
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBus? CreateEntityBus(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityBus)) { return null; }
return new EntityBus(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}
}

View File

@ -1,63 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus
{
/// <summary>
/// класс-сущность "автобус с гормошкой"
/// </summary>
public class EntityAccordionBus
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Одна часть
/// </summary>
public bool OnePart { get; set; }
/// <summary>
/// 5 дверей
/// </summary>
public bool FiveDoors { get; set; }
/// <summary>
/// Шаг
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// инициализация полей объекта-класса
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="threeDoors">3 двери</param>
/// <param name="fourDoors">4 двери</param>
/// <param name="fiveDoors">5 дверей</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool onePart, bool fiveDoors)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
OnePart = onePart;
FiveDoors = fiveDoors;
}
}
}

View File

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

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 AccordionBus.Exceptions
{
public class ObjectExistsException : ApplicationException
{
public ObjectExistsException() : base("Такой объект уже есть в соллекции") { }
public ObjectExistsException(string message) : base(message) { }
public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
public ObjectExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Exceptions
{
[Serializable]
public 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 context) : base(info, context) { }
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Exceptions
{
[Serializable]
public class PozitionOutOfCollectionException : ApplicationException
{
public PozitionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PozitionOutOfCollectionException() : base() { }
public PozitionOutOfCollectionException(string message) : base(message) { }
public PozitionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PozitionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -29,42 +29,32 @@
private void InitializeComponent()
{
pictureBoxAccordionBus = new PictureBox();
buttonCreate = new Button();
ButtonUp = new Button();
ButtonRight = new Button();
ButtonLeft = new Button();
ButtonDown = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStap = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit();
SuspendLayout();
//
// pictureBoxAccordionBus
//
pictureBoxAccordionBus.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
pictureBoxAccordionBus.Dock = DockStyle.Fill;
pictureBoxAccordionBus.Location = new Point(0, 0);
pictureBoxAccordionBus.Name = "pictureBoxAccordionBus";
pictureBoxAccordionBus.Size = new Size(882, 453);
pictureBoxAccordionBus.Size = new Size(1182, 653);
pictureBoxAccordionBus.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxAccordionBus.TabIndex = 0;
pictureBoxAccordionBus.TabStop = false;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 412);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// ButtonUp
//
ButtonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
ButtonUp.BackgroundImage = Properties.Resources.buttUp;
ButtonUp.BackgroundImageLayout = ImageLayout.Stretch;
ButtonUp.ImageAlign = ContentAlignment.MiddleLeft;
ButtonUp.Location = new Point(773, 375);
ButtonUp.Location = new Point(1073, 575);
ButtonUp.Name = "ButtonUp";
ButtonUp.Size = new Size(30, 30);
ButtonUp.TabIndex = 2;
@ -77,7 +67,7 @@
ButtonRight.BackgroundImage = Properties.Resources.buttRIght;
ButtonRight.BackgroundImageLayout = ImageLayout.Stretch;
ButtonRight.ImageAlign = ContentAlignment.MiddleLeft;
ButtonRight.Location = new Point(809, 411);
ButtonRight.Location = new Point(1109, 611);
ButtonRight.Name = "ButtonRight";
ButtonRight.Size = new Size(30, 30);
ButtonRight.TabIndex = 3;
@ -90,7 +80,7 @@
ButtonLeft.BackgroundImage = Properties.Resources.buttLeft;
ButtonLeft.BackgroundImageLayout = ImageLayout.Stretch;
ButtonLeft.ImageAlign = ContentAlignment.MiddleLeft;
ButtonLeft.Location = new Point(737, 411);
ButtonLeft.Location = new Point(1037, 611);
ButtonLeft.Name = "ButtonLeft";
ButtonLeft.Size = new Size(30, 30);
ButtonLeft.TabIndex = 4;
@ -103,23 +93,44 @@
ButtonDown.BackgroundImage = Properties.Resources.buttDown;
ButtonDown.BackgroundImageLayout = ImageLayout.Stretch;
ButtonDown.ImageAlign = ContentAlignment.MiddleLeft;
ButtonDown.Location = new Point(773, 411);
ButtonDown.Location = new Point(1073, 611);
ButtonDown.Name = "ButtonDown";
ButtonDown.Size = new Size(30, 30);
ButtonDown.TabIndex = 5;
ButtonDown.UseVisualStyleBackColor = true;
ButtonDown.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(988, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStap
//
buttonStrategyStap.Location = new Point(1061, 46);
buttonStrategyStap.Name = "buttonStrategyStap";
buttonStrategyStap.Size = new Size(78, 29);
buttonStrategyStap.TabIndex = 8;
buttonStrategyStap.Text = "Шаг";
buttonStrategyStap.UseVisualStyleBackColor = true;
buttonStrategyStap.Click += buttonStrategyStap_Click;
//
// FormAccordionBus
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
ClientSize = new Size(1182, 653);
Controls.Add(buttonStrategyStap);
Controls.Add(comboBoxStrategy);
Controls.Add(ButtonDown);
Controls.Add(ButtonLeft);
Controls.Add(ButtonRight);
Controls.Add(ButtonUp);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxAccordionBus);
Name = "FormAccordionBus";
StartPosition = FormStartPosition.CenterScreen;
@ -132,10 +143,11 @@
#endregion
private PictureBox pictureBoxAccordionBus;
private Button buttonCreate;
private Button ButtonUp;
private Button ButtonRight;
private Button ButtonLeft;
private Button ButtonDown;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStap;
}
}

View File

@ -7,44 +7,48 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AccordionBus.Drawnings;
using AccordionBus.MovementStrategy;
namespace AccordionBus
{
public partial class FormAccordionBus : Form
{
private DrawningAccordionBus? _drawningAccordionBus;
private DrawningBus? _drawningBus;
private AbstractStrategy? _strategy;
public DrawningBus SetBus
{
set
{
_drawningBus = value;
_drawningBus.SetPictureSize(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
public FormAccordionBus()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
{
if (_drawningAccordionBus == null)
if (_drawningBus == null)
{
return;
}
Bitmap bmp = new(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningAccordionBus.DrawTransport(gr);
_drawningBus.DrawTransport(gr);
pictureBoxAccordionBus.Image = bmp;
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawningAccordionBus = new DrawningAccordionBus();
_drawningAccordionBus.Init(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)),
Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningAccordionBus.SetPictureSize(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
_drawningAccordionBus.SetPosition(random.Next(50, 300), random.Next(50, 300));
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningAccordionBus == null)
if (_drawningBus == null)
{
return;
}
@ -54,16 +58,16 @@ namespace AccordionBus
switch (name)
{
case "ButtonUp":
result = _drawningAccordionBus.MoveTransport(DirectionType.Up);
result = _drawningBus.MoveTransport(DirectionType.Up);
break;
case "ButtonDown":
result = _drawningAccordionBus.MoveTransport(DirectionType.Down);
result = _drawningBus.MoveTransport(DirectionType.Down);
break;
case "ButtonLeft":
result = _drawningAccordionBus.MoveTransport(DirectionType.Left);
result = _drawningBus.MoveTransport(DirectionType.Left);
break;
case "ButtonRight":
result = _drawningAccordionBus.MoveTransport(DirectionType.Right);
result = _drawningBus.MoveTransport(DirectionType.Right);
break;
}
@ -72,5 +76,32 @@ namespace AccordionBus
Draw();
}
}
private void buttonStrategyStap_Click(object sender, EventArgs e)
{
if (_drawningBus == null) return;
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null
};
if (_strategy == null) return;
_strategy.SetData(new MoveableBus(_drawningBus), pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
}
if (_strategy == null) return;
comboBoxStrategy.Enabled = false;
_strategy.MakeStap();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

View File

@ -0,0 +1,369 @@
namespace AccordionBus
{
partial class FormBusCollection
{
/// <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();
buttonCreateCompany = new Button();
comboBoxSelectedCompany = new ComboBox();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
panelTools = new Panel();
buttonAddBus = new Button();
buttonRefresh = new Button();
maskedTextBox = new MaskedTextBox();
buttonGoToCheck = new Button();
buttonRemoveBus = new Button();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout();
panelTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(comboBoxSelectedCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(panelTools);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(948, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(234, 801);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(12, 361);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(207, 29);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += buttonCreateCompany_Click;
//
// comboBoxSelectedCompany
//
comboBoxSelectedCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectedCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectedCompany.FormattingEnabled = true;
comboBoxSelectedCompany.Items.AddRange(new object[] { "Станция" });
comboBoxSelectedCompany.Location = new Point(12, 327);
comboBoxSelectedCompany.Name = "comboBoxSelectedCompany";
comboBoxSelectedCompany.Size = new Size(207, 28);
comboBoxSelectedCompany.TabIndex = 0;
comboBoxSelectedCompany.SelectedIndexChanged += comboBoxSelectedCompany_SelectedIndexChanged;
//
// 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, 23);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(228, 291);
panelStorage.TabIndex = 8;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(9, 241);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(207, 29);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += buttonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.Location = new Point(9, 131);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(207, 104);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(9, 96);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(207, 29);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += buttonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(125, 66);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(22, 66);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(9, 33);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(207, 27);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(40, 10);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(155, 20);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
//
// panelTools
//
panelTools.Controls.Add(buttonSortByColor);
panelTools.Controls.Add(buttonSortByType);
panelTools.Controls.Add(buttonAddBus);
panelTools.Controls.Add(buttonRefresh);
panelTools.Controls.Add(maskedTextBox);
panelTools.Controls.Add(buttonGoToCheck);
panelTools.Controls.Add(buttonRemoveBus);
panelTools.Dock = DockStyle.Bottom;
panelTools.Enabled = false;
panelTools.Location = new Point(3, 396);
panelTools.Name = "panelTools";
panelTools.Size = new Size(228, 402);
panelTools.TabIndex = 7;
//
// buttonAddBus
//
buttonAddBus.Location = new Point(9, 13);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(207, 54);
buttonAddBus.TabIndex = 1;
buttonAddBus.Text = "Добавить автобус";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += buttonAddBus_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(9, 226);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(207, 54);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(9, 73);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(207, 27);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(9, 166);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(207, 54);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += buttonGoToCheck_Click;
//
// buttonRemoveBus
//
buttonRemoveBus.Location = new Point(9, 106);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(207, 54);
buttonRemoveBus.TabIndex = 4;
buttonRemoveBus.Text = "Удалить автобус";
buttonRemoveBus.UseVisualStyleBackColor = true;
buttonRemoveBus.Click += buttonRemoveBus_Click;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(948, 801);
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.Size = new Size(1182, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(9, 346);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(207, 54);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортирока по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(9, 286);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(207, 54);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1182, 829);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormBusCollection";
StartPosition = FormStartPosition.CenterScreen;
Text = "Коллекция автобусов";
groupBoxTools.ResumeLayout(false);
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectedCompany;
private Button buttonAddBus;
private PictureBox pictureBox;
private Button buttonRemoveBus;
private MaskedTextBox maskedTextBox;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Panel panelTools;
private Panel panelStorage;
private Label labelCollectionName;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private RadioButton radioButtonList;
private Button buttonCollectionAdd;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Button buttonCreateCompany;
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,276 @@
using AccordionBus.CollectionGenericObjects;
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccordionBus
{
public partial class FormBusCollection : Form
{
private StorageCollection<DrawningBus> _storageCollection;
private AbstractCompany? _company = null;
private readonly ILogger _logger;
public FormBusCollection(ILogger<FormBusCollection> logger)
{
InitializeComponent();
_storageCollection = new StorageCollection<DrawningBus>();
_logger = logger;
}
private void comboBoxSelectedCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelTools.Enabled = false;
}
private void buttonAddBus_Click(object sender, EventArgs e)
{
FormBusConfig form = new FormBusConfig();
form.Show();
form.AddEvent(SetCar);
}
private void SetCar(DrawningBus bus)
{
if (_company == null || bus == null) return;
bus.SetPictureSize(pictureBox.Width, pictureBox.Height);
try
{
if (_company + bus)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен в коллекцию, " + bus.GetDataForSave());
}
}
catch (ObjectExistsException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {message}", ex.Message);
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {message}", ex.Message);
}
}
private void buttonRemoveBus_Click(object sender, EventArgs e)
{
if (_company == null || string.IsNullOrEmpty(maskedTextBox.Text)) return;
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos)
{
MessageBox.Show("Объект удалён");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект по позиции {0} удалён", pos);
}
}
catch (PozitionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект. Не верно указана позиция");
_logger.LogError("Ошибка: {message}", ex.Message);
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект, его не существует");
_logger.LogError("Ошибка: {message}", ex.Message);
}
}
private void buttonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null) return;
DrawningBus? bus = null;
int counter = 100;
try
{
while (bus == null && counter > 0)
{
bus = _company.GetRandomObject();
counter--;
}
}
catch (PozitionOutOfCollectionException ex)
{
_logger.LogError("Ошибка: {message}", ex.Message);
}
if (bus == null) return;
FormAccordionBus form = new()
{
SetBus = bus
};
form.ShowDialog();
bus.SetPictureSize(pictureBox.Width, pictureBox.Height);
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
if (_company == null) return;
pictureBox.Image = _company.Show();
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonMassive.Checked && !radioButtonList.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("Добавлена новая коллекция {0}", textBoxCollectionName.Text);
textBoxCollectionName.Text = "";
RefreshListBoxItems();
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItem == null) return;
if (MessageBox.Show("Вы действительно хотите удалить выбранный элемент?",
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
MessageBox.Show("Компания удалена");
_logger.LogInformation("Компания удалена");
}
else
{
MessageBox.Show("Не удалось удалить компанию");
_logger.LogError("Ошибка: не удалось удалить компанию");
}
}
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Компания не выбрана");
return;
}
ICollectionGenericObjects<DrawningBus?> collection =
_storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Компания не инициализирована");
return;
}
switch (comboBoxSelectedCompany.Text)
{
case "Станция":
_company = new BusStation(pictureBox.Width, pictureBox.Height, collection);
pictureBox.Image = _company.Show();
break;
}
panelTools.Enabled = true;
}
private void RefreshListBoxItems()
{
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 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);
}
}
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {message}", ex.Message);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareBuses(new DrawningBusCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareBuses(new DrawningBusCompareByColor());
}
private void CompareBuses(IComparer<DrawningBus?> comparer)
{
if (_company == 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,368 @@
namespace AccordionBus
{
partial class FormBusConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfig = new GroupBox();
groupBoxColor = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxFiveDoors = new CheckBox();
checkBoxHatch = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfig.SuspendLayout();
groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(groupBoxColor);
groupBoxConfig.Controls.Add(checkBoxFiveDoors);
groupBoxConfig.Controls.Add(checkBoxHatch);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Controls.Add(labelModifiedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(493, 229);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// groupBoxColor
//
groupBoxColor.Controls.Add(panelPurple);
groupBoxColor.Controls.Add(panelBlack);
groupBoxColor.Controls.Add(panelGray);
groupBoxColor.Controls.Add(panelWhite);
groupBoxColor.Controls.Add(panelYellow);
groupBoxColor.Controls.Add(panelBlue);
groupBoxColor.Controls.Add(panelGreen);
groupBoxColor.Controls.Add(panelRed);
groupBoxColor.Location = new Point(221, 17);
groupBoxColor.Name = "groupBoxColor";
groupBoxColor.Size = new Size(262, 147);
groupBoxColor.TabIndex = 8;
groupBoxColor.TabStop = false;
groupBoxColor.Text = "Цвета";
//
// panelPurple
//
panelPurple.AllowDrop = true;
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(205, 90);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(35, 35);
panelPurple.TabIndex = 6;
//
// panelBlack
//
panelBlack.AllowDrop = true;
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(143, 90);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(35, 35);
panelBlack.TabIndex = 1;
//
// panelGray
//
panelGray.AllowDrop = true;
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(77, 90);
panelGray.Name = "panelGray";
panelGray.Size = new Size(35, 35);
panelGray.TabIndex = 5;
//
// panelWhite
//
panelWhite.AllowDrop = true;
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(15, 90);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(35, 35);
panelWhite.TabIndex = 4;
//
// panelYellow
//
panelYellow.AllowDrop = true;
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(205, 26);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(35, 35);
panelYellow.TabIndex = 3;
//
// panelBlue
//
panelBlue.AllowDrop = true;
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(143, 26);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(35, 35);
panelBlue.TabIndex = 2;
//
// panelGreen
//
panelGreen.AllowDrop = true;
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(77, 26);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(35, 35);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.AllowDrop = true;
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(15, 26);
panelRed.Name = "panelRed";
panelRed.Size = new Size(35, 35);
panelRed.TabIndex = 0;
//
// checkBoxFiveDoors
//
checkBoxFiveDoors.AutoSize = true;
checkBoxFiveDoors.Location = new Point(24, 160);
checkBoxFiveDoors.Name = "checkBoxFiveDoors";
checkBoxFiveDoors.Size = new Size(93, 24);
checkBoxFiveDoors.TabIndex = 7;
checkBoxFiveDoors.Text = "5 дверей";
checkBoxFiveDoors.UseVisualStyleBackColor = true;
//
// checkBoxOnePart
//
checkBoxHatch.AutoSize = true;
checkBoxHatch.Location = new Point(24, 118);
checkBoxHatch.Name = "checkBoxOnePart";
checkBoxHatch.Size = new Size(69, 24);
checkBoxHatch.TabIndex = 6;
checkBoxHatch.Text = "Люки";
checkBoxHatch.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(94, 78);
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(106, 27);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(12, 78);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(94, 37);
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(106, 27);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(12, 37);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.AllowDrop = true;
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(361, 176);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(122, 39);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += labelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.AllowDrop = true;
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(221, 176);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(122, 39);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += labelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(16, 64);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(200, 100);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(515, 186);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(621, 186);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
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(499, 0);
panelObject.Name = "panelObject";
panelObject.Size = new Size(226, 178);
panelObject.TabIndex = 4;
panelObject.DragDrop += panelObject_DragDrop;
panelObject.DragEnter += panelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(128, 26);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(88, 25);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(16, 26);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(94, 25);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelColor_DragEnter;
//
// FormBusConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(737, 229);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfig);
Name = "FormBusConfig";
StartPosition = FormStartPosition.CenterScreen;
Text = "Создание объекта";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.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 groupBoxConfig;
private Label labelSimpleObject;
private Label labelModifiedObject;
private Label labelSpeed;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxHatch;
private CheckBox checkBoxFiveDoors;
private GroupBox groupBoxColor;
private Panel panelRed;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelBodyColor;
private Label labelAdditionalColor;
}
}

View File

@ -0,0 +1,184 @@
using AccordionBus.Drawnings;
using AccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccordionBus
{
public partial class FormBusConfig : Form
{
private DrawningBus _bus;
private event Action<DrawningBus> _busDelegate;
public FormBusConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
public void AddEvent(Action<DrawningBus> busDelegate)
{
_busDelegate += busDelegate;
}
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
Panel panel = sender as Panel;
panel.DoDragDrop(panel.Name, DragDropEffects.Copy);
}
private void DrawObject()
{
if (_bus == null) return;
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_bus.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_bus.SetPosition(5, 5);
_bus.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
Label label = sender as Label;
label.DoDragDrop(label.Name, 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":
_bus = new DrawningBus((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_bus = new DrawningAccordionBus((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxHatch.Checked, checkBoxFiveDoors.Checked);
break;
}
DrawObject();
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "panelRed":
_bus.EntityBus.SetBodyColor(Color.Red);
break;
case "panelBlue":
_bus.EntityBus.SetBodyColor(Color.Blue);
break;
case "panelGreen":
_bus.EntityBus.SetBodyColor(Color.Green);
break;
case "panelYellow":
_bus.EntityBus.SetBodyColor(Color.Yellow);
break;
case "panelWhite":
_bus.EntityBus.SetBodyColor(Color.White);
break;
case "panelGray":
_bus.EntityBus.SetBodyColor(Color.Gray);
break;
case "panelBlack":
_bus.EntityBus.SetBodyColor(Color.Black);
break;
case "panelPurple":
_bus.EntityBus.SetBodyColor(Color.Purple);
break;
}
DrawObject();
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_bus.EntityBus is EntityAccordionBus entityAccordionBus)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "panelRed":
entityAccordionBus.SetAdditionalColor(Color.Red);
break;
case "panelBlue":
entityAccordionBus.SetAdditionalColor(Color.Blue);
break;
case "panelGreen":
entityAccordionBus.SetAdditionalColor(Color.Green);
break;
case "panelYellow":
entityAccordionBus.SetAdditionalColor(Color.Yellow);
break;
case "panelWhite":
entityAccordionBus.SetAdditionalColor(Color.White);
break;
case "panelGray":
entityAccordionBus.SetAdditionalColor(Color.Gray);
break;
case "panelBlack":
entityAccordionBus.SetAdditionalColor(Color.Black);
break;
case "panelPurple":
entityAccordionBus.SetAdditionalColor(Color.Purple);
break;
}
DrawObject() ;
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_bus != null)
{
_busDelegate.Invoke(_bus);
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,125 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
public abstract class AbstractStrategy
{
/// <summary>
/// Объект
/// </summary>
private IMoveableObjects? _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>
/// <returns></returns>
public StrategyStatus? GetStatus() { return _state; }
/// <summary>
/// Инициализация полей
/// </summary>
/// <param name="moveableObject"></param>
/// <param name="width"></param>
/// <param name="height"></param>
public void SetData(IMoveableObjects 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 MakeStap()
{
if (_state != StrategyStatus.InProgress) return;
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Шаг влево
/// </summary>
/// <returns></returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Шаг вправо
/// </summary>
/// <returns></returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Шаг вверх
/// </summary>
/// <returns></returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Шаг вниз
/// </summary>
/// <returns></returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Получение параметров
/// </summary>
/// <returns></returns>
protected ObjectParameters? GetObjectParameters() => _moveableObject?.GetObjectPosition;
/// <summary>
/// Получение шага
/// </summary>
/// <returns></returns>
protected int? GetStap()
{
if(_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Шаг к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достижение цели
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestination();
/// <summary>
/// Сделать шаг
/// </summary>
/// <param name="movementDirection"></param>
/// <returns></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 AccordionBus.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с пперемещаемым объектом
/// </summary>
public interface IMoveableObjects
{
/// <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,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters();
if (objParams == null)
{
return false;
}
return objParams.RightBorder() == FieldWidth && objParams.DownBorder() == FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters();
if (objParams == null)
{
return;
}
if (objParams.RightBorder() < FieldWidth) MoveRight();
if (objParams.DownBorder() < FieldHeight) MoveDown();
}
}
}

View File

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

View File

@ -0,0 +1,67 @@
using AccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
/// <summary>
/// Класс-реализация IMoveableObjects с использованием DrawningBus
/// </summary>
public class MoveableBus : IMoveableObjects
{
/// <summary>
/// Поле-объект DrawningBus
/// </summary>
private readonly DrawningBus? _car;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="car">Объект класса DrawningBus</param>
public MoveableBus(DrawningBus? car)
{
_car = car;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_car == null || _car.EntityBus == null || _car.GetPosX() == null || _car.GetPosY() == null)
{
return null;
}
return new ObjectParameters(_car.GetPosX().Value, _car.GetPosY().Value, _car.GetWidth(), _car.GetHeigth());
}
}
public int GetStep => (int)(_car?.EntityBus?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_car == null || _car.EntityBus == null)
{
return false;
}
return _car.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction"></param>
/// <returns></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,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
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 AccordionBus.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
/// <summary>
/// Координата Х
/// </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>
/// <returns></returns>
public int LeftBorder() => _x;
/// <summary>
/// Верхняя граница
/// </summary>
/// <returns></returns>
public int TopBorder() => _y;
/// <summary>
/// Правая граница
/// </summary>
/// <returns></returns>
public int RightBorder() => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
/// <returns></returns>
public int DownBorder() => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
/// <returns></returns>
public int ObjectMiddleHorizontal() => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
/// <returns></returns>
public int ObjectMiddleVertical() => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.MovementStrategy
{
public enum StrategyStatus
{
/// <summary>
/// всё готово к началу
/// </summary>
NotInit,
/// <summary>
/// В процессе
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
namespace AccordionBus
{
internal static class Program
@ -10,8 +16,24 @@ namespace AccordionBus
{
// 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 FormAccordionBus());
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBusCollection>()
.AddLogging(option => {
option.SetMinimumLevel(LogLevel.Debug);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile("C:\\Users\\Professional\\Desktop\\labs\\8\\AccordionBus\\AccordionBus\\serilog.json")
.Build())
.CreateLogger());
});
}
}
}

View File

@ -0,0 +1,18 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs\\log.txt",
"outputTemplate": "[{Level:u}] [{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}] {Message:1j}{NewLine}{Exception}"
}
}
],
"Properties": {
"Application": "Sample"
}
}
}