From 344124546e1fdd21cbc119b830ef8c6249e2e5de Mon Sep 17 00:00:00 2001 From: Marselchi Date: Mon, 25 Sep 2023 09:57:18 +0400 Subject: [PATCH 1/6] =?UTF-8?q?=D0=92=D0=BE=D1=81=D1=81=D1=82=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF=D0=BE=D1=82?= =?UTF-8?q?=D0=B5=D1=80=D1=8F=D1=88=D0=B5=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Liner/Liner.csproj | 26 ++++++++++++++++++++++++++ Liner/Liner.sln | 25 +++++++++++++++++++++++++ Liner/Program.cs | 17 +++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 Liner/Liner.csproj create mode 100644 Liner/Liner.sln create mode 100644 Liner/Program.cs diff --git a/Liner/Liner.csproj b/Liner/Liner.csproj new file mode 100644 index 0000000..13ee123 --- /dev/null +++ b/Liner/Liner.csproj @@ -0,0 +1,26 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + \ No newline at end of file diff --git a/Liner/Liner.sln b/Liner/Liner.sln new file mode 100644 index 0000000..44bab19 --- /dev/null +++ b/Liner/Liner.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.6.33815.320 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Liner", "Liner.csproj", "{3EF53D4D-3ED6-42CC-A624-222DCB3C5114}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3EF53D4D-3ED6-42CC-A624-222DCB3C5114}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3EF53D4D-3ED6-42CC-A624-222DCB3C5114}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3EF53D4D-3ED6-42CC-A624-222DCB3C5114}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3EF53D4D-3ED6-42CC-A624-222DCB3C5114}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B3D86E6B-CC33-4EF3-A79E-2BF6171C6AF9} + EndGlobalSection +EndGlobal diff --git a/Liner/Program.cs b/Liner/Program.cs new file mode 100644 index 0000000..8976e9d --- /dev/null +++ b/Liner/Program.cs @@ -0,0 +1,17 @@ +namespace Liner +{ + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + Application.Run(new MainScreen()); + } + } +} \ No newline at end of file -- 2.25.1 From fffb93e61b24db6f12b5cf8d972bd9d06432b635 Mon Sep 17 00:00:00 2001 From: Marselchi Date: Mon, 25 Sep 2023 14:04:52 +0400 Subject: [PATCH 2/6] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=B0=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Liner/Drawing/DrawingBigLiner.cs | 81 ++++++++ Liner/{ => Drawing}/DrawingLiner.cs | 206 +++++++++++-------- Liner/Entities/EntityBigLiner.cs | 34 +++ Liner/{ => Entities}/EntityLiner.cs | 29 +-- Liner/Liner.csproj | 6 + Liner/MainScreen.Designer.cs | 64 ++++-- Liner/MainScreen.cs | 76 ++++++- Liner/MovingStrategies/AbstractStrategy.cs | 132 ++++++++++++ Liner/MovingStrategies/DrawingObjectLiner.cs | 40 ++++ Liner/MovingStrategies/IMoveableObject.cs | 34 +++ Liner/MovingStrategies/MoveToBorder.cs | 59 ++++++ Liner/MovingStrategies/MoveToCenter.cs | 59 ++++++ Liner/MovingStrategies/ObjectParameters.cs | 57 +++++ Liner/MovingStrategies/Status.cs | 18 ++ 14 files changed, 766 insertions(+), 129 deletions(-) create mode 100644 Liner/Drawing/DrawingBigLiner.cs rename Liner/{ => Drawing}/DrawingLiner.cs (50%) create mode 100644 Liner/Entities/EntityBigLiner.cs rename Liner/{ => Entities}/EntityLiner.cs (51%) create mode 100644 Liner/MovingStrategies/AbstractStrategy.cs create mode 100644 Liner/MovingStrategies/DrawingObjectLiner.cs create mode 100644 Liner/MovingStrategies/IMoveableObject.cs create mode 100644 Liner/MovingStrategies/MoveToBorder.cs create mode 100644 Liner/MovingStrategies/MoveToCenter.cs create mode 100644 Liner/MovingStrategies/ObjectParameters.cs create mode 100644 Liner/MovingStrategies/Status.cs diff --git a/Liner/Drawing/DrawingBigLiner.cs b/Liner/Drawing/DrawingBigLiner.cs new file mode 100644 index 0000000..2eb6608 --- /dev/null +++ b/Liner/Drawing/DrawingBigLiner.cs @@ -0,0 +1,81 @@ +using Liner.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Liner.Drawing +{ + public class DrawingBigLiner : DrawingLiner + { + /// + /// Конструктор + /// + /// Скорость + /// Вес лайнера + /// Основной цвет + /// Признак наличия бассейна + /// Признак наличия доп палубы + /// Ширина картинки + /// Высота картинки + public DrawingBigLiner(int speed, double weight, Color bodyColor, Color bottomColor, bool swimmingPool, bool deck, int width, int height) + : base(speed,weight,bodyColor,bottomColor,width,height,100,80) + { + if(EntityLiner!= null) + { + EntityLiner = new EntityBigLiner(speed, weight, bodyColor, bottomColor, deck, swimmingPool); + } + + } + /// + /// Прорисовка объекта + /// + /// + // высота палубы - 20 пикселей + public override void DrawTransport(Graphics g) + { + if (EntityLiner is not EntityBigLiner liner) + { + return; + } + Pen pen = new(Color.Black); + Brush poolBrush = new SolidBrush(Color.Blue); + Brush bottomBrush = new SolidBrush(EntityLiner.BottomColor); + Brush deckBrush = new SolidBrush(EntityLiner.BodyColor); + // палуба + Point[] firstDeck = {new Point(_startPosX + 30, _startPosY), new Point(_startPosX + 30 + 60, _startPosY), + new Point(_startPosX + 30 + 60, _startPosY + 20), new Point(_startPosX + 30, _startPosY + 20)}; + int addY = 20; + // нижний корпус + Point[] bottom = {new Point(_startPosX, _startPosY), new Point(_startPosX + 100, _startPosY), + new Point(_startPosX+80, _startPosY + 40), new Point(_startPosX + 20, _startPosY + 40)}; + // бассейн + Point[] pool = {new Point(_startPosX + 10, _startPosY), new Point(_startPosX + 30, _startPosY), + new Point(_startPosX+30, _startPosY + 10), new Point(_startPosX + 10, _startPosY + 10)}; + g.FillPolygon(deckBrush, firstDeck); + g.DrawPolygon(pen, firstDeck);//рисуем палубу + Point[] currentDeck = new Point[4]; //буффер для прорисовки доп палуб + firstDeck.CopyTo(currentDeck, 0); + if (liner.Deck) //рисуем вторую палубу + { + for (int i = 0; i < 4; i++) + { + currentDeck[i].Y += addY; + } + g.FillPolygon(deckBrush, currentDeck); + g.DrawPolygon(pen, currentDeck); + addY += 20; + } + for (int i = 0; i < 4; i++) //сдвигаем элементы вниз на кол-во палуб + { + bottom[i].Y += addY; + pool[i].Y += addY; + } + g.FillPolygon(bottomBrush, bottom); + g.DrawPolygon(pen, bottom);//рисуем нижний корпус + if (liner.SwimmingPool) { g.FillPolygon(poolBrush, pool); }//рисуем бассейн + g.Dispose(); + } + } +} diff --git a/Liner/DrawingLiner.cs b/Liner/Drawing/DrawingLiner.cs similarity index 50% rename from Liner/DrawingLiner.cs rename to Liner/Drawing/DrawingLiner.cs index 4579e25..fa08cac 100644 --- a/Liner/DrawingLiner.cs +++ b/Liner/Drawing/DrawingLiner.cs @@ -3,16 +3,16 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Liner.Entities; -namespace Liner +namespace Liner.Drawing { public class DrawingLiner { - private Brush poolBrush = new SolidBrush(Color.Blue); /// /// Класс-сущность /// - public EntityLiner? EntityLiner { get; private set; } + public EntityLiner? EntityLiner { get; protected set; } /// /// Ширина окна /// @@ -24,42 +24,88 @@ namespace Liner /// /// Левая координата прорисовки лайнера /// - private int _startPosX; + protected int _startPosX; /// /// Верхняя координата прорисовки лайнера /// - private int _startPosY; + protected int _startPosY; /// /// Ширина прорисовки лайнера /// - private readonly int _linerWidth = 100; + protected readonly int _linerWidth = 100; /// /// Высота прорисовки лайнера /// - private readonly int _linerHeight = 80; + protected readonly int _linerHeight = 60; /// - /// Инициализация свойств + /// Координата X объекта + /// + public int GetPosX => _startPosX; + /// + /// Координата Y объекта + /// + public int GetPosY => _startPosY; + /// + /// Ширина объекта + /// + public int GetWidth => _linerWidth; + /// + /// Высота объекта + /// + public int GetHeight => _linerHeight; + /// + /// Конструктор /// /// Скорость /// Вес лайнера /// Основной цвет - /// Признак наличия бассейна - /// Признак наличия доп палубы /// Ширина картинки /// Высота картинки - /// true - объект создан, false - проверка не пройдена, - /// нельзя создать объект в этих размерах - public bool Init(int speed, double weight, Color bodyColor,Color bottomColor, bool swimmingPool, bool deck, int width, int height) + public DrawingLiner(int speed, double weight, Color bodyColor, Color bottomColor, int width, int height) { - if(width < _linerWidth || height < _linerHeight) + //TODO: придумать проверку + /* + if (width < _linerWidth || height < _linerHeight) { - return false; + } + else + { + + } + */ _pictureWidth = width; _pictureHeight = height; - EntityLiner = new EntityLiner(); - EntityLiner.Init(speed, weight, bodyColor,bottomColor, swimmingPool,deck); - return true; + EntityLiner = new EntityLiner(speed, weight, bodyColor, bottomColor); + } + /// + /// Конструктор + /// + /// Скорость + /// Вес лайнера + /// Основной цвет + /// Ширина картинки + /// Высота картинки + /// Ширина прорисовки лайнера + /// Высота прорисовки лайнера + protected DrawingLiner(int speed, double weight, Color bodyColor, Color bottomColor, int width, int height,int linerWidth,int linerHeight) + { + //TODO: придумать проверку + /* + if (width < _linerWidth || height < _linerHeight) + { + + } + else + { + + } + */ + _linerHeight = linerHeight; + _linerWidth = linerWidth; + _pictureWidth = width; + _pictureHeight = height; + EntityLiner = new EntityLiner(speed, weight, bodyColor, bottomColor); } /// /// Установка позиции @@ -68,7 +114,7 @@ namespace Liner /// Координата Y public void SetPosition(int x, int y) { - if(x > _pictureWidth || y > _pictureHeight || x < 0 || y < 0) + if (x > _pictureWidth || y > _pictureHeight || x < 0 || y < 0) { _startPosX = 0; _startPosY = 0; @@ -76,54 +122,8 @@ namespace Liner _startPosX = x; _startPosY = y; } - /// - /// Изменение направления перемещения - /// - /// Направление - public void MoveTransport(DirectionType direction) - { - if (EntityLiner == null) - { - return; - } - switch (direction) - { - //влево - case DirectionType.Left: - if (_startPosX - EntityLiner.Step > 0) - { - _startPosX -= (int)EntityLiner.Step; - } - break; - //вверх - case DirectionType.Up: - if (_startPosY - EntityLiner.Step > 0) - { - _startPosY -= (int)EntityLiner.Step; - } - break; - // вправо - case DirectionType.Right: - if (_startPosX + EntityLiner.Step < _pictureWidth - _linerWidth) - { - _startPosX += (int)EntityLiner.Step; - } - break; - //вниз - case DirectionType.Down: - if (_startPosY + EntityLiner.Step < _pictureHeight - _linerHeight) - { - _startPosY += (int)EntityLiner.Step; - } - break; - } - } - /// - /// Прорисовка объекта - /// - /// // высота палубы - 20 пикселей - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) { if (EntityLiner == null) { @@ -135,36 +135,72 @@ namespace Liner // палуба Point[] firstDeck = {new Point(_startPosX + 30, _startPosY), new Point(_startPosX + 30 + 60, _startPosY), new Point(_startPosX + 30 + 60, _startPosY + 20), new Point(_startPosX + 30, _startPosY + 20)}; - int addY = 20; // нижний корпус Point[] bottom = {new Point(_startPosX, _startPosY), new Point(_startPosX + 100, _startPosY), new Point(_startPosX+80, _startPosY + 40), new Point(_startPosX + 20, _startPosY + 40)}; // бассейн - Point[] pool = {new Point(_startPosX + 10, _startPosY), new Point(_startPosX + 30, _startPosY), - new Point(_startPosX+30, _startPosY + 10), new Point(_startPosX + 10, _startPosY + 10)}; g.FillPolygon(deckBrush, firstDeck); g.DrawPolygon(pen, firstDeck);//рисуем палубу - Point[] currentDeck = new Point[4]; //буффер для прорисовки доп палуб - firstDeck.CopyTo(currentDeck, 0); - if(EntityLiner.Deck) //рисуем вторую палубу + for (int i = 0; i < 4; i++) //сдвигаем элементы вниз на кол-во палуб { - for(int i = 0; i < 4; i++) - { - currentDeck[i].Y += addY; - } - g.FillPolygon(deckBrush, currentDeck); - g.DrawPolygon(pen, currentDeck); - addY += 20; - } - for(int i = 0; i < 4; i++) //сдвигаем элементы вниз на кол-во палуб - { - bottom[i].Y += addY; - pool[i].Y += addY; + bottom[i].Y += 20; } g.FillPolygon(bottomBrush, bottom); g.DrawPolygon(pen, bottom);//рисуем нижний корпус - if (EntityLiner.SwimmingPool) { g.FillPolygon(poolBrush, pool); }//рисуем бассейн g.Dispose(); } + /// + /// Проверка, что объект может переместится по указанному направлению + /// + /// Направление + /// true - можно переместится по указанному направлению + public bool CanMove(DirectionType direction) + { + if (EntityLiner == null) + { + return false; + } + return direction switch + { + //влево + DirectionType.Left => _startPosX - EntityLiner.Step > 0, + //вверх + DirectionType.Up => _startPosY - EntityLiner.Step > 0, + //вправо + DirectionType.Right => _startPosX + EntityLiner.Step + _linerWidth < _pictureWidth, + //вниз + DirectionType.Down => _startPosY + EntityLiner.Step + _linerHeight < _pictureHeight + }; + } + /// + /// Изменение направления перемещения + /// + /// Направление + public void MoveTransport(DirectionType direction) + { + if (!CanMove(direction) || EntityLiner == null) + { + return; + } + switch (direction) + { + //влево + case DirectionType.Left: + _startPosX -= (int)EntityLiner.Step; + break; + //вверх + case DirectionType.Up: + _startPosY -= (int)EntityLiner.Step; + break; + // вправо + case DirectionType.Right: + _startPosX += (int)EntityLiner.Step; + break; + //вниз + case DirectionType.Down: + _startPosY += (int)EntityLiner.Step; + break; + } + } } } diff --git a/Liner/Entities/EntityBigLiner.cs b/Liner/Entities/EntityBigLiner.cs new file mode 100644 index 0000000..387e10e --- /dev/null +++ b/Liner/Entities/EntityBigLiner.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Liner.Entities +{ + public class EntityBigLiner : EntityLiner + { + /// + /// Признак (опция) наличия бассейна + /// + public bool SwimmingPool { get; private set; } + /// + /// Признак (опция) наличия доп палубы + /// + public bool Deck { get; private set; } + /// + /// Конструктор с параметрами + /// + /// Скорость + /// Вес автомобиля + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия доп палубы + /// Признак наличия бассейна + public EntityBigLiner(int speed, double weight, Color bodyColor, Color bottomColor,bool deck, bool swimmingPool) : base(speed, weight, bodyColor,bottomColor) + { + Deck = deck; + SwimmingPool = swimmingPool; + } + } +} diff --git a/Liner/EntityLiner.cs b/Liner/Entities/EntityLiner.cs similarity index 51% rename from Liner/EntityLiner.cs rename to Liner/Entities/EntityLiner.cs index 36da029..7bb84ee 100644 --- a/Liner/EntityLiner.cs +++ b/Liner/Entities/EntityLiner.cs @@ -5,7 +5,7 @@ using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; -namespace Liner +namespace Liner.Entities { public class EntityLiner { @@ -22,43 +22,26 @@ namespace Liner /// public Color BodyColor { get; private set; } /// - /// Основной цвет + /// Доп цвет /// - public Color BottomColor { get; private set; } /// - /// Цвет палубы - /// - public bool SwimmingPool { get; private set; } - /// - /// Признак (опция) наличия бассейна - /// - public bool Deck { get; private set; } - /// - /// Признак (опция) наличия доп палубы - /// - public bool SportLine { get; private set; } - /// - /// Шаг перемещения лайнера + /// Шаг /// public double Step => (double)Speed * 100 / Weight; /// - /// Инициализация полей объекта-класса лайнера + /// Конструктор с параметрами /// /// Скорость /// Вес лайнера /// Основной цвет - /// Цвет палубы - /// Признак наличия бассейна - /// Признак наличия доп палубы - public void Init(int speed, double weight, Color bodyColor, Color bottomColor, bool swimmingPool, bool deck) + /// Доп цвет + public EntityLiner(int speed, double weight, Color bodyColor, Color bottomColor) { Speed = speed; Weight = weight; BodyColor = bodyColor; BottomColor = bottomColor; - SwimmingPool = swimmingPool; - Deck = deck; } } } diff --git a/Liner/Liner.csproj b/Liner/Liner.csproj index 13ee123..803e517 100644 --- a/Liner/Liner.csproj +++ b/Liner/Liner.csproj @@ -8,6 +8,12 @@ enable + + + + + + True diff --git a/Liner/MainScreen.Designer.cs b/Liner/MainScreen.Designer.cs index c909ae9..29844b1 100644 --- a/Liner/MainScreen.Designer.cs +++ b/Liner/MainScreen.Designer.cs @@ -29,11 +29,14 @@ private void InitializeComponent() { pictureBoxLiner = new PictureBox(); - buttonCreate = new Button(); + buttonCreateLiner = new Button(); buttonUp = new Button(); buttonDown = new Button(); buttonLeft = new Button(); buttonRight = new Button(); + buttonCreateBigLiner = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxLiner).BeginInit(); SuspendLayout(); // @@ -47,16 +50,16 @@ pictureBoxLiner.TabIndex = 0; pictureBoxLiner.TabStop = false; // - // buttonCreate + // buttonCreateLiner // - buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; - buttonCreate.Location = new Point(34, 584); - buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(87, 43); - buttonCreate.TabIndex = 1; - buttonCreate.Text = "Create Liner"; - buttonCreate.UseVisualStyleBackColor = true; - buttonCreate.Click += buttonCreate_Click; + buttonCreateLiner.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateLiner.Location = new Point(34, 584); + buttonCreateLiner.Name = "buttonCreateLiner"; + buttonCreateLiner.Size = new Size(87, 43); + buttonCreateLiner.TabIndex = 1; + buttonCreateLiner.Text = "Create Liner"; + buttonCreateLiner.UseVisualStyleBackColor = true; + buttonCreateLiner.Click += buttonCreateLiner_Click; // // buttonUp // @@ -106,16 +109,50 @@ buttonRight.UseVisualStyleBackColor = true; buttonRight.Click += buttonMove_Click; // + // buttonCreateBigLiner + // + buttonCreateBigLiner.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateBigLiner.Location = new Point(127, 584); + buttonCreateBigLiner.Name = "buttonCreateBigLiner"; + buttonCreateBigLiner.Size = new Size(87, 43); + buttonCreateBigLiner.TabIndex = 6; + buttonCreateBigLiner.Text = "Create BIG Liner"; + buttonCreateBigLiner.UseVisualStyleBackColor = true; + buttonCreateBigLiner.Click += buttonCreateBigLiner_Click; + // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" }); + comboBoxStrategy.Location = new Point(829, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(121, 23); + comboBoxStrategy.TabIndex = 7; + // + // buttonStep + // + buttonStep.Location = new Point(856, 41); + buttonStep.Name = "buttonStep"; + buttonStep.Size = new Size(75, 23); + buttonStep.TabIndex = 8; + buttonStep.Text = "Step"; + buttonStep.UseVisualStyleBackColor = true; + buttonStep.Click += buttonStep_Click; + // // MainScreen // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(984, 661); + Controls.Add(buttonStep); + Controls.Add(comboBoxStrategy); + Controls.Add(buttonCreateBigLiner); Controls.Add(buttonRight); Controls.Add(buttonLeft); Controls.Add(buttonDown); Controls.Add(buttonUp); - Controls.Add(buttonCreate); + Controls.Add(buttonCreateLiner); Controls.Add(pictureBoxLiner); Name = "MainScreen"; Text = "Liner"; @@ -127,10 +164,13 @@ #endregion private PictureBox pictureBoxLiner; - private Button buttonCreate; + private Button buttonCreateLiner; private Button buttonUp; private Button buttonDown; private Button buttonLeft; private Button buttonRight; + private Button buttonCreateBigLiner; + private ComboBox comboBoxStrategy; + private Button buttonStep; } } \ No newline at end of file diff --git a/Liner/MainScreen.cs b/Liner/MainScreen.cs index 5aca5b3..46f67e3 100644 --- a/Liner/MainScreen.cs +++ b/Liner/MainScreen.cs @@ -1,3 +1,7 @@ +using Liner.Drawing; +using Liner.Entities; +using Liner.MovingStrategies; + namespace Liner { public partial class MainScreen : Form @@ -8,6 +12,10 @@ namespace Liner private DrawingLiner? _drawingLiner; private Bitmap bmp; /// + /// + /// + private AbstractStrategy? _abstractStrategy; + /// /// /// public MainScreen() @@ -30,18 +38,17 @@ namespace Liner pictureBoxLiner.Image = bmp; gr.Dispose(); } - private void buttonCreate_Click(object sender, EventArgs e) + private void buttonCreateLiner_Click(object sender, EventArgs e) { Random random = new(); - _drawingLiner = new DrawingLiner(); - _drawingLiner.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)), + _drawingLiner = new DrawingLiner(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)), pictureBoxLiner.Width, pictureBoxLiner.Height); - _drawingLiner.SetPosition(random.Next(10, 100), - random.Next(10, 100)); + _drawingLiner.SetPosition(random.Next(10, 100), random.Next(10, 100)); Draw(); } @@ -68,7 +75,58 @@ namespace Liner break; } Draw(); + } + private void buttonCreateBigLiner_Click(object sender, EventArgs e) + { + Random random = new(); + _drawingLiner = new DrawingBigLiner(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(1, 2)), + pictureBoxLiner.Width, pictureBoxLiner.Height); + _drawingLiner.SetPosition(random.Next(10, 100), random.Next(10, 100)); + Draw(); + } + + private void buttonStep_Click(object sender, EventArgs e) + { + if (_drawingLiner == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _abstractStrategy = comboBoxStrategy.SelectedIndex + switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_abstractStrategy == null) + { + return; + } + _abstractStrategy.SetData(new DrawingObjectLiner(_drawingLiner), pictureBoxLiner.Width, + pictureBoxLiner.Height); + comboBoxStrategy.Enabled = false; + } + if (_abstractStrategy == null) + { + return; + } + _abstractStrategy.MakeStep(); + Draw(); + if (_abstractStrategy.GetStatus() == Status.Finish) + { + comboBoxStrategy.Enabled = true; + _abstractStrategy = null; + } } } } \ No newline at end of file diff --git a/Liner/MovingStrategies/AbstractStrategy.cs b/Liner/MovingStrategies/AbstractStrategy.cs new file mode 100644 index 0000000..12c00e0 --- /dev/null +++ b/Liner/MovingStrategies/AbstractStrategy.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Liner.MovingStrategies +{ + /// + /// Класс-стратегия перемещения объекта + /// + public abstract class AbstractStrategy + { + /// + /// Перемещаемый объект + /// + private IMoveableObject? _moveableObject; + /// + /// Статус перемещения + /// + private Status _state = Status.NotInit; + /// + /// Ширина поля + /// + protected int FieldWidth { get; private set; } + /// + /// Высота поля + /// + protected int FieldHeight { get; private set; } + /// + /// Статус перемещения + /// + public Status GetStatus() { return _state; } + /// + /// Установка данных + /// + /// Перемещаемый объект + /// Ширина поля + /// Высота поля + public void SetData(IMoveableObject moveableObject, int width, int height) + { + if (moveableObject == null) + { + _state = Status.NotInit; + return; + } + _state = Status.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + /// + /// Шаг перемещения + /// + public void MakeStep() + { + if (_state != Status.InProgress) + { + return; + } + if (IsTargetDestinaion()) + { + _state = Status.Finish; + return; + } + MoveToTarget(); + } + /// + /// Перемещение влево + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveLeft() => MoveTo(DirectionType.Left); + /// + /// Перемещение вправо + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveRight() => MoveTo(DirectionType.Right); + /// + /// Перемещение вверх + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveUp() => MoveTo(DirectionType.Up); + /// + /// Перемещение вниз + /// + /// Результат перемещения (true - удалось переместиться, false - неудача) + protected bool MoveDown() => MoveTo(DirectionType.Down); + /// + /// Параметры объекта + /// + protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; + /// + /// Шаг объекта + /// + /// + protected int? GetStep() + { + if (_state != Status.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + /// + /// Перемещение к цели + /// + protected abstract void MoveToTarget(); + /// + /// Достигнута ли цель + /// + /// + protected abstract bool IsTargetDestinaion(); + /// + /// Попытка перемещения в требуемом направлении + /// + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(DirectionType directionType) + { + if (_state != Status.InProgress) + { + return false; + } + if (_moveableObject?.CheckCanMove(directionType) ?? false) + { + _moveableObject.MoveObject(directionType); + return true; + } + return false; + } + } +} diff --git a/Liner/MovingStrategies/DrawingObjectLiner.cs b/Liner/MovingStrategies/DrawingObjectLiner.cs new file mode 100644 index 0000000..9a94b25 --- /dev/null +++ b/Liner/MovingStrategies/DrawingObjectLiner.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Liner.Drawing; + +namespace Liner.MovingStrategies +{ + /// + /// Реализация интерфейса IMovableObject для работы с объектом DrawingLiner (паттерн Adapter) + /// + public class DrawingObjectLiner : IMoveableObject + { + private readonly DrawingLiner? _drawingLiner = null; + public DrawingObjectLiner(DrawingLiner DrawingLiner) + { + _drawingLiner = DrawingLiner; + } + public ObjectParameters? GetObjectPosition + { + get + { + if (_drawingLiner == null || _drawingLiner.EntityLiner == + null) + { + return null; + } + return new ObjectParameters(_drawingLiner.GetPosX, + _drawingLiner.GetPosY, _drawingLiner.GetWidth, _drawingLiner.GetHeight); + } + } + public int GetStep => (int)(_drawingLiner?.EntityLiner?.Step ?? 0); + public bool CheckCanMove(DirectionType direction) => + _drawingLiner?.CanMove(direction) ?? false; + public void MoveObject(DirectionType direction) => + _drawingLiner?.MoveTransport(direction); + } + +} diff --git a/Liner/MovingStrategies/IMoveableObject.cs b/Liner/MovingStrategies/IMoveableObject.cs new file mode 100644 index 0000000..2b24f7a --- /dev/null +++ b/Liner/MovingStrategies/IMoveableObject.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Liner.MovingStrategies +{ + /// + /// Интерфейс для работы с перемещаемым объектом + /// + public interface IMoveableObject + { + /// + /// Получение координаты X объекта + /// + ObjectParameters? GetObjectPosition { get; } + /// + /// Шаг объекта + /// + int GetStep { get; } + /// + /// Проверка, можно ли переместиться по нужному направлению + /// + /// + /// + bool CheckCanMove(DirectionType direction); + /// + /// Изменение направления пермещения объекта + /// + /// Направление + void MoveObject(DirectionType direction); + } +} diff --git a/Liner/MovingStrategies/MoveToBorder.cs b/Liner/MovingStrategies/MoveToBorder.cs new file mode 100644 index 0000000..67803d5 --- /dev/null +++ b/Liner/MovingStrategies/MoveToBorder.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Liner.MovingStrategies +{ + /// + /// Стратегия перемещения объекта в центр экрана + /// + public class MoveToBorder : AbstractStrategy + { + protected override bool IsTargetDestinaion() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.RightBorder <= FieldWidth && + objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder <= FieldHeight && + objParams.DownBorder + GetStep() >= FieldHeight; + } + protected override void MoveToTarget() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + var diffX = objParams.RightBorder - FieldWidth; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + var diffY = objParams.DownBorder - FieldHeight; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } + } +} diff --git a/Liner/MovingStrategies/MoveToCenter.cs b/Liner/MovingStrategies/MoveToCenter.cs new file mode 100644 index 0000000..278f197 --- /dev/null +++ b/Liner/MovingStrategies/MoveToCenter.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Liner.MovingStrategies +{ + /// + /// Стратегия перемещения объекта в центр экрана + /// + public class MoveToCenter : AbstractStrategy + { + protected override bool IsTargetDestinaion() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 && + objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 && + objParams.ObjectMiddleVertical <= FieldHeight / 2 && + objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2; + } + protected override void MoveToTarget() + { + var objParams = GetObjectParameters; + if (objParams == null) + { + return; + } + var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2; + if (Math.Abs(diffX) > GetStep()) + { + if (diffX > 0) + { + MoveLeft(); + } + else + { + MoveRight(); + } + } + var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2; + if (Math.Abs(diffY) > GetStep()) + { + if (diffY > 0) + { + MoveUp(); + } + else + { + MoveDown(); + } + } + } + } +} diff --git a/Liner/MovingStrategies/ObjectParameters.cs b/Liner/MovingStrategies/ObjectParameters.cs new file mode 100644 index 0000000..ff30ae6 --- /dev/null +++ b/Liner/MovingStrategies/ObjectParameters.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Liner.MovingStrategies +{ + /// + /// Параметры-координаты объекта + /// + public class ObjectParameters + { + private readonly int _x; + 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/Liner/MovingStrategies/Status.cs b/Liner/MovingStrategies/Status.cs new file mode 100644 index 0000000..cde340d --- /dev/null +++ b/Liner/MovingStrategies/Status.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Liner.MovingStrategies +{ + /// + /// Статус выполнения операции перемещения + /// + public enum Status + { + NotInit, + InProgress, + Finish + } +} -- 2.25.1 From 7bdefd69c145f6446bb3d9e4ebfac63b461e5474 Mon Sep 17 00:00:00 2001 From: Marselchi Date: Mon, 25 Sep 2023 14:09:01 +0400 Subject: [PATCH 3/6] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BE=D1=87=D0=BA?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Liner/Drawing/DrawingLiner.cs | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/Liner/Drawing/DrawingLiner.cs b/Liner/Drawing/DrawingLiner.cs index fa08cac..04a9047 100644 --- a/Liner/Drawing/DrawingLiner.cs +++ b/Liner/Drawing/DrawingLiner.cs @@ -63,17 +63,6 @@ namespace Liner.Drawing /// Высота картинки public DrawingLiner(int speed, double weight, Color bodyColor, Color bottomColor, int width, int height) { - //TODO: придумать проверку - /* - if (width < _linerWidth || height < _linerHeight) - { - - } - else - { - - } - */ _pictureWidth = width; _pictureHeight = height; EntityLiner = new EntityLiner(speed, weight, bodyColor, bottomColor); @@ -90,17 +79,6 @@ namespace Liner.Drawing /// Высота прорисовки лайнера protected DrawingLiner(int speed, double weight, Color bodyColor, Color bottomColor, int width, int height,int linerWidth,int linerHeight) { - //TODO: придумать проверку - /* - if (width < _linerWidth || height < _linerHeight) - { - - } - else - { - - } - */ _linerHeight = linerHeight; _linerWidth = linerWidth; _pictureWidth = width; -- 2.25.1 From e1257a26e45c70cdc910e7542c7c28e4ebfc186e Mon Sep 17 00:00:00 2001 From: Marselchi Date: Mon, 25 Sep 2023 14:25:04 +0400 Subject: [PATCH 4/6] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BE=D1=87=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Liner/MovingStrategies/DrawingObjectLiner.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Liner/MovingStrategies/DrawingObjectLiner.cs b/Liner/MovingStrategies/DrawingObjectLiner.cs index 9a94b25..0afe82d 100644 --- a/Liner/MovingStrategies/DrawingObjectLiner.cs +++ b/Liner/MovingStrategies/DrawingObjectLiner.cs @@ -21,8 +21,7 @@ namespace Liner.MovingStrategies { get { - if (_drawingLiner == null || _drawingLiner.EntityLiner == - null) + if (_drawingLiner == null || _drawingLiner.EntityLiner == null) { return null; } @@ -36,5 +35,4 @@ namespace Liner.MovingStrategies public void MoveObject(DirectionType direction) => _drawingLiner?.MoveTransport(direction); } - } -- 2.25.1 From 2a48e6436c99b074df4fe891c176a7457a1c78f4 Mon Sep 17 00:00:00 2001 From: Marselchi Date: Mon, 25 Sep 2023 14:04:52 +0400 Subject: [PATCH 5/6] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=B0=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Liner/Drawing/DrawingLiner.cs | 23 ++++++++++++++++++++ Liner/MovingStrategies/DrawingObjectLiner.cs | 1 + 2 files changed, 24 insertions(+) diff --git a/Liner/Drawing/DrawingLiner.cs b/Liner/Drawing/DrawingLiner.cs index 04a9047..6a11ae7 100644 --- a/Liner/Drawing/DrawingLiner.cs +++ b/Liner/Drawing/DrawingLiner.cs @@ -151,6 +151,29 @@ namespace Liner.Drawing }; } /// + /// Проверка, что объект может переместится по указанному направлению + /// + /// Направление + /// true - можно переместится по указанному направлению + public bool CanMove(DirectionType direction) + { + if (EntityLiner == null) + { + return false; + } + return direction switch + { + //влево + DirectionType.Left => _startPosX - EntityLiner.Step > 0, + //вверх + DirectionType.Up => _startPosY - EntityLiner.Step > 0, + //вправо + DirectionType.Right => _startPosX + EntityLiner.Step + _linerWidth < _pictureWidth, + //вниз + DirectionType.Down => _startPosY + EntityLiner.Step + _linerHeight < _pictureHeight + }; + } + /// /// Изменение направления перемещения /// /// Направление diff --git a/Liner/MovingStrategies/DrawingObjectLiner.cs b/Liner/MovingStrategies/DrawingObjectLiner.cs index 0afe82d..aa00f5c 100644 --- a/Liner/MovingStrategies/DrawingObjectLiner.cs +++ b/Liner/MovingStrategies/DrawingObjectLiner.cs @@ -35,4 +35,5 @@ namespace Liner.MovingStrategies public void MoveObject(DirectionType direction) => _drawingLiner?.MoveTransport(direction); } + } -- 2.25.1 From f245f6a830d3491be5780a738574ac9a2cdb4a3e Mon Sep 17 00:00:00 2001 From: Marselchi Date: Fri, 24 Nov 2023 12:28:31 +0400 Subject: [PATCH 6/6] =?UTF-8?q?=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C=D1=88?= =?UTF-8?q?=D0=B0=D1=8F=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Liner/Drawing/DrawingLiner.cs | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/Liner/Drawing/DrawingLiner.cs b/Liner/Drawing/DrawingLiner.cs index 6a11ae7..04a9047 100644 --- a/Liner/Drawing/DrawingLiner.cs +++ b/Liner/Drawing/DrawingLiner.cs @@ -151,29 +151,6 @@ namespace Liner.Drawing }; } /// - /// Проверка, что объект может переместится по указанному направлению - /// - /// Направление - /// true - можно переместится по указанному направлению - public bool CanMove(DirectionType direction) - { - if (EntityLiner == null) - { - return false; - } - return direction switch - { - //влево - DirectionType.Left => _startPosX - EntityLiner.Step > 0, - //вверх - DirectionType.Up => _startPosY - EntityLiner.Step > 0, - //вправо - DirectionType.Right => _startPosX + EntityLiner.Step + _linerWidth < _pictureWidth, - //вниз - DirectionType.Down => _startPosY + EntityLiner.Step + _linerHeight < _pictureHeight - }; - } - /// /// Изменение направления перемещения /// /// Направление -- 2.25.1