ПИбд-21 Кувшинов Тимур лаба2 простая #3

Closed
TImourka wants to merge 2 commits from laba2 into laba1
14 changed files with 900 additions and 280 deletions

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

@ -8,36 +8,8 @@ using System.Windows.Forms;
namespace Laba1Loco
{
internal class DrawingLoco
internal class DrawingLoco : DrawingTrain
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityLoco EntityLoco { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки локомотива
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки локомотива
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки локомотива
/// </summary>
private int _locoWidth => (EntityLoco?.FuelTank ?? false) ? 169 : 83;
/// <summary>
/// Высота прорисовки локомотива
/// </summary>
private readonly int _locoHeight = 41;
/// <summary>
/// Инициализация свойств
/// </summary>
@ -50,142 +22,21 @@ namespace Laba1Loco
/// <param name="locoLine">Признак наличия паровозной полосы</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
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;
}
/// <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);
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
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;
}
}
/// <summary>
/// класс облака
/// </summary>
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>
List<cloud> clouds = new List<cloud>();
/// <summary>
/// шаг времени для облаков
/// </summary>
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
/// <param name="g"></param>
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);
}
}
}

View File

@ -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
{
/// <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);
}
/// <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

@ -7,23 +7,8 @@ using System.Threading.Tasks;
namespace Laba1Loco
{
internal class EntityLoco
internal class EntityLoco : 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 Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия трубы
@ -38,10 +23,6 @@ namespace Laba1Loco
/// </summary>
public bool LocoLine { get; private set; }
/// <summary>
/// Шаг перемещения поезда
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса Локомотива
/// </summary>
/// <param name="speed">Скорость</param>
@ -51,12 +32,10 @@ namespace Laba1Loco
/// <param name="tube">Признак наличия трубы</param>
/// <param name="fuelTank">Признак наличия бака</param>
/// <param name="locoLine">Признак наличия паровозной полосы</param>
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;

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

@ -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;
}
}

View File

@ -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
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingLoco _drawingLoco;
private DrawingTrain _drawingTrain;
/// <summary>
/// Инициализация формы
/// </summary>
@ -29,27 +30,32 @@ namespace Laba1Loco
/// </summary>
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;
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// Обработка нажатия кнопки "Создать локомотив"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();
}
/// <summary>
@ -59,7 +65,7 @@ namespace Laba1Loco
/// <param name="e"></param>
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
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
if (_drawingLoco != null)
_drawingLoco.timeTick();
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();
_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;
/// <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;
}
}
}
}

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

@ -46,17 +46,26 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AbstractStrategy.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="Status.cs" />
<EmbeddedResource Include="FormLocomotive.resx">
<DependentUpon>FormLocomotive.cs</DependentUpon>
</EmbeddedResource>

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,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
}
}