diff --git a/Laba1Loco/Laba1Loco/AbstractStrategy.cs b/Laba1Loco/Laba1Loco/AbstractStrategy.cs new file mode 100644 index 0000000..9806ffa --- /dev/null +++ b/Laba1Loco/Laba1Loco/AbstractStrategy.cs @@ -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 + { + /// + /// Перемещаемый объект + /// + private IMoveableObject _moveableObject; + /// + /// Статус перемещения + /// + private Status _state = Status.NotInit; + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + /// + /// Статус перемещения + /// + public Status GetStatus() { return _state; } + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObject moveableObject, int width, int + height) + { + if (moveableObject == null) + { + _state = Status.NotInit; + return; + } + _state = Status.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != Status.InProgress) + { + return; + } + if (IsTargetDestinaion()) + { + _state = Status.Finish; + return; + } + MoveToTarget(); + } + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(Direction.Left); + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться,false - неудача) + protected bool MoveRight() => MoveTo(Direction.Right); + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться,false - неудача) + protected bool MoveUp() => MoveTo(Direction.Up); + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться,false - неудача) + protected bool MoveDown() => MoveTo(Direction.Down); + /// + /// Параметры объекта + /// + protected ObjectParameters GetObjectParameters => _moveableObject?.GetObjectPosition; + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != Status.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestinaion(); + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(Direction Direction) + { + if (_state != Status.InProgress) + { + return false; + } + if (_moveableObject?.CheckCanMove(Direction) ?? false) + { + _moveableObject.MoveObject(Direction); + return true; + } + return false; + } + + } +} diff --git a/Laba1Loco/Laba1Loco/DrawingLoco.cs b/Laba1Loco/Laba1Loco/DrawingLoco.cs index 212f248..f751475 100644 --- a/Laba1Loco/Laba1Loco/DrawingLoco.cs +++ b/Laba1Loco/Laba1Loco/DrawingLoco.cs @@ -8,36 +8,8 @@ using System.Windows.Forms; namespace Laba1Loco { - internal class DrawingLoco + internal class DrawingLoco : DrawingTrain { - /// - /// Класс-сущность - /// - public EntityLoco EntityLoco { get; private set; } - /// - /// Ширина окна - /// - private int _pictureWidth; - /// - /// Высота окна - /// - private int _pictureHeight; - /// - /// Левая координата прорисовки локомотива - /// - private int _startPosX; - /// - /// Верхняя кооридната прорисовки локомотива - /// - private int _startPosY; - /// - /// Ширина прорисовки локомотива - /// - private int _locoWidth => (EntityLoco?.FuelTank ?? false) ? 169 : 83; - /// - /// Высота прорисовки локомотива - /// - private readonly int _locoHeight = 41; /// /// Инициализация свойств /// @@ -50,142 +22,21 @@ namespace Laba1Loco /// Признак наличия паровозной полосы /// Ширина картинки /// Высота картинки - /// true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах - public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool tube, bool fuelTank, bool locoLine, int width, int height) + 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) { - _pictureWidth = width; - _pictureHeight = height; - if (_pictureHeight < _locoHeight || _pictureWidth < _locoWidth) - return false; - EntityLoco = new EntityLoco(); - EntityLoco.Init(speed, weight, bodyColor, additionalColor, tube, fuelTank, locoLine); - - return true; + EntityTrain = new EntityLoco(speed, weight, bodyColor, additionalColor, tube, fuelTank, locoLine); + _locoWidth = ((EntityTrain as EntityLoco)?.FuelTank ?? false) ? 169 : 83; } - /// - /// Установка позиции - /// - /// Координата X - /// Координата Y - public void SetPosition(int x, int y) - { - _startPosX = Math.Min(x, _pictureWidth-_locoWidth); - _startPosY = Math.Min(y, _pictureHeight-_locoHeight); - } - /// - /// Изменение направления перемещения - /// - /// Направление - public void MoveTransport(Direction direction) - { - if (EntityLoco == null){ - return; - } - switch (direction) - { - //влево - case Direction.Left: - if (_startPosX - EntityLoco.Step > 0) - { - _startPosX -= (int)EntityLoco.Step; - } - break; - //вверх - case Direction.Up: - if (_startPosY - EntityLoco.Step > 0) - { - _startPosY -= (int)EntityLoco.Step; - } - break; - // вправо - case Direction.Right: - if (_startPosX + _locoWidth + EntityLoco.Step < _pictureWidth) - { - _startPosX += (int)EntityLoco.Step; - } - break; - //вниз - case Direction.Down: - if (_startPosY + _locoHeight + EntityLoco.Step < _pictureHeight) - { - _startPosY += (int)EntityLoco.Step; - } - break; - } - } - /// - /// класс облака - /// - class cloud - { - /// - /// просто рандом - /// - Random random; - /// - /// координаты облака - /// - int x, y; - /// - /// размер облака - /// - int size; - /// - /// прозрачность облака - /// - public int opasity; - /// - /// intialisation облака - /// - /// координата облака по горизонтали - /// координата облака по вертикали - public cloud(int x_, int y_) - { - random = new Random(); - x = x_; - y = y_ - 5; - size = 10; - opasity = 255; - } - /// - /// шаг времени для облака - /// - 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); - } - /// - /// отрисовка облака - /// - /// - public void Draw(Graphics g) - { - g.DrawEllipse(new Pen(Color.FromArgb(opasity, Pens.Gray.Color)), x - size / 2, y-size/2, size, size); - } - - } - /// - /// массив облачков - /// - List clouds = new List(); - /// /// шаг времени для облаков /// - public void timeTick() + public override void timeTick() { - if (EntityLoco != null) + if (EntityTrain != null) { if (clouds.Count < 10) - clouds.Add(new cloud(_startPosX+40, EntityLoco.Tube ? _startPosY : _startPosY + 9)); + clouds.Add(new cloud(_startPosX+40, (EntityTrain as EntityLoco).Tube ? _startPosY : _startPosY + 9)); } for (int i = 0; i < clouds.Count; i++) { @@ -205,90 +56,24 @@ namespace Laba1Loco /// public void DrawTransport(Graphics g) { - if (EntityLoco == null) + if (EntityTrain == null) { return; } - Pen pen = new Pen(EntityLoco.BodyColor); - Brush brush = new SolidBrush(EntityLoco.BodyColor); - Pen additionalPen = new Pen(EntityLoco.AdditionalColor); - Brush additionalBrush = new SolidBrush(EntityLoco.AdditionalColor); - //smoke - foreach(var it in clouds){ - it.Draw(g); + base.DrawTransport(g); + + if (!(EntityTrain is EntityLoco)) + { + return; } - // 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), - } - ); + 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); - // 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(additionalBrush, _startPosX + 4, _startPosY + 35, 6, 6); - g.FillEllipse(brush, _startPosX + 26, _startPosY + 34, 8, 8); - g.FillEllipse(additionalBrush, _startPosX + 27, _startPosY + 35, 6, 6); - g.FillEllipse(brush, _startPosX + 46, _startPosY + 34, 8, 8); - g.FillEllipse(additionalBrush, _startPosX + 47, _startPosY + 35, 6, 6); - g.FillEllipse(brush, _startPosX + 72, _startPosY + 34, 8, 8); - g.FillEllipse(additionalBrush, _startPosX + 73, _startPosY + 35, 6, 6); - - if (EntityLoco.Tube) + if ((EntityTrain as EntityLoco).Tube) { g.DrawLines(additionalPen, new Point[] { @@ -303,7 +88,7 @@ namespace Laba1Loco new Point(_startPosX + 45, _startPosY+9), }); } - if (EntityLoco.LocoLine) + if ((EntityTrain as EntityLoco).LocoLine) { g.DrawLines(additionalPen, new Point[] { @@ -321,7 +106,7 @@ namespace Laba1Loco new Point(_startPosX + 48, _startPosY+32), }); } - if (EntityLoco.FuelTank) + if ((EntityTrain as EntityLoco).FuelTank) { // body g.DrawLines(pen, @@ -380,13 +165,9 @@ namespace Laba1Loco //wheels g.FillEllipse(brush, _startPosX + 3 + 85, _startPosY + 34, 8, 8); - g.FillEllipse(additionalBrush, _startPosX + 4, _startPosY + 35, 6, 6); g.FillEllipse(brush, _startPosX + 26 + 85, _startPosY + 34, 8, 8); - g.FillEllipse(additionalBrush, _startPosX + 27, _startPosY + 35, 6, 6); g.FillEllipse(brush, _startPosX + 46 + 85, _startPosY + 34, 8, 8); - g.FillEllipse(additionalBrush, _startPosX + 47, _startPosY + 35, 6, 6); g.FillEllipse(brush, _startPosX + 72 + 85, _startPosY + 34, 8, 8); - g.FillEllipse(additionalBrush, _startPosX + 73, _startPosY + 35, 6, 6); } } } diff --git a/Laba1Loco/Laba1Loco/DrawingTrain.cs b/Laba1Loco/Laba1Loco/DrawingTrain.cs new file mode 100644 index 0000000..f368110 --- /dev/null +++ b/Laba1Loco/Laba1Loco/DrawingTrain.cs @@ -0,0 +1,314 @@ +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 EntityTrain EntityTrain { get; protected set; } + /// + /// Ширина окна + /// + protected int _pictureWidth; + /// + /// Высота окна + /// + protected int _pictureHeight; + /// + /// Левая координата прорисовки локомотива + /// + protected int _startPosX; + /// + /// Верхняя кооридната прорисовки локомотива + /// + protected int _startPosY; + /// + /// Ширина прорисовки локомотива + /// + protected int _locoWidth = 83; + /// + /// Высота прорисовки локомотива + /// + protected readonly int _locoHeight = 41; + /// + /// Инициализация свойств + /// + /// Скорость + /// Вес + /// Цвет кузова + /// Ширина картинки + /// Высота картинки + 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); + + } + /// + /// Установка позиции + /// + /// Координата X + /// Координата Y + public void SetPosition(int x, int y) + { + _startPosX = Math.Min(x, _pictureWidth - _locoWidth); + _startPosY = Math.Min(y, _pictureHeight - _locoHeight); + } + /// + /// Координата X объекта + /// + public int GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _locoWidth; + /// + /// Высота объекта + /// + public int GetHeight => _locoHeight; + /// + /// Проверка, что объект может переместится по указанному направлению + /// + /// Направление + /// true - можно переместится по указанному направлению + 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; + } + } + /// + /// Изменение направления перемещения + /// + /// Направление + 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; + } + } + /// + /// класс облака + /// + protected class cloud + { + /// + /// просто рандом + /// + Random random; + /// + /// координаты облака + /// + int x, y; + /// + /// размер облака + /// + int size; + /// + /// прозрачность облака + /// + public int opasity; + /// + /// intialisation облака + /// + /// координата облака по горизонтали + /// координата облака по вертикали + public cloud(int x_, int y_) + { + random = new Random(); + x = x_; + y = y_ - 5; + size = 10; + opasity = 255; + } + /// + /// шаг времени для облака + /// + 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); + } + /// + /// отрисовка облака + /// + /// + public void Draw(Graphics g) + { + g.DrawEllipse(new Pen(Color.FromArgb(opasity, Pens.Gray.Color)), x - size / 2, y - size / 2, size, size); + } + + } + /// + /// массив облачков + /// + protected List clouds = new List(); + + /// + /// шаг времени для облаков + /// + 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); + } + } + } + } + /// + /// Прорисовка объекта + /// + /// + 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); + + } + + } +} diff --git a/Laba1Loco/Laba1Loco/DrawningObjectTrain.cs b/Laba1Loco/Laba1Loco/DrawningObjectTrain.cs new file mode 100644 index 0000000..78dc401 --- /dev/null +++ b/Laba1Loco/Laba1Loco/DrawningObjectTrain.cs @@ -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); + + } +} diff --git a/Laba1Loco/Laba1Loco/EntityLoco.cs b/Laba1Loco/Laba1Loco/EntityLoco.cs index 3d68c9a..e158b55 100644 --- a/Laba1Loco/Laba1Loco/EntityLoco.cs +++ b/Laba1Loco/Laba1Loco/EntityLoco.cs @@ -7,23 +7,8 @@ using System.Threading.Tasks; namespace Laba1Loco { - internal class EntityLoco + internal class EntityLoco : EntityTrain { - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// - /// Дополнительный цвет (для опциональных элементов) - /// public Color AdditionalColor { get; private set; } /// /// Признак (опция) наличия трубы @@ -38,10 +23,6 @@ namespace Laba1Loco /// public bool LocoLine { get; private set; } /// - /// Шаг перемещения поезда - /// - public double Step => (double)Speed * 100 / Weight; - /// /// Инициализация полей объекта-класса Локомотива /// /// Скорость @@ -51,12 +32,10 @@ namespace Laba1Loco /// Признак наличия трубы /// Признак наличия бака /// Признак наличия паровозной полосы - public void Init(int speed, double weight, Color bodyColor, Color + public EntityLoco(int speed, double weight, Color bodyColor, Color additionalColor, bool tube, bool fuelTank, bool locoLine) + : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; Tube = tube; FuelTank = fuelTank; diff --git a/Laba1Loco/Laba1Loco/EntityTrain.cs b/Laba1Loco/Laba1Loco/EntityTrain.cs new file mode 100644 index 0000000..aa2b403 --- /dev/null +++ b/Laba1Loco/Laba1Loco/EntityTrain.cs @@ -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 + { + /// + /// Скорость + /// + public int Speed { get; private set; } + /// + /// Вес + /// + public double Weight { get; private set; } + /// + /// Основной цвет + /// + public Color BodyColor { get; private set; } + /// + /// Шаг перемещения поезда + /// + public double Step => (double)Speed * 100 / Weight; + /// + /// Инициализация полей объекта-класса Локомотива + /// + /// Скорость + /// Вес автомобиля + /// Основной цвет + public EntityTrain(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } + } +} diff --git a/Laba1Loco/Laba1Loco/FormLocomotive.Designer.cs b/Laba1Loco/Laba1Loco/FormLocomotive.Designer.cs index 318ed48..300072d 100644 --- a/Laba1Loco/Laba1Loco/FormLocomotive.Designer.cs +++ b/Laba1Loco/Laba1Loco/FormLocomotive.Designer.cs @@ -36,6 +36,9 @@ 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(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); this.SuspendLayout(); // @@ -55,7 +58,7 @@ this.create.Name = "create"; this.create.Size = new System.Drawing.Size(75, 23); this.create.TabIndex = 1; - this.create.Text = "create"; + this.create.Text = "create train"; this.create.UseVisualStyleBackColor = true; this.create.Click += new System.EventHandler(this.create_Click); // @@ -108,11 +111,46 @@ 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); + // // 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.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); @@ -135,6 +173,9 @@ private System.Windows.Forms.Button down; private System.Windows.Forms.Button right; private System.Windows.Forms.Timer timer1; + private System.Windows.Forms.ComboBox comboBoxStrategy; + private System.Windows.Forms.Button strategysstep; + private System.Windows.Forms.Button createLocomotive; } } diff --git a/Laba1Loco/Laba1Loco/FormLocomotive.cs b/Laba1Loco/Laba1Loco/FormLocomotive.cs index f067f25..cf6639a 100644 --- a/Laba1Loco/Laba1Loco/FormLocomotive.cs +++ b/Laba1Loco/Laba1Loco/FormLocomotive.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.ComponentModel.Design; using System.Data; using System.Drawing; using System.Linq; @@ -15,7 +16,7 @@ namespace Laba1Loco /// /// Поле-объект для прорисовки объекта /// - private DrawingLoco _drawingLoco; + private DrawingTrain _drawingTrain; /// /// Инициализация формы /// @@ -29,27 +30,32 @@ namespace Laba1Loco /// private void Draw() { - if (_drawingLoco == null) + if (_drawingTrain == null) { return; } Bitmap bmp = new Bitmap(pictureBox.Width, pictureBox.Height); Graphics gr = Graphics.FromImage(bmp); - _drawingLoco.DrawTransport(gr); + if (_drawingTrain is DrawingLoco) + (_drawingTrain as DrawingLoco).DrawTransport(gr); + else + _drawingTrain.DrawTransport(gr); pictureBox.Image = bmp; } /// - /// Обработка нажатия кнопки "Создать" + /// Обработка нажатия кнопки "Создать локомотив" /// /// /// private void create_Click(object sender, EventArgs e) { Random random = new Random(); - _drawingLoco = new DrawingLoco(); - _drawingLoco.Init(random.Next(100, 300), random.Next(2000, 4000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), pictureBox.Width, pictureBox.Height); - _drawingLoco.SetPosition(random.Next(10, 100), random.Next(10, 100)); + _drawingTrain = new DrawingTrain( + random.Next(100, 300), random.Next(2000, 4000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + pictureBox.Width, pictureBox.Height + ); + _drawingTrain.SetPosition(random.Next(10, 100), random.Next(10, 100)); Draw(); } /// @@ -59,7 +65,7 @@ namespace Laba1Loco /// private void Click(object sender, EventArgs e) { - if (_drawingLoco == null) + if (_drawingTrain == null) { return; } @@ -67,16 +73,16 @@ namespace Laba1Loco switch (name) { case "up": - _drawingLoco.MoveTransport(Direction.Up); + _drawingTrain.MoveTransport(Direction.Up); break; case "down": - _drawingLoco.MoveTransport(Direction.Down); + _drawingTrain.MoveTransport(Direction.Down); break; case "left": - _drawingLoco.MoveTransport(Direction.Left); + _drawingTrain.MoveTransport(Direction.Left); break; case "right": - _drawingLoco.MoveTransport(Direction.Right); + _drawingTrain.MoveTransport(Direction.Right); break; } Draw(); @@ -89,9 +95,78 @@ namespace Laba1Loco /// private void timer1_Tick(object sender, EventArgs e) { - if (_drawingLoco != null) - _drawingLoco.timeTick(); + if (_drawingTrain != null) + _drawingTrain.timeTick(); Draw(); } + + /// + /// нажатие кнопки: "создание поезда" + /// + /// + /// + private void createLocomotive_Click(object sender, EventArgs e) + { + Random random = new Random(); + _drawingTrain = new DrawingLoco( + random.Next(100, 300), random.Next(2000, 4000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + 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(); + + } + AbstractStrategy abstractStrategy; + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + + 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; + } + + } } } diff --git a/Laba1Loco/Laba1Loco/IMoveableObject.cs b/Laba1Loco/Laba1Loco/IMoveableObject.cs new file mode 100644 index 0000000..fd0214c --- /dev/null +++ b/Laba1Loco/Laba1Loco/IMoveableObject.cs @@ -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 + { + /// + /// Получение координаты X объекта + /// + ObjectParameters GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Проверка, можно ли переместиться по нужному направлению + /// + /// + /// + bool CheckCanMove(Direction direction); + /// + /// Изменение направления пермещения объекта + /// + /// Направление + void MoveObject(Direction direction); + + } +} diff --git a/Laba1Loco/Laba1Loco/Laba1Loco.csproj b/Laba1Loco/Laba1Loco/Laba1Loco.csproj index 68d4bfc..0909c1c 100644 --- a/Laba1Loco/Laba1Loco/Laba1Loco.csproj +++ b/Laba1Loco/Laba1Loco/Laba1Loco.csproj @@ -46,17 +46,26 @@ + + + + Form FormLocomotive.cs + + + + + FormLocomotive.cs diff --git a/Laba1Loco/Laba1Loco/MoveToBorder.cs b/Laba1Loco/Laba1Loco/MoveToBorder.cs new file mode 100644 index 0000000..03e38ed --- /dev/null +++ b/Laba1Loco/Laba1Loco/MoveToBorder.cs @@ -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(); + } + } + } + } +} diff --git a/Laba1Loco/Laba1Loco/MoveToCenter.cs b/Laba1Loco/Laba1Loco/MoveToCenter.cs new file mode 100644 index 0000000..733392c --- /dev/null +++ b/Laba1Loco/Laba1Loco/MoveToCenter.cs @@ -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(); + } + } + } + + } +} diff --git a/Laba1Loco/Laba1Loco/ObjectParameters.cs b/Laba1Loco/Laba1Loco/ObjectParameters.cs new file mode 100644 index 0000000..27563d3 --- /dev/null +++ b/Laba1Loco/Laba1Loco/ObjectParameters.cs @@ -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; + /// + /// Левая граница + /// + public int LeftBorder => _x; + /// + /// Верхняя граница + /// + public int TopBorder => _y; + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + /// + /// Середина объекта + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + /// + /// Середина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + /// + /// Конструктор + /// + /// Координата X + /// Координата Y + /// Ширина + /// Высота + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } + + } +} diff --git a/Laba1Loco/Laba1Loco/Status.cs b/Laba1Loco/Laba1Loco/Status.cs new file mode 100644 index 0000000..0e89d9c --- /dev/null +++ b/Laba1Loco/Laba1Loco/Status.cs @@ -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 + } +}