Compare commits

..

6 Commits
main ... laba3

34 changed files with 2583 additions and 0 deletions

25
Laba1Loco/Laba1Loco.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33424.131
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Laba1Loco", "Laba1Loco\Laba1Loco.csproj", "{9F9C9603-3EF7-403E-A895-04EA0CBC5586}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9F9C9603-3EF7-403E-A895-04EA0CBC5586}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9F9C9603-3EF7-403E-A895-04EA0CBC5586}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9F9C9603-3EF7-403E-A895-04EA0CBC5586}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9F9C9603-3EF7-403E-A895-04EA0CBC5586}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EF8E2621-D5D1-4E60-BC18-2388B1EB5E59}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
internal 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(Direction.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveRight() => MoveTo(Direction.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveUp() => MoveTo(Direction.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveDown() => MoveTo(Direction.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="Direction">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(Direction Direction)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(Direction) ?? false)
{
_moveableObject.MoveObject(Direction);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

View File

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

View File

@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Laba1Loco
{
internal class DrawingLoco : DrawingTrain
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="tube">Признак наличия трубы</param>
/// <param name="fuelTank">Признак наличия бака</param>
/// <param name="locoLine">Признак наличия паровозной полосы</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingLoco(int speed, double weight, Color bodyColor, Color additionalColor, bool tube, bool fuelTank, bool locoLine, int width, int height)
: base(speed, weight, bodyColor, width, height)
{
EntityTrain = new EntityLoco(speed, weight, bodyColor, additionalColor, tube, fuelTank, locoLine);
_locoWidth = ((EntityTrain as EntityLoco)?.FuelTank ?? false) ? 169 : 83;
}
/// <summary>
/// шаг времени для облаков
/// </summary>
public override void timeTick()
{
if (EntityTrain != null)
{
if (clouds.Count < 10)
clouds.Add(new cloud(_startPosX+40, (EntityTrain as EntityLoco).Tube ? _startPosY : _startPosY + 9));
}
for (int i = 0; i < clouds.Count; i++)
{
if (i < clouds.Count)
{
clouds[i].timeTick();
if (clouds[i].opasity < 20)
{
clouds.RemoveAt(i);
}
}
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntityTrain == null)
{
return;
}
base.DrawTransport(g);
if (!(EntityTrain is EntityLoco))
{
return;
}
Pen pen = new Pen(EntityTrain.BodyColor);
Brush brush = new SolidBrush(EntityTrain.BodyColor);
Pen additionalPen = new Pen((EntityTrain as EntityLoco).AdditionalColor);
Brush additionalBrush = new SolidBrush((EntityTrain as EntityLoco).AdditionalColor);
if ((EntityTrain as EntityLoco).Tube)
{
g.DrawLines(additionalPen,
new Point[] {
new Point(_startPosX + 40, _startPosY+9),
new Point(_startPosX + 40, _startPosY+3),
new Point(_startPosX + 45, _startPosY+3),
new Point(_startPosX + 41, _startPosY+3),
new Point(_startPosX + 41, _startPosY),
new Point(_startPosX + 44, _startPosY),
new Point(_startPosX + 44, _startPosY+3),
new Point(_startPosX + 45, _startPosY+3),
new Point(_startPosX + 45, _startPosY+9),
});
}
if ((EntityTrain as EntityLoco).LocoLine)
{
g.DrawLines(additionalPen,
new Point[] {
new Point(_startPosX + 60, _startPosY+10),
new Point(_startPosX + 38, _startPosY+32),
});
g.DrawLines(additionalPen,
new Point[] {
new Point(_startPosX + 65, _startPosY+10),
new Point(_startPosX + 43, _startPosY+32),
});
g.DrawLines(additionalPen,
new Point[] {
new Point(_startPosX + 70, _startPosY+10),
new Point(_startPosX + 48, _startPosY+32),
});
}
if ((EntityTrain as EntityLoco).FuelTank)
{
// body
g.DrawLines(pen,
new Point[] {
new Point(_startPosX + 89, _startPosY+10),
new Point(_startPosX + 164, _startPosY+10),
new Point(_startPosX + 164, _startPosY+32),
new Point(_startPosX + 89, _startPosY+32),
new Point(_startPosX + 89, _startPosY+10),
}
);
g.DrawLines(pen,
new Point[] {
new Point(_startPosX + 89, _startPosY+21),
new Point(_startPosX + 164, _startPosY+21),
}
);
// trucks
g.FillPolygon(brush,
new Point[] {
new Point(_startPosX + 0+85, _startPosY+37),
new Point(_startPosX + 5+85, _startPosY+33),
new Point(_startPosX + 32+85, _startPosY+33),
new Point(_startPosX + 36+85, _startPosY+37),
}
);
g.FillPolygon(brush,
new Point[] {
new Point(_startPosX + 44+85, _startPosY+37),
new Point(_startPosX + 49+85, _startPosY+33),
new Point(_startPosX + 76+85, _startPosY+33),
new Point(_startPosX + 80+85, _startPosY+37),
}
);
//front
g.FillPolygon(brush,
new Point[] {
new Point(_startPosX + 86, _startPosY+12),
new Point(_startPosX + 89, _startPosY+12),
new Point(_startPosX + 89, _startPosY+30),
new Point(_startPosX + 86, _startPosY+30),
}
);
//back
g.FillPolygon(brush,
new Point[] {
new Point(_startPosX + 79+85, _startPosY+12),
new Point(_startPosX + 82+85, _startPosY+12),
new Point(_startPosX + 82+85, _startPosY+30),
new Point(_startPosX + 79+85, _startPosY+30),
}
);
//wheels
g.FillEllipse(brush, _startPosX + 3 + 85, _startPosY + 34, 8, 8);
g.FillEllipse(brush, _startPosX + 26 + 85, _startPosY + 34, 8, 8);
g.FillEllipse(brush, _startPosX + 46 + 85, _startPosY + 34, 8, 8);
g.FillEllipse(brush, _startPosX + 72 + 85, _startPosY + 34, 8, 8);
}
}
}
}

View File

@ -0,0 +1,316 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Laba1Loco
{
internal class DrawingTrain
{
public IMoveableObject GetMoveableObject => new DrawningObjectTrain(this);
/// <summary>
/// Класс-сущность
/// </summary>
public EntityTrain EntityTrain { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
protected int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected int _pictureHeight;
/// <summary>
/// Левая координата прорисовки локомотива
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки локомотива
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки локомотива
/// </summary>
protected int _locoWidth = 83;
/// <summary>
/// Высота прорисовки локомотива
/// </summary>
protected readonly int _locoHeight = 41;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingTrain(int speed, double weight, Color bodyColor, int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureHeight < _locoHeight || _pictureWidth < _locoWidth)
return;
EntityTrain = new EntityTrain(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
_startPosX = Math.Min(x, _pictureWidth - _locoWidth);
_startPosY = Math.Min(y, _pictureHeight - _locoHeight);
clouds = new List<cloud>();
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _locoWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _locoHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(Direction direction)
{
if (EntityTrain == null)
{
return false;
}
switch (direction)
{
case Direction.Left:
return _startPosX - EntityTrain.Step > 0;
case Direction.Right:
return _startPosX + _locoWidth + EntityTrain.Step < _pictureWidth;
case Direction.Up:
return _startPosY - EntityTrain.Step > 0;
case Direction.Down:
return _startPosY + _locoHeight + EntityTrain.Step < _pictureHeight;
default:
return false;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{
if (!CanMove(direction) || EntityTrain == null)
{
return;
}
switch (direction)
{
//влево
case Direction.Left:
_startPosX -= (int)EntityTrain.Step;
break;
//вверх
case Direction.Up:
_startPosY -= (int)EntityTrain.Step;
break;
// вправо
case Direction.Right:
_startPosX += (int)EntityTrain.Step;
break;
//вниз
case Direction.Down:
_startPosY += (int)EntityTrain.Step;
break;
}
}
/// <summary>
/// класс облака
/// </summary>
protected class cloud
{
/// <summary>
/// просто рандом
/// </summary>
Random random;
/// <summary>
/// координаты облака
/// </summary>
int x, y;
/// <summary>
/// размер облака
/// </summary>
int size;
/// <summary>
/// прозрачность облака
/// </summary>
public int opasity;
/// <summary>
/// intialisation облака
/// </summary>
/// <param name="x_">координата облака по горизонтали</param>
/// <param name="y_">координата облака по вертикали</param>
public cloud(int x_, int y_)
{
random = new Random();
x = x_;
y = y_ - 5;
size = 10;
opasity = 255;
}
/// <summary>
/// шаг времени для облака
/// </summary>
public void timeTick()
{
y -= 3;
size += 5;
opasity -= 20;
/// добавляем случайности
y += random.Next(-1, 2);
x += random.Next(-1, 2);
size += random.Next(-1, 2);
opasity += random.Next(-1, 2);
}
/// <summary>
/// отрисовка облака
/// </summary>
/// <param name="g"></param>
public void Draw(Graphics g)
{
g.DrawEllipse(new Pen(Color.FromArgb(opasity, Pens.Gray.Color)), x - size / 2, y - size / 2, size, size);
}
}
/// <summary>
/// массив облачков
/// </summary>
protected List<cloud> clouds = new List<cloud>();
/// <summary>
/// шаг времени для облаков
/// </summary>
public virtual void timeTick()
{
if (EntityTrain != null)
{
if (clouds.Count < 10)
clouds.Add(new cloud(_startPosX + 40, _startPosY + 9));
}
for (int i = 0; i < clouds.Count; i++)
{
if (i < clouds.Count)
{
clouds[i].timeTick();
if (clouds[i].opasity < 20)
{
clouds.RemoveAt(i);
}
}
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityTrain == null)
{
return;
}
//smoke
foreach (var it in clouds)
{
it.Draw(g);
}
Pen pen = new Pen(EntityTrain.BodyColor);
Brush brush = new SolidBrush(EntityTrain.BodyColor);
// body
g.DrawLines(pen,
new Point[] {
new Point(_startPosX + 8, _startPosY+10),
new Point(_startPosX + 79, _startPosY+10),
new Point(_startPosX + 79, _startPosY+32),
new Point(_startPosX + 4, _startPosY+32),
new Point(_startPosX + 4, _startPosY+20),
new Point(_startPosX + 8, _startPosY+10),
}
);
g.DrawLines(pen,
new Point[] {
new Point(_startPosX + 4, _startPosY+21),
new Point(_startPosX + 29, _startPosY+21),
new Point(_startPosX + 29, _startPosY+14),
new Point(_startPosX + 37, _startPosY+14),
new Point(_startPosX + 37, _startPosY+21),
new Point(_startPosX + 79, _startPosY+21),
new Point(_startPosX + 37, _startPosY+21),
new Point(_startPosX + 37, _startPosY+29),
new Point(_startPosX + 29, _startPosY+29),
new Point(_startPosX + 29, _startPosY+21),
}
);
// trucks
g.FillPolygon(brush,
new Point[] {
new Point(_startPosX + 0, _startPosY+37),
new Point(_startPosX + 5, _startPosY+33),
new Point(_startPosX + 32, _startPosY+33),
new Point(_startPosX + 36, _startPosY+37),
}
);
g.FillPolygon(brush,
new Point[] {
new Point(_startPosX + 44, _startPosY+37),
new Point(_startPosX + 49, _startPosY+33),
new Point(_startPosX + 76, _startPosY+33),
new Point(_startPosX + 80, _startPosY+37),
}
);
//back
g.FillPolygon(brush,
new Point[] {
new Point(_startPosX + 79, _startPosY+12),
new Point(_startPosX + 82, _startPosY+12),
new Point(_startPosX + 82, _startPosY+30),
new Point(_startPosX + 79, _startPosY+30),
}
);
//windows
g.DrawRectangle(Pens.Blue, _startPosX + 10, _startPosY + 12, 6, 7);
g.DrawRectangle(Pens.Blue, _startPosX + 19, _startPosY + 12, 6, 7);
g.DrawRectangle(Pens.Blue, _startPosX + 72, _startPosY + 12, 6, 7);
//wheels
g.FillEllipse(brush, _startPosX + 3, _startPosY + 34, 8, 8);
g.FillEllipse(brush, _startPosX + 26, _startPosY + 34, 8, 8);
g.FillEllipse(brush, _startPosX + 46, _startPosY + 34, 8, 8);
g.FillEllipse(brush, _startPosX + 72, _startPosY + 34, 8, 8);
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
internal class DrawningObjectTrain : IMoveableObject
{
private readonly DrawingTrain _drawingTrain = null;
public DrawningObjectTrain(DrawingTrain drawningCar)
{
_drawingTrain = drawningCar;
}
public ObjectParameters GetObjectPosition
{
get
{
if (_drawingTrain == null || _drawingTrain.EntityTrain ==
null)
{
return null;
}
return new ObjectParameters(_drawingTrain.GetPosX,
_drawingTrain.GetPosY, _drawingTrain.GetWidth, _drawingTrain.GetHeight);
}
}
public int GetStep => (int)(_drawingTrain?.EntityTrain?.Step ?? 0);
public bool CheckCanMove(Direction direction) => _drawingTrain?.CanMove(direction) ?? false;
public void MoveObject(Direction direction) => _drawingTrain?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
internal class EntityLoco : EntityTrain
{
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия трубы
/// </summary>
public bool Tube { get; private set; }
/// <summary>
/// Признак (опция) наличия топливного бака
/// </summary>
public bool FuelTank { get; private set; }
/// <summary>
/// Признак (опция) наличия паровозной полосы
/// </summary>
public bool LocoLine { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса Локомотива
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="tube">Признак наличия трубы</param>
/// <param name="fuelTank">Признак наличия бака</param>
/// <param name="locoLine">Признак наличия паровозной полосы</param>
public EntityLoco(int speed, double weight, Color bodyColor, Color
additionalColor, bool tube, bool fuelTank, bool locoLine)
: base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Tube = tube;
FuelTank = fuelTank;
LocoLine = locoLine;
}
}
}

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
internal 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 => (double)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,196 @@
namespace Laba1Loco
{
partial class FormLocomotive
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.create = new System.Windows.Forms.Button();
this.left = new System.Windows.Forms.Button();
this.up = new System.Windows.Forms.Button();
this.down = new System.Windows.Forms.Button();
this.right = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.strategysstep = new System.Windows.Forms.Button();
this.createLocomotive = new System.Windows.Forms.Button();
this.SelectTrain = new System.Windows.Forms.Button();
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.SuspendLayout();
//
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(800, 450);
this.pictureBox.TabIndex = 0;
this.pictureBox.TabStop = false;
//
// create
//
this.create.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.create.Location = new System.Drawing.Point(12, 415);
this.create.Name = "create";
this.create.Size = new System.Drawing.Size(75, 23);
this.create.TabIndex = 1;
this.create.Text = "create train";
this.create.UseVisualStyleBackColor = true;
this.create.Click += new System.EventHandler(this.create_Click);
//
// left
//
this.left.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.left.Image = global::Laba1Loco.Properties.Resources.arowL340x259;
this.left.Location = new System.Drawing.Point(632, 390);
this.left.Name = "left";
this.left.Size = new System.Drawing.Size(48, 48);
this.left.TabIndex = 3;
this.left.UseVisualStyleBackColor = true;
this.left.Click += new System.EventHandler(this.Click);
//
// up
//
this.up.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.up.Image = global::Laba1Loco.Properties.Resources.arowUp340x259;
this.up.Location = new System.Drawing.Point(686, 336);
this.up.Name = "up";
this.up.Size = new System.Drawing.Size(48, 48);
this.up.TabIndex = 4;
this.up.UseVisualStyleBackColor = true;
this.up.Click += new System.EventHandler(this.Click);
//
// down
//
this.down.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.down.Image = global::Laba1Loco.Properties.Resources.arowDown340x259;
this.down.Location = new System.Drawing.Point(686, 390);
this.down.Name = "down";
this.down.Size = new System.Drawing.Size(48, 48);
this.down.TabIndex = 5;
this.down.UseVisualStyleBackColor = true;
this.down.Click += new System.EventHandler(this.Click);
//
// right
//
this.right.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.right.Image = global::Laba1Loco.Properties.Resources.arowR340x259;
this.right.Location = new System.Drawing.Point(740, 390);
this.right.Name = "right";
this.right.Size = new System.Drawing.Size(48, 48);
this.right.TabIndex = 6;
this.right.UseVisualStyleBackColor = true;
this.right.Click += new System.EventHandler(this.Click);
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"to center",
"to bottom right"});
this.comboBoxStrategy.Location = new System.Drawing.Point(667, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(121, 21);
this.comboBoxStrategy.TabIndex = 8;
//
// strategysstep
//
this.strategysstep.Location = new System.Drawing.Point(705, 40);
this.strategysstep.Name = "strategysstep";
this.strategysstep.Size = new System.Drawing.Size(83, 23);
this.strategysstep.TabIndex = 9;
this.strategysstep.Text = "strategy\'s step";
this.strategysstep.UseVisualStyleBackColor = true;
this.strategysstep.Click += new System.EventHandler(this.strategysstep_Click);
//
// createLocomotive
//
this.createLocomotive.Location = new System.Drawing.Point(93, 415);
this.createLocomotive.Name = "createLocomotive";
this.createLocomotive.Size = new System.Drawing.Size(113, 23);
this.createLocomotive.TabIndex = 10;
this.createLocomotive.Text = "create Locomotive";
this.createLocomotive.UseVisualStyleBackColor = true;
this.createLocomotive.Click += new System.EventHandler(this.createLocomotive_Click);
//
// SelectTrain
//
this.SelectTrain.Location = new System.Drawing.Point(346, 415);
this.SelectTrain.Name = "SelectTrain";
this.SelectTrain.Size = new System.Drawing.Size(75, 23);
this.SelectTrain.TabIndex = 11;
this.SelectTrain.Text = "Select Train";
this.SelectTrain.UseVisualStyleBackColor = true;
this.SelectTrain.Click += new System.EventHandler(this.ButtonSelectTrain_Click);
//
// FormLocomotive
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.SelectTrain);
this.Controls.Add(this.createLocomotive);
this.Controls.Add(this.strategysstep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.right);
this.Controls.Add(this.down);
this.Controls.Add(this.up);
this.Controls.Add(this.left);
this.Controls.Add(this.create);
this.Controls.Add(this.pictureBox);
this.Name = "FormLocomotive";
this.Text = "Locomotive(moving)";
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBox;
private System.Windows.Forms.Button create;
private System.Windows.Forms.Button left;
private System.Windows.Forms.Button up;
private System.Windows.Forms.Button down;
private System.Windows.Forms.Button right;
public System.Windows.Forms.Timer timer1;
private System.Windows.Forms.ComboBox comboBoxStrategy;
private System.Windows.Forms.Button strategysstep;
private System.Windows.Forms.Button createLocomotive;
private System.Windows.Forms.Button SelectTrain;
private System.ComponentModel.BackgroundWorker backgroundWorker1;
}
}

View File

@ -0,0 +1,208 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Laba1Loco
{
public partial class FormLocomotive : Form
{
AbstractStrategy abstractStrategy;
internal DrawingTrain SelectedTrain { get; private set; }
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingTrain _drawingTrain;
/// <summary>
/// Инициализация формы
/// </summary>
public FormLocomotive()
{
InitializeComponent();
abstractStrategy = null;
SelectedTrain = null;
}
/// <summary>
/// Метод прорисовки локомотива
/// </summary>
private void Draw()
{
if (_drawingTrain == null)
{
return;
}
Bitmap bmp = new Bitmap(pictureBox.Width, pictureBox.Height);
Graphics gr = Graphics.FromImage(bmp);
if (_drawingTrain is DrawingLoco)
(_drawingTrain as DrawingLoco).DrawTransport(gr);
else
_drawingTrain.DrawTransport(gr);
pictureBox.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать локомотив"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void create_Click(object sender, EventArgs e)
{
Random random = new Random();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new ColorDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawingTrain = new DrawingTrain(
random.Next(100, 300), random.Next(2000, 4000),
color,
pictureBox.Width, pictureBox.Height
);
_drawingTrain.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// клик движения мышки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Click(object sender, EventArgs e)
{
if (_drawingTrain == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "up":
_drawingTrain.MoveTransport(Direction.Up);
break;
case "down":
_drawingTrain.MoveTransport(Direction.Down);
break;
case "left":
_drawingTrain.MoveTransport(Direction.Left);
break;
case "right":
_drawingTrain.MoveTransport(Direction.Right);
break;
}
Draw();
}
/// <summary>
/// таймер для дымка
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
if (_drawingTrain != null)
_drawingTrain.timeTick();
Draw();
}
/// <summary>
/// нажатие кнопки: "создание поезда"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void createLocomotive_Click(object sender, EventArgs e)
{
Random random = new Random();
Color color1 = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog1 = new ColorDialog();
if (dialog1.ShowDialog() == DialogResult.OK)
{
color1 = dialog1.Color;
}
Color color2 = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog2 = new ColorDialog();
if (dialog2.ShowDialog() == DialogResult.OK)
{
color2 = dialog2.Color;
}
_drawingTrain = new DrawingLoco(
random.Next(100, 300), random.Next(2000, 4000),
color1,
color2,
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBox.Width, pictureBox.Height
);
_drawingTrain.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void strategysstep_Click(object sender, EventArgs e)
{
if (_drawingTrain == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
switch (comboBoxStrategy.SelectedIndex)
{
case 0:
abstractStrategy = new MoveToCenter();
break;
case 1:
abstractStrategy = new MoveToBorder();
break;
default:
abstractStrategy = null;
break;
};
if (abstractStrategy == null)
{
return;
}
abstractStrategy.SetData(new
DrawningObjectTrain(_drawingTrain), pictureBox.Width,
pictureBox.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 ButtonSelectTrain_Click(object sender, EventArgs e)
{
SelectedTrain = _drawingTrain;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,126 @@
<?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="timer1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="backgroundWorker1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>104, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,124 @@
namespace Laba1Loco
{
partial class FormTrainCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.panel1 = new System.Windows.Forms.Panel();
this.maskedTextBoxNumber = new System.Windows.Forms.TextBox();
this.ButtonAddTrain = new System.Windows.Forms.Button();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.ButtonRemoveTrain = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Dock = System.Windows.Forms.DockStyle.Left;
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(633, 473);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// panel1
//
this.panel1.Controls.Add(this.maskedTextBoxNumber);
this.panel1.Controls.Add(this.ButtonAddTrain);
this.panel1.Controls.Add(this.ButtonRefreshCollection);
this.panel1.Controls.Add(this.ButtonRemoveTrain);
this.panel1.Dock = System.Windows.Forms.DockStyle.Right;
this.panel1.Location = new System.Drawing.Point(639, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(166, 473);
this.panel1.TabIndex = 1;
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(59, 170);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(100, 20);
this.maskedTextBoxNumber.TabIndex = 4;
//
// ButtonAddTrain
//
this.ButtonAddTrain.Location = new System.Drawing.Point(71, 31);
this.ButtonAddTrain.Name = "ButtonAddTrain";
this.ButtonAddTrain.Size = new System.Drawing.Size(75, 23);
this.ButtonAddTrain.TabIndex = 3;
this.ButtonAddTrain.Text = "Add Train";
this.ButtonAddTrain.UseVisualStyleBackColor = true;
this.ButtonAddTrain.Click += new System.EventHandler(this.ButtonAddTrain_Click);
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(71, 320);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(75, 23);
this.ButtonRefreshCollection.TabIndex = 2;
this.ButtonRefreshCollection.Text = "Refresh Collection";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
this.ButtonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// ButtonRemoveTrain
//
this.ButtonRemoveTrain.Location = new System.Drawing.Point(71, 196);
this.ButtonRemoveTrain.Name = "ButtonRemoveTrain";
this.ButtonRemoveTrain.Size = new System.Drawing.Size(75, 23);
this.ButtonRemoveTrain.TabIndex = 0;
this.ButtonRemoveTrain.Text = "Remove Train";
this.ButtonRemoveTrain.UseVisualStyleBackColor = true;
this.ButtonRemoveTrain.Click += new System.EventHandler(this.ButtonRemoveTrain_Click);
//
// FormTrainCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(805, 473);
this.Controls.Add(this.panel1);
this.Controls.Add(this.pictureBoxCollection);
this.Name = "FormTrainCollection";
this.Text = "FormTrainCollection";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBoxCollection;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button ButtonRefreshCollection;
private System.Windows.Forms.Button ButtonRemoveTrain;
private System.Windows.Forms.Button ButtonAddTrain;
private System.Windows.Forms.TextBox maskedTextBoxNumber;
}
}

View File

@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Laba1Loco
{
public partial class FormTrainCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly TrainsGenericCollection<DrawingTrain, DrawningObjectTrain> _trains;
/// <summary>
/// Конструктор
/// </summary>
public FormTrainCollection()
{
InitializeComponent();
_trains = new TrainsGenericCollection<DrawingTrain, DrawningObjectTrain>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTrain_Click(object sender, EventArgs e)
{
FormLocomotive form = new FormLocomotive();
if (form.ShowDialog() == DialogResult.OK)
{
if ((_trains + form.SelectedTrain) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _trains.ShowTrains();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
form.timer1.Stop();
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveTrain_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
foreach (var it in maskedTextBoxNumber.Text)
if (it < '0' || it > '9')
{
MessageBox.Show("Не удалось удалить объект");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_trains - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _trains.ShowTrains();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _trains.ShowTrains();
}
}
}

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

View File

@ -0,0 +1,122 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9F9C9603-3EF7-403E-A895-04EA0CBC5586}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>Laba1Loco</RootNamespace>
<AssemblyName>Laba1Loco</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AbstractStrategy.cs" />
<Compile Include="FormTrainCollection.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FormTrainCollection.Designer.cs">
<DependentUpon>FormTrainCollection.cs</DependentUpon>
</Compile>
<Compile Include="TrainsGenericCollection.cs" />
<Compile Include="Direction.cs" />
<Compile Include="DrawingLoco.cs" />
<Compile Include="DrawingTrain.cs" />
<Compile Include="DrawningObjectTrain.cs" />
<Compile Include="EntityLoco.cs" />
<Compile Include="EntityTrain.cs" />
<Compile Include="FormLocomotive.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FormLocomotive.Designer.cs">
<DependentUpon>FormLocomotive.cs</DependentUpon>
</Compile>
<Compile Include="IMoveableObject.cs" />
<Compile Include="MoveToBorder.cs" />
<Compile Include="MoveToCenter.cs" />
<Compile Include="ObjectParameters.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SetGeneric.cs" />
<Compile Include="Status.cs" />
<EmbeddedResource Include="FormLocomotive.resx">
<DependentUpon>FormLocomotive.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FormTrainCollection.resx">
<DependentUpon>FormTrainCollection.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<None Include="arow340x259.png" />
</ItemGroup>
<ItemGroup>
<None Include="arowDown340x259.png" />
</ItemGroup>
<ItemGroup>
<None Include="arowL340x259.png" />
</ItemGroup>
<ItemGroup>
<None Include="arowR340x259.png" />
</ItemGroup>
<ItemGroup>
<None Include="arowUp340x259.png" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
internal 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,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
internal class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return
Math.Abs(objParams.ObjectMiddleHorizontal - FieldWidth / 2) <= GetStep()
&&
Math.Abs(objParams.ObjectMiddleVertical - FieldHeight / 2) <= GetStep();
}
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,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
internal 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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Laba1Loco
{
internal static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormTrainCollection());
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанных со сборкой.
[assembly: AssemblyTitle("Laba1Loco")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Laba1Loco")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, следует установить атрибут ComVisible в TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("9f9c9603-3ef7-403e-a895-04ea0cbc5586")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,113 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Laba1Loco.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("Laba1Loco.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 arow340x259 {
get {
object obj = ResourceManager.GetObject("arow340x259", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arowDown340x259 {
get {
object obj = ResourceManager.GetObject("arowDown340x259", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arowL340x259 {
get {
object obj = ResourceManager.GetObject("arowL340x259", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arowR340x259 {
get {
object obj = ResourceManager.GetObject("arowR340x259", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arowUp340x259 {
get {
object obj = ResourceManager.GetObject("arowUp340x259", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,136 @@
<?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="arow340x259" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\arow340x259.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arowDown340x259" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\arowDown340x259.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arowL340x259" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\arowL340x259.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arowR340x259" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\arowR340x259.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arowUp340x259" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\arowUp340x259.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

View File

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Laba1Loco.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="train">Добавляемый поезд</param>
/// <returns></returns>
public int Insert(T train)
{
int i = 0;
for (;i < _places.Length; i++)
{
if (_places[i] == null)
break;
}
if (i == _places.Length)
return -1;
for (; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[i] = train;
return i;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="train">Добавляемый поезд</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T train, int position)
{
if (position < 0 || position >= _places.Length)
return false;
for (; position < _places.Length; position++)
{
if (_places[position] == null)
break;
}
if (position == _places.Length)
return false;
for (; position > 0; position--)
{
_places[position] = _places[position - 1];
}
_places[position] = train;
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= _places.Length)
return false;
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Get(int position)
{
if (position < 0 || position >= _places.Length)
return null;
return _places[position];
}
}
}

View File

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

View File

@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laba1Loco
{
internal class TrainsGenericCollection<T, U>
where T : DrawingTrain
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public TrainsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(TrainsGenericCollection<T, U> collect, T obj)
{
if (obj == null)
{
return -1;
}
return collect?._collection.Insert(obj) ?? -1;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T operator -(TrainsGenericCollection<T, U> collect, int pos)
{
T obj = collect._collection.Get(pos);
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U GetU(int pos)
{
return (U)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowTrains()
{
Bitmap bmp = new Bitmap(_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 Pen(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
for (int i = 0; i < _collection.Count; i++)
{
T t = _collection.Get(i);
if (t != null)
{
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (t is DrawingLoco)
(t as DrawingLoco).DrawTransport(g);
else
t.DrawTransport(g);
}
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 541 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 546 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 518 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 513 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 541 B