diff --git a/Tank/Tank/DirectionType.cs b/Tank/Tank/Drowings/DirectionType.cs similarity index 66% rename from Tank/Tank/DirectionType.cs rename to Tank/Tank/Drowings/DirectionType.cs index 8923629..c5ad9a8 100644 --- a/Tank/Tank/DirectionType.cs +++ b/Tank/Tank/Drowings/DirectionType.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Tank; +namespace Tank.Drowings; public enum DirectionType { @@ -23,5 +17,6 @@ public enum DirectionType /// /// Вправо /// - Right = 4 + Right = 4, + Unknow = -1 } diff --git a/Tank/Tank/DrawningTank.cs b/Tank/Tank/Drowings/DrawningMachine.cs similarity index 71% rename from Tank/Tank/DrawningTank.cs rename to Tank/Tank/Drowings/DrawningMachine.cs index 48820a5..f60e70a 100644 --- a/Tank/Tank/DrawningTank.cs +++ b/Tank/Tank/Drowings/DrawningMachine.cs @@ -3,15 +3,16 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Tank.Entities; -namespace Tank; +namespace Tank.Drowings; -public class DrawningTank +public class DrawningMachine { /// /// Класс-сущность /// - public EntityTank? EntityTank { get; private set; } + public EntityMachine? EntityMachine { get; protected set; } /// /// Ширина окна /// @@ -23,11 +24,11 @@ public class DrawningTank /// /// Левая координата прорисовки автомобиля /// - private int? _startPosX; + protected int? _startPosX; /// /// Верхняя кооридната прорисовки автомобиля /// - private int? _startPosY; + protected int? _startPosY; /// /// Ширина прорисовки автомобиля /// @@ -37,25 +38,56 @@ public class DrawningTank /// private readonly int _drawningTankHeight = 105; /// - /// Инициализация свойств + /// Координата X /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия обвеса - /// Признак наличия антикрыла - - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool pushka, bool pulemet) + public int? GetPosX => _startPosX; + /// + /// Координата Y + /// + public int? GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _drawningTankWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningTankHeight; + /// + /// Пустой конструктор + /// + private DrawningMachine() { - EntityTank = new EntityTank(); - EntityTank.Init(speed, weight, bodyColor, additionalColor, pushka, pulemet); _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + + public DrawningMachine(int speed, double weight, Color bodyColor) : this() + { + EntityMachine = new EntityMachine(speed, weight, bodyColor); + } + + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки автомобиля + /// Высота прорисовки автомобиля + /// Основной цвет + + protected DrawningMachine(int drawningTankWidth, int drawningTankHeight) : this() + { + _drawningTankWidth = drawningTankWidth; + _drawningTankHeight = drawningTankHeight; + } + /// /// Установка границ поля /// /// Ширина поля @@ -115,7 +147,7 @@ public class DrawningTank /// true - перемещене выполнено, false - перемещение невозможно public bool MoveTransport(DirectionType direction) { - if (EntityTank == null || !_startPosX.HasValue || + if (EntityMachine == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; @@ -124,23 +156,23 @@ public class DrawningTank { //влево case DirectionType.Left: - if (_startPosX.Value - EntityTank.Step > 0) - _startPosX -= (int)EntityTank.Step; + if (_startPosX.Value - EntityMachine.Step > 0) + _startPosX -= (int)EntityMachine.Step; return true; //вверх case DirectionType.Up: - if (_startPosY.Value - EntityTank.Step > 0) - _startPosY -= (int)EntityTank.Step; + if (_startPosY.Value - EntityMachine.Step > 0) + _startPosY -= (int)EntityMachine.Step; return true; // вправо case DirectionType.Right: - if (_startPosX.Value + _drawningTankWidth + EntityTank.Step < _pictureWidth) - _startPosX += (int)EntityTank.Step; + if (_startPosX.Value + _drawningTankWidth + EntityMachine.Step < _pictureWidth) + _startPosX += (int)EntityMachine.Step; return true; //вниз case DirectionType.Down: - if (_startPosY.Value + _drawningTankHeight + EntityTank.Step < _pictureHeight) - _startPosY += (int)EntityTank.Step; + if (_startPosY.Value + _drawningTankHeight + EntityMachine.Step < _pictureHeight) + _startPosY += (int)EntityMachine.Step; return true; default: return false; @@ -150,16 +182,16 @@ public class DrawningTank /// Прорисовка объекта /// /// - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { - if (EntityTank == null || !_startPosX.HasValue || + if (EntityMachine == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black); - Brush additionalBrush = new SolidBrush(EntityTank.AdditionalColor); - Brush bodyBrush = new SolidBrush(EntityTank.BodyColor); + + Brush bodyBrush = new SolidBrush(EntityMachine.BodyColor); g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 45, 150, 60); g.DrawEllipse(pen, _startPosX.Value + 5, _startPosY.Value + 60, 33, 33); @@ -177,17 +209,5 @@ public class DrawningTank g.FillRectangle(bodyBrush, _startPosX.Value + 30, _startPosY.Value + 10, 100, 30); g.FillRectangle(bodyBrush, _startPosX.Value + 5, _startPosY.Value + 40, 140, 25); - if (EntityTank.Pushka) - g.FillRectangle(additionalBrush, _startPosX.Value + 120, _startPosY.Value + 20, 100, 15); - - if (EntityTank.Pulemet) - { - Point p = new Point(_startPosX.Value + 75, _startPosY.Value + 10); - Point p1 = new Point(_startPosX.Value + 80, _startPosY.Value + 1); - Point p2 = new Point(_startPosX.Value + 87, _startPosY.Value + 2); - Point p3 = new Point(_startPosX.Value + 80, _startPosY.Value + 10); - Point[] p_pulemet = { p, p1, p2, p3 }; - g.FillPolygon(additionalBrush, p_pulemet); - } } } diff --git a/Tank/Tank/Drowings/DrawningTank.cs b/Tank/Tank/Drowings/DrawningTank.cs new file mode 100644 index 0000000..b141379 --- /dev/null +++ b/Tank/Tank/Drowings/DrawningTank.cs @@ -0,0 +1,52 @@ +using Tank.Entities; + +namespace Tank.Drowings; + +/// +/// Класс, отвечающий за прорисовку и перемещение объекта-сущности +/// +public class DrawningTank : DrawningMachine +{ + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия обвеса + /// Признак наличия антикрыла + + public DrawningTank(int speed, double weight, Color bodyColor, Color additionalColor, bool pushka, bool pulemet) : base(218, 105) + { + EntityMachine = new EntityTank(speed, weight, bodyColor, additionalColor, pushka, pulemet); + } + /// + /// Прорисовка объекта + /// + /// + + public override void DrawTransport(Graphics g) + { + if (EntityMachine == null || EntityMachine is not EntityTank tank || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + base.DrawTransport(g); + Brush additionalBrush = new SolidBrush(tank.AdditionalColor); + + if (tank.Pushka) + g.FillRectangle(additionalBrush, _startPosX.Value + 120, _startPosY.Value + 20, 100, 15); + + if (tank.Pulemet) + { + Point p = new Point(_startPosX.Value + 75, _startPosY.Value + 10); + Point p1 = new Point(_startPosX.Value + 80, _startPosY.Value + 1); + Point p2 = new Point(_startPosX.Value + 87, _startPosY.Value + 2); + Point p3 = new Point(_startPosX.Value + 80, _startPosY.Value + 10); + Point[] p_pulemet1 = { p, p1, p2, p3 }; + g.FillPolygon(additionalBrush, p_pulemet1); + } + } +} \ No newline at end of file diff --git a/Tank/Tank/Entities/EntityMachine.cs b/Tank/Tank/Entities/EntityMachine.cs new file mode 100644 index 0000000..2716dad --- /dev/null +++ b/Tank/Tank/Entities/EntityMachine.cs @@ -0,0 +1,39 @@ +namespace Tank.Entities; + +/// +/// Класс-сущность "Машина" +/// +public class EntityMachine +{ + /// + /// Скорость + /// + public int Speed { get; private set; } + /// + /// Вес + /// + public double Weight { get; private set; } + /// + /// Основной цвет + /// + public Color BodyColor { get; private set; } + + /// + /// Конструктор сущности + /// + /// Скорость + /// Вес автомобиля + /// Основной цвет + + /// + /// Шаг перемещения автомобиля + /// + public double Step => Speed * 100 / Weight; + + public EntityMachine(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + } +} diff --git a/Tank/Tank/EntityTank.cs b/Tank/Tank/Entities/EntityTank.cs similarity index 65% rename from Tank/Tank/EntityTank.cs rename to Tank/Tank/Entities/EntityTank.cs index b8303da..7d98f61 100644 --- a/Tank/Tank/EntityTank.cs +++ b/Tank/Tank/Entities/EntityTank.cs @@ -1,19 +1,7 @@ -namespace Tank; +namespace Tank.Entities; -public class EntityTank +public class EntityTank : EntityMachine { - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } /// /// Дополнительный цвет (для опциональных элементов) /// @@ -27,10 +15,7 @@ public class EntityTank /// public bool Pulemet { get; private set; } public bool Gusenica { get; private set; } - /// - /// Шаг перемещения автомобиля - /// - public double Step => Speed * 100 / Weight; + /// /// Инициализация полей объекта-класса спортивного автомобиля /// @@ -41,14 +26,11 @@ public class EntityTank /// Признак наличия обвеса /// Признак наличия антикрыла /// Признак наличия гоночной полосы - public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool pushka, bool pulemet) + public EntityTank(int speed, double weight, Color bodyColor, Color additionalColor, bool pushka, bool pulemet) : base(speed, weight, bodyColor) { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; AdditionalColor = additionalColor; Pushka = pushka; Pulemet = pulemet; - + } } \ No newline at end of file diff --git a/Tank/Tank/FormTank.Designer.cs b/Tank/Tank/FormTank.Designer.cs index ef5db72..dbb0c46 100644 --- a/Tank/Tank/FormTank.Designer.cs +++ b/Tank/Tank/FormTank.Designer.cs @@ -31,32 +31,33 @@ pictureBoxTank = new PictureBox(); buttonCreate = new Button(); buttonLeft = new Button(); - buttonUp = new Button(); buttonRight = new Button(); + buttonUp = new Button(); buttonDown = new Button(); + buttonCreateMachine = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit(); SuspendLayout(); // // pictureBoxTank // - pictureBoxTank.AccessibleRole = AccessibleRole.None; pictureBoxTank.Dock = DockStyle.Fill; pictureBoxTank.Location = new Point(0, 0); pictureBoxTank.Name = "pictureBoxTank"; - pictureBoxTank.Size = new Size(1235, 854); + pictureBoxTank.Size = new Size(1128, 715); pictureBoxTank.SizeMode = PictureBoxSizeMode.AutoSize; - pictureBoxTank.TabIndex = 1; + pictureBoxTank.TabIndex = 0; pictureBoxTank.TabStop = false; - pictureBoxTank.Click += ButtonMove_Click; // // buttonCreate // buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(12, 796); + buttonCreate.Location = new Point(29, 642); buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(150, 46); - buttonCreate.TabIndex = 2; - buttonCreate.Text = "Создать"; + buttonCreate.Size = new Size(166, 46); + buttonCreate.TabIndex = 1; + buttonCreate.Text = "Создать танк"; buttonCreate.UseVisualStyleBackColor = true; buttonCreate.Click += ButtonCreateTank_Click; // @@ -64,58 +65,97 @@ // buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.BackgroundImage = Properties.Resources.left; - buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; - buttonLeft.Location = new Point(1021, 786); + buttonLeft.BackgroundImageLayout = ImageLayout.Zoom; + buttonLeft.Location = new Point(919, 633); buttonLeft.Name = "buttonLeft"; - buttonLeft.Size = new Size(45, 45); - buttonLeft.TabIndex = 3; + buttonLeft.Size = new Size(55, 55); + buttonLeft.TabIndex = 2; + buttonLeft.Text = " "; buttonLeft.UseVisualStyleBackColor = true; buttonLeft.Click += ButtonMove_Click; // - // buttonUp - // - buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - buttonUp.BackgroundImage = Properties.Resources.up; - buttonUp.BackgroundImageLayout = ImageLayout.Stretch; - buttonUp.Location = new Point(1072, 735); - buttonUp.Name = "buttonUp"; - buttonUp.Size = new Size(45, 45); - buttonUp.TabIndex = 4; - buttonUp.UseVisualStyleBackColor = true; - buttonUp.Click += ButtonMove_Click; - // // buttonRight // buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.BackgroundImage = Properties.Resources.right; - buttonRight.BackgroundImageLayout = ImageLayout.Stretch; - buttonRight.Location = new Point(1123, 786); + buttonRight.BackgroundImageLayout = ImageLayout.Zoom; + buttonRight.Location = new Point(1061, 633); buttonRight.Name = "buttonRight"; - buttonRight.Size = new Size(45, 45); - buttonRight.TabIndex = 5; + buttonRight.Size = new Size(55, 55); + buttonRight.TabIndex = 3; + buttonRight.Text = " "; buttonRight.UseVisualStyleBackColor = true; buttonRight.Click += ButtonMove_Click; // + // buttonUp + // + buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonUp.BackgroundImage = Properties.Resources.up; + buttonUp.BackgroundImageLayout = ImageLayout.Zoom; + buttonUp.Location = new Point(991, 562); + buttonUp.Name = "buttonUp"; + buttonUp.Size = new Size(55, 55); + buttonUp.TabIndex = 4; + buttonUp.Text = " "; + buttonUp.UseVisualStyleBackColor = true; + buttonUp.Click += ButtonMove_Click; + // // buttonDown // buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.BackgroundImage = Properties.Resources.down; - buttonDown.BackgroundImageLayout = ImageLayout.Stretch; - buttonDown.Location = new Point(1072, 786); + buttonDown.BackgroundImageLayout = ImageLayout.Zoom; + buttonDown.Location = new Point(991, 633); buttonDown.Name = "buttonDown"; - buttonDown.Size = new Size(45, 45); - buttonDown.TabIndex = 6; + buttonDown.Size = new Size(55, 55); + buttonDown.TabIndex = 5; + buttonDown.Text = " "; buttonDown.UseVisualStyleBackColor = true; buttonDown.Click += ButtonMove_Click; // + // buttonCreateMachine + // + buttonCreateMachine.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateMachine.Location = new Point(210, 642); + buttonCreateMachine.Name = "buttonCreateMachine"; + buttonCreateMachine.Size = new Size(215, 46); + buttonCreateMachine.TabIndex = 6; + buttonCreateMachine.Text = "Создать Машину"; + buttonCreateMachine.UseVisualStyleBackColor = true; + buttonCreateMachine.Click += ButtonCreateMachine_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; + comboBoxStrategy.BackColor = SystemColors.Window; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(874, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(242, 40); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(1031, 68); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(85, 46); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += ButtonStrategyStep_Click; + // // FormTank // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1235, 854); + ClientSize = new Size(1128, 715); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateMachine); Controls.Add(buttonDown); - Controls.Add(buttonRight); Controls.Add(buttonUp); + Controls.Add(buttonRight); Controls.Add(buttonLeft); Controls.Add(buttonCreate); Controls.Add(pictureBoxTank); @@ -127,11 +167,15 @@ } #endregion + private PictureBox pictureBoxTank; private Button buttonCreate; private Button buttonLeft; - private Button buttonUp; private Button buttonRight; + private Button buttonUp; private Button buttonDown; + private Button buttonCreateMachine; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/Tank/Tank/FormTank.cs b/Tank/Tank/FormTank.cs index 46566fd..b1b8505 100644 --- a/Tank/Tank/FormTank.cs +++ b/Tank/Tank/FormTank.cs @@ -7,6 +7,8 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Tank.Drowings; +using Tank.MovementStrategy; namespace Tank; @@ -15,52 +17,79 @@ public partial class FormTank : Form /// /// Поле-объект для прорисовки объекта /// - private DrawningTank? _drawningTank; + private DrawningMachine? _drawningMachine; + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; /// /// Конструктор формы /// public FormTank() { InitializeComponent(); + _strategy = null; } /// /// Метод прорисовки машины /// private void Draw() { - if (_drawningTank == null) + if (_drawningMachine == null) { return; } Bitmap bmp = new(pictureBoxTank.Width, pictureBoxTank.Height); Graphics gr = Graphics.FromImage(bmp); - _drawningTank.DrawTransport(gr); + _drawningMachine.DrawTransport(gr); pictureBoxTank.Image = bmp; } + + /// + ///Создание объекта класса-перемещения + /// + /// Тип создаваемого объётека + + private void CreateObject(string type) + { + Random rnd = new Random(); + switch (type) + { + case nameof(DrawningMachine): + _drawningMachine = new DrawningMachine(rnd.Next(100, 300), rnd.Next(1000, 3000), + Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256))); + break; + case nameof(DrawningTank): + _drawningMachine = new DrawningTank(rnd.Next(650, 700), rnd.Next(15760, 16130), + Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)), + 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))); + break; + default: + return; + } + _drawningMachine.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height); + _drawningMachine.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100)); + _strategy = null; + + Draw(); + } + /// - /// Обработка нажатия кнопки "Создать" + /// Обработка нажатия кнопки "Создать автобус с гармошкой" /// /// /// - private void ButtonCreateTank_Click(object sender, EventArgs e) - { - Random random = new(); - _drawningTank = new DrawningTank(); + private void ButtonCreateTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank)); - _drawningTank.Init(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))); - _drawningTank.SetPictureSize(pictureBoxTank.Width, - pictureBoxTank.Height); - _drawningTank.SetPosition(random.Next(10, 100), random.Next(10, - 100)); - Draw(); - } + /// + /// Обработка нажатия кнопки "Создать автобус" + /// + /// + /// + public void ButtonCreateMachine_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningMachine)); /// /// Перемещение объекта по форме (нажатие кнопок навигации) @@ -69,7 +98,7 @@ public partial class FormTank : Form /// private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawningTank == null) + if (_drawningMachine == null) { return; } @@ -79,19 +108,19 @@ public partial class FormTank : Form { case "buttonUp": result = - _drawningTank.MoveTransport(DirectionType.Up); + _drawningMachine.MoveTransport(DirectionType.Up); break; case "buttonDown": result = - _drawningTank.MoveTransport(DirectionType.Down); + _drawningMachine.MoveTransport(DirectionType.Down); break; case "buttonLeft": result = - _drawningTank.MoveTransport(DirectionType.Left); + _drawningMachine.MoveTransport(DirectionType.Left); break; case "buttonRight": result = - _drawningTank.MoveTransport(DirectionType.Right); + _drawningMachine.MoveTransport(DirectionType.Right); break; } if (result) @@ -99,4 +128,44 @@ public partial class FormTank : Form Draw(); } } -} \ No newline at end of file + + /// + /// Обработка нажатия кнопки "Шаг" + /// + /// + /// + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningMachine == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableMachine(_drawningMachine), + pictureBoxTank.Width, pictureBoxTank.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } +} diff --git a/Tank/Tank/MovementStrategy/AbstractStrategy.cs b/Tank/Tank/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..2f82ebc --- /dev/null +++ b/Tank/Tank/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tank.MovementStrategy; + +public abstract class AbstractStrategy +{ + /// + /// Перемещаемый объект + /// + private IMoveableObject? _moveableObject; + /// + /// Статус перемещения + /// + private StrategyStatus _state = StrategyStatus.NotInit; + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + /// + /// Статус перемещения + /// + public StrategyStatus GetStatus() { return _state; } + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObject moveableObject, int width, int height) + { + if (moveableObject == null) + { + _state = StrategyStatus.NotInit; + return; + } + _state = StrategyStatus.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + if (IsTargetDestinaion()) + { + _state = StrategyStatus.Finish; + return; + } + MoveToTarget(); + } + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveRight() => MoveTo(MovementDirection.Right); + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveUp() => MoveTo(MovementDirection.Up); + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться, false -неудача) + protected bool MoveDown() => MoveTo(MovementDirection.Down); + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => + _moveableObject?.GetObjectPosition; + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != StrategyStatus.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestinaion(); + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } +} diff --git a/Tank/Tank/MovementStrategy/IMoveableObject.cs b/Tank/Tank/MovementStrategy/IMoveableObject.cs new file mode 100644 index 0000000..58cde98 --- /dev/null +++ b/Tank/Tank/MovementStrategy/IMoveableObject.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tank.MovementStrategy; + +public interface IMoveableObject +{ + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Попытка переместить объект в указанном направлении + /// + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/Tank/Tank/MovementStrategy/MoveToBorder.cs b/Tank/Tank/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..60bbee3 --- /dev/null +++ b/Tank/Tank/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tank.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder <= FieldHeight && objParams.DownBorder + GetStep() >= FieldHeight; + } + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + int diffX = objParams.RightBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + int diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} diff --git a/Tank/Tank/MovementStrategy/MoveToCenter.cs b/Tank/Tank/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..94a64cc --- /dev/null +++ b/Tank/Tank/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tank.MovementStrategy; + +public class MoveToCenter : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 + && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && + objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 + && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; + } + protected override void MoveToTarget() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } +} diff --git a/Tank/Tank/MovementStrategy/MoveableTank.cs b/Tank/Tank/MovementStrategy/MoveableTank.cs new file mode 100644 index 0000000..585dc97 --- /dev/null +++ b/Tank/Tank/MovementStrategy/MoveableTank.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Tank.Drowings; + +namespace Tank.MovementStrategy; + +public class MoveableMachine : IMoveableObject +{ + /// + /// Поле-объект класса DrawningMachine или его наследника + /// + private readonly DrawningMachine? _tank = null; + /// + /// Конструктор + /// + /// Объект класса DrawningMachine + public MoveableMachine(DrawningMachine tank) + { + _tank = tank; + } + public ObjectParameters? GetObjectPosition + { + get + { + if (_tank == null || _tank.EntityMachine == null || + !_tank.GetPosX.HasValue || !_tank.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_tank.GetPosX.Value, + _tank.GetPosY.Value, _tank.GetWidth, _tank.GetHeight); + } + } + public int GetStep => (int)(_tank?.EntityMachine?.Step ?? 0); + public bool TryMoveObject(MovementDirection direction) + { + if (_tank == null || _tank.EntityMachine == null) + { + return false; + } + return _tank.MoveTransport(GetDirectionType(direction)); + } + /// + /// Конвертация из MovementDirection в DirectionType + /// + /// MovementDirection + /// DirectionType + private static DirectionType GetDirectionType(MovementDirection direction) + { + return direction switch + { + MovementDirection.Left => DirectionType.Left, + MovementDirection.Right => DirectionType.Right, + MovementDirection.Up => DirectionType.Up, + MovementDirection.Down => DirectionType.Down, + _ => DirectionType.Unknow, + }; + } +} diff --git a/Tank/Tank/MovementStrategy/MovementDirection.cs b/Tank/Tank/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..492eb8f --- /dev/null +++ b/Tank/Tank/MovementStrategy/MovementDirection.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tank.MovementStrategy; + +public enum MovementDirection +{ + Up = 1, Down = 2, Left = 3, Right = 4 +} diff --git a/Tank/Tank/MovementStrategy/ObjectParameters.cs b/Tank/Tank/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..2743406 --- /dev/null +++ b/Tank/Tank/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tank.MovementStrategy; + +public class ObjectParameters +{ + /// + /// Координата X + /// + private readonly int _x; + /// + /// Координата Y + /// + private readonly int _y; + /// + /// Ширина объекта + /// + private readonly int _width; + /// + /// Высота объекта + /// + private readonly int _height; + /// + /// Левая граница + /// + public int LeftBorder => _x; + /// + /// Верхняя граница + /// + public int TopBorder => _y; + /// + /// Правая граница + /// + public int RightBorder => _x + _width; + /// + /// Нижняя граница + /// + public int DownBorder => _y + _height; + /// + /// Середина объекта + /// + public int ObjectMiddleHorizontal => _x + _width / 2; + /// + /// Середина объекта + /// + public int ObjectMiddleVertical => _y + _height / 2; + /// + /// Конструктор + /// + /// Координата X + /// Координата Y + /// Ширина объекта + /// Высота объекта + public ObjectParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/Tank/Tank/MovementStrategy/StrategyStatus.cs b/Tank/Tank/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..339c8a5 --- /dev/null +++ b/Tank/Tank/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tank.MovementStrategy; + +public enum StrategyStatus +{ + /// + ///Всё готово к началу + /// + NotInit, + + /// + ///Выполняется + /// + InProgress, + + /// + ///Завершено + /// + Finish +} diff --git a/labalaba3/labalaba3.sln b/labalaba3/labalaba3.sln new file mode 100644 index 0000000..00b34bf --- /dev/null +++ b/labalaba3/labalaba3.sln @@ -0,0 +1,51 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34221.43 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "labalaba3", "labalaba3\labalaba3.vcxproj", "{BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lll", "lll\lll.vcxproj", "{EB92EF71-83FC-4188-9F00-2585E05A4899}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llll", "llll\llll.vcxproj", "{79F0852A-46F9-4575-999C-013A7DDDCC2D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}.Debug|x64.ActiveCfg = Debug|x64 + {BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}.Debug|x64.Build.0 = Debug|x64 + {BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}.Debug|x86.ActiveCfg = Debug|Win32 + {BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}.Debug|x86.Build.0 = Debug|Win32 + {BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}.Release|x64.ActiveCfg = Release|x64 + {BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}.Release|x64.Build.0 = Release|x64 + {BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}.Release|x86.ActiveCfg = Release|Win32 + {BBEBBE45-49A2-41F6-A798-1FFD74A6A9B1}.Release|x86.Build.0 = Release|Win32 + {EB92EF71-83FC-4188-9F00-2585E05A4899}.Debug|x64.ActiveCfg = Debug|x64 + {EB92EF71-83FC-4188-9F00-2585E05A4899}.Debug|x64.Build.0 = Debug|x64 + {EB92EF71-83FC-4188-9F00-2585E05A4899}.Debug|x86.ActiveCfg = Debug|Win32 + {EB92EF71-83FC-4188-9F00-2585E05A4899}.Debug|x86.Build.0 = Debug|Win32 + {EB92EF71-83FC-4188-9F00-2585E05A4899}.Release|x64.ActiveCfg = Release|x64 + {EB92EF71-83FC-4188-9F00-2585E05A4899}.Release|x64.Build.0 = Release|x64 + {EB92EF71-83FC-4188-9F00-2585E05A4899}.Release|x86.ActiveCfg = Release|Win32 + {EB92EF71-83FC-4188-9F00-2585E05A4899}.Release|x86.Build.0 = Release|Win32 + {79F0852A-46F9-4575-999C-013A7DDDCC2D}.Debug|x64.ActiveCfg = Debug|x64 + {79F0852A-46F9-4575-999C-013A7DDDCC2D}.Debug|x64.Build.0 = Debug|x64 + {79F0852A-46F9-4575-999C-013A7DDDCC2D}.Debug|x86.ActiveCfg = Debug|Win32 + {79F0852A-46F9-4575-999C-013A7DDDCC2D}.Debug|x86.Build.0 = Debug|Win32 + {79F0852A-46F9-4575-999C-013A7DDDCC2D}.Release|x64.ActiveCfg = Release|x64 + {79F0852A-46F9-4575-999C-013A7DDDCC2D}.Release|x64.Build.0 = Release|x64 + {79F0852A-46F9-4575-999C-013A7DDDCC2D}.Release|x86.ActiveCfg = Release|Win32 + {79F0852A-46F9-4575-999C-013A7DDDCC2D}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BDC6D94C-5D3D-4E1A-B136-03128DB2565F} + EndGlobalSection +EndGlobal diff --git a/labalaba3/labalaba3/labalaba3.vcxproj b/labalaba3/labalaba3/labalaba3.vcxproj new file mode 100644 index 0000000..237d2e7 --- /dev/null +++ b/labalaba3/labalaba3/labalaba3.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {bbebbe45-49a2-41f6-a798-1ffd74a6a9b1} + labalaba3 + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/labalaba3/labalaba3/labalaba3.vcxproj.filters b/labalaba3/labalaba3/labalaba3.vcxproj.filters new file mode 100644 index 0000000..ff7636d --- /dev/null +++ b/labalaba3/labalaba3/labalaba3.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Исходные файлы + + + \ No newline at end of file diff --git a/labalaba3/labalaba3/zadanie1.cpp b/labalaba3/labalaba3/zadanie1.cpp new file mode 100644 index 0000000..d4beaba --- /dev/null +++ b/labalaba3/labalaba3/zadanie1.cpp @@ -0,0 +1,82 @@ +#include +#include +#include +#include +#include +#include + +using namespace std; + +typedef pair iPair; + +class Graph { + int V; + list>* adj; + +public: + Graph(int V) { + this->V = V; + adj = new list[V]; + } + + void addEdge(int u, int v, int w) { + adj[u].push_back(make_pair(v, w)); + adj[v].push_back(make_pair(u, w)); + } + + void shortestPath(int src) { + vector dist(V, INT_MAX); + set pq; + + dist[src] = 0; + pq.insert(make_pair(0, src)); + + while (!pq.empty()) { + int u = pq.begin()->second; + pq.erase(pq.begin()); + + for (auto i = adj[u].begin(); i != adj[u].end(); ++i) { + int v = (*i).first; + int weight = (*i).second; + + if (dist[v] > dist[u] + weight) { + if (dist[v] != INT_MAX) { + pq.erase(pq.find(make_pair(dist[v], v))); + } + + dist[v] = dist[u] + weight; + pq.insert(make_pair(dist[v], v)); + } + } + } + + cout << "Vertex Distance from Source\n"; + for (int i = 0; i < V; ++i) { + cout << i << "\t\t" << dist[i] << endl; + } + } +}; + +int main() { + int V = 9; + Graph g(V); + + g.addEdge(0, 1, 4); + g.addEdge(0, 7, 8); + g.addEdge(1, 2, 8); + g.addEdge(1, 7, 11); + g.addEdge(2, 3, 7); + g.addEdge(2, 8, 2); + g.addEdge(2, 5, 4); + g.addEdge(3, 4, 9); + g.addEdge(3, 5, 14); + g.addEdge(4, 5, 10); + g.addEdge(5, 6, 2); + g.addEdge(6, 7, 1); + g.addEdge(6, 8, 6); + g.addEdge(7, 8, 7); + + g.shortestPath(0); + + return 0; +} \ No newline at end of file diff --git a/labalaba3/lll/lll.vcxproj b/labalaba3/lll/lll.vcxproj new file mode 100644 index 0000000..d2e5f7c --- /dev/null +++ b/labalaba3/lll/lll.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {eb92ef71-83fc-4188-9f00-2585e05a4899} + lll + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/labalaba3/lll/lll.vcxproj.filters b/labalaba3/lll/lll.vcxproj.filters new file mode 100644 index 0000000..e53a161 --- /dev/null +++ b/labalaba3/lll/lll.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Исходные файлы + + + \ No newline at end of file diff --git a/labalaba3/lll/zadanie2.cpp b/labalaba3/lll/zadanie2.cpp new file mode 100644 index 0000000..343f3d7 --- /dev/null +++ b/labalaba3/lll/zadanie2.cpp @@ -0,0 +1,59 @@ +#include +#include +#include + +using namespace std; + +class Graph { + int V; + list* adj; + +public: + Graph(int V) { + this->V = V; + adj = new list[V]; + } + + void addEdge(int v, int w) { + adj[v].push_back(w); + } + + void BFS(int s) { + bool* visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + queue queue; + + visited[s] = true; + queue.push(s); + + while (!queue.empty()) { + s = queue.front(); + cout << s << " "; + queue.pop(); + + for (auto i = adj[s].begin(); i != adj[s].end(); ++i) { + if (!visited[*i]) { + visited[*i] = true; + queue.push(*i); + } + } + } + } +}; + +int main() { + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Breadth First Traversal (starting from vertex 2): "; + g.BFS(2); + + return 0; +} \ No newline at end of file diff --git a/labalaba3/llll/llll.vcxproj b/labalaba3/llll/llll.vcxproj new file mode 100644 index 0000000..a3666cb --- /dev/null +++ b/labalaba3/llll/llll.vcxproj @@ -0,0 +1,135 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {79f0852a-46f9-4575-999c-013a7dddcc2d} + llll + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/labalaba3/llll/llll.vcxproj.filters b/labalaba3/llll/llll.vcxproj.filters new file mode 100644 index 0000000..caab71f --- /dev/null +++ b/labalaba3/llll/llll.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Исходные файлы + + + \ No newline at end of file diff --git a/labalaba3/llll/zadanie3.cpp b/labalaba3/llll/zadanie3.cpp new file mode 100644 index 0000000..98a1ad7 --- /dev/null +++ b/labalaba3/llll/zadanie3.cpp @@ -0,0 +1,59 @@ +#include +#include +#include + +using namespace std; + +#define V 5 + +int minKey(int key[], bool mstSet[]) { + int min = INT_MAX, min_index; + + for (int v = 0; v < V; v++) + if (mstSet[v] == false && key[v] < min) + min = key[v], min_index = v; + + return min_index; +} + +void printMST(int parent[], int graph[V][V]) { + cout << "Edge \tWeight\n"; + for (int i = 1; i < V; i++) + cout << parent[i] << " - " << i << " \t" << graph[i][parent[i]] << " \n"; +} + +void primMST(int graph[V][V]) { + int parent[V]; + int key[V]; + bool mstSet[V]; + + for (int i = 0; i < V; i++) + key[i] = INT_MAX, mstSet[i] = false; + + key[0] = 0; + parent[0] = -1; + + for (int count = 0; count < V - 1; count++) { + int u = minKey(key, mstSet); + + mstSet[u] = true; + + for (int v = 0; v < V; v++) + if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) + parent[v] = u, key[v] = graph[u][v]; + } + + printMST(parent, graph); +} + +int main() { + int graph[V][V] = { { 0, 2, 0, 6, 0 }, + { 2, 0, 3, 8, 5 }, + { 0, 3, 0, 0, 7 }, + { 6, 8, 0, 0, 9 }, + { 0, 5, 7, 9, 0 } }; + + primMST(graph); + + return 0; +} \ No newline at end of file