Compare commits

..

24 Commits
main ... Lab8

Author SHA1 Message Date
405afb65a9 Lab8 pull 2023-12-22 18:35:02 +04:00
f629e43cea Lab8 почти пул 2023-12-22 09:25:23 +04:00
b877c5e45c Lab8 2023-12-21 01:43:04 +04:00
7678a19627 Lab7 pull request 2023-12-09 10:26:29 +04:00
0e533c7136 Lab7++ 2023-12-06 21:00:20 +04:00
9fceaf0eed Lab7+ 2023-12-06 20:58:03 +04:00
336b0a05fd Lab7 2023-12-06 19:46:43 +04:00
a96cb7156e Lab6 Done+ 2023-12-06 17:18:36 +04:00
9b61350dbf Lab6 2023-11-22 21:14:32 +04:00
3bd218f664 Lab5 error fix 2023-11-22 19:42:40 +04:00
f31ccdc593 Lab5 Done 2023-11-17 17:53:02 +04:00
de631fcdf5 Lab4 Done 2023-11-08 23:23:24 +04:00
38a949a2ca It Done 2023-10-28 00:28:20 +04:00
5b6e6256ff Готово 2023-10-21 17:51:21 +04:00
7305320931 Done+++ 2023-10-21 16:39:13 +04:00
be4a8c4f1d Done++ 2023-10-21 15:11:32 +04:00
0dade24b81 Done+ 2023-10-21 13:15:16 +04:00
04fb769aef Done 2023-10-21 13:10:15 +04:00
2807485943 perfecto 2023-10-12 23:10:38 +04:00
8c86fdc0ca Сделано 2023-10-12 21:21:29 +04:00
a1a6743ce1 Сделано 2023-10-12 18:32:33 +04:00
8d300a2aec Сделано 2023-10-11 20:42:20 +04:00
aef61e0dc3 Lab1 perfecto 2023-10-05 21:26:52 +04:00
bb6a8b0275 ЛР1 готово 2023-09-28 17:22:01 +04:00
42 changed files with 3135 additions and 79 deletions

View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrolleybus.MovementStrategy
{
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private Status _state = Status.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public Status GetStatus() { return _state; }
public void SetData(IMoveableObject moveableObject, int width, int
height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(DirectionType.Left);
protected bool MoveRight() => MoveTo(DirectionType.Right);
protected bool MoveUp() => MoveTo(DirectionType.Up);
protected bool MoveDown() => MoveTo(DirectionType.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestinaion();
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTrolleybus.DrawingObjects;
namespace ProjectTrolleybus.Generics
{
internal class BusCompareByColor : IComparer<DrawingBus?>
{
public int Compare(DrawingBus? x, DrawingBus? y)
{
if (x == null || x.EntityBus == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityBus.BodyColor.Name != y.EntityBus.BodyColor.Name)
{
return x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.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,36 @@
using ProjectTrolleybus.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrolleybus.Generics
{
internal class BusCompareByType : IComparer<DrawingBus?>
{
public int Compare(DrawingBus? x, DrawingBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
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,15 @@
using System.Runtime.Serialization;
namespace ProjectTrolleybus.Exceptions
{
[Serializable]
internal class BusNotFoundException : ApplicationException
{
public BusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BusNotFoundException() : base() { }
public BusNotFoundException(string message) : base(message) { }
public BusNotFoundException(string message, Exception exception) : base(message, exception) { }
protected BusNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

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

View File

@ -0,0 +1,136 @@
using ProjectTrolleybus.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTrolleybus.DrawingObjects;
namespace ProjectTrolleybus.Generics
{
internal class BusesGenericCollection<T, U>
where T : DrawingBus
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 170;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 124;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public BusesGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool operator +(BusesGenericCollection<T, U>? collect, T? obj)
{
if (obj == null || collect == null)
return false;
collect?._collection.Insert(obj, new DrawingBusEqutables());
return true;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(BusesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowBuses()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j)
{//линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int i = 0;
foreach (var bus in _collection.GetBuses())
{
if (bus != null)
{
int inRow = _pictureWidth / _placeSizeWidth;
bus.SetPosition(_placeSizeWidth * (inRow - 1) - (i % inRow * _placeSizeWidth), i / inRow * _placeSizeHeight);
bus.DrawTransport(g);
}
i++;
}
}
public IEnumerable<T?> GetBuses => _collection.GetBuses();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
}
}

View File

@ -0,0 +1,171 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTrolleybus.DrawingObjects;
using ProjectTrolleybus.MovementStrategy;
namespace ProjectTrolleybus.Generics
{
internal class BusesGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<BusesCollectionInfo, BusesGenericCollection<DrawingBus,
DrawingObjectBus>> _busStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<BusesCollectionInfo> Keys => _busStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public BusesGenericStorage(int pictureWidth, int pictureHeight)
{
_busStorages = new Dictionary<BusesCollectionInfo, BusesGenericCollection<DrawingBus, DrawingObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_busStorages.Add(new BusesCollectionInfo(name, string.Empty), new BusesGenericCollection<DrawingBus,
DrawingObjectBus>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_busStorages.ContainsKey(new BusesCollectionInfo(name, string.Empty)))
return;
_busStorages.Remove(new BusesCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BusesGenericCollection<DrawingBus, DrawingObjectBus>? this[string ind]
{
get
{
BusesCollectionInfo indObj = new BusesCollectionInfo(ind, string.Empty);
if (_busStorages.ContainsKey(indObj))
return _busStorages[indObj];
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<BusesCollectionInfo,
BusesGenericCollection<DrawingBus, DrawingObjectBus>> record in _busStorages)
{
StringBuilder records = new();
foreach (DrawingBus? elem in record.Value.GetBuses)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new IOException("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter streamWriter = new(filename))
{
streamWriter.WriteLine($"BusStorages{Environment.NewLine}{data}");
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new IOException("Файл не найден");
}
using (StreamReader streamReader = new(filename))
{
string str = streamReader.ReadLine();
var strings = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strings == null || strings.Length == 0)
{
throw new IOException("Нет данных для загрузки");
}
if (!strings[0].StartsWith("BusStorages"))
{
throw new IOException("Неверный формат данных");
}
_busStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = streamReader.ReadLine();
continue;
}
BusesGenericCollection<DrawingBus, DrawingObjectBus> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingBus? bus = elem?.CreateDrawingBus(_separatorForObject, _pictureWidth, _pictureHeight);
if (bus != null)
{
if (!(collection + bus))
{
throw new IOException("Ошибка добавления в коллекцию");
}
}
}
_busStorages.Add(new BusesCollectionInfo(record[0], string.Empty), collection);
str = streamReader.ReadLine();
} while (str != null);
}
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrolleybus
{
public enum DirectionType
{
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
}

View File

@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTrolleybus.Entities;
using ProjectTrolleybus.MovementStrategy;
namespace ProjectTrolleybus.DrawingObjects
{
public class DrawingBus
{
public EntityBus? EntityBus { get; protected set; }
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected readonly int _busWidth = 170;
protected readonly int _busHeight = 124;
public DrawingBus(int speed, double weight, Color bodyColor, int
width, int height)
{
if (width < _busWidth || height < _busHeight)
return;
_pictureWidth = width;
_pictureHeight = height;
EntityBus = new EntityBus(speed, weight, bodyColor);
}
protected DrawingBus(int speed, double weight, Color bodyColor, int
width, int height, int busWidth, int busHeight)
{
if (width < _busWidth || height < _busHeight)
return;
_pictureWidth = width;
_pictureHeight = height;
_busWidth = busWidth;
_busHeight = busHeight;
EntityBus = new EntityBus(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)
{
if (x < 0 || y < 0 || x + _busWidth >= _pictureWidth || y + _busHeight >= _pictureHeight)
x = y = 10;
_startPosX = x;
_startPosY = y;
}
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _busWidth;
public int GetHeight => _busHeight;
public bool CanMove(DirectionType direction)
{
if (EntityBus == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityBus.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityBus.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityBus.Step + _busWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityBus.Step + _busHeight < _pictureHeight,
_ => false,
};
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityBus == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityBus.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityBus.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityBus.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityBus.Step;
break;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityBus == null)
{
return;
}
Pen pen = new(Color.Black);
//кузов
Brush br = new SolidBrush(EntityBus.BodyColor);
g.FillRectangle(br, _startPosX + 6, _startPosY + 31, 164, 79);
//задние фары
Brush brRed = new SolidBrush(Color.Red);
g.FillRectangle(brRed, _startPosX + 5, _startPosY + 85, 10, 20);
//передние фары
Brush brYellow = new SolidBrush(Color.Yellow);
g.FillRectangle(brYellow, _startPosX + 160, _startPosY + 85, 10, 20);
//стекла
Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBlue, _startPosX + 150, _startPosY + 40, 20, 40);
g.FillEllipse(brBlue, _startPosX + 10, _startPosY + 40, 20, 40);
g.FillEllipse(brBlue, _startPosX + 35, _startPosY + 40, 20, 40);
g.FillEllipse(brBlue, _startPosX + 95, _startPosY + 40, 20, 40);
g.FillEllipse(brBlue, _startPosX + 120, _startPosY + 40, 20, 40);
//дверь
Brush brDoor = new SolidBrush(EntityBus.BodyColor);
g.FillRectangle(brDoor, _startPosX + 60, _startPosY + 50, 30, 60);
//колеса
Brush brblack = new SolidBrush(Color.Black);
g.FillEllipse(brblack, _startPosX + 25, _startPosY + 95, 30, 30);
g.FillEllipse(brblack, _startPosX + 120, _startPosY + 95, 30, 30);
//границы троллейбуса
g.DrawRectangle(pen, _startPosX + 5, _startPosY + 30, 165, 80);
g.DrawEllipse(pen, _startPosX + 25, _startPosY + 95, 30, 30);
g.DrawEllipse(pen, _startPosX + 120, _startPosY + 95, 30, 30);
g.DrawRectangle(pen, _startPosX + 5, _startPosY + 85, 10, 20);
g.DrawRectangle(pen, _startPosX + 160, _startPosY + 85, 10, 20);
g.DrawRectangle(pen, _startPosX + 60, _startPosY + 50, 30, 60);
g.DrawRectangle(pen, _startPosX + 150, _startPosY + 40, 20, 40);
g.DrawEllipse(pen, _startPosX + 10, _startPosY + 40, 20, 40);
g.DrawEllipse(pen, _startPosX + 35, _startPosY + 40, 20, 40);
g.DrawEllipse(pen, _startPosX + 95, _startPosY + 40, 20, 40);
g.DrawEllipse(pen, _startPosX + 120, _startPosY + 40, 20, 40);
}
public IMoveableObject GetMoveableObject => new DrawingObjectBus(this);
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTrolleybus.DrawingObjects;
using ProjectTrolleybus.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectTrolleybus
{
internal class DrawingBusEqutables : IEqualityComparer<DrawingBus?>
{
public bool Equals(DrawingBus? x, DrawingBus? y)
{
if (x == null || x.EntityBus == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityBus == null)
{
throw new ArgumentNullException(nameof(y));
}
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 DrawingTrolleybus && y is DrawingTrolleybus)
{
EntityTrolleybus EntityX = (EntityTrolleybus)x.EntityBus;
EntityTrolleybus EntityY = (EntityTrolleybus)y.EntityBus;
if (EntityX.Roga != EntityY.Roga)
return false;
if (EntityX.Battery != EntityY.Battery)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingBus? obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTrolleybus.DrawingObjects;
namespace ProjectTrolleybus.MovementStrategy
{
public class DrawingObjectBus : IMoveableObject
{
private readonly DrawingBus? _drawningCar = null;
public DrawingObjectBus(DrawingBus drawningCar)
{
_drawningCar = drawningCar;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningCar == null || _drawningCar.EntityBus ==
null)
{
return null;
}
return new ObjectParameters(_drawningCar.GetPosX,
_drawningCar.GetPosY, _drawningCar.GetWidth, _drawningCar.GetHeight);
}
}
public int GetStep => (int)(_drawningCar?.EntityBus?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawningCar?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawningCar?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using ProjectTrolleybus.DrawingObjects;
using ProjectTrolleybus.Entities;
namespace ProjectTrolleybus
{
public class DrawingTrolleybus : DrawingBus
{
public DrawingTrolleybus(int speed, double weight, Color bodyColor, Color additionalColor, bool roga, bool battery, int width, int height)
: base(speed, weight, bodyColor, width, height, 170, 124)
{
if (EntityBus != null)
{
EntityBus = new EntityTrolleybus(speed, weight, bodyColor, additionalColor, roga, battery);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityBus is not EntityTrolleybus trolleybus)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new
SolidBrush(trolleybus.AdditionalColor);
base.DrawTransport(g);
//"рога"
if (trolleybus.Roga)
{
g.DrawLine(new Pen(Color.Black, 3), _startPosX + 120, _startPosY + 30, _startPosX + 20, _startPosY + 3);
g.DrawLine(new Pen(Color.Black, 3), _startPosX + 140, _startPosY + 30, _startPosX + 40, _startPosY + 3);
g.DrawLine(new Pen(Color.Black, 1), _startPosX + 40, _startPosY + 30, _startPosX + 20, _startPosY + 3);
g.DrawLine(new Pen(Color.Black, 1), _startPosX + 60, _startPosY + 30, _startPosX + 40, _startPosY + 3);
}
//Батарея
if(trolleybus.Battery)
{
Brush brBattery = new SolidBrush(trolleybus.AdditionalColor);
g.FillRectangle(brBattery, _startPosX + 95, _startPosY + 85, 20, 25);
g.DrawLine(new Pen(Color.Yellow, 2), _startPosX + 112, _startPosY + 90, _startPosX + 97, _startPosY + 100);
g.DrawLine(new Pen(Color.Yellow, 2), _startPosX + 97, _startPosY + 100, _startPosX + 112, _startPosY + 100);
g.DrawLine(new Pen(Color.Yellow, 2), _startPosX + 112, _startPosY + 100, _startPosX + 97, _startPosY + 110);
g.DrawRectangle(pen, _startPosX + 95, _startPosY + 85, 20, 25);
}
}
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrolleybus.Entities
{
public class EntityBus
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public double Step => (double)Speed * 100 / Weight;
public EntityBus(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
public void ChangeColor(Color color)
{
BodyColor = color;
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrolleybus.Entities
{
public class EntityTrolleybus : EntityBus
{
public Color AdditionalColor { get; private set; }
public bool Roga { get; private set; }
public bool Battery { get; private set; }
public EntityTrolleybus(int speed, double weight, Color bodyColor, Color
additionalColor, bool roga, bool battery)
: base (speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Roga = roga;
Battery = battery;
}
public void ChangeAdditColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTrolleybus.Entities;
namespace ProjectTrolleybus.DrawingObjects
{
public static class ExtentionDrawingBus
{
public static DrawingBus? CreateDrawingBus(this string info, char separatorForObject, int width, int height)
{
string[] strings = info.Split(separatorForObject);
if (strings.Length == 3)
{
return new DrawingBus(Convert.ToInt32(strings[0]),
Convert.ToInt32(strings[1]), Color.FromName(strings[2]), width, height);
}
if (strings.Length == 6)
{
return new DrawingTrolleybus(Convert.ToInt32(strings[0]),
Convert.ToInt32(strings[1]),
Color.FromName(strings[2]),
Color.FromName(strings[3]),
Convert.ToBoolean(strings[4]),
Convert.ToBoolean(strings[5]),
width, height);
}
return null;
}
public static string GetDataForSave(this DrawingBus drawingBus, char separatorForObject)
{
var bus = drawingBus.EntityBus;
if (bus == null)
{
return string.Empty;
}
var str = $"{bus.Speed}{separatorForObject}{bus.Weight}{separatorForObject}{bus.BodyColor.Name}";
if (bus is not EntityTrolleybus trolleybus)
{
return str;
}
return $"{str}{separatorForObject}{trolleybus.AdditionalColor.Name}{separatorForObject}{trolleybus.Roga}{separatorForObject}{trolleybus.Battery}";
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,291 @@
namespace ProjectTrolleybus
{
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()
{
groupBoxTrolleybus = new GroupBox();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxSets = new GroupBox();
textBoxStorageName = new TextBox();
buttonDelObject = new Button();
listBoxStorages = new ListBox();
buttonAddObject = new Button();
buttonUpdateCollection = new Button();
buttonDeleteBus = new Button();
maskedTextBoxNumber = new MaskedTextBox();
buttonAddBus = new Button();
pictureBoxCollection = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTrolleybus.SuspendLayout();
groupBoxSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTrolleybus
//
groupBoxTrolleybus.Controls.Add(buttonSortByColor);
groupBoxTrolleybus.Controls.Add(buttonSortByType);
groupBoxTrolleybus.Controls.Add(groupBoxSets);
groupBoxTrolleybus.Controls.Add(buttonUpdateCollection);
groupBoxTrolleybus.Controls.Add(buttonDeleteBus);
groupBoxTrolleybus.Controls.Add(maskedTextBoxNumber);
groupBoxTrolleybus.Controls.Add(buttonAddBus);
groupBoxTrolleybus.Location = new Point(615, 32);
groupBoxTrolleybus.Margin = new Padding(3, 4, 3, 4);
groupBoxTrolleybus.Name = "groupBoxTrolleybus";
groupBoxTrolleybus.Padding = new Padding(3, 4, 3, 4);
groupBoxTrolleybus.Size = new Size(299, 568);
groupBoxTrolleybus.TabIndex = 0;
groupBoxTrolleybus.TabStop = false;
groupBoxTrolleybus.Text = "Инструменты";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(11, 361);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(273, 33);
buttonSortByColor.TabIndex = 6;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(11, 320);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(275, 35);
buttonSortByType.TabIndex = 5;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// groupBoxSets
//
groupBoxSets.Anchor = AnchorStyles.Top | AnchorStyles.Right;
groupBoxSets.Controls.Add(textBoxStorageName);
groupBoxSets.Controls.Add(buttonDelObject);
groupBoxSets.Controls.Add(listBoxStorages);
groupBoxSets.Controls.Add(buttonAddObject);
groupBoxSets.Location = new Point(11, 28);
groupBoxSets.Margin = new Padding(3, 4, 3, 4);
groupBoxSets.Name = "groupBoxSets";
groupBoxSets.Padding = new Padding(3, 4, 3, 4);
groupBoxSets.Size = new Size(280, 286);
groupBoxSets.TabIndex = 4;
groupBoxSets.TabStop = false;
groupBoxSets.Text = "Наборы";
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(7, 28);
textBoxStorageName.Margin = new Padding(3, 4, 3, 4);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(266, 27);
textBoxStorageName.TabIndex = 4;
//
// buttonDelObject
//
buttonDelObject.Location = new Point(7, 238);
buttonDelObject.Margin = new Padding(3, 4, 3, 4);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(266, 40);
buttonDelObject.TabIndex = 3;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += ButtonDelObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(8, 106);
listBoxStorages.Margin = new Padding(3, 4, 3, 4);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(266, 124);
listBoxStorages.TabIndex = 2;
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// buttonAddObject
//
buttonAddObject.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonAddObject.Location = new Point(8, 63);
buttonAddObject.Margin = new Padding(3, 4, 3, 4);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(266, 35);
buttonAddObject.TabIndex = 1;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// buttonUpdateCollection
//
buttonUpdateCollection.Location = new Point(11, 523);
buttonUpdateCollection.Margin = new Padding(3, 4, 3, 4);
buttonUpdateCollection.Name = "buttonUpdateCollection";
buttonUpdateCollection.Size = new Size(275, 37);
buttonUpdateCollection.TabIndex = 3;
buttonUpdateCollection.Text = "Обновить коллекцию";
buttonUpdateCollection.UseVisualStyleBackColor = true;
buttonUpdateCollection.Click += ButtonRefreshCollection_Click;
//
// buttonDeleteBus
//
buttonDeleteBus.Location = new Point(11, 476);
buttonDeleteBus.Margin = new Padding(3, 4, 3, 4);
buttonDeleteBus.Name = "buttonDeleteBus";
buttonDeleteBus.Size = new Size(275, 39);
buttonDeleteBus.TabIndex = 2;
buttonDeleteBus.Text = "Удалить автобус";
buttonDeleteBus.UseVisualStyleBackColor = true;
buttonDeleteBus.Click += ButtonRemoveBus_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(73, 446);
maskedTextBoxNumber.Margin = new Padding(3, 4, 3, 4);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(131, 27);
maskedTextBoxNumber.TabIndex = 1;
//
// buttonAddBus
//
buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonAddBus.Location = new Point(11, 401);
buttonAddBus.Margin = new Padding(3, 4, 3, 4);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(275, 37);
buttonAddBus.TabIndex = 0;
buttonAddBus.Text = "Добавить автобус";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += ButtonAddBus_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
pictureBoxCollection.Location = new Point(0, 32);
pictureBoxCollection.Margin = new Padding(3, 4, 3, 4);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(616, 568);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.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(920, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(166, 26);
SaveToolStripMenuItem.Text = "Сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(166, 26);
LoadToolStripMenuItem.Text = "Загрузить";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "busStorages";
openFileDialog.Filter = "«txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.FileName = "busStorages";
saveFileDialog.Filter = "«txt file | *.txt";
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(920, 600);
Controls.Add(groupBoxTrolleybus);
Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 4, 3, 4);
Name = "FormBusCollection";
StartPosition = FormStartPosition.CenterScreen;
Text = "Набор автобусов";
groupBoxTrolleybus.ResumeLayout(false);
groupBoxTrolleybus.PerformLayout();
groupBoxSets.ResumeLayout(false);
groupBoxSets.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBoxTrolleybus;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonAddBus;
private Button buttonUpdateCollection;
private Button buttonDeleteBus;
private PictureBox pictureBoxCollection;
private GroupBox groupBoxSets;
private Button buttonDelObject;
private ListBox listBoxStorages;
private Button buttonAddObject;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -0,0 +1,215 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectTrolleybus.DrawingObjects;
using ProjectTrolleybus.MovementStrategy;
using ProjectTrolleybus.Generics;
using ProjectTrolleybus;
using ProjectTrolleybus.Exceptions;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
using Serilog;
namespace ProjectTrolleybus
{
public partial class FormBusCollection : Form
{
private readonly BusesGenericStorage _storage;
public FormBusCollection()
{
InitializeComponent();
_storage = new BusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
}
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
string name = (listBoxStorages.SelectedItem.ToString() ?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
private void ButtonAddBus_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormBusConfig form = new FormBusConfig(pictureBoxCollection.Width, pictureBoxCollection.Height);
form.Show();
Action<DrawingBus>? busDelegate = new((bus) =>
{
try
{
bool q = obj + bus;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBuses();
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
catch (ArgumentException)
{
Log.Warning($"Добавляемый объект уже существует в коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
form.AddEvent(busDelegate);
}
private void ButtonRemoveBus_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowBuses();
}
catch (BusNotFoundException ex)
{
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message); ;
}
catch (FormatException)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowBuses();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
catch (Exception ex)
{
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareBuses(new BusCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareBuses(new BusCompareByColor());
private void CompareBuses(IComparer<DrawingBus?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowBuses();
}
}
}

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="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>315, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,365 @@
namespace ProjectTrolleybus
{
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();
labelAdvanced = new Label();
labelSimple = new Label();
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();
checkBoxBattery = new CheckBox();
checkBoxRoga = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
panelAllow = new Panel();
pictureBoxObject = new PictureBox();
labelAdditionalColor = new Label();
labelColor = new Label();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxConfig.SuspendLayout();
groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelAllow.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(labelAdvanced);
groupBoxConfig.Controls.Add(labelSimple);
groupBoxConfig.Controls.Add(groupBoxColor);
groupBoxConfig.Controls.Add(checkBoxBattery);
groupBoxConfig.Controls.Add(checkBoxRoga);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Location = new Point(12, 12);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(737, 337);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// labelAdvanced
//
labelAdvanced.BorderStyle = BorderStyle.FixedSingle;
labelAdvanced.Location = new Point(574, 262);
labelAdvanced.Name = "labelAdvanced";
labelAdvanced.Size = new Size(120, 52);
labelAdvanced.TabIndex = 8;
labelAdvanced.Text = "Продвинутый";
labelAdvanced.TextAlign = ContentAlignment.MiddleCenter;
labelAdvanced.MouseDown += LabelObject_MouseDown;
//
// labelSimple
//
labelSimple.BorderStyle = BorderStyle.FixedSingle;
labelSimple.Location = new Point(443, 262);
labelSimple.Name = "labelSimple";
labelSimple.Size = new Size(116, 52);
labelSimple.TabIndex = 7;
labelSimple.Text = "Простой";
labelSimple.TextAlign = ContentAlignment.MiddleCenter;
labelSimple.MouseDown += LabelObject_MouseDown;
//
// 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(411, 53);
groupBoxColor.Name = "groupBoxColor";
groupBoxColor.Size = new Size(306, 182);
groupBoxColor.TabIndex = 6;
groupBoxColor.TabStop = false;
groupBoxColor.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(236, 98);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(58, 49);
panelPurple.TabIndex = 1;
panelPurple.MouseDown += PanelColor_MouseDown;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(163, 98);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(58, 49);
panelBlack.TabIndex = 1;
panelBlack.MouseDown += PanelColor_MouseDown;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(90, 98);
panelGray.Name = "panelGray";
panelGray.Size = new Size(58, 49);
panelGray.TabIndex = 1;
panelGray.MouseDown += PanelColor_MouseDown;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(15, 98);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(58, 49);
panelWhite.TabIndex = 1;
panelWhite.MouseDown += PanelColor_MouseDown;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(236, 33);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(58, 49);
panelYellow.TabIndex = 1;
panelYellow.MouseDown += PanelColor_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(163, 33);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(58, 49);
panelBlue.TabIndex = 1;
panelBlue.MouseDown += PanelColor_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(90, 33);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(58, 49);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += PanelColor_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(15, 33);
panelRed.Name = "panelRed";
panelRed.Size = new Size(58, 49);
panelRed.TabIndex = 0;
panelRed.MouseDown += PanelColor_MouseDown;
//
// checkBoxBattery
//
checkBoxBattery.AutoSize = true;
checkBoxBattery.Location = new Point(6, 214);
checkBoxBattery.Name = "checkBoxBattery";
checkBoxBattery.Size = new Size(399, 24);
checkBoxBattery.TabIndex = 5;
checkBoxBattery.Text = "Признак наличия отсека под электрические батареи";
checkBoxBattery.UseVisualStyleBackColor = true;
//
// checkBoxRoga
//
checkBoxRoga.AutoSize = true;
checkBoxRoga.Location = new Point(6, 171);
checkBoxRoga.Name = "checkBoxRoga";
checkBoxRoga.Size = new Size(277, 24);
checkBoxRoga.TabIndex = 4;
checkBoxRoga.Text = "Признак наличия токоприёмников";
checkBoxRoga.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(102, 111);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(150, 27);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(102, 53);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(150, 27);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(6, 113);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(6, 55);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// panelAllow
//
panelAllow.AllowDrop = true;
panelAllow.Controls.Add(pictureBoxObject);
panelAllow.Controls.Add(labelAdditionalColor);
panelAllow.Controls.Add(labelColor);
panelAllow.Location = new Point(755, 12);
panelAllow.Name = "panelAllow";
panelAllow.Size = new Size(362, 292);
panelAllow.TabIndex = 1;
panelAllow.DragDrop += PanelObject_DragDrop;
panelAllow.DragEnter += PanelObject_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(61, 86);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(227, 161);
pictureBoxObject.TabIndex = 2;
pictureBoxObject.TabStop = false;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(200, 13);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(129, 49);
labelAdditionalColor.TabIndex = 1;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(26, 13);
labelColor.Name = "labelColor";
labelColor.Size = new Size(142, 49);
labelColor.TabIndex = 0;
labelColor.Text = "Цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += labelColor_DragDrop;
labelColor.DragEnter += labelColor_DragEnter;
//
// buttonAdd
//
buttonAdd.Location = new Point(781, 321);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(142, 45);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonOk_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(955, 321);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(129, 45);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormBusConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1123, 386);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelAllow);
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();
panelAllow.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private GroupBox groupBoxColor;
private CheckBox checkBoxBattery;
private CheckBox checkBoxRoga;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private Label labelAdvanced;
private Label labelSimple;
private Panel panelAllow;
private Label labelColor;
private PictureBox pictureBoxObject;
private Label labelAdditionalColor;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectTrolleybus.DrawingObjects;
using ProjectTrolleybus.Entities;
namespace ProjectTrolleybus
{
public partial class FormBusConfig : Form
{
private readonly int _pictureWidth;
private readonly int _pictureHeight;
DrawingBus? _bus = null;
Action<DrawingBus>? EventAddBus;
public FormBusConfig(int Width, int Height)
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
_pictureWidth = Width;
_pictureHeight = Height;
}
private void DrawBus()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_bus?.SetPosition(5, 5);
_bus?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
public void AddEvent(Action<DrawingBus> ev)
{
if (EventAddBus == null)
{
EventAddBus = ev;
}
else
{
EventAddBus += ev;
}
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimple":
_bus = new DrawingBus((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, _pictureWidth, _pictureHeight);
break;
case "labelAdvanced":
_bus = new DrawingTrolleybus((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxRoga.Checked,
checkBoxBattery.Checked, _pictureWidth, _pictureHeight);
break;
}
DrawBus();
}
private void PanelColor_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void ButtonOk_Click(object sender, EventArgs e)
{
if (_bus == null)
return;
EventAddBus?.Invoke(_bus);
Close();
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_bus == null || _bus.EntityBus == null)
return;
Color colorBody = (Color)e.Data.GetData(typeof(Color));
_bus.EntityBus.ChangeColor(colorBody);
DrawBus();
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_bus == null || _bus.EntityBus == null || _bus is DrawingTrolleybus == false)
return;
Color colorAdditional = (Color)e.Data.GetData(typeof(Color));
((EntityTrolleybus)_bus.EntityBus).ChangeAdditColor(colorAdditional);
DrawBus();
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,190 @@
namespace ProjectTrolleybus
{
partial class FormTrolleybus
{
/// <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()
{
ButtonCreateTrolleybus = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonUp = new Button();
ButtonCreateBus = new Button();
comboBoxStrategy = new ComboBox();
ButtonStep = new Button();
ButtonSelectBus = new Button();
pictureBoxTrolleybus = new PictureBox();
((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).BeginInit();
SuspendLayout();
//
// ButtonCreateTrolleybus
//
ButtonCreateTrolleybus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCreateTrolleybus.Location = new Point(12, 411);
ButtonCreateTrolleybus.Name = "ButtonCreateTrolleybus";
ButtonCreateTrolleybus.Size = new Size(92, 38);
ButtonCreateTrolleybus.TabIndex = 1;
ButtonCreateTrolleybus.Text = "Создать троллейбус";
ButtonCreateTrolleybus.UseVisualStyleBackColor = true;
ButtonCreateTrolleybus.Click += ButtonCreateTrolleybus_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = ProjectTrolleybus.Properties.Resources.Right;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(842, 419);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 2;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = ProjectTrolleybus.Properties.Resources.Down;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(806, 419);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = ProjectTrolleybus.Properties.Resources.Left;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(770, 419);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = ProjectTrolleybus.Properties.Resources.Up;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(806, 383);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 5;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// ButtonCreateBus
//
ButtonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCreateBus.Location = new Point(110, 411);
ButtonCreateBus.Name = "ButtonCreateBus";
ButtonCreateBus.Size = new Size(75, 38);
ButtonCreateBus.TabIndex = 6;
ButtonCreateBus.Text = "Создать автобус";
ButtonCreateBus.UseVisualStyleBackColor = true;
ButtonCreateBus.Click += ButtonCreateBus_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Движение в центр", "Движение в правый угол" });
comboBoxStrategy.Location = new Point(751, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// ButtonStep
//
ButtonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
ButtonStep.Location = new Point(797, 41);
ButtonStep.Name = "ButtonStep";
ButtonStep.Size = new Size(75, 23);
ButtonStep.TabIndex = 8;
ButtonStep.Text = "Шаг";
ButtonStep.UseVisualStyleBackColor = true;
ButtonStep.Click += ButtonStep_Click;
//
// ButtonSelectBus
//
ButtonSelectBus.Location = new Point(797, 95);
ButtonSelectBus.Name = "ButtonSelectBus";
ButtonSelectBus.Size = new Size(75, 25);
ButtonSelectBus.TabIndex = 9;
ButtonSelectBus.Text = "Создание";
ButtonSelectBus.UseVisualStyleBackColor = true;
ButtonSelectBus.Click += ButtonSelectBus_Click;
//
// pictureBoxTrolleybus
//
pictureBoxTrolleybus.Dock = DockStyle.Fill;
pictureBoxTrolleybus.Location = new Point(0, 0);
pictureBoxTrolleybus.Name = "pictureBoxTrolleybus";
pictureBoxTrolleybus.Size = new Size(884, 461);
pictureBoxTrolleybus.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxTrolleybus.TabIndex = 10;
pictureBoxTrolleybus.TabStop = false;
//
// FormTrolleybus
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(ButtonSelectBus);
Controls.Add(ButtonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(ButtonCreateBus);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(ButtonCreateTrolleybus);
Controls.Add(pictureBoxTrolleybus);
Name = "FormTrolleybus";
StartPosition = FormStartPosition.CenterScreen;
Text = "Троллейбус";
((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button ButtonCreateTrolleybus;
private Button buttonRight;
private Button buttonDown;
private Button buttonLeft;
private Button buttonUp;
private Button ButtonCreateBus;
private ComboBox comboBoxStrategy;
private Button ButtonStep;
private Button ButtonSelectBus;
private PictureBox pictureBoxTrolleybus;
}
}

View File

@ -0,0 +1,135 @@
using ProjectTrolleybus.MovementStrategy;
using ProjectTrolleybus.DrawingObjects;
namespace ProjectTrolleybus
{
public partial class FormTrolleybus : Form
{
private DrawingBus? _drawingBus;
private AbstractStrategy? _strategy;
public DrawingBus? SelectedBus { get; private set; }
public FormTrolleybus()
{
InitializeComponent();
_strategy = null;
SelectedBus = null;
}
private void Draw()
{
if (_drawingBus == null)
{
return;
}
Bitmap bmp = new Bitmap(pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingBus.DrawTransport(gr);
pictureBoxTrolleybus.Image = bmp;
}
private void ButtonCreateTrolleybus_Click(object sender, EventArgs e)
{
Random random = new();
Color mainColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
Color additColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
mainColor = dialog.Color;
}
if (dialog.ShowDialog() == DialogResult.OK)
{
additColor = dialog.Color;
}
_drawingBus = new DrawingTrolleybus(random.Next(100, 300),
random.Next(1000, 3000), mainColor, additColor, Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
_drawingBus.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonCreateBus_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawingBus = new DrawingBus(random.Next(100, 300),
random.Next(1000, 3000), color,
pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
_drawingBus.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingBus == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingBus.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingBus.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingBus.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingBus.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawingBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new
DrawingObjectBus(_drawingBus), pictureBoxTrolleybus.Width,
pictureBoxTrolleybus.Height);
comboBoxStrategy.Enabled = false;
}
if (_strategy == null)
{
return;
}
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
private void ButtonSelectBus_Click(object sender, EventArgs e)
{
SelectedBus = _drawingBus;
DialogResult = DialogResult.OK;
}
}
}

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,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrolleybus.MovementStrategy
{
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

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

View File

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

View File

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

View File

@ -1,4 +1,12 @@
namespace Trolleybus
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace ProjectTrolleybus
{
internal static class Program
{
@ -8,10 +16,24 @@ namespace Trolleybus
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormBusCollection());
}
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectTrolleybus.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Trolleybus.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Down {
get {
object obj = ResourceManager.GetObject("Down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Left {
get {
object obj = ResourceManager.GetObject("Left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Right {
get {
object obj = ResourceManager.GetObject("Right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Up {
get {
object obj = ResourceManager.GetObject("Up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@ -0,0 +1,80 @@
using ProjectTrolleybus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrolleybus.Generics
{
internal class SetGeneric<T>
where T : class
{
private readonly List<T?> _places;
private readonly int _maxCount;
public int Count => _places.Count;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public void Insert(T bus, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(bus, 0, equal);
}
public void Insert(T bus, int position, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
throw new Exception("Неверная позиция для вставки");
if (equal != null)
{
if (_places.Contains(bus, equal))
throw new ArgumentException(nameof(bus));
}
_places.Insert(position, bus);
}
public void Remove(int position)
{
if (!(position >= 0 && position < Count))
throw new BusNotFoundException(position);
_places.RemoveAt(position);
}
public T? this[int position]
{
get
{
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
return;
_places.Insert(position, value);
}
}
public IEnumerable<T?> GetBuses(int? maxBuses = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxBuses.HasValue && i == maxBuses.Value)
{
yield break;
}
}
}
}
}

View File

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

View File

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

View File

@ -8,4 +8,37 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.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>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,12 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{ "Name": "File", "Args": { "path": "log.log" } }
],
"Properties": {
"Application": "Sample"
}
}
}