Compare commits

...

7 Commits

Author SHA1 Message Date
e591f4771a Залил лаб 6 2023-11-18 20:48:04 +03:00
d9904c783e Залил лаб5 2023-11-11 20:29:38 +03:00
7b3777a796 Залил лаб4 2023-10-25 21:44:34 +03:00
3e84994000 Залил лаб3 2023-10-25 20:28:25 +03:00
77ea779c6b Залил лаб2 2023-10-21 21:27:46 +03:00
e8a24da5cd Проверил Лаб1 2023-10-19 19:12:45 +03:00
efcf9cea4b Залил лаб1 2023-10-18 20:42:11 +03:00
33 changed files with 3372 additions and 0 deletions

25
Trolleybus/Trolleybus.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34024.191
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Trolleybus", "Trolleybus\Trolleybus.csproj", "{D0EC2C7B-1218-45A1-95F1-7697825B93CF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D0EC2C7B-1218-45A1-95F1-7697825B93CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D0EC2C7B-1218-45A1-95F1-7697825B93CF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D0EC2C7B-1218-45A1-95F1-7697825B93CF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D0EC2C7B-1218-45A1-95F1-7697825B93CF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7BD35329-9874-48AD-A3F4-50BA7A354CF5}
EndGlobalSection
EndGlobal

View File

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

View File

@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
using Trolleybus.MovementStrategy;
namespace Trolleybus.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawingBus
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
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 = 150;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 95;
/// <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; //width - кол-во помещаемых на PictureBox автобусов по горизонтали
int height = picHeight / _placeSizeHeight; //height - кол-во помещаемых на PictureBox автобусов по вертикали
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height); //width*height - кол-во мест на PictureBox для автобусов; размер массива
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
//Возвращается место в коллекции, в которое добавлено
public static int operator +(BusesGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(BusesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
return true;
}
return false;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap 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++)
{
g.DrawLine(pen, i * (_placeSizeWidth + 10), 0, i * (_placeSizeWidth + 10), (_pictureHeight / _placeSizeHeight) * (_placeSizeHeight + 10));
}
//горизонтальные линии
for (int i = 0; i <= _pictureHeight / _placeSizeHeight; i++)
{
for (int j = 0; j < _pictureWidth / _placeSizeWidth; j++)
{
g.DrawLine(pen, j * (_placeSizeWidth + 10), i * (_placeSizeHeight + 10), j * (_placeSizeWidth + 10) + _placeSizeWidth / 2, i * (_placeSizeHeight + 10));
}
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int i = 0;
int j = _pictureWidth / _placeSizeWidth - 1;
foreach (var bus in _collection.GetBuses())
{
if (bus != null)
{
bus.SetPosition(j * (_placeSizeWidth + 10) + 5, i * (_placeSizeHeight) + 10);
bus.DrawTransport(g);
}
j--;
//переход на новую строчку
if (j < 0)
{
j = _pictureWidth / _placeSizeWidth - 1;
i++;
}
}
}
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetBuses => _collection.GetBuses();
}
}

View File

@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
using Trolleybus.MovementStrategy;
namespace Trolleybus.Generics
{
internal class BusesGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, BusesGenericCollection<DrawingBus, DrawingObjectBus>> _busStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> 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<string, BusesGenericCollection<DrawingBus, DrawingObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// проверка, существует ли набор с таким ключём
if (_busStorages.ContainsKey(name))
{
return;
}
var busCollection = new BusesGenericCollection<DrawingBus, DrawingObjectBus>(_pictureWidth, _pictureHeight);
_busStorages.Add(name, busCollection);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_busStorages.ContainsKey(name))
{
_busStorages.Remove(name);
}
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BusesGenericCollection<DrawingBus, DrawingObjectBus>? this[string ind]
{
get
{
if (!_busStorages.ContainsKey(ind))
{
return null;
}
return _busStorages[ind];
}
}
/// <summary>
/// Сохранение информации по автобусам из хранилища в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, 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}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using StreamWriter sw = new StreamWriter(filename, false);
sw.WriteLine($"BusesStorage");
sw.WriteLine(data);
return true;
}
/// <summary>
/// Загрузка информации по автобусам из файла в хранилище
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using(StreamReader sr = File.OpenText(filename))
{
String currentLine = sr.ReadLine();
// Если первая строка пустая или в файле не те данные
if (currentLine == null || !currentLine.Contains("BusesStorage"))
{
return false;
}
// Очистка хранилища
_busStorages.Clear();
currentLine = sr.ReadLine();
while (currentLine != "" && currentLine != null)
{
string[] record = currentLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
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) == -1)
{
return false;
}
}
}
_busStorages.Add(record[0], collection);
currentLine = sr.ReadLine();
}
}
return true;
}
}
}

View File

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

View File

@ -0,0 +1,227 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.Entities;
using Trolleybus.MovementStrategy;
namespace Trolleybus.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingBus
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBus? EntityBus { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автобуса
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автобуса
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автобуса
/// </summary>
protected readonly int _busWidth = 150;
/// <summary>
/// Высота прорисовки автобуса
/// </summary>
protected readonly int _busHeight = 95;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _busWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _busHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningBus
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectBus(this);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
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);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="busWidth">Ширина прорисовки автобуса</param>
/// <param name="busHeight">Высота прорисовки автобус</param>
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);
}
//Метод для того, чтобы изменить размеры окна, т.к. pictureBoxObject в FormBusConfig и pictureBoxCollection в FormBusesCollection
//имеют разные размеры, из-за чего объекты некорректно отрисовываются в FormBusesCollection после FormBusConfig
public void ChangePictureSize(int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
_startPosX = Math.Min(Math.Max(x, 0), _pictureWidth - _busWidth);
_startPosY = Math.Min(Math.Max(y, 0), _pictureHeight - _busHeight);
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityBus == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX - EntityBus.Step > 0)
{
_startPosX -= (int)EntityBus.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityBus.Step > 0)
{
_startPosY -= (int)EntityBus.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + _busWidth + EntityBus.Step < _pictureWidth)
{
_startPosX += (int)EntityBus.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _busHeight + EntityBus.Step < _pictureHeight)
{
_startPosY += (int)EntityBus.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
Pen pen = new(Color.Black); //чёрный цвет для колёс
Pen bodyPen = new(EntityBus.BodyColor);
Pen windowPen = new(Color.Cyan); //цвет окон
//РИСОВАНИЕ САМОГО АВТОБУСА
//корпус
g.DrawLine(bodyPen, _startPosX, _startPosY + 30, _startPosX, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX, _startPosY + 80, _startPosX + 20, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 45, _startPosY + 80, _startPosX + 105, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 130, _startPosY + 80, _startPosX + 150, _startPosY + 80);
g.DrawLine(bodyPen, _startPosX + 150, _startPosY + 80, _startPosX + 150, _startPosY + 30);
g.DrawLine(bodyPen, _startPosX + 150, _startPosY + 30, _startPosX, _startPosY + 30);
//колёса
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 70, 25, 25);
g.DrawEllipse(pen, _startPosX + 105, _startPosY + 70, 25, 25);
//дверь
g.DrawRectangle(bodyPen, _startPosX + 55, _startPosY + 50, 15, 30);
//окна
//окна до двери
for (int i = 0; i < 2; i++)
{
g.DrawEllipse(windowPen, _startPosX + 5 + 25 * i, _startPosY + 35, 16, 24);
}
//окна после двери
for (int i = 0; i < 3; i++)
{
g.DrawEllipse(windowPen, _startPosX + 75 + 25 * i, _startPosY + 35, 16, 24);
}
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
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 + _busWidth + EntityBus.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _busHeight + EntityBus.Step < _pictureHeight,
_ => false,
};
}
}
}

View File

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

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Trolleybus.Entities;
namespace Trolleybus.DrawingObjects
{
public class DrawingTrolleybus : DrawingBus
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="horns">Признак наличия "рогов"</param>
/// <param name="batteries">Признак наличия отсека под электрические батареи</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawingTrolleybus(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool batteries, int width, int height) : base(speed, weight, bodyColor, width, height, 150, 95)
{
if (EntityBus != null)
{
EntityBus = new EntityTrolleybus(speed, weight, bodyColor, additionalColor, horns, batteries);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityBus is not EntityTrolleybus trolleyBus)
{
return;
}
Pen additionalPen = new(trolleyBus.AdditionalColor);
Brush additionalBrush = new SolidBrush(trolleyBus.AdditionalColor);
base.DrawTransport(g);
//опциональные "рога"
if (trolleyBus.Horns)
{
g.DrawLine(additionalPen, _startPosX + 70, _startPosY + 30, _startPosX + 40, _startPosY);
g.DrawLine(additionalPen, _startPosX + 70, _startPosY + 30, _startPosX + 60, _startPosY);
}
//опциональный отсек для батареи
if (trolleyBus.Batteries)
{
Point[] pointsOfBatteries = { new Point(_startPosX + 70, _startPosY + 30), new Point(_startPosX + 70, _startPosY + 25), new Point(_startPosX + 100, _startPosY + 25), new Point(_startPosX + 110, _startPosY + 30)};
g.FillPolygon(additionalBrush, pointsOfBatteries);
}
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.Entities;
using Trolleybus.DrawingObjects;
using System.Configuration;
namespace Trolleybus
{
public static class ExtensionDrawingBus
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingBus? CreateDrawingBus(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingBus(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingTrolleybus(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingBus">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
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}";
//Если это автобус (т.е. не троллейбус), то строки из 3 свойств достаточно
if (bus is not EntityTrolleybus trolleyBus)
{
return str;
}
//Если это троллейбус, то дополнение строки из 3 свойств доп. свойствами
return $"{str}{separatorForObject}{trolleyBus.AdditionalColor.Name}{separatorForObject}{trolleyBus.Horns}{separatorForObject}{trolleyBus.Batteries}";
}
}
}

View File

@ -0,0 +1,357 @@
namespace Trolleybus
{
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();
labelAdvancedObject = new Label();
labelSimpleObject = new Label();
groupBoxColor = new GroupBox();
panelLightBlue = new Panel();
panelBlue = new Panel();
panelPurple = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelYellow = new Panel();
panelOrange = new Panel();
panelRed = new Panel();
checkBoxBatteries = new CheckBox();
checkBoxHorns = new CheckBox();
numericUpDownSpeed = new NumericUpDown();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
pictureBoxObject = new PictureBox();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelMainColor = new Label();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxConfig.SuspendLayout();
groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfig
//
groupBoxConfig.Controls.Add(labelAdvancedObject);
groupBoxConfig.Controls.Add(labelSimpleObject);
groupBoxConfig.Controls.Add(groupBoxColor);
groupBoxConfig.Controls.Add(checkBoxBatteries);
groupBoxConfig.Controls.Add(checkBoxHorns);
groupBoxConfig.Controls.Add(numericUpDownSpeed);
groupBoxConfig.Controls.Add(numericUpDownWeight);
groupBoxConfig.Controls.Add(labelWeight);
groupBoxConfig.Controls.Add(labelSpeed);
groupBoxConfig.Location = new Point(12, 81);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(570, 250);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
//
// labelAdvancedObject
//
labelAdvancedObject.BorderStyle = BorderStyle.FixedSingle;
labelAdvancedObject.Location = new Point(440, 188);
labelAdvancedObject.Name = "labelAdvancedObject";
labelAdvancedObject.Size = new Size(120, 30);
labelAdvancedObject.TabIndex = 8;
labelAdvancedObject.Text = "Продвинутый";
labelAdvancedObject.TextAlign = ContentAlignment.MiddleCenter;
labelAdvancedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(283, 188);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(120, 30);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// groupBoxColor
//
groupBoxColor.Controls.Add(panelLightBlue);
groupBoxColor.Controls.Add(panelBlue);
groupBoxColor.Controls.Add(panelPurple);
groupBoxColor.Controls.Add(panelGray);
groupBoxColor.Controls.Add(panelGreen);
groupBoxColor.Controls.Add(panelYellow);
groupBoxColor.Controls.Add(panelOrange);
groupBoxColor.Controls.Add(panelRed);
groupBoxColor.Location = new Point(283, 32);
groupBoxColor.Name = "groupBoxColor";
groupBoxColor.Size = new Size(277, 145);
groupBoxColor.TabIndex = 6;
groupBoxColor.TabStop = false;
groupBoxColor.Text = "Цвета";
//
// panelLightBlue
//
panelLightBlue.BackColor = Color.Aqua;
panelLightBlue.Location = new Point(5, 85);
panelLightBlue.Name = "panelLightBlue";
panelLightBlue.Size = new Size(50, 40);
panelLightBlue.TabIndex = 0;
//
// panelBlue
//
panelBlue.BackColor = Color.DarkBlue;
panelBlue.Location = new Point(75, 85);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(50, 40);
panelBlue.TabIndex = 0;
//
// panelPurple
//
panelPurple.BackColor = Color.DarkViolet;
panelPurple.Location = new Point(145, 85);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(50, 40);
panelPurple.TabIndex = 0;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(215, 85);
panelGray.Name = "panelGray";
panelGray.Size = new Size(50, 40);
panelGray.TabIndex = 0;
//
// panelGreen
//
panelGreen.BackColor = Color.DarkGreen;
panelGreen.Location = new Point(215, 25);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(50, 40);
panelGreen.TabIndex = 0;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(145, 25);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(50, 40);
panelYellow.TabIndex = 0;
//
// panelOrange
//
panelOrange.BackColor = Color.DarkOrange;
panelOrange.Location = new Point(75, 25);
panelOrange.Name = "panelOrange";
panelOrange.Size = new Size(50, 40);
panelOrange.TabIndex = 0;
//
// panelRed
//
panelRed.BackColor = Color.Firebrick;
panelRed.Location = new Point(5, 25);
panelRed.Name = "panelRed";
panelRed.Size = new Size(50, 40);
panelRed.TabIndex = 0;
//
// checkBoxBatteries
//
checkBoxBatteries.AutoSize = true;
checkBoxBatteries.Location = new Point(13, 149);
checkBoxBatteries.Name = "checkBoxBatteries";
checkBoxBatteries.Size = new Size(230, 24);
checkBoxBatteries.TabIndex = 5;
checkBoxBatteries.Text = "Наличие отсека для батарей";
checkBoxBatteries.UseVisualStyleBackColor = true;
//
// checkBoxHorns
//
checkBoxHorns.AutoSize = true;
checkBoxHorns.Location = new Point(13, 119);
checkBoxHorns.Name = "checkBoxHorns";
checkBoxHorns.Size = new Size(149, 24);
checkBoxHorns.TabIndex = 4;
checkBoxHorns.Text = "Наличие \"рогов\"";
checkBoxHorns.UseVisualStyleBackColor = true;
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(94, 32);
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 = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(94, 83);
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 = 2;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(6, 85);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(6, 32);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// pictureBoxObject
//
pictureBoxObject.BorderStyle = BorderStyle.FixedSingle;
pictureBoxObject.Location = new Point(35, 84);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(327, 204);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelMainColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(612, 29);
panelObject.Name = "panelObject";
panelObject.Size = new Size(401, 302);
panelObject.TabIndex = 2;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(272, 19);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(90, 50);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
//
// labelMainColor
//
labelMainColor.AllowDrop = true;
labelMainColor.BorderStyle = BorderStyle.FixedSingle;
labelMainColor.Location = new Point(35, 19);
labelMainColor.Name = "labelMainColor";
labelMainColor.Size = new Size(90, 50);
labelMainColor.TabIndex = 2;
labelMainColor.Text = "Цвет";
labelMainColor.TextAlign = ContentAlignment.MiddleCenter;
labelMainColor.DragDrop += LabelMainColor_DragDrop;
labelMainColor.DragEnter += LabelMainColor_DragEnter;
//
// buttonAdd
//
buttonAdd.Location = new Point(647, 337);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29);
buttonAdd.TabIndex = 3;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(884, 337);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 4;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormBusConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1032, 383);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxConfig);
Name = "FormBusConfig";
Text = "FormBusConfig";
groupBoxConfig.ResumeLayout(false);
groupBoxConfig.PerformLayout();
groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private NumericUpDown numericUpDownSpeed;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxBatteries;
private CheckBox checkBoxHorns;
private GroupBox groupBoxColor;
private Panel panelLightBlue;
private Panel panelBlue;
private Panel panelPurple;
private Panel panelGray;
private Panel panelGreen;
private Panel panelYellow;
private Panel panelOrange;
private Panel panelRed;
private Label labelAdvancedObject;
private Label labelSimpleObject;
private PictureBox pictureBoxObject;
private Panel panelObject;
private Label labelAdditionalColor;
private Label labelMainColor;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,198 @@
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 Trolleybus.DrawingObjects;
using Trolleybus.Entities;
namespace Trolleybus
{
public partial class FormBusConfig : Form
{
/// <summary>
/// Переменная-выбранный автобус
/// </summary>
DrawingBus? _bus = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingBus>? EventAddBus;
/// <summary>
/// Конструктор
/// </summary>
public FormBusConfig()
{
InitializeComponent();
panelRed.MouseDown += PanelColor_MouseDown;
panelOrange.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelLightBlue.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовка объекта
/// </summary>
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;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawingBus> ev)
{
if (EventAddBus == null)
{
EventAddBus = ev;
}
else
{
EventAddBus += ev;
}
}
/// <summary>
/// Передача информации (имени Label) при нажатии на Label (простой / продвинутый объект)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому: текст) для панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации (имени Label)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_bus = new DrawingBus(
(int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.White,
pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelAdvancedObject":
_bus = new DrawingTrolleybus(
(int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value,
Color.White, Color.Black,
checkBoxHorns.Checked, checkBoxBatteries.Checked,
pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
DrawBus();
}
/// <summary>
/// Передача цвета при нажатии на одну из Panel с цветом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому: цвет) для Label с основным цветом
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelMainColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _bus != null)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемого цвета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelMainColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
_bus.EntityBus.ChangeBodyColor(color);
DrawBus();
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому: цвет) для Label с доп. цветом
/// и проверка, что создаётся троллейбус
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _bus != null && _bus is DrawingTrolleybus)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
//Приведение к EntityTrolleybus для замены доп. цвета
EntityTrolleybus? _trolleybus = _bus.EntityBus as EntityTrolleybus;
_trolleybus.ChangeAdditionalColor(color);
DrawBus();
}
/// <summary>
/// Добавление автобуса
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
EventAddBus?.Invoke(_bus);
Close();
}
}
}

View File

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

View File

@ -0,0 +1,439 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
using Trolleybus.Generics;
using Trolleybus.MovementStrategy;
namespace Trolleybus
{
/// <summary>
/// Форма для работы с набором объектов класса DrawingBus
/// </summary>
public partial class FormBusesCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly BusesGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormBusesCollection()
{
InitializeComponent();
_storage = new BusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxSets.SelectedIndex;
listBoxSets.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxSets.Items.Add(_storage.Keys[i]);
}
if (listBoxSets.Items.Count > 0 && (index == -1 || index >= listBoxSets.Items.Count))
{
listBoxSets.SelectedIndex = 0;
}
else if (listBoxSets.Items.Count > 0 && index > -1 && index < listBoxSets.Items.Count)
{
listBoxSets.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddSetOfObjects_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxNameOfSet.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxNameOfSet.Text);
ReloadObjects();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxSets_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxSets.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteSetOfObjects_Click(object sender, EventArgs e)
{
if (listBoxSets.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxSets.SelectedItem}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxSets.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddBus_Click(object sender, EventArgs e)
{
var formBusConfig = new FormBusConfig();
formBusConfig.AddEvent(AddBus);
formBusConfig.Show();
}
private void AddBus(DrawingBus selectedBus)
{
if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
//Возвращение объекту размеров pictureBox с этой формы (до этого создался с размерами pictureBox с FormBusConfig)
selectedBus.ChangePictureSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
if (obj + selectedBus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBuses();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveBus_Click(object sender, EventArgs e)
{
if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
String pos_string = maskedTextBoxNumber.Text;
if (pos_string == "")
{
pos_string = "0";
}
int pos = Convert.ToInt32(pos_string);
if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowBuses();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowBuses();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DownloadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не удалось загрузить данные", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void InitializeComponent()
{
pictureBoxCollection = new PictureBox();
panelTools = new Panel();
panelSets = new Panel();
buttonDeleteSetOfObjects = new Button();
textBoxNameOfSet = new TextBox();
listBoxSets = new ListBox();
buttonAddSetOfObjects = new Button();
buttonRefreshCollection = new Button();
maskedTextBoxNumber = new MaskedTextBox();
buttonRemoveBus = new Button();
buttonAddBus = new Button();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
downloadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
panelSets.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
pictureBoxCollection.Location = new Point(0, 36);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(670, 517);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// panelTools
//
panelTools.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
panelTools.BorderStyle = BorderStyle.FixedSingle;
panelTools.Controls.Add(panelSets);
panelTools.Controls.Add(buttonRefreshCollection);
panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRemoveBus);
panelTools.Controls.Add(buttonAddBus);
panelTools.Location = new Point(676, 36);
panelTools.Name = "panelTools";
panelTools.Size = new Size(200, 517);
panelTools.TabIndex = 1;
//
// panelSets
//
panelSets.Anchor = AnchorStyles.Top | AnchorStyles.Right;
panelSets.BorderStyle = BorderStyle.FixedSingle;
panelSets.Controls.Add(buttonDeleteSetOfObjects);
panelSets.Controls.Add(textBoxNameOfSet);
panelSets.Controls.Add(listBoxSets);
panelSets.Controls.Add(buttonAddSetOfObjects);
panelSets.Location = new Point(17, 11);
panelSets.Name = "panelSets";
panelSets.Size = new Size(170, 283);
panelSets.TabIndex = 4;
//
// buttonDeleteSetOfObjects
//
buttonDeleteSetOfObjects.Location = new Point(3, 222);
buttonDeleteSetOfObjects.Name = "buttonDeleteSetOfObjects";
buttonDeleteSetOfObjects.Size = new Size(162, 45);
buttonDeleteSetOfObjects.TabIndex = 3;
buttonDeleteSetOfObjects.Text = "Удалить набор";
buttonDeleteSetOfObjects.UseVisualStyleBackColor = true;
buttonDeleteSetOfObjects.Click += ButtonDeleteSetOfObjects_Click;
//
// textBoxNameOfSet
//
textBoxNameOfSet.Location = new Point(3, 19);
textBoxNameOfSet.Name = "textBoxNameOfSet";
textBoxNameOfSet.Size = new Size(162, 27);
textBoxNameOfSet.TabIndex = 2;
//
// listBoxSets
//
listBoxSets.FormattingEnabled = true;
listBoxSets.ItemHeight = 20;
listBoxSets.Location = new Point(3, 112);
listBoxSets.Name = "listBoxSets";
listBoxSets.Size = new Size(162, 104);
listBoxSets.TabIndex = 1;
listBoxSets.SelectedIndexChanged += ListBoxSets_SelectedIndexChanged;
//
// buttonAddSetOfObjects
//
buttonAddSetOfObjects.Location = new Point(3, 52);
buttonAddSetOfObjects.Name = "buttonAddSetOfObjects";
buttonAddSetOfObjects.Size = new Size(162, 45);
buttonAddSetOfObjects.TabIndex = 0;
buttonAddSetOfObjects.Text = "Добавить набор";
buttonAddSetOfObjects.UseVisualStyleBackColor = true;
buttonAddSetOfObjects.Click += ButtonAddSetOfObjects_Click;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(17, 465);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(170, 40);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(39, 366);
maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(125, 27);
maskedTextBoxNumber.TabIndex = 2;
maskedTextBoxNumber.ValidatingType = typeof(int);
//
// buttonRemoveBus
//
buttonRemoveBus.Location = new Point(17, 409);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(170, 40);
buttonRemoveBus.TabIndex = 1;
buttonRemoveBus.Text = "Удалить автобус";
buttonRemoveBus.UseVisualStyleBackColor = true;
buttonRemoveBus.Click += ButtonRemoveBus_Click;
//
// buttonAddBus
//
buttonAddBus.Location = new Point(17, 311);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(170, 40);
buttonAddBus.TabIndex = 0;
buttonAddBus.Text = "Добавить автобус";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += ButtonAddBus_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(882, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, downloadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(59, 24);
fileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(224, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// downloadToolStripMenuItem
//
downloadToolStripMenuItem.Name = "downloadToolStripMenuItem";
downloadToolStripMenuItem.Size = new Size(224, 26);
downloadToolStripMenuItem.Text = "Загрузка";
downloadToolStripMenuItem.Click += DownloadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormBusesCollection
//
ClientSize = new Size(882, 553);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormBusesCollection";
Text = "Набор автобусов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
private PictureBox pictureBoxCollection;
private Panel panelTools;
private Button buttonRefreshCollection;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonRemoveBus;
private Panel panelSets;
private Button buttonAddSetOfObjects;
private ListBox listBoxSets;
private TextBox textBoxNameOfSet;
private Button buttonDeleteSetOfObjects;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem downloadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonAddBus;
}
}

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>323, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,190 @@
namespace Trolleybus
{
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()
{
pictureBoxTrolleybus = new PictureBox();
buttonCreateTrolleybus = new Button();
buttonUp = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonCreateBus = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonSelectBus = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).BeginInit();
SuspendLayout();
//
// pictureBoxTrolleybus
//
pictureBoxTrolleybus.Dock = DockStyle.Fill;
pictureBoxTrolleybus.Location = new Point(0, 0);
pictureBoxTrolleybus.Name = "pictureBoxTrolleybus";
pictureBoxTrolleybus.Size = new Size(882, 453);
pictureBoxTrolleybus.TabIndex = 5;
pictureBoxTrolleybus.TabStop = false;
//
// buttonCreateTrolleybus
//
buttonCreateTrolleybus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTrolleybus.Location = new Point(12, 389);
buttonCreateTrolleybus.Name = "buttonCreateTrolleybus";
buttonCreateTrolleybus.Size = new Size(120, 50);
buttonCreateTrolleybus.TabIndex = 6;
buttonCreateTrolleybus.Text = "Создать троллейбус";
buttonCreateTrolleybus.UseVisualStyleBackColor = true;
buttonCreateTrolleybus.Click += ButtonCreateTrolleybus_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.стрелка_вверх;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(812, 377);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 7;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.стрелка_влево;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(776, 413);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 8;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.стрелка_вниз;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(812, 413);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 9;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.стрелка_вправо;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(848, 413);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 10;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonCreateBus
//
buttonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBus.Location = new Point(138, 389);
buttonCreateBus.Name = "buttonCreateBus";
buttonCreateBus.Size = new Size(120, 50);
buttonCreateBus.TabIndex = 11;
buttonCreateBus.Text = "Создать автобус";
buttonCreateBus.UseVisualStyleBackColor = true;
buttonCreateBus.Click += ButtonCreateBus_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "В центр", "В правый нижний угол" });
comboBoxStrategy.Location = new Point(719, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 12;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(748, 46);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(94, 29);
buttonStep.TabIndex = 13;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// buttonSelectBus
//
buttonSelectBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSelectBus.Location = new Point(264, 388);
buttonSelectBus.Name = "buttonSelectBus";
buttonSelectBus.Size = new Size(120, 50);
buttonSelectBus.TabIndex = 14;
buttonSelectBus.Text = "Выбрать";
buttonSelectBus.UseVisualStyleBackColor = true;
buttonSelectBus.Click += ButtonSelectBus_Click;
//
// FormTrolleybus
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(buttonSelectBus);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBus);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonUp);
Controls.Add(buttonCreateTrolleybus);
Controls.Add(pictureBoxTrolleybus);
Name = "FormTrolleybus";
Text = "Троллейбус";
((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxTrolleybus;
private Button buttonCreateTrolleybus;
private Button buttonUp;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateBus;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectBus;
}
}

View File

@ -0,0 +1,182 @@
using Trolleybus.DrawingObjects;
using Trolleybus.MovementStrategy;
namespace Trolleybus
{
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Òðîëëåéáóñ"
/// </summary>
public partial class FormTrolleybus : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingBus? _drawingBus;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âûáðàííûé àâòîáóñ
/// </summary>
public DrawingBus? SelectedBus { get; private set; }
public FormTrolleybus()
{
InitializeComponent();
_abstractStrategy = null;
SelectedBus = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè òðîëëåéáóñà
/// </summary>
private void Draw()
{
if (_drawingBus == null)
{
return;
}
Bitmap bmp = new(pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingBus.DrawTransport(gr);
pictureBoxTrolleybus.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü òðîëëåéáóñ"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTrolleybus_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//âûáîð îñíîâíîãî öâåòà
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//âûáîð äîïîëíèòåëüíîãî öâåòà
ColorDialog dopDialog = new();
if (dopDialog.ShowDialog() == DialogResult.OK)
{
dopColor = dopDialog.Color;
}
_drawingBus = new DrawingTrolleybus(random.Next(100, 300),
random.Next(1000, 3000),
color,
dopColor,
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();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîáóñ"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïîê äâèæåíèÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawingBus == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectBus(_drawingBus), pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
/// <summary>
/// Âûáîð àâòîáóñà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
namespace Trolleybus.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,17 @@
namespace Trolleybus
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[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 FormBusesCollection());
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Trolleybus.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 стрелка_вверх {
get {
object obj = ResourceManager.GetObject("стрелка вверх", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap стрелка_влево {
get {
object obj = ResourceManager.GetObject("стрелка влево", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap стрелка_вниз {
get {
object obj = ResourceManager.GetObject("стрелка вниз", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap стрелка_вправо {
get {
object obj = ResourceManager.GetObject("стрелка вправо", 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="стрелка вверх" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\стрелка вверх.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="стрелка влево" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\стрелка влево.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="стрелка вниз" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\стрелка вниз.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="стрелка вправо" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\стрелка вправо.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: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

View File

@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trolleybus.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T>? _places;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в начало набора
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <returns></returns>
public int Insert(T bus)
{
if (Count + 1 <= _maxCount)
{
_places.Insert(0, bus);
//0 в данном случае место, на котоорое добавился элемннт, вставка прошла успешно
return 0;
}
//если при добавлении в списке станет больше макс. кол-ва элементов, то как бы вставлять будет некуда
return -1;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T bus, int position)
{
if (position >= _maxCount || position < 0)
{
//позиция неверная, значит вставить нельзя
return -1;
}
if (Count + 1 <= _maxCount)
{
_places.Insert(position, bus);
//место в списке, по которому вставили, вставка прошла успешно
return position;
}
//места в списке нет
return -1;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position >= Count || position < 0)
{
return false;
}
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (position >= Count || position < 0)
{
return null;
}
return _places[position];
}
set
{
if (position >= Count || position < 0)
{
return;
}
_places[position] = value;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetBuses(int? maxBuses = null)
{
for (int i = 0; i < 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 Trolleybus.MovementStrategy
{
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>