From c99b5e5b3c8bb56f7b612044abee9a02bd36a402 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C?= Date: Wed, 12 Oct 2022 11:21:29 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Locomotives/Locomotives/AbstractMap.cs | 244 ++++++++++++++++++ Locomotives/Locomotives/CrossMap.cs | 52 ++++ Locomotives/Locomotives/Direction.cs | 4 + Locomotives/Locomotives/DrawningLocomotive.cs | 39 ++- .../Locomotives/DrawningObjectLocomotive.cs | 35 +++ .../Locomotives/DrawningWarmlyLocomotive.cs | 61 +++++ Locomotives/Locomotives/EntityLocomotive.cs | 2 +- .../Locomotives/EntityWarmlyLocomotive.cs | 36 +++ Locomotives/Locomotives/FormLocomotive.cs | 3 +- Locomotives/Locomotives/FormMap.Designer.cs | 239 +++++++++++++++++ Locomotives/Locomotives/FormMap.cs | 121 +++++++++ Locomotives/Locomotives/FormMap.resx | 63 +++++ Locomotives/Locomotives/IDrawningObject.cs | 36 +++ Locomotives/Locomotives/Program.cs | 2 +- Locomotives/Locomotives/RoadsMap.cs | 45 ++++ Locomotives/Locomotives/SimpleMap.cs | 49 ++++ 16 files changed, 1016 insertions(+), 15 deletions(-) create mode 100644 Locomotives/Locomotives/AbstractMap.cs create mode 100644 Locomotives/Locomotives/CrossMap.cs create mode 100644 Locomotives/Locomotives/DrawningObjectLocomotive.cs create mode 100644 Locomotives/Locomotives/DrawningWarmlyLocomotive.cs create mode 100644 Locomotives/Locomotives/EntityWarmlyLocomotive.cs create mode 100644 Locomotives/Locomotives/FormMap.Designer.cs create mode 100644 Locomotives/Locomotives/FormMap.cs create mode 100644 Locomotives/Locomotives/FormMap.resx create mode 100644 Locomotives/Locomotives/IDrawningObject.cs create mode 100644 Locomotives/Locomotives/RoadsMap.cs create mode 100644 Locomotives/Locomotives/SimpleMap.cs diff --git a/Locomotives/Locomotives/AbstractMap.cs b/Locomotives/Locomotives/AbstractMap.cs new file mode 100644 index 0000000..f27ed6e --- /dev/null +++ b/Locomotives/Locomotives/AbstractMap.cs @@ -0,0 +1,244 @@ +namespace Locomotives +{ + internal abstract class AbstractMap + { + /// + /// Поле от интерфейса прорисовки + /// + private IDrawningObject _drawningObject = null; + /// + /// Массив карты + /// + protected int[,] _map = null; + /// + /// Ширина карты (графической панели) + /// + protected int _width; + /// + /// Высота карты (графической панели) + /// + protected int _height; + /// + /// Ширина ячейки + /// + protected float _size_x; + /// + /// Высота ячейки + /// + protected float _size_y; + protected readonly Random _random = new(); + /// + /// Доступная для движения ячейка + /// + protected readonly int _freeRoad = 0; + /// + /// Недоступная для движения ячейка + /// + protected readonly int _barrier = 1; + /// + /// Наполнение графической панели + /// + /// Ширина + /// Высота + /// + /// + public Bitmap CreateMap(int width, int height, IDrawningObject drawningObject) + { + _width = width; + _height = height; + _drawningObject = drawningObject; + GenerateMap(); + while (!SetObjectOnMap()) + { + GenerateMap(); + } + return DrawMapWithObject(); + } + /// + /// Получение координат отрисовываемого объекта в массиве + /// + /// + 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) + ); + } + /// + /// Проверка возможности движения в данном направлении + /// + /// Направление + /// + 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; + } + /// + /// Проверка возможности установить объект на карте + /// + /// + 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; + } + /// + /// Передвижение объекта по карте + /// + /// Направление + /// + public Bitmap MoveObject(Direction direction) + { + if (!AbleToMove(direction)) + { + return DrawMapWithObject(); + } + _drawningObject.MoveObject(direction); + return DrawMapWithObject(); + } + /// + /// Создание объекта на карте + /// + /// Возможность создать объект + 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; + } + /// + /// Отрисовка карты + /// + /// + 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; + } + /// + /// Генерация массива карты + /// + protected abstract void GenerateMap(); + /// + /// Отрисовка ячейки со свободным пространством (дорогой) + /// + /// + /// + /// + protected abstract void DrawRoadPart(Graphics g, int i, int j); + /// + /// Отрисовка ячейки с барьером + /// + /// + /// + /// + protected abstract void DrawBarrierPart(Graphics g, int i, int j); + } +} diff --git a/Locomotives/Locomotives/CrossMap.cs b/Locomotives/Locomotives/CrossMap.cs new file mode 100644 index 0000000..fc41c06 --- /dev/null +++ b/Locomotives/Locomotives/CrossMap.cs @@ -0,0 +1,52 @@ +namespace Locomotives +{ + /// + /// Карта в виде креста + /// + internal class CrossMap : AbstractMap + { + /// + /// Цвет участка закрытого + /// + private readonly Brush barrierColor = new SolidBrush(Color.Red); + /// + /// Цвет участка открытого + /// + 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; + } + } + } + } +} diff --git a/Locomotives/Locomotives/Direction.cs b/Locomotives/Locomotives/Direction.cs index 1a83fbb..9be36dd 100644 --- a/Locomotives/Locomotives/Direction.cs +++ b/Locomotives/Locomotives/Direction.cs @@ -5,6 +5,10 @@ /// internal enum Direction { + /// + /// никуда + /// + None = 0, /// /// вверх /// diff --git a/Locomotives/Locomotives/DrawningLocomotive.cs b/Locomotives/Locomotives/DrawningLocomotive.cs index 39ddb63..9b05ca1 100644 --- a/Locomotives/Locomotives/DrawningLocomotive.cs +++ b/Locomotives/Locomotives/DrawningLocomotive.cs @@ -8,15 +8,15 @@ /// /// Класс-сущность /// - public EntityLocomotive Locomotive { get; private set; } + public EntityLocomotive Locomotive { get; protected set; } /// /// Левая координата отрисовки локомотива /// - private float _startPosX; + protected float _startPosX; /// /// Верхняя координата отрисовки локомотива /// - private float _startPosY; + protected float _startPosY; /// /// Ширина окна отрисовки /// @@ -39,10 +39,23 @@ /// Скорость /// Вес /// Цвет кузова - public void Init(int speed, float weight, Color bodyColor) + public DrawningLocomotive(int speed, float weight, Color bodyColor) { - Locomotive = new EntityLocomotive(); - Locomotive.Init(speed, weight, bodyColor); + Locomotive = new EntityLocomotive(speed, weight, bodyColor); + } + /// + /// Конструктор для изменения размеров локомотива + /// + /// Скорость + /// Вес + /// Цвет кузова + /// Ширина локомотива + /// Высота локомотива + protected DrawningLocomotive(int speed, float weight, Color bodyColor, int locomotiveWidth, int locomotiveHeight) + : this(speed, weight, bodyColor) + { + _locomotiveWidth = locomotiveWidth; + _locomotiveHeight = locomotiveHeight; } /// /// Установка начальной позиции локомотива @@ -68,10 +81,6 @@ /// Направление public void MoveLocomotive(Direction direction) { - if (!_pictureWidth.HasValue || !_pictureHeight.HasValue) - { - return; - } if (!_pictureWidth.HasValue || !_pictureHeight.HasValue) { return; @@ -112,7 +121,7 @@ /// Метод отрисовки локомотива /// /// Графика - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { if (_startPosX < 0 || _startPosY < 0 || !_pictureHeight.HasValue || !_pictureWidth.HasValue) { @@ -186,5 +195,13 @@ _startPosY = _pictureHeight.Value - _locomotiveHeight; } } + /// + /// Получение текущей позиции объекта + /// + /// + public (float Top, float Bottom, float Left, float Right) GetCurrentPosition() + { + return (_startPosY, _startPosY + _locomotiveHeight, _startPosX, _startPosX + _locomotiveWidth); + } } } diff --git a/Locomotives/Locomotives/DrawningObjectLocomotive.cs b/Locomotives/Locomotives/DrawningObjectLocomotive.cs new file mode 100644 index 0000000..0b697c0 --- /dev/null +++ b/Locomotives/Locomotives/DrawningObjectLocomotive.cs @@ -0,0 +1,35 @@ +namespace Locomotives +{ +/// +/// Класс-наследник от интерфейса (реализация) +/// + internal class DrawningObjectLocomotive : IDrawningObject + { + /// + /// Объект от класса отрисовки локомотива + /// + 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); + } + + } +} diff --git a/Locomotives/Locomotives/DrawningWarmlyLocomotive.cs b/Locomotives/Locomotives/DrawningWarmlyLocomotive.cs new file mode 100644 index 0000000..5a0e788 --- /dev/null +++ b/Locomotives/Locomotives/DrawningWarmlyLocomotive.cs @@ -0,0 +1,61 @@ +namespace Locomotives +{ + /// + /// Класс-наследник от класса отрисовки локомотива + /// + internal class DrawningWarmlyLocomotive : DrawningLocomotive + { + /// + /// Конструктор, передаём в protected конструктор базового класса обычные параметры и вводим новые + /// + /// Скорость + /// Вес + /// Цвет кузова + /// Ширина локомотива + /// Высота локомотива + /// Дополнительный цвет + /// Признак наличия трубы + /// Признак наличия топливного бака + 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); + } + /// + /// Отрисовываем базовую часть локомотива и добавляем дополнительные элементы, если они есть + /// + /// + 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); + } + } + } + } +} diff --git a/Locomotives/Locomotives/EntityLocomotive.cs b/Locomotives/Locomotives/EntityLocomotive.cs index ed3183c..d12a486 100644 --- a/Locomotives/Locomotives/EntityLocomotive.cs +++ b/Locomotives/Locomotives/EntityLocomotive.cs @@ -27,7 +27,7 @@ /// скорость /// вес /// цвет кузова - public void Init(int speed, float weight, Color bodyColor) + public EntityLocomotive (int speed, float weight, Color bodyColor) { Random rnd = new(); Speed = speed <= 0 ? rnd.Next(50, 150) : speed; diff --git a/Locomotives/Locomotives/EntityWarmlyLocomotive.cs b/Locomotives/Locomotives/EntityWarmlyLocomotive.cs new file mode 100644 index 0000000..e8ddb29 --- /dev/null +++ b/Locomotives/Locomotives/EntityWarmlyLocomotive.cs @@ -0,0 +1,36 @@ +namespace Locomotives +{ + /// + /// Класс-наследник от класса-сущности локомотива (усложнённый локомотив/тепловоз) + /// + internal class EntityWarmlyLocomotive : EntityLocomotive + { + /// + /// Дополнительный цвет + /// + public Color AdditionalColor { get; private set; } + /// + /// Признак наличия трубы + /// + public bool HasPipe { get; private set; } + /// + /// Признак наличия топливного бака + /// + public bool HasFuelTank { get; private set; } + /// + /// Инициализация свойств усложнённого локомотива (тепловоза) + /// + /// Скорость + /// Вес + /// Цвет кузова + /// Дополнительный цвет + /// Признак наличия трубы + /// Признак наличия топливного бака + public EntityWarmlyLocomotive(int speed, float weight, Color bodyColor, Color additionalColor, bool hasPipe, bool hasFuelTank) : base (speed, weight, bodyColor) + { + AdditionalColor = additionalColor; + HasPipe = hasPipe; + HasFuelTank = hasFuelTank; + } + } +} diff --git a/Locomotives/Locomotives/FormLocomotive.cs b/Locomotives/Locomotives/FormLocomotive.cs index 63b2178..20d5cbe 100644 --- a/Locomotives/Locomotives/FormLocomotive.cs +++ b/Locomotives/Locomotives/FormLocomotive.cs @@ -29,8 +29,7 @@ private void ButtonCreate_Click(object sender, EventArgs e) { Random rnd = new(); - _locomotive = new DrawningLocomotive(); - _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 = 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.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxLocomotive.Width, pictureBoxLocomotive.Height); toolStripStatusLabelSpeed.Text = $"Скорость: {_locomotive.Locomotive.Speed}"; toolStripStatusLabelWeight.Text = $"Вес: {_locomotive.Locomotive.Weight}"; diff --git a/Locomotives/Locomotives/FormMap.Designer.cs b/Locomotives/Locomotives/FormMap.Designer.cs new file mode 100644 index 0000000..1d77af6 --- /dev/null +++ b/Locomotives/Locomotives/FormMap.Designer.cs @@ -0,0 +1,239 @@ +namespace Locomotives +{ + partial class FormMap + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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; + } +} \ No newline at end of file diff --git a/Locomotives/Locomotives/FormMap.cs b/Locomotives/Locomotives/FormMap.cs new file mode 100644 index 0000000..96188d1 --- /dev/null +++ b/Locomotives/Locomotives/FormMap.cs @@ -0,0 +1,121 @@ +namespace Locomotives +{ + public partial class FormMap : Form + { + /// + /// Создание объекта от абстрактного класса карты + /// + private AbstractMap _abstractMap; + public FormMap() + { + InitializeComponent(); + _abstractMap = new SimpleMap(); + } + /// + /// Заполнение информации по объекту + /// + /// Объект от класса отрисовки или его наследника + 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)); + } + /// + /// Заполнение дополнительной информации по объекту (только для усложнённого объекта) + /// + /// Объект от наследника класса отрисовки + private void SetAdditionalData(DrawningWarmlyLocomotive warmlylocomotive) + { + if (warmlylocomotive.Locomotive is EntityWarmlyLocomotive entityWarmlyLocomotive) + { + toolStripStatusLabelAdditionalColor.Text = $"Дополнительный цвет: {entityWarmlyLocomotive.AdditionalColor.Name}"; + toolStripStatusLabelHasPipe.Text = $"Наличие трубы: {entityWarmlyLocomotive.HasPipe}"; + toolStripStatusLabelHasFuelTank.Text = $"Наличие топливного бака: {entityWarmlyLocomotive.HasFuelTank}"; + } + } + /// + /// Обработка нажатия кнопки "Создать" + /// + /// + /// + 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); + } + /// + /// Перемещение объекта по форме + /// + /// + /// + 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); + } + /// + /// Обработка нажатия кнопки "Модификация" + /// + /// + /// + 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); + } + /// + /// Смена карты + /// + /// + /// + 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; + } + } + } +} diff --git a/Locomotives/Locomotives/FormMap.resx b/Locomotives/Locomotives/FormMap.resx new file mode 100644 index 0000000..2c0949d --- /dev/null +++ b/Locomotives/Locomotives/FormMap.resx @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/Locomotives/Locomotives/IDrawningObject.cs b/Locomotives/Locomotives/IDrawningObject.cs new file mode 100644 index 0000000..18e3dcc --- /dev/null +++ b/Locomotives/Locomotives/IDrawningObject.cs @@ -0,0 +1,36 @@ +namespace Locomotives +{ + /// + /// Интерфейс для отрисовки + /// + internal interface IDrawningObject + { + /// + /// Шаг перемещения объекта + /// + public float Step { get; } + /// + /// Установка позиции объекта + /// + /// Координата X + /// Координата Y + /// Ширина полотна + /// Высота полотна + void SetObject(int x, int y, int width, int height); + /// + /// Изменение направления пермещения объекта + /// + /// Направление + void MoveObject(Direction direction); + /// + /// Отрисовка объекта + /// + /// + void DrawningObject(Graphics g); + /// + /// Получение текущей позиции объекта + /// + /// + (float Top, float Bottom, float Left, float Right) GetCurrentPosition(); + } +} diff --git a/Locomotives/Locomotives/Program.cs b/Locomotives/Locomotives/Program.cs index e09e379..82857a8 100644 --- a/Locomotives/Locomotives/Program.cs +++ b/Locomotives/Locomotives/Program.cs @@ -9,7 +9,7 @@ namespace Locomotives static void Main() { ApplicationConfiguration.Initialize(); - Application.Run(new FormLocomotive()); + Application.Run(new FormMap()); } } } \ No newline at end of file diff --git a/Locomotives/Locomotives/RoadsMap.cs b/Locomotives/Locomotives/RoadsMap.cs new file mode 100644 index 0000000..84aeb69 --- /dev/null +++ b/Locomotives/Locomotives/RoadsMap.cs @@ -0,0 +1,45 @@ +namespace Locomotives +{ + /// + /// Карта в виде дорожек + /// + internal class RoadsMap : AbstractMap + { + /// + /// Цвет участка закрытого + /// + private readonly Brush barrierColor = new SolidBrush(Color.Blue); + /// + /// Цвет участка открытого + /// + 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; + } + } + } + } +} \ No newline at end of file diff --git a/Locomotives/Locomotives/SimpleMap.cs b/Locomotives/Locomotives/SimpleMap.cs new file mode 100644 index 0000000..0a3969b --- /dev/null +++ b/Locomotives/Locomotives/SimpleMap.cs @@ -0,0 +1,49 @@ +namespace Locomotives +{ + /// + /// Карта с 50-ю барьерами в случайных местах + /// + internal class SimpleMap : AbstractMap + { + /// + /// Цвет участка закрытого + /// + private readonly Brush barrierColor = new SolidBrush(Color.Black); + /// + /// Цвет участка открытого + /// + 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++; + } + } + } + } +}