Лабораторная 2

This commit is contained in:
Мельников Игорь 2022-10-12 11:21:29 +04:00
parent a8b275748d
commit c99b5e5b3c
16 changed files with 1016 additions and 15 deletions

View File

@ -0,0 +1,244 @@
namespace Locomotives
{
internal abstract class AbstractMap
{
/// <summary>
/// Поле от интерфейса прорисовки
/// </summary>
private IDrawningObject _drawningObject = null;
/// <summary>
/// Массив карты
/// </summary>
protected int[,] _map = null;
/// <summary>
/// Ширина карты (графической панели)
/// </summary>
protected int _width;
/// <summary>
/// Высота карты (графической панели)
/// </summary>
protected int _height;
/// <summary>
/// Ширина ячейки
/// </summary>
protected float _size_x;
/// <summary>
/// Высота ячейки
/// </summary>
protected float _size_y;
protected readonly Random _random = new();
/// <summary>
/// Доступная для движения ячейка
/// </summary>
protected readonly int _freeRoad = 0;
/// <summary>
/// Недоступная для движения ячейка
/// </summary>
protected readonly int _barrier = 1;
/// <summary>
/// Наполнение графической панели
/// </summary>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <param name="drawningObject"></param>
/// <returns></returns>
public Bitmap CreateMap(int width, int height, IDrawningObject drawningObject)
{
_width = width;
_height = height;
_drawningObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
/// <summary>
/// Получение координат отрисовываемого объекта в массиве
/// </summary>
/// <returns></returns>
public (int Top, int Bottom, int Left, int Right) GetObjectCoordinates()
{
return
(
(int)(_drawningObject.GetCurrentPosition().Top / _size_y),
(int)(_drawningObject.GetCurrentPosition().Bottom / _size_y),
(int)(_drawningObject.GetCurrentPosition().Left / _size_x),
(int)(_drawningObject.GetCurrentPosition().Right / _size_x)
);
}
/// <summary>
/// Проверка возможности движения в данном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
private bool AbleToMove(Direction direction)
{
switch (direction)
{
case Direction.Up:
if (GetObjectCoordinates().Top - 1 < 0)
{
return false;
}
break;
case Direction.Down:
if (GetObjectCoordinates().Bottom + 1 > _map.GetLength(0))
{
return false;
}
break;
case Direction.Left:
if (GetObjectCoordinates().Left - 1 < 0)
{
return false;
}
break;
case Direction.Right:
if (GetObjectCoordinates().Right + 1 > _map.GetLength(1))
{
return false;
}
break;
}
for (int i = GetObjectCoordinates().Left; i <= GetObjectCoordinates().Right; i++)
{
for (int j = GetObjectCoordinates().Top; j <= GetObjectCoordinates().Bottom; j++)
{
if (i - 1 < 0 || j - 1 < 0 || i + 1 > _map.GetLength(0) || j + 1 > _map.GetLength(1))
{
return false;
}
switch (direction)
{
case Direction.Up:
if (_map[i, j - 1] == _barrier)
{
return false;
}
break;
case Direction.Down:
if (_map[i, j + 1] == _barrier)
{
return false;
}
break;
case Direction.Left:
if (_map[i - 1, j] == _barrier)
{
return false;
}
break;
case Direction.Right:
if (_map[i + 1, j] == _barrier)
{
return false;
}
break;
}
}
}
return true;
}
/// <summary>
/// Проверка возможности установить объект на карте
/// </summary>
/// <returns></returns>
private bool AbleToSetObject()
{
for (int i = GetObjectCoordinates().Left; i <= GetObjectCoordinates().Right; i++)
{
for (int j = GetObjectCoordinates().Top; j <= GetObjectCoordinates().Bottom; j++)
{
if (_map[i, j] == _barrier || i < 0 || j < 0)
{
return false;
}
}
}
return true;
}
/// <summary>
/// Передвижение объекта по карте
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
public Bitmap MoveObject(Direction direction)
{
if (!AbleToMove(direction))
{
return DrawMapWithObject();
}
_drawningObject.MoveObject(direction);
return DrawMapWithObject();
}
/// <summary>
/// Создание объекта на карте
/// </summary>
/// <returns>Возможность создать объект</returns>
private bool SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.Next(10, 100);
int y = _random.Next(10, 100);
_drawningObject.SetObject(x, y, _width, _height);
// TODO првоерка, что объект не "накладывается" на закрытые участки
if (!AbleToSetObject())
{
return false;
}
return true;
}
/// <summary>
/// Отрисовка карты
/// </summary>
/// <returns></returns>
private Bitmap DrawMapWithObject()
{
Bitmap bmp = new(_width, _height);
if (_drawningObject == null || _map == null)
{
return bmp;
}
Graphics gr = Graphics.FromImage(bmp);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
if (_map[i, j] == _freeRoad)
{
DrawRoadPart(gr, i, j);
}
else if (_map[i, j] == _barrier)
{
DrawBarrierPart(gr, i, j);
}
}
}
_drawningObject.DrawningObject(gr);
return bmp;
}
/// <summary>
/// Генерация массива карты
/// </summary>
protected abstract void GenerateMap();
/// <summary>
/// Отрисовка ячейки со свободным пространством (дорогой)
/// </summary>
/// <param name="g"></param>
/// <param name="i"></param>
/// <param name="j"></param>
protected abstract void DrawRoadPart(Graphics g, int i, int j);
/// <summary>
/// Отрисовка ячейки с барьером
/// </summary>
/// <param name="g"></param>
/// <param name="i"></param>
/// <param name="j"></param>
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
}
}

View File

@ -0,0 +1,52 @@
namespace Locomotives
{
/// <summary>
/// Карта в виде креста
/// </summary>
internal class CrossMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Red);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.Transparent);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, i * _size_x, _size_y);
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
for (int i = 45; i < 55; i++)
{
for (int j = 15; j < 85; j++)
{
_map[i, j] = _barrier;
}
}
for (int i = 45; i < 55; i++)
{
for (int j = 30; j < 80; j++)
{
_map[j, i] = _barrier;
}
}
}
}
}

View File

@ -5,6 +5,10 @@
/// </summary> /// </summary>
internal enum Direction internal enum Direction
{ {
/// <summary>
/// никуда
/// </summary>
None = 0,
/// <summary> /// <summary>
/// вверх /// вверх
/// </summary> /// </summary>

View File

@ -8,15 +8,15 @@
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityLocomotive Locomotive { get; private set; } public EntityLocomotive Locomotive { get; protected set; }
/// <summary> /// <summary>
/// Левая координата отрисовки локомотива /// Левая координата отрисовки локомотива
/// </summary> /// </summary>
private float _startPosX; protected float _startPosX;
/// <summary> /// <summary>
/// Верхняя координата отрисовки локомотива /// Верхняя координата отрисовки локомотива
/// </summary> /// </summary>
private float _startPosY; protected float _startPosY;
/// <summary> /// <summary>
/// Ширина окна отрисовки /// Ширина окна отрисовки
/// </summary> /// </summary>
@ -39,10 +39,23 @@
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param> /// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param> /// <param name="bodyColor">Цвет кузова</param>
public void Init(int speed, float weight, Color bodyColor) public DrawningLocomotive(int speed, float weight, Color bodyColor)
{ {
Locomotive = new EntityLocomotive(); Locomotive = new EntityLocomotive(speed, weight, bodyColor);
Locomotive.Init(speed, weight, bodyColor); }
/// <summary>
/// Конструктор для изменения размеров локомотива
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="locomotiveWidth">Ширина локомотива</param>
/// <param name="locomotiveHeight">Высота локомотива</param>
protected DrawningLocomotive(int speed, float weight, Color bodyColor, int locomotiveWidth, int locomotiveHeight)
: this(speed, weight, bodyColor)
{
_locomotiveWidth = locomotiveWidth;
_locomotiveHeight = locomotiveHeight;
} }
/// <summary> /// <summary>
/// Установка начальной позиции локомотива /// Установка начальной позиции локомотива
@ -68,10 +81,6 @@
/// <param name="direction">Направление</param> /// <param name="direction">Направление</param>
public void MoveLocomotive(Direction direction) public void MoveLocomotive(Direction direction)
{ {
if (!_pictureWidth.HasValue || !_pictureHeight.HasValue)
{
return;
}
if (!_pictureWidth.HasValue || !_pictureHeight.HasValue) if (!_pictureWidth.HasValue || !_pictureHeight.HasValue)
{ {
return; return;
@ -112,7 +121,7 @@
/// Метод отрисовки локомотива /// Метод отрисовки локомотива
/// </summary> /// </summary>
/// <param name="g">Графика</param> /// <param name="g">Графика</param>
public void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (_startPosX < 0 || _startPosY < 0 || !_pictureHeight.HasValue || !_pictureWidth.HasValue) if (_startPosX < 0 || _startPosY < 0 || !_pictureHeight.HasValue || !_pictureWidth.HasValue)
{ {
@ -186,5 +195,13 @@
_startPosY = _pictureHeight.Value - _locomotiveHeight; _startPosY = _pictureHeight.Value - _locomotiveHeight;
} }
} }
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public (float Top, float Bottom, float Left, float Right) GetCurrentPosition()
{
return (_startPosY, _startPosY + _locomotiveHeight, _startPosX, _startPosX + _locomotiveWidth);
}
} }
} }

View File

@ -0,0 +1,35 @@
namespace Locomotives
{
/// <summary>
/// Класс-наследник от интерфейса (реализация)
/// </summary>
internal class DrawningObjectLocomotive : IDrawningObject
{
/// <summary>
/// Объект от класса отрисовки локомотива
/// </summary>
private DrawningLocomotive _locomotive = null;
public DrawningObjectLocomotive(DrawningLocomotive locomotive)
{
_locomotive = locomotive;
}
public float Step => _locomotive?.Locomotive?.Step ?? 0;
public (float Top, float Bottom, float Left, float Right) GetCurrentPosition()
{
return _locomotive?.GetCurrentPosition() ?? default;
}
public void MoveObject(Direction direction)
{
_locomotive?.MoveLocomotive(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_locomotive.SetPosition(x, y, width, height);
}
public void DrawningObject(Graphics g)
{
_locomotive.DrawTransport(g);
}
}
}

View File

@ -0,0 +1,61 @@
namespace Locomotives
{
/// <summary>
/// Класс-наследник от класса отрисовки локомотива
/// </summary>
internal class DrawningWarmlyLocomotive : DrawningLocomotive
{
/// <summary>
/// Конструктор, передаём в protected конструктор базового класса обычные параметры и вводим новые
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="locomotiveWidth">Ширина локомотива</param>
/// <param name="locomotiveHeight">Высота локомотива</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="hasPipe">Признак наличия трубы</param>
/// <param name="hasFuelTank">Признак наличия топливного бака</param>
public DrawningWarmlyLocomotive(int speed, float weight, Color bodyColor, int locomotiveWidth, int locomotiveHeight, Color additionalColor, bool hasPipe, bool hasFuelTank) : base(speed, weight, bodyColor, locomotiveWidth, locomotiveHeight)
{
Locomotive = new EntityWarmlyLocomotive(speed, weight, bodyColor, additionalColor, hasPipe, hasFuelTank);
}
/// <summary>
/// Отрисовываем базовую часть локомотива и добавляем дополнительные элементы, если они есть
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (Locomotive is not EntityWarmlyLocomotive warmlyLocomotive)
{
return;
}
//Прорисовка трубы
if (warmlyLocomotive.HasPipe)
{
Pen pen = new Pen(Color.Black);
Brush brAdditionalColor = new SolidBrush(warmlyLocomotive.AdditionalColor);
g.FillRectangle(brAdditionalColor, _startPosX + 20, _startPosY, 25, 10);
g.DrawRectangle(pen, _startPosX + 20, _startPosY, 25, 10);
g.FillRectangle(brAdditionalColor, _startPosX + 25, _startPosY + 10, 15, 20);
g.DrawRectangle(pen, _startPosX + 25, _startPosY + 10, 15, 20);
}
_startPosY += 30;
base.DrawTransport(g);
_startPosY -= 30;
//Прорисовка топливного бака
if (warmlyLocomotive.HasFuelTank)
{
Pen pen = new Pen(Color.Black);
Brush brAdditionalColor = new SolidBrush(warmlyLocomotive.AdditionalColor);
Pen penYellow = new Pen(Color.Yellow);
g.FillRectangle(brAdditionalColor, _startPosX + 80, _startPosY + 40, 45, 20);
g.DrawRectangle(pen, _startPosX + 80, _startPosY + 40, 45, 20);
for (int i = (int)_startPosX + 100; i < (int)_startPosX + 110; i++)
{
g.DrawLine(penYellow, _startPosX + 105, _startPosY + 45, i, _startPosY + 55);
}
}
}
}
}

View File

@ -27,7 +27,7 @@
/// <param name="speed">скорость</param> /// <param name="speed">скорость</param>
/// <param name="weight">вес</param> /// <param name="weight">вес</param>
/// <param name="bodyColor">цвет кузова</param> /// <param name="bodyColor">цвет кузова</param>
public void Init(int speed, float weight, Color bodyColor) public EntityLocomotive (int speed, float weight, Color bodyColor)
{ {
Random rnd = new(); Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed; Speed = speed <= 0 ? rnd.Next(50, 150) : speed;

View File

@ -0,0 +1,36 @@
namespace Locomotives
{
/// <summary>
/// Класс-наследник от класса-сущности локомотива (усложнённый локомотив/тепловоз)
/// </summary>
internal class EntityWarmlyLocomotive : EntityLocomotive
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак наличия трубы
/// </summary>
public bool HasPipe { get; private set; }
/// <summary>
/// Признак наличия топливного бака
/// </summary>
public bool HasFuelTank { get; private set; }
/// <summary>
/// Инициализация свойств усложнённого локомотива (тепловоза)
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="hasPipe">Признак наличия трубы</param>
/// <param name="hasFuelTank">Признак наличия топливного бака</param>
public EntityWarmlyLocomotive(int speed, float weight, Color bodyColor, Color additionalColor, bool hasPipe, bool hasFuelTank) : base (speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
HasPipe = hasPipe;
HasFuelTank = hasFuelTank;
}
}
}

View File

@ -29,8 +29,7 @@
private void ButtonCreate_Click(object sender, EventArgs e) private void ButtonCreate_Click(object sender, EventArgs e)
{ {
Random rnd = new(); Random rnd = new();
_locomotive = new DrawningLocomotive(); _locomotive = new DrawningLocomotive(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_locomotive.Init(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_locomotive.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxLocomotive.Width, pictureBoxLocomotive.Height); _locomotive.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
toolStripStatusLabelSpeed.Text = $"Скорость: {_locomotive.Locomotive.Speed}"; toolStripStatusLabelSpeed.Text = $"Скорость: {_locomotive.Locomotive.Speed}";
toolStripStatusLabelWeight.Text = $"Вес: {_locomotive.Locomotive.Weight}"; toolStripStatusLabelWeight.Text = $"Вес: {_locomotive.Locomotive.Weight}";

View File

@ -0,0 +1,239 @@
namespace Locomotives
{
partial class FormMap
{
/// <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.pictureBoxLocomotive = new System.Windows.Forms.PictureBox();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabelSpeed = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelWeight = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelBodyColor = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelAdditionalColor = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelHasPipe = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelHasFuelTank = new System.Windows.Forms.ToolStripStatusLabel();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.buttonCreateModif = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxLocomotive)).BeginInit();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxLocomotive
//
this.pictureBoxLocomotive.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxLocomotive.Location = new System.Drawing.Point(0, 0);
this.pictureBoxLocomotive.MinimumSize = new System.Drawing.Size(1, 1);
this.pictureBoxLocomotive.Name = "pictureBoxLocomotive";
this.pictureBoxLocomotive.Size = new System.Drawing.Size(800, 450);
this.pictureBoxLocomotive.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxLocomotive.TabIndex = 0;
this.pictureBoxLocomotive.TabStop = false;
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabelSpeed,
this.toolStripStatusLabelWeight,
this.toolStripStatusLabelBodyColor,
this.toolStripStatusLabelAdditionalColor,
this.toolStripStatusLabelHasPipe,
this.toolStripStatusLabelHasFuelTank});
this.statusStrip.Location = new System.Drawing.Point(0, 428);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(800, 22);
this.statusStrip.TabIndex = 1;
this.statusStrip.Text = "statusStrip1";
//
// toolStripStatusLabelSpeed
//
this.toolStripStatusLabelSpeed.Name = "toolStripStatusLabelSpeed";
this.toolStripStatusLabelSpeed.Size = new System.Drawing.Size(65, 17);
this.toolStripStatusLabelSpeed.Text = "Скорость: ";
//
// toolStripStatusLabelWeight
//
this.toolStripStatusLabelWeight.Name = "toolStripStatusLabelWeight";
this.toolStripStatusLabelWeight.Size = new System.Drawing.Size(32, 17);
this.toolStripStatusLabelWeight.Text = "Вес: ";
//
// toolStripStatusLabelBodyColor
//
this.toolStripStatusLabelBodyColor.Name = "toolStripStatusLabelBodyColor";
this.toolStripStatusLabelBodyColor.Size = new System.Drawing.Size(39, 17);
this.toolStripStatusLabelBodyColor.Text = "Цвет: ";
//
// toolStripStatusLabelAdditionalColor
//
this.toolStripStatusLabelAdditionalColor.Name = "toolStripStatusLabelAdditionalColor";
this.toolStripStatusLabelAdditionalColor.Size = new System.Drawing.Size(137, 17);
this.toolStripStatusLabelAdditionalColor.Text = "Дополнительный цвет: ";
//
// toolStripStatusLabelHasPipe
//
this.toolStripStatusLabelHasPipe.Name = "toolStripStatusLabelHasPipe";
this.toolStripStatusLabelHasPipe.Size = new System.Drawing.Size(99, 17);
this.toolStripStatusLabelHasPipe.Text = "Наличие трубы: ";
//
// toolStripStatusLabelHasFuelTank
//
this.toolStripStatusLabelHasFuelTank.Name = "toolStripStatusLabelHasFuelTank";
this.toolStripStatusLabelHasFuelTank.Size = new System.Drawing.Size(158, 17);
this.toolStripStatusLabelHasFuelTank.Text = "Наличие топливного бака: ";
//
// buttonCreate
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(12, 395);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(90, 30);
this.buttonCreate.TabIndex = 2;
this.buttonCreate.Text = "Создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.ButtonCreate_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Locomotives.Properties.Resources.ArrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(758, 395);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 3;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Locomotives.Properties.Resources.ArrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(686, 395);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 4;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Locomotives.Properties.Resources.ArrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(722, 395);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 5;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Locomotives.Properties.Resources.ArrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(722, 359);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 6;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Карта с крестом",
"Карта с дорожками"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(12, 12);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(141, 23);
this.comboBoxSelectorMap.TabIndex = 7;
this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorMap_SelectedIndexChanged);
this.comboBoxSelectorMap.SelectedIndex = 0;
//
// buttonCreateModif
//
this.buttonCreateModif.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateModif.Location = new System.Drawing.Point(108, 395);
this.buttonCreateModif.Name = "buttonCreateModif";
this.buttonCreateModif.Size = new System.Drawing.Size(109, 30);
this.buttonCreateModif.TabIndex = 8;
this.buttonCreateModif.Text = "Модификация";
this.buttonCreateModif.UseVisualStyleBackColor = true;
this.buttonCreateModif.Click += new System.EventHandler(this.ButtonCreateModif_Click);
//
// FormMap
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonCreateModif);
this.Controls.Add(this.comboBoxSelectorMap);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.pictureBoxLocomotive);
this.Name = "FormMap";
this.Text = "Локомотив";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxLocomotive)).EndInit();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private PictureBox pictureBoxLocomotive;
private StatusStrip statusStrip;
private ToolStripStatusLabel toolStripStatusLabelSpeed;
private ToolStripStatusLabel toolStripStatusLabelWeight;
private ToolStripStatusLabel toolStripStatusLabelBodyColor;
private Button buttonCreate;
private Button buttonRight;
private Button buttonLeft;
private Button buttonDown;
private Button buttonUp;
private ComboBox comboBoxSelectorMap;
private Button buttonCreateModif;
private ToolStripStatusLabel toolStripStatusLabelAdditionalColor;
private ToolStripStatusLabel toolStripStatusLabelHasPipe;
private ToolStripStatusLabel toolStripStatusLabelHasFuelTank;
}
}

View File

@ -0,0 +1,121 @@
namespace Locomotives
{
public partial class FormMap : Form
{
/// <summary>
/// Создание объекта от абстрактного класса карты
/// </summary>
private AbstractMap _abstractMap;
public FormMap()
{
InitializeComponent();
_abstractMap = new SimpleMap();
}
/// <summary>
/// Заполнение информации по объекту
/// </summary>
/// <param name="locomotive">Объект от класса отрисовки или его наследника</param>
private void SetData(DrawningLocomotive locomotive)
{
toolStripStatusLabelSpeed.Text = $"Скорость: {locomotive.Locomotive.Speed}";
toolStripStatusLabelWeight.Text = $"Вес: {locomotive.Locomotive.Weight}";
toolStripStatusLabelBodyColor.Text = $"Цвет: {locomotive.Locomotive.BodyColor.Name}";
toolStripStatusLabelAdditionalColor.Text = $"Дополнительный цвет: н/д";
toolStripStatusLabelHasPipe.Text = $"Наличие трубы: н/д";
toolStripStatusLabelHasFuelTank.Text = $"Наличие топливного бака: н/д";
pictureBoxLocomotive.Image = _abstractMap.CreateMap(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height,
new DrawningObjectLocomotive(locomotive));
}
/// <summary>
/// Заполнение дополнительной информации по объекту (только для усложнённого объекта)
/// </summary>
/// <param name="warmlylocomotive">Объект от наследника класса отрисовки</param>
private void SetAdditionalData(DrawningWarmlyLocomotive warmlylocomotive)
{
if (warmlylocomotive.Locomotive is EntityWarmlyLocomotive entityWarmlyLocomotive)
{
toolStripStatusLabelAdditionalColor.Text = $"Дополнительный цвет: {entityWarmlyLocomotive.AdditionalColor.Name}";
toolStripStatusLabelHasPipe.Text = $"Наличие трубы: {entityWarmlyLocomotive.HasPipe}";
toolStripStatusLabelHasFuelTank.Text = $"Наличие топливного бака: {entityWarmlyLocomotive.HasFuelTank}";
}
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
var locomotive = new DrawningLocomotive(rnd.Next(100, 300), rnd.Next(1000, 2000),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
SetData(locomotive);
}
/// <summary>
/// Перемещение объекта по форме
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
{
case "buttonUp":
dir = Direction.Up;
break;
case "buttonDown":
dir = Direction.Down;
break;
case "buttonLeft":
dir = Direction.Left;
break;
case "buttonRight":
dir = Direction.Right;
break;
}
pictureBoxLocomotive.Image = _abstractMap?.MoveObject(dir);
}
/// <summary>
/// Обработка нажатия кнопки "Модификация"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateModif_Click(object sender, EventArgs e)
{
Random rnd = new();
var locomotive = new DrawningWarmlyLocomotive(rnd.Next(100, 300), rnd.Next(1000, 2000),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
160, 85,
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Convert.ToBoolean(rnd.Next(0, 2)),
Convert.ToBoolean(rnd.Next(0, 2)));
SetData(locomotive);
SetAdditionalData(locomotive);
}
/// <summary>
/// Смена карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectorMap.Text)
{
case "Простая карта":
_abstractMap = new SimpleMap();
break;
case "Карта с крестом":
_abstractMap = new CrossMap();
break;
case "Карта с дорожками":
_abstractMap = new RoadsMap();
break;
default:
break;
}
}
}
}

View File

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

View File

@ -0,0 +1,36 @@
namespace Locomotives
{
/// <summary>
/// Интерфейс для отрисовки
/// </summary>
internal interface IDrawningObject
{
/// <summary>
/// Шаг перемещения объекта
/// </summary>
public float Step { get; }
/// <summary>
/// Установка позиции объекта
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина полотна</param>
/// <param name="height">Высота полотна</param>
void SetObject(int x, int y, int width, int height);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(Direction direction);
/// <summary>
/// Отрисовка объекта
/// </summary>
/// <param name="g"></param>
void DrawningObject(Graphics g);
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
(float Top, float Bottom, float Left, float Right) GetCurrentPosition();
}
}

View File

@ -9,7 +9,7 @@ namespace Locomotives
static void Main() static void Main()
{ {
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormLocomotive()); Application.Run(new FormMap());
} }
} }
} }

View File

@ -0,0 +1,45 @@
namespace Locomotives
{
/// <summary>
/// Карта в виде дорожек
/// </summary>
internal class RoadsMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Blue);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.Green);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, i * _size_x, _size_y);
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
for (int i = 25; i < _map.GetLength(1) - 20; i++)
{
for (int j = 30; j < _map.GetLength(0); j += 20)
{
_map[i, j] = _barrier;
}
}
}
}
}

View File

@ -0,0 +1,49 @@
namespace Locomotives
{
/// <summary>
/// Карта с 50-ю барьерами в случайных местах
/// </summary>
internal class SimpleMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Black);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.Gray);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
while (counter < 50)
{
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}