Compare commits

..

6 Commits
main ... Lab_3

Author SHA1 Message Date
be22fa43e8 ыва 2024-04-26 16:28:13 +04:00
af2710431b lab3/ 2024-04-25 18:54:43 +04:00
13c943ceda вап 2024-04-25 18:36:41 +04:00
1429394e5a LAb2 2024-04-25 18:36:21 +04:00
079f73fef7 akl 2024-04-25 16:12:44 +04:00
969ba7728c lab0 2024-04-25 16:09:15 +04:00
27 changed files with 3586 additions and 0 deletions

63
.gitattributes vendored Normal file
View File

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34728.123
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjertTrain", "ProjertTrain\ProjertTrain.csproj", "{C3A1D95F-D40D-4B35-8109-2358CFEA941D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C3A1D95F-D40D-4B35-8109-2358CFEA941D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C3A1D95F-D40D-4B35-8109-2358CFEA941D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3A1D95F-D40D-4B35-8109-2358CFEA941D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3A1D95F-D40D-4B35-8109-2358CFEA941D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C05A158C-DDB4-4ECA-8451-4EDD98AAADFB}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,115 @@
using ProjectTrain.Drawnings;
namespace ProjectTrain.CollectionGenericObjects
{
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 180;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 70;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция автомобилей
/// </summary>
protected ICollectionGenericObjects<DrawningTrain>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция автомобилей</param>
public AbstractCompany(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningTrain> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="сruiser">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrain сruiser)
{
return company._collection.Insert(сruiser);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningTrain operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningTrain? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningTrain? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}
}

View File

@ -0,0 +1,45 @@
namespace ProjectTrain.CollectionGenericObjects
{
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
}
}

View File

@ -0,0 +1,97 @@
using ProjectTrain.Drawnings;
namespace ProjectTrain.CollectionGenericObjects
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } }
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
// TODO проверка позиции
if (position >= _collection.Length || position < 0)
{
return null;
}
return _collection[position];
}
public int Insert(T obj)
{
// TODO вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index++;
}
return -1;
}
public int Insert(T obj, int position)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{ return null; }
T drawningTrain = _collection[position];
_collection[position] = null;
return drawningTrain;
}
}
}

View File

@ -0,0 +1,65 @@
using ProjectTrain.Drawnings;
namespace ProjectTrain.CollectionGenericObjects
{
/// <summary>
/// Реализация абстрактной компании - каршеринг
/// </summary>
public class TrainDockingService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public TrainDockingService(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningTrain> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 2);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth - 20, j * _placeSizeHeight);
g.DrawLine(pen, i * _placeSizeWidth + _placeSizeWidth - 20, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth - 20, j * _placeSizeHeight + _placeSizeHeight);
}
}
}
protected override void SetObjectsPosition()
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int curWidth = 0;
int curHeight = 0;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
if (curWidth < width - 1)
curWidth++;
else
{
curWidth = 0;
curHeight ++;
}
if (curHeight >= height)
{
return;
}
}
}
}
}

View File

@ -0,0 +1,27 @@
namespace ProjectTrain.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,72 @@
using System.Drawing.Drawing2D;
using ProjectTrain.Entities;
namespace ProjectTrain.Drawnings
{
public class DrawningElectroTrain : DrawningTrain
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="horns">Признак наличия рогов</param>
/// <param name="electro">Признак наличия электрической батареи</param>
/// <param name="headlight">Признак наличия фары</param>
public DrawningElectroTrain(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool electro, bool headlight)
: base(150, 50)
{
EntityTrain = new EntityElectroTrain(speed, weight, bodyColor, additionalColor, horns, electro, headlight);
}
public override void DrawTransport(Graphics g)
{
if (EntityTrain == null || EntityTrain is not EntityElectroTrain entityElectroTrain || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black, 2);
Pen pen2 = new(Color.White, 1);
Brush wheelBrush = new SolidBrush(Color.Black);
Brush wheelBrush2 = new SolidBrush(Color.Gray);
Brush headlightBrush = new SolidBrush(Color.Yellow);
Brush glassBrush = new SolidBrush(Color.Cyan);
Brush ElectroBrush = new HatchBrush(HatchStyle.ZigZag, entityElectroTrain.AdditionalColor, Color.FromArgb(163, 163, 163));
Brush additionalBrush = new SolidBrush(entityElectroTrain.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityTrain.BodyColor);
Point[] points = { new Point(_startPosX.Value + 5, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value, _startPosY.Value + 20) };
g.FillPolygon(additionalBrush, points);
base.DrawTransport(g);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value, _startPosX.Value + 47, _startPosY.Value - 5);
g.DrawLine(pen, _startPosX.Value + 47, _startPosY.Value - 5, _startPosX.Value + 67, _startPosY.Value - 10);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value - 10, _startPosX.Value + 87, _startPosY.Value - 5);
g.DrawLine(pen, _startPosX.Value + 87, _startPosY.Value - 5, _startPosX.Value + 67, _startPosY.Value);
if (entityElectroTrain.Electro)
{
g.FillRectangle(ElectroBrush, _startPosX.Value + 107, _startPosY.Value - 5 + 3, 33, 28);
g.DrawRectangle(pen, _startPosX.Value + 107, _startPosY.Value - 5 + 3, 33, 28);
}
if (entityElectroTrain.Headlight)
{
g.FillEllipse(headlightBrush, _startPosX.Value - 3, _startPosY.Value + 23, 6, 14);
g.DrawEllipse(pen, _startPosX.Value - 3, _startPosY.Value + 23, 6, 14);
}
}
}
}

View File

@ -0,0 +1,252 @@
using ProjectTrain.Entities;
using System.Drawing.Drawing2D;
namespace ProjectTrain.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningTrain
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityTrain? EntityTrain { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки поезда
/// </summary>
private readonly int _drawningTrainWidth = 150;
/// <summary>
/// Высота прорисовки поезда
/// </summary>
private readonly int _drawningTrainHeight = 50;
private readonly int _drawningEnginesWidth = 3;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningTrainWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningTrainHeight;
/// <summary>
/// Пустой онструктор
/// </summary>
private DrawningTrain()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningTrain(int speed, double weight, Color bodyColor) : this()
{
EntityTrain = new EntityTrain(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningCarWidth">Ширина прорисовки автомобиля</param>
/// <param name="drawningCarHeight">Высота прорисовки автомобиля</param>
protected DrawningTrain(int drawningCarWidth, int drawningCarHeight) : this()
{
_drawningTrainWidth = drawningCarWidth;
_pictureHeight = drawningCarHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта,если она была уже установлена
if (_drawningTrainHeight > height || _drawningTrainWidth > width)
{
return false;
}
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
SetPosition(_startPosX.Value, _startPosY.Value);
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x < 0 || x + _drawningTrainWidth > _pictureWidth || y < 0 || y + _drawningTrainHeight > _pictureHeight)
{
_startPosX = _pictureWidth - _drawningTrainWidth;
_startPosY = _pictureHeight - _drawningTrainHeight;
}
else
{
_startPosX = x;
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityTrain == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityTrain.Step - _drawningEnginesWidth > 0)
{
_startPosX -= (int)EntityTrain.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityTrain.Step > 0)
{
_startPosY -= (int)EntityTrain.Step;
}
return true;
// вправо
case DirectionType.Right:
//TODO прописать логику сдвига в право
if (_startPosX.Value + EntityTrain.Step + _drawningTrainWidth < _pictureWidth)
{
_startPosX += (int)EntityTrain.Step;
}
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityTrain.Step + _drawningTrainHeight < _pictureHeight)
{
_startPosY += (int)EntityTrain.Step;
}
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityTrain == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black, 2);
Pen pen2 = new(Color.White, 1);
Brush wheelBrush = new SolidBrush(Color.Black);
Brush wheelBrush2 = new SolidBrush(Color.Gray);
Brush headlightBrush = new SolidBrush(Color.Yellow);
Brush glassBrush = new SolidBrush(Color.Cyan);
//Brush ElectroBrush = new HatchBrush(HatchStyle.ZigZag, entityElectroTrain.AdditionalColor, Color.FromArgb(163, 163, 163));
//Brush additionalBrush = new SolidBrush(entityElectroTrain.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityTrain.BodyColor);
//границы круисера
Point[] points = { new Point(_startPosX.Value + 5, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value, _startPosY.Value + 20) };
//g.FillPolygon(additionalBrush, points);
g.FillRectangle(bodyBrush, _startPosX.Value, _startPosY.Value + 20, 140, 20);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 20, 140, 20);
g.DrawLine(pen, _startPosX.Value + 5, _startPosY.Value, _startPosX.Value + 140, _startPosY.Value);
g.DrawLine(pen, _startPosX.Value + 140, _startPosY.Value, _startPosX.Value + 140, _startPosY.Value + 20);
g.DrawLine(pen, _startPosX.Value, _startPosY.Value + 20, _startPosX.Value + 5, _startPosY.Value);
g.FillRectangle(wheelBrush, _startPosX.Value + 140, _startPosY.Value + 3, 7, 34);
//дверь
g.FillRectangle(bodyBrush, _startPosX.Value + 47, _startPosY.Value + 6, 15, 29);
g.DrawRectangle(pen, _startPosX.Value + 47, _startPosY.Value + 6, 15, 29);
//окна
g.FillRectangle(glassBrush, _startPosX.Value + 12, _startPosY.Value + 3, 13, 14);
g.FillRectangle(glassBrush, _startPosX.Value + 28, _startPosY.Value + 3, 13, 14);
g.FillRectangle(glassBrush, _startPosX.Value + 124, _startPosY.Value + 3, 13, 14);
//колёса
Point[] points2 = { new Point(_startPosX.Value + 5, _startPosY.Value + 40), new Point(_startPosX.Value + 55, _startPosY.Value + 40), new Point(_startPosX.Value + 45, _startPosY.Value + 47), new Point(_startPosX.Value - 5, _startPosY.Value + 47) };
g.FillPolygon(wheelBrush, points2);
Point[] points3 = { new Point(_startPosX.Value + 145, _startPosY.Value + 47), new Point(_startPosX.Value + 95, _startPosY.Value + 47), new Point(_startPosX.Value + 85, _startPosY.Value + 40), new Point(_startPosX.Value + 135, _startPosY.Value + 40) };
g.FillPolygon(wheelBrush, points3);
g.FillEllipse(wheelBrush2, _startPosX.Value + 37, _startPosY.Value + 41, 14, 14);
g.DrawEllipse(pen2, _startPosX.Value + 37, _startPosY.Value + 41, 15, 15);
g.FillEllipse(wheelBrush2, _startPosX.Value + 10, _startPosY.Value + 41, 14, 14);
g.DrawEllipse(pen2, _startPosX.Value + 10, _startPosY.Value + 41, 15, 15);
g.FillEllipse(wheelBrush2, _startPosX.Value + 93, _startPosY.Value + 41, 14, 14);
g.DrawEllipse(pen2, _startPosX.Value + 93, _startPosY.Value + 41, 15, 15);
g.FillEllipse(wheelBrush2, _startPosX.Value + 120, _startPosY.Value + 41, 14, 14);
g.DrawEllipse(pen2, _startPosX.Value + 120, _startPosY.Value + 41, 15, 15);
}
}

View File

@ -0,0 +1,30 @@
namespace ProjectTrain.Entities
{
internal class EntityElectroTrain : EntityTrain
{
/// <summary>
/// Признак (опция) наличие рогов
/// </summary>
public bool Horns { get; private set; }
/// <summary>
/// Признак (опция) наличие электробатареи
/// </summary>
public bool Electro { get; private set; }
/// <summary>
/// Признак (опция) наличие фары
/// </summary>
public bool Headlight { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
public EntityElectroTrain(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool electro, bool headlight) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Horns = horns;
Electro = electro;
Headlight = headlight;
}
}
}

View File

@ -0,0 +1,38 @@
namespace ProjectTrain.Entities;
/// <summary>
/// Класс-сущность "поед"
/// </summary>
public class EntityTrain
{
//свойства
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса поеда
/// </summary>
/// <param name="speed">скорость</param>
/// <param name="weight">вес</param>
/// <param name="bodyColor">основной цвет</param>
public EntityTrain(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -0,0 +1,151 @@
namespace ProjectTrain
{
partial class FormTrain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormTrain));
pictureBoxTrain = new PictureBox();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonLeft = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTrain).BeginInit();
SuspendLayout();
//
// pictureBoxTrain
//
pictureBoxTrain.Dock = DockStyle.Fill;
pictureBoxTrain.Location = new Point(0, 0);
pictureBoxTrain.Name = "pictureBoxTrain";
pictureBoxTrain.Size = new Size(800, 450);
pictureBoxTrain.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxTrain.TabIndex = 0;
pictureBoxTrain.TabStop = false;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage");
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(722, 373);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 2;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(722, 409);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage");
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(758, 409);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(686, 409);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 5;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "к центру", "к краю" });
comboBoxStrategy.Location = new Point(637, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 6;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(694, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// FormTrain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonLeft);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(pictureBoxTrain);
Name = "FormTrain";
Text = "FormTrain";
Click += ButtonMove_Click;
((System.ComponentModel.ISupportInitialize)pictureBoxTrain).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxTrain;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private Button buttonLeft;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -0,0 +1,139 @@
using ProjectTrain.Drawnings;
using ProjectTrain.MovementStrategy;
namespace ProjectTrain
{
public partial class FormTrain : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningTrain? _drawningTrain;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawningTrain SetTrain
{
set
{
_drawningTrain = value;
_drawningTrain.SetPictureSize(pictureBoxTrain.Width,
pictureBoxTrain.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// Конструктор формы
/// </summary>
public FormTrain()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Метод прорисовки круисера
/// </summary>
private void Draw()
{
if (_drawningTrain == null)
{
return;
}
Bitmap bmp = new(pictureBoxTrain.Width,
pictureBoxTrain.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningTrain.DrawTransport(gr);
pictureBoxTrain.Image = bmp;
}
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningTrain == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningTrain.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningTrain.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningTrain.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningTrain.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
/// <summary>
/// обработка нажатия кнопки шаг
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningTrain == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableTrain(_drawningTrain), pictureBoxTrain.Width, pictureBoxTrain.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,184 @@
namespace ProjectTrain
{
partial class FormTrainsCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
maskedTextBoxPosision = new MaskedTextBox();
buttonRefresh = new Button();
buttonGetToTest = new Button();
ButtonRemoveTrain = new Button();
ButtonAddElectroTrain = new Button();
ButtonAddTrain = new Button();
comboBoxSelectorCompany = new ComboBox();
pictureBoxTrain = new PictureBox();
groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxTrain).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(maskedTextBoxPosision);
groupBoxTools.Controls.Add(buttonRefresh);
groupBoxTools.Controls.Add(buttonGetToTest);
groupBoxTools.Controls.Add(ButtonRemoveTrain);
groupBoxTools.Controls.Add(ButtonAddElectroTrain);
groupBoxTools.Controls.Add(ButtonAddTrain);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(522, 0);
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(194, 430);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты";
//
// maskedTextBoxPosision
//
maskedTextBoxPosision.Location = new Point(18, 172);
maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision";
maskedTextBoxPosision.Size = new Size(163, 23);
maskedTextBoxPosision.TabIndex = 2;
maskedTextBoxPosision.ValidatingType = typeof(int);
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRefresh.Location = new Point(18, 359);
buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(163, 30);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGetToTest
//
buttonGetToTest.Anchor = AnchorStyles.Right;
buttonGetToTest.Location = new Point(18, 274);
buttonGetToTest.Margin = new Padding(3, 2, 3, 2);
buttonGetToTest.Name = "buttonGetToTest";
buttonGetToTest.Size = new Size(163, 30);
buttonGetToTest.TabIndex = 4;
buttonGetToTest.Text = "передать на тесты";
buttonGetToTest.UseVisualStyleBackColor = true;
buttonGetToTest.Click += ButtonGetToTest_Click;
//
// ButtonRemoveTrain
//
ButtonRemoveTrain.Anchor = AnchorStyles.Right;
ButtonRemoveTrain.Location = new Point(18, 203);
ButtonRemoveTrain.Margin = new Padding(3, 2, 3, 2);
ButtonRemoveTrain.Name = "ButtonRemoveTrain";
ButtonRemoveTrain.Size = new Size(163, 30);
ButtonRemoveTrain.TabIndex = 3;
ButtonRemoveTrain.Text = "удалить поезд";
ButtonRemoveTrain.UseVisualStyleBackColor = true;
ButtonRemoveTrain.Click += ButtonRemoveTrain_Click;
//
// ButtonAddElectroTrain
//
ButtonAddElectroTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddElectroTrain.Location = new Point(18, 114);
ButtonAddElectroTrain.Margin = new Padding(3, 2, 3, 2);
ButtonAddElectroTrain.Name = "ButtonAddElectroTrain";
ButtonAddElectroTrain.Size = new Size(163, 38);
ButtonAddElectroTrain.TabIndex = 2;
ButtonAddElectroTrain.Text = "добваление электро-поеда";
ButtonAddElectroTrain.UseVisualStyleBackColor = true;
ButtonAddElectroTrain.Click += ButtonAddElectroTrain_Click;
//
// ButtonAddTrain
//
ButtonAddTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddTrain.BackgroundImageLayout = ImageLayout.Center;
ButtonAddTrain.Location = new Point(18, 80);
ButtonAddTrain.Margin = new Padding(3, 2, 3, 2);
ButtonAddTrain.Name = "ButtonAddTrain";
ButtonAddTrain.Size = new Size(163, 30);
ButtonAddTrain.TabIndex = 1;
ButtonAddTrain.Text = "добваление поезда";
ButtonAddTrain.UseVisualStyleBackColor = true;
ButtonAddTrain.Click += ButtonAddTrain_Click;
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "хранилище" });
comboBoxSelectorCompany.Location = new Point(18, 20);
comboBoxSelectorCompany.Margin = new Padding(3, 2, 3, 2);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(163, 23);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged_1;
//
// pictureBoxTrain
//
pictureBoxTrain.Dock = DockStyle.Fill;
pictureBoxTrain.Location = new Point(0, 0);
pictureBoxTrain.Margin = new Padding(3, 2, 3, 2);
pictureBoxTrain.Name = "pictureBoxTrain";
pictureBoxTrain.Size = new Size(522, 430);
pictureBoxTrain.TabIndex = 1;
pictureBoxTrain.TabStop = false;
//
// FormTrainsCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(716, 430);
Controls.Add(pictureBoxTrain);
Controls.Add(groupBoxTools);
Margin = new Padding(3, 2, 3, 2);
Name = "FormTrainsCollection";
Text = "FormTrainsCollection";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxTrain).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button ButtonAddElectroTrain;
private Button ButtonAddTrain;
private Button ButtonRemoveTrain;
private Button buttonRefresh;
private Button buttonGetToTest;
private PictureBox pictureBoxTrain;
private MaskedTextBox maskedTextBoxPosision;
}
}

View File

@ -0,0 +1,169 @@
using ProjectTrain.CollectionGenericObjects;
using ProjectTrain.Drawnings;
namespace ProjectTrain
{
public partial class FormTrainsCollection : Form
{
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormTrainsCollection()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged_1(object sender, EventArgs e)
{
switch (comboBoxSelectorCompany.Text)
{
case "хранилище":
_company = new TrainDockingService(pictureBoxTrain.Width,
pictureBoxTrain.Height, new MassiveGenericObjects<DrawningTrain>());
break;
}
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningTrain drawningTrain;
switch (type)
{
case nameof(DrawningTrain):
drawningTrain = new DrawningTrain(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningElectroTrain):
drawningTrain = new DrawningElectroTrain(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random),
GetColor(random),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningTrain != -1)
{
MessageBox.Show("объект добавлен");
pictureBoxTrain.Image = _company.Show();
}
else
{
MessageBox.Show("не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
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;
}
return color;
}
//private void ButtonAddTrain_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTrain));
//private void ButtonAddElectroTrain_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningElectroTrain));
private void ButtonAddTrain_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningTrain));
}
private void ButtonAddElectroTrain_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningElectroTrain));
}
private void ButtonRemoveTrain_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosision.Text) || _company == null)
{
return;
}
if (MessageBox.Show("удалить объект?", "удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosision.Text);
if (_company - pos != null)
{
MessageBox.Show("объект удален");
pictureBoxTrain.Image = _company.Show();
}
else
{
MessageBox.Show("не удалось удалить объект");
}
}
private void ButtonGetToTest_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningTrain? cruiser = null;
int counter = 100;
while (cruiser == null)
{
cruiser = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (cruiser == null)
{
return;
}
FormTrain form = new()
{
SetTrain = cruiser
};
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBoxTrain.Image = _company.Show();
}
}
}

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,123 @@
namespace ProjectTrain.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}
}

View File

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

View File

@ -0,0 +1,53 @@
namespace ProjectTrain.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта к краю экрана
/// </summary>
internal class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder - GetStep() <= FieldWidth
&& objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder - GetStep() <= FieldHeight
&& objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

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

View File

@ -0,0 +1,62 @@
using ProjectTrain.Drawnings;
namespace ProjectTrain.MovementStrategy
{
/// <summary>
/// класс реалтзация для IMoveableObject с использованием DrawningTrain
/// </summary>
public class MoveableTrain : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningTrain или его наследника
/// </summary>
private readonly DrawningTrain? _cruiser = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="cruiser">Объект класса DrawningTrain</param>
public MoveableTrain(DrawningTrain cruiser)
{
_cruiser = cruiser;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_cruiser == null || _cruiser.EntityTrain == null ||
!_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_cruiser.GetPosX.Value,
_cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight);
}
}
public int GetStep => (int)(_cruiser?.EntityTrain?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_cruiser == null || _cruiser.EntityTrain == null)
{
return false;
}
return _cruiser.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}
}

View File

@ -0,0 +1,26 @@
namespace ProjectTrain.MovementStrategy
{
/// <summary>
/// Направление перемещения
/// </summary>
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

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

View File

@ -0,0 +1,22 @@
namespace ProjectTrain.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}
}

View File

@ -0,0 +1,16 @@
namespace ProjectTrain
{
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 FormTrainsCollection());
}
}
}

View File

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>