Лаб.2-Добавление родителей и ввод конструкторов

This commit is contained in:
VladaM 2024-02-13 21:11:47 +04:00
parent 5f13bd979f
commit a78b9561d0
7 changed files with 230 additions and 117 deletions

View File

@ -1,4 +1,4 @@
namespace GasolineTanker; namespace GasolineTanker.Drawnings;
/// <summary> /// <summary>
/// Направление перемещения /// Направление перемещения

View File

@ -0,0 +1,53 @@
using GasolineTanker.Entities;
namespace GasolineTanker.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningGasolineTanker : DrawningTanker
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="signalBeacon">Признак наличия сигнального маячка</param>
/// <param name="cistern">Признак наличия цистерны</param>
public DrawningGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool signalBeacon, bool cistern) : base(155, 95)
{
EntityTanker = new EntityGasolineTanker(speed, weight, bodyColor, additionalColor, signalBeacon, cistern);
}
public override void DrawTransport(Graphics g)
{
if (EntityTanker == null || EntityTanker is not EntityGasolineTanker gasolineTanker || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(gasolineTanker.AdditionalColor);
base.DrawTransport(g);
// Цистерна
if (gasolineTanker.Cistern)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 25, _startPosY.Value + 15, 90, 40);
g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 5);
}
// Сигнальный маячок
if (gasolineTanker.SignalBeacon)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 145, _startPosY.Value + 5, 10, 10);
}
}
}

View File

@ -1,14 +1,20 @@
namespace GasolineTanker; using GasolineTanker.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GasolineTanker.Drawnings;
/// <summary> /// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности /// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary> /// </summary>
public class DrawningGasolineTanker public class DrawningTanker
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityGasolineTanker? EntityGasolineTanker { get; private set; } public EntityTanker? EntityTanker { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@ -23,45 +29,57 @@ public class DrawningGasolineTanker
/// <summary> /// <summary>
/// Левая координата прорисовки грузовика /// Левая координата прорисовки грузовика
/// </summary> /// </summary>
private int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя кооридната прорисовки грузовика /// Верхняя кооридната прорисовки грузовика
/// </summary> /// </summary>
private int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки грузовика /// Ширина прорисовки грузовика
/// </summary> /// </summary>
private readonly int _drawningGasolineTankerWidth = 155; private readonly int _drawningTankerWidth = 155;
/// <summary> /// <summary>
/// Высота прорисовки грузовика /// Высота прорисовки грузовика
/// </summary> /// </summary>
private readonly int _drawningGasolineTankerHeight = 95; private readonly int _drawningTankerHeight = 95;
/// <summary> /// <summary>
/// Инициализация свойств /// Пустой конструктор
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> private DrawningTanker()
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="signalBeacon">Признак наличия сигнального маячка</param>
/// <param name="cistern">Признак наличия цистерны</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool signalBeacon, bool cistern)
{ {
EntityGasolineTanker = new EntityGasolineTanker();
EntityGasolineTanker.Init(speed, weight, bodyColor, additionalColor, signalBeacon, cistern);
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
_startPosX = null; _startPosX = null;
_startPosY = null; _startPosY = null;
} }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningTanker(int speed, double weight, Color bodyColor) : this()
{
EntityTanker = new EntityTanker(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningTankerWidth">Ширина грузовика</param>
/// <param name="drawningTankerHeight">Высота грузовика</param>
protected DrawningTanker(int drawningTankerWidth, int drawningTankerHeight) : this()
{
_drawningTankerWidth= drawningTankerWidth;
_drawningTankerHeight= drawningTankerHeight;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
@ -72,7 +90,7 @@ public class DrawningGasolineTanker
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {
if (width >= _drawningGasolineTankerWidth && height >= _drawningGasolineTankerHeight) if (width >= _drawningTankerWidth && height >= _drawningTankerHeight)
{ {
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
@ -93,8 +111,8 @@ public class DrawningGasolineTanker
return; return;
} }
int endOfDrawingWidth = x + _drawningGasolineTankerWidth; int endOfDrawingWidth = x + _drawningTankerWidth;
int endOfDrawingHeight = y + _drawningGasolineTankerHeight; int endOfDrawingHeight = y + _drawningTankerHeight;
_startPosX = x; _startPosX = x;
_startPosY = y; _startPosY = y;
@ -108,7 +126,6 @@ public class DrawningGasolineTanker
} }
} }
/// <summary> /// <summary>
/// Изменение направления перемещения /// Изменение направления перемещения
/// </summary> /// </summary>
@ -116,7 +133,7 @@ public class DrawningGasolineTanker
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns> /// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction) public bool MoveTransport(DirectionType direction)
{ {
if (EntityGasolineTanker == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityTanker == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return false; return false;
} }
@ -125,30 +142,30 @@ public class DrawningGasolineTanker
{ {
//влево //влево
case DirectionType.Left: case DirectionType.Left:
if (_startPosX.Value - EntityGasolineTanker.Step > 0) if (_startPosX.Value - EntityTanker.Step > 0)
{ {
_startPosX -= (int)EntityGasolineTanker.Step; _startPosX -= (int)EntityTanker.Step;
} }
return true; return true;
//вверх //вверх
case DirectionType.Up: case DirectionType.Up:
if (_startPosY.Value - EntityGasolineTanker.Step > 0) if (_startPosY.Value - EntityTanker.Step > 0)
{ {
_startPosY -= (int)EntityGasolineTanker.Step; _startPosY -= (int)EntityTanker.Step;
} }
return true; return true;
// вправо // вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + _drawningGasolineTankerWidth + EntityGasolineTanker.Step < _pictureWidth) if (_startPosX.Value + _drawningTankerWidth + EntityTanker.Step < _pictureWidth)
{ {
_startPosX += (int)EntityGasolineTanker.Step; _startPosX += (int)EntityTanker.Step;
} }
return true; return true;
//вниз //вниз
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + _drawningGasolineTankerHeight + EntityGasolineTanker.Step < _pictureHeight) if (_startPosY.Value + _drawningTankerHeight + EntityTanker.Step < _pictureHeight)
{ {
_startPosY += (int)EntityGasolineTanker.Step; _startPosY += (int)EntityTanker.Step;
} }
return true; return true;
default: default:
@ -156,21 +173,19 @@ public class DrawningGasolineTanker
} }
} }
/// <summary> /// <summary>
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
public void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntityGasolineTanker == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityTanker == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityGasolineTanker.AdditionalColor);
// Границы бензовоза // Границы бензовоза
@ -187,30 +202,13 @@ public class DrawningGasolineTanker
// Кузов // Кузов
Brush br = new SolidBrush(EntityGasolineTanker.BodyColor); Brush br = new SolidBrush(EntityTanker.BodyColor);
g.FillRectangle(br, _startPosX.Value + 115, _startPosY.Value + 15, 40, 40); g.FillRectangle(br, _startPosX.Value + 116, _startPosY.Value + 16, 39, 39);
g.FillRectangle(br, _startPosX.Value + 25, _startPosY.Value + 55, 130, 15); g.FillRectangle(br, _startPosX.Value + 26, _startPosY.Value + 56, 129, 14);
// Стекло // Стекло
Brush brBlue = new SolidBrush(Color.LightBlue); Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBlue, _startPosX.Value + 120, _startPosY.Value + 20, 25, 25); g.FillRectangle(brBlue, _startPosX.Value + 120, _startPosY.Value + 20, 25, 25);
// Цистерна
if (EntityGasolineTanker.Cistern)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 25, _startPosY.Value + 15, 90, 40);
g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 5);
}
// Сигнальный маячок
if (EntityGasolineTanker.SignalBeacon)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 145, _startPosY.Value + 5, 10, 10);
}
} }
}
}

View File

@ -1,26 +1,11 @@
namespace GasolineTanker; namespace GasolineTanker.Entities;
/// <summary> /// <summary>
/// Класс-сущность "Бензовоз" /// Класс-сущность "Бензовоз"
/// </summary> /// </summary>
public class EntityGasolineTanker public class EntityGasolineTanker : EntityTanker
{ {
/// <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>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
@ -34,15 +19,10 @@ public class EntityGasolineTanker
/// <summary> /// <summary>
/// Признак (опция) наличия цистерны /// Признак (опция) наличия цистерны
/// </summary> /// </summary>
public bool Cistern { get; private set; } public bool Cistern { get; private set; }
/// <summary> /// <summary>
/// Шаг перемещения автомобиля /// Инициализация полей объекта-класса бензовоза
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param> /// <param name="weight">Вес автомобиля</param>
@ -50,14 +30,11 @@ public class EntityGasolineTanker
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="signalBeacon">Признак наличия сигнального маячка</param> /// <param name="signalBeacon">Признак наличия сигнального маячка</param>
/// <param name="cistern">Признак наличия цистерны</param> /// <param name="cistern">Признак наличия цистерны</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool signalBeacon, bool cistern) public EntityGasolineTanker(int speed, double weight, Color bodyColor, Color additionalColor, bool signalBeacon, bool cistern) : base(speed, weight, bodyColor)
{ {
Speed = speed; AdditionalColor = additionalColor;
Weight = weight; SignalBeacon = signalBeacon;
BodyColor = bodyColor; Cistern = cistern;
AdditionalColor = additionalColor; }
SignalBeacon = signalBeacon;
Cistern = cistern;
}
} }

View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GasolineTanker.Entities;
/// <summary>
/// Класс-сущность "Грузовик"
/// </summary>
public class EntityTanker
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; protected set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; protected set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; protected set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Конструктор сущности
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityTanker(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -34,6 +34,7 @@
buttonDown = new Button(); buttonDown = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonCreateTanker = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxGasolineTanker).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxGasolineTanker).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -49,11 +50,11 @@
// ButtonCreateGasolineTanker // ButtonCreateGasolineTanker
// //
ButtonCreateGasolineTanker.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; ButtonCreateGasolineTanker.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCreateGasolineTanker.Location = new Point(12, 433); ButtonCreateGasolineTanker.Location = new Point(12, 421);
ButtonCreateGasolineTanker.Name = "ButtonCreateGasolineTanker"; ButtonCreateGasolineTanker.Name = "ButtonCreateGasolineTanker";
ButtonCreateGasolineTanker.Size = new Size(75, 23); ButtonCreateGasolineTanker.Size = new Size(153, 35);
ButtonCreateGasolineTanker.TabIndex = 1; ButtonCreateGasolineTanker.TabIndex = 1;
ButtonCreateGasolineTanker.Text = "Создать"; ButtonCreateGasolineTanker.Text = "Создать бензовоз";
ButtonCreateGasolineTanker.UseVisualStyleBackColor = true; ButtonCreateGasolineTanker.UseVisualStyleBackColor = true;
ButtonCreateGasolineTanker.Click += buttonCreateGasolineTanker_Click; ButtonCreateGasolineTanker.Click += buttonCreateGasolineTanker_Click;
// //
@ -105,11 +106,23 @@
buttonLeft.UseVisualStyleBackColor = true; buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click; buttonLeft.Click += ButtonMove_Click;
// //
// buttonCreateTanker
//
buttonCreateTanker.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTanker.Location = new Point(171, 421);
buttonCreateTanker.Name = "buttonCreateTanker";
buttonCreateTanker.Size = new Size(153, 35);
buttonCreateTanker.TabIndex = 6;
buttonCreateTanker.Text = "Создать грузовик";
buttonCreateTanker.UseVisualStyleBackColor = true;
buttonCreateTanker.Click += buttonCreateTanker_Click;
//
// FormGasolineTanker // FormGasolineTanker
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(945, 474); ClientSize = new Size(945, 474);
Controls.Add(buttonCreateTanker);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonDown); Controls.Add(buttonDown);
@ -130,5 +143,6 @@
private Button buttonDown; private Button buttonDown;
private Button buttonUp; private Button buttonUp;
private Button buttonLeft; private Button buttonLeft;
private Button buttonCreateTanker;
} }
} }

View File

@ -8,12 +8,13 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.Windows.Forms.VisualStyles; using System.Windows.Forms.VisualStyles;
using GasolineTanker.Drawnings;
namespace GasolineTanker namespace GasolineTanker
{ {
public partial class FormGasolineTanker : Form public partial class FormGasolineTanker : Form
{ {
private DrawningGasolineTanker? _drawningGasolineTanker; private DrawningTanker? _drawningTanker;
public FormGasolineTanker() public FormGasolineTanker()
{ {
@ -25,31 +26,40 @@ namespace GasolineTanker
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawningGasolineTanker == null) if (_drawningTanker == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxGasolineTanker.Width, pictureBoxGasolineTanker.Height); Bitmap bmp = new(pictureBoxGasolineTanker.Width, pictureBoxGasolineTanker.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningGasolineTanker.DrawTransport(gr); _drawningTanker.DrawTransport(gr);
pictureBoxGasolineTanker.Image = bmp; pictureBoxGasolineTanker.Image = bmp;
} }
/// <summary> /// <summary>
/// Обработка нажатия кнопки "Создать" /// Создание объекта класса-перемещения
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="type">Тип создаваемого объекта</param>
/// <param name="e"></param> private void CreateObject(string type)
private void buttonCreateGasolineTanker_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawningGasolineTanker = new DrawningGasolineTanker(); switch (type)
_drawningGasolineTanker.Init(random.Next(100, 300), random.Next(1000, 3000), {
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), case nameof(DrawningTanker):
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), _drawningTanker = new DrawningTanker(random.Next(100, 300), random.Next(1000, 3000),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
if (!_drawningGasolineTanker.SetPictureSize(pictureBoxGasolineTanker.Width, pictureBoxGasolineTanker.Height)) break;
case nameof(DrawningGasolineTanker):
_drawningTanker = new DrawningGasolineTanker(random.Next(100, 300), random.Next(1000, 3000),
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)));
break;
default:
return;
}
if (!_drawningTanker.SetPictureSize(pictureBoxGasolineTanker.Width, pictureBoxGasolineTanker.Height))
{ {
MessageBox.Show("Размер транспорта для отрисовки больше, чем форма! ", "Ошибка", MessageBox.Show("Размер транспорта для отрисовки больше, чем форма! ", "Ошибка",
MessageBoxButtons.OK, MessageBoxButtons.OK,
@ -57,11 +67,26 @@ namespace GasolineTanker
} }
else else
{ {
_drawningGasolineTanker.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawningTanker.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
} }
} }
/// <summary>
/// Обработка нажатия кнопки "Создать бензовоз"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateGasolineTanker_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningGasolineTanker));
/// <summary>
/// Обработка нажатия кнопки "Создать грузовик"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateTanker_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTanker));
/// <summary> /// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации) /// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary> /// </summary>
@ -69,7 +94,7 @@ namespace GasolineTanker
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawningGasolineTanker == null) if (_drawningTanker == null)
{ {
return; return;
} }
@ -79,16 +104,16 @@ namespace GasolineTanker
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawningGasolineTanker.MoveTransport(DirectionType.Up); result = _drawningTanker.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawningGasolineTanker.MoveTransport(DirectionType.Down); result = _drawningTanker.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawningGasolineTanker.MoveTransport(DirectionType.Left); result = _drawningTanker.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = _drawningGasolineTanker.MoveTransport(DirectionType.Right); result = _drawningTanker.MoveTransport(DirectionType.Right);
break; break;
} }
@ -97,6 +122,5 @@ namespace GasolineTanker
Draw(); Draw();
} }
} }
} }
} }