From a22d317814070e3592583cb699c150f25d1402cb Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Sun, 3 Mar 2024 15:22:55 +0300 Subject: [PATCH 1/3] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=80=D0=BE=D0=B4=D0=B8=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D0=B5=D0=B9=20=D0=B8=20=D0=B2=D0=B2=D0=BE=D0=B4=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BA=D1=82=D0=BE=D1=80=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lab_1/Data_Structure.cpp | 1 + Lab_1/Data_Structure.h | 42 ++++ Lab_1/Lab_1.sln | 31 +++ Lab_1/Lab_1.vcxproj | 139 ++++++++++++ Lab_1/Lab_1.vcxproj.filters | 30 +++ Lab_1/Source.cpp | 199 +++++++++++++++++ .../DrawningElectricLocomotive.cs | 209 ------------------ .../{ => Drawnings}/DirectionType.cs | 2 +- .../Drawnings/DrawningElectricLocomotive.cs | 76 +++++++ .../Drawnings/DrawningLocomotive.cs | 204 +++++++++++++++++ .../Entities/EntityElectricLocomotive.cs | 45 ++++ .../Entities/EntityLocomotive.cs | 47 ++++ .../EntityElectricLocomotive.cs | 62 ------ .../FormlectricLocomotive.Designer.cs | 20 +- .../FormlectricLocomotive.cs | 69 ++++-- 15 files changed, 878 insertions(+), 298 deletions(-) create mode 100644 Lab_1/Data_Structure.cpp create mode 100644 Lab_1/Data_Structure.h create mode 100644 Lab_1/Lab_1.sln create mode 100644 Lab_1/Lab_1.vcxproj create mode 100644 Lab_1/Lab_1.vcxproj.filters create mode 100644 Lab_1/Source.cpp delete mode 100644 ProjectElectricLocomotive/DrawningElectricLocomotive.cs rename ProjectElectricLocomotive/{ => Drawnings}/DirectionType.cs (91%) create mode 100644 ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs create mode 100644 ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs create mode 100644 ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs create mode 100644 ProjectElectricLocomotive/Entities/EntityLocomotive.cs delete mode 100644 ProjectElectricLocomotive/EntityElectricLocomotive.cs diff --git a/Lab_1/Data_Structure.cpp b/Lab_1/Data_Structure.cpp new file mode 100644 index 0000000..16afe1c --- /dev/null +++ b/Lab_1/Data_Structure.cpp @@ -0,0 +1 @@ +#include "Data_Structure.h" diff --git a/Lab_1/Data_Structure.h b/Lab_1/Data_Structure.h new file mode 100644 index 0000000..68c2813 --- /dev/null +++ b/Lab_1/Data_Structure.h @@ -0,0 +1,42 @@ +//#include +//#include +// +//#pragma once +// +//struct Node { +// int data; +// Node* next; +//}; +// +//class Data_Structure +//{ +//private: +// Node* head; +// struct Node { +// int data; +// Node* next; +// }; +//public: +// Data_Structure(){ +// head = NULL; +// } +// void addNode(int val){ +// Node* newNode = new Node; +// newNode->data = val; +// newNode->next = head; +// head = newNode; +// +// +// } +// void printList() { +// Node* currentNode = head; +// while (currentNode->next != NULL) { +// printf("%d", currentNode->data); +// currentNode = currentNode->next; +// +// } +// +// +// } +//}; +// diff --git a/Lab_1/Lab_1.sln b/Lab_1/Lab_1.sln new file mode 100644 index 0000000..76a53c9 --- /dev/null +++ b/Lab_1/Lab_1.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34024.191 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Lab_1", "Lab_1.vcxproj", "{B3B62C1B-E8D8-4038-8DFD-248406A48EE2}" +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 + {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x64.ActiveCfg = Debug|x64 + {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x64.Build.0 = Debug|x64 + {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x86.ActiveCfg = Debug|Win32 + {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Debug|x86.Build.0 = Debug|Win32 + {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x64.ActiveCfg = Release|x64 + {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x64.Build.0 = Release|x64 + {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x86.ActiveCfg = Release|Win32 + {B3B62C1B-E8D8-4038-8DFD-248406A48EE2}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FF15C0FB-D559-46A6-B4E8-E461B8F5C363} + EndGlobalSection +EndGlobal diff --git a/Lab_1/Lab_1.vcxproj b/Lab_1/Lab_1.vcxproj new file mode 100644 index 0000000..0d6ac74 --- /dev/null +++ b/Lab_1/Lab_1.vcxproj @@ -0,0 +1,139 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {b3b62c1b-e8d8-4038-8dfd-248406a48ee2} + Lab1 + 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/Lab_1/Lab_1.vcxproj.filters b/Lab_1/Lab_1.vcxproj.filters new file mode 100644 index 0000000..6d47a77 --- /dev/null +++ b/Lab_1/Lab_1.vcxproj.filters @@ -0,0 +1,30 @@ + + + + + {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/Lab_1/Source.cpp b/Lab_1/Source.cpp new file mode 100644 index 0000000..bbe0097 --- /dev/null +++ b/Lab_1/Source.cpp @@ -0,0 +1,199 @@ +/* + 4 + - + - + - , + , +*/ + +#include +#include +#include "Data_Structure.h" + +int unsorted_array[10] = { 2, 5, 1,8,3,4,7,6,9,0 }; +int arr[10] = { 2, 5, 1,8,3,4,7,6,9,0 }; +int n = 10; + +void Buble_sort() { + for (int i = 0; i < n; i++) { + for (int j = n - 1; j > i; j--) { + if (arr[j - 1] > arr[j]) { + int temp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp; + } + } + } +} + + +void Merge(int arr[], int begin, int end) { + int mid = begin + (end - begin) / 2; + int i = begin; + int j = mid + 1; + int d[11] = { 0 }; + int k = 0; + + while (i <= mid && j <= end) { + if (arr[i] <= arr[j]) { + d[k] = arr[i]; + i++; + } + else { + d[k] = arr[j]; + j++; + } + k++; + } + while (i <= mid) { + d[k] = arr[i]; + k++; + i++; + } + while (j <= end) { + d[k] = arr[j]; + k++; + j++; + } + for (i = 0; i < k; i++) { + arr[begin + i] = d[i]; + } + +} + +void Merge_sort(int* arr, int left, int right) { + int temp = 0; + if (left < right) { + if (right - left == 1) { + if (arr[left] > arr[right]) { + temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + } + } + else { + Merge_sort(arr, left, (right - left) / 2); + Merge_sort(arr, left + (right - left) / 2 + 1, right); + Merge(arr, left, right); + } + } + +} + + +void Shake_sort() { + int direction = 0; + int left = arr[0]; + int left_index = 0; + int right = arr[n]; + int right_index = n; + for (int _ = 0; _ < n - 1; _++) { + if (direction == 0) { + for (int i = left_index; i < right_index - 1; i++) { + if (arr[i] > arr[i + 1]) { + int temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + } + } + if (right != arr[right_index]) { + for (int i = n; i > 0; i--) { + if (arr[i] == right) { + right_index = i; + } + } + } + direction = 1; + } + else { + for (int j = right_index; j > left_index; j--) { + if (arr[j] < arr[j - 1]) { + int temp1 = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp1; + } + } + if (left != arr[left_index]) { + for (int i = 0; i < n; i++) { + if (arr[i] == left) { + left_index = i; + } + } + } + } + direction = 0; + } + +} + +void print_list() { + for (int i = 0; i < n; i++) { + printf("%d ", arr[i]); + } + printf("\n"); +} + + + +struct Node { + int student_year; + int student_group; + struct Node* next; + + +}; + +struct Node* first = NULL; + + + +void s_addToHead(int year, int group) { + struct Node* NewNode = (struct Node*)malloc(sizeof(NewNode)); + NewNode->student_year = year; + NewNode->student_group = group; + NewNode->next = first; + + first = NewNode; + +} + +void s_deleteFromHead() { + struct Node* DelNode = first; + int val1 = DelNode->student_year; + int val2 = DelNode->student_group; + + first = first->next; + printf("****|PI-%d, %d| - Deleted\n", val2, val1); + +} + +void s_print() { + struct Node* i = first; + while (i) { + printf("|PI-%d, %d|\n", i->student_group, i->student_year); + i = i->next; + } + + +} + + +int main() { + s_addToHead(2020, 12); + s_addToHead(2021, 13); + s_addToHead(2022, 14); + s_addToHead(2024, 15); + s_print(); + printf("------------------------\n"); + s_deleteFromHead(); + s_print(); + + print_list(); + Shake_sort(); + //Merge_sort(arr, 0, n - 1); + print_list(); + //Data_structure newStructure; + + + return 0; +} \ No newline at end of file diff --git a/ProjectElectricLocomotive/DrawningElectricLocomotive.cs b/ProjectElectricLocomotive/DrawningElectricLocomotive.cs deleted file mode 100644 index 9dbdb5e..0000000 --- a/ProjectElectricLocomotive/DrawningElectricLocomotive.cs +++ /dev/null @@ -1,209 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectElectricLocomotive -{ - /// - /// Класс, отвечающий за отрисовку и перемещение обьекта-сущности - /// - public class DrawningElectricLocomotive - { - - /// - /// Класс-сущность - /// - public EntityElectricLocomotive? EntityElectricLocomotive { get; private set; } - /// - /// Ширина окна - /// - private int? _pictureWidth; - /// - /// Высота окна - /// - private int? _pictureHeight; - /// - /// Левая координата прорисовки Электровоза - /// - private int? _startPosX; - /// - /// Верхняя кооридната прорисовки Электровоза - /// - private int? _startPosY; - - /// - /// Ширина прорисовки Локомотива - /// - private readonly int _drawningElectriLocomotiveWidth = 155; - /// - /// Высота прорисовки локомотива - /// - private readonly int _drawningElectricLocomotiveHeight = 100; - - /// - /// Инициализация свойств - /// - /// Скорость - /// Вес - /// Основной цвет - /// Дополнительный цвет - /// Признак наличия обвеса - /// Признак наличия антикрыла - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool pantograph, bool batterystorage) - { - EntityElectricLocomotive = new EntityElectricLocomotive(); - EntityElectricLocomotive.Init(speed, weight, bodyColor, additionalColor, - pantograph, batterystorage); - _pictureWidth = null; - _pictureHeight = null; - _startPosX = null; - _startPosY = null; - - } - /// - /// Установка границ поля - /// - /// Ширина поля - /// Высота поля - /// true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах -public bool SetPictureSize(int width, int height) - { - - // TODO проверка, что объект "влезает" в размеры поля - if(_drawningElectriLocomotiveWidth > width || _drawningElectricLocomotiveHeight > height) - { - return false; - } - if(_startPosX.HasValue && _startPosY.HasValue) - { - if(_startPosX + _drawningElectriLocomotiveWidth > width) - { - _startPosX = width - _drawningElectriLocomotiveWidth; - } - if(_startPosY + _drawningElectricLocomotiveHeight > height) - { - _startPosY = height - _drawningElectricLocomotiveHeight; - } - } - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - // если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена - _pictureWidth = width; - _pictureHeight = height; - return true; - } - public void SetPosition(int x, int y) - { - if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) - { - return; - } - // TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы - if(x < 0 || x + _drawningElectriLocomotiveWidth > _pictureWidth.Value) - { - x = _pictureWidth.Value - _drawningElectriLocomotiveWidth; - } - if(y < 0 || y + _drawningElectricLocomotiveHeight > _pictureHeight.Value) - { - y = _pictureHeight.Value - _drawningElectricLocomotiveHeight; - } - // то надо изменить координаты, чтобы он оставался в этих границах - - _startPosX = x; - _startPosY = y; - } - public bool MoveTransport(DirectionType direction) - { - if (EntityElectricLocomotive == null || !_startPosX.HasValue || - !_startPosY.HasValue) - { - return false; - } - switch (direction) - { - //влево - case DirectionType.Left: - if (_startPosX.Value - EntityElectricLocomotive.Step > 0) - { - _startPosX -= (int)EntityElectricLocomotive.Step; - } - return true; - //вверх - case DirectionType.Up: - if ((_startPosY.Value) - EntityElectricLocomotive.Step > 0) - { - - _startPosY -= (int)EntityElectricLocomotive.Step; - } - return true; - // вправо - case DirectionType.Right: - if (_startPosX.Value + EntityElectricLocomotive.Step < _pictureWidth - _drawningElectriLocomotiveWidth) - { - _startPosX += (int)EntityElectricLocomotive.Step; - } - return true; - //вниз - case DirectionType.Down: - if (_startPosY.Value + EntityElectricLocomotive.Step < _pictureHeight - _drawningElectricLocomotiveHeight) - { - _startPosY += (int)EntityElectricLocomotive.Step; - } - return true; - default: - return false; - } - } - public void DrawTransport(Graphics g) - { - if (EntityElectricLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) - { - return; - } - Pen pen = new(Color.Black); - Brush additonalBrush = new SolidBrush(EntityElectricLocomotive.AdditionalColor); - Brush bodyBrush = new SolidBrush(EntityElectricLocomotive.BodyColor); - //границы Электровоза - //колеса - g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 65, 20, 20); - g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 65, 20, 20); - g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 65, 20, 20); - g.DrawEllipse(pen, _startPosX.Value + 120, _startPosY.Value + 65, 20, 20); - //кузов - g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 50, 155, 40); - g.DrawLine(pen, _startPosX.Value, _startPosY.Value + 50, _startPosX.Value + 20, _startPosY.Value + 30); - g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 30, 135,20 ); - //покраска кузова - g.FillEllipse(Brushes.Black, _startPosX.Value + 10, _startPosY.Value + 85, 20, 20); - g.FillEllipse(Brushes.Black, _startPosX.Value + 30, _startPosY.Value + 85, 20, 20); - g.FillEllipse(Brushes.Black, _startPosX.Value + 100, _startPosY.Value + 85, 20, 20); - g.FillEllipse(Brushes.Black, _startPosX.Value + 120, _startPosY.Value + 85, 20, 20); - g.FillRectangle(bodyBrush, _startPosX.Value+1, _startPosY.Value + 51, 154, 39); - g.FillRectangle(bodyBrush, _startPosX.Value + 21, _startPosY.Value + 31, 134, 19); - - g.DrawRectangle(pen, _startPosX.Value , _startPosY.Value + 50, 155, 10); - g.FillRectangle(additonalBrush, _startPosX.Value + 1, _startPosY.Value + 51, 154, 9); - //g.FillPolygon(Brushes.AliceBlue, _startPosX.Value + 1, _startPosY.Value + 31, _startPosX.Value + 19, _startPosY.Value + 9, _startPosX.Value + 19, _startPosY.Value + 1); - //Пантограф - if (EntityElectricLocomotive.Pantograph) - { - g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 30, _startPosX.Value + 70, _startPosY.Value + 10); - g.DrawLine(pen, _startPosX.Value + 50, _startPosY.Value + 10, _startPosX.Value + 90, _startPosY.Value + 10); - } - //Отсек для батарей - if (EntityElectricLocomotive.BatteryStorage) - { - g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value + 30, 30, 20); - g.FillRectangle(additonalBrush, _startPosX.Value + 101, _startPosY.Value + 31, 29, 19); - g.DrawLine(pen, _startPosX.Value + 120, _startPosY.Value + 40, _startPosX.Value + 115, _startPosY.Value + 50); - g.DrawLine(pen, _startPosX.Value + 115, _startPosY.Value + 40, _startPosX.Value + 120, _startPosY.Value + 40); - g.DrawLine(pen, _startPosX.Value + 120, _startPosY.Value + 30, _startPosX.Value + 115, _startPosY.Value + 40); - } - - } - - } - } - diff --git a/ProjectElectricLocomotive/DirectionType.cs b/ProjectElectricLocomotive/Drawnings/DirectionType.cs similarity index 91% rename from ProjectElectricLocomotive/DirectionType.cs rename to ProjectElectricLocomotive/Drawnings/DirectionType.cs index 8cec3e4..db3f0e7 100644 --- a/ProjectElectricLocomotive/DirectionType.cs +++ b/ProjectElectricLocomotive/Drawnings/DirectionType.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectElectricLocomotive +namespace ProjectElectricLocomotive.Drawnings { public enum DirectionType { diff --git a/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs b/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs new file mode 100644 index 0000000..2270eb2 --- /dev/null +++ b/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProjectElectricLocomotive.Entities; + +namespace ProjectElectricLocomotive.Drawnings +{ + /// + /// Класс, отвечающий за отрисовку и перемещение обьекта-сущности + /// + public class DrawningElectricLocomotive: DrawningLocomotive + { + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + /// Дополнительный цвет + /// Признак наличия обвеса + /// Признак наличия антикрыла + /// -------------------------------------------------------------------------- + /// Требуется конструктор, вызывать надо будет у класса EntityElectricLocomotive + /// ДОДЕЛАТЬ САМИМ!!! + public DrawningElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool pantograph, bool batterystorage) : base(155, 100) + { + EntityLocomotive = new EntityElectricLocomotive(speed, weight, bodyColor, additionalColor, + pantograph, batterystorage); + } + + public override void DrawTransport(Graphics g) + { + if (EntityLocomotive == null || EntityLocomotive is not EntityElectricLocomotive electricLocomotive || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + + _startPosX += 0; + _startPosY += 0; + base.DrawTransport(g); + _startPosX -= 0; + _startPosY -= 0; + + Pen pen = new(Color.Black); + Brush additonalBrush = new SolidBrush(electricLocomotive.AdditionalColor); + Brush bodyBrush = new SolidBrush(electricLocomotive.BodyColor); + + g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 50, 155, 10); + g.FillRectangle(additonalBrush, _startPosX.Value + 1, _startPosY.Value + 51, 154, 9); + + //Пантограф + if (electricLocomotive.Pantograph) + { + g.DrawLine(pen, _startPosX.Value + 60, _startPosY.Value + 30, _startPosX.Value + 70, _startPosY.Value + 10); + g.DrawLine(pen, _startPosX.Value + 50, _startPosY.Value + 10, _startPosX.Value + 90, _startPosY.Value + 10); + } + //Отсек для батарей + if (electricLocomotive.BatteryStorage) + { + g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value + 30, 30, 20); + g.FillRectangle(additonalBrush, _startPosX.Value + 101, _startPosY.Value + 31, 29, 19); + g.DrawLine(pen, _startPosX.Value + 120, _startPosY.Value + 40, _startPosX.Value + 115, _startPosY.Value + 50); + g.DrawLine(pen, _startPosX.Value + 115, _startPosY.Value + 40, _startPosX.Value + 120, _startPosY.Value + 40); + g.DrawLine(pen, _startPosX.Value + 120, _startPosY.Value + 30, _startPosX.Value + 115, _startPosY.Value + 40); + } + + } + + } +} + diff --git a/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs b/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs new file mode 100644 index 0000000..42fce8c --- /dev/null +++ b/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs @@ -0,0 +1,204 @@ +using ProjectElectricLocomotive.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Drawnings; + +public class DrawningLocomotive +{ + + /// + /// Класс-сущность + /// + public EntityLocomotive? EntityLocomotive { get; protected set; } + /// + /// Ширина окна + /// + private int? _pictureWidth; + /// + /// Высота окна + /// + private int? _pictureHeight; + /// + /// Левая координата прорисовки Электровоза + /// + protected int? _startPosX; + /// + /// Верхняя кооридната прорисовки Электровоза + /// + protected int? _startPosY; + + /// + /// Ширина прорисовки Локомотива + /// + private readonly int _drawningLocomotiveWidth = 155; + /// + /// Высота прорисовки локомотива + /// + private readonly int _drawningLocomotiveHeight = 90; + + /// + /// Пустой конструктор + /// + private DrawningLocomotive() + { + + _pictureWidth = null; + _pictureHeight = null; + _startPosX = null; + _startPosY = null; + } + + /// + /// Конструктор + /// + /// Скорость + /// Вес + /// Основной цвет + + public DrawningLocomotive(int speed, double weight, Color bodyColor) : this() + { + EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor); + + } + /// + /// Конструктор для наследников + /// + /// Ширина прорисовки локомотива + /// Высота прорисовки локомотива + protected DrawningLocomotive(int drawningLocomotiveWidtе, int drawningLocomotiveHeight) : this() + { + _drawningLocomotiveHeight = drawningLocomotiveHeight; + _drawningLocomotiveWidth = drawningLocomotiveWidtе; + + } + + /// + /// Установка границ поля + /// + /// Ширина поля + /// Высота поля + /// true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах + public bool SetPictureSize(int width, int height) + { + + // TODO проверка, что объект "влезает" в размеры поля + if (_drawningLocomotiveWidth > width || _drawningLocomotiveHeight > height) + { + return false; + } + if (_startPosX.HasValue && _startPosY.HasValue) + { + if (_startPosX + _drawningLocomotiveWidth > width) + { + _startPosX = width - _drawningLocomotiveWidth; + } + if (_startPosY + _drawningLocomotiveHeight > height) + { + _startPosY = height - _drawningLocomotiveHeight; + } + } + //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + // если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена + _pictureWidth = width; + _pictureHeight = height; + return true; + } + public void SetPosition(int x, int y) + { + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) + { + return; + } + // TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы + if (x < 0 || x + _drawningLocomotiveWidth > _pictureWidth.Value) + { + x = _pictureWidth.Value - _drawningLocomotiveWidth; + } + if (y < 0 || y + _drawningLocomotiveHeight > _pictureHeight.Value) + { + y = _pictureHeight.Value - _drawningLocomotiveHeight; + } + // то надо изменить координаты, чтобы он оставался в этих границах + + _startPosX = x; + _startPosY = y; + } + public bool MoveTransport(DirectionType direction) + { + if (EntityLocomotive == null || !_startPosX.HasValue || + !_startPosY.HasValue) + { + return false; + } + switch (direction) + { + //влево + case DirectionType.Left: + if (_startPosX.Value - EntityLocomotive.Step > 0) + { + _startPosX -= (int)EntityLocomotive.Step; + } + return true; + //вверх + case DirectionType.Up: + if (_startPosY.Value - EntityLocomotive.Step > 0) + { + + _startPosY -= (int)EntityLocomotive.Step; + } + return true; + // вправо + case DirectionType.Right: + if (_startPosX.Value + EntityLocomotive.Step < _pictureWidth - _drawningLocomotiveWidth) + { + _startPosX += (int)EntityLocomotive.Step; + } + return true; + //вниз + case DirectionType.Down: + if (_startPosY.Value + EntityLocomotive.Step < _pictureHeight - _drawningLocomotiveHeight) + { + _startPosY += (int)EntityLocomotive.Step; + } + return true; + default: + return false; + } + } + public virtual void DrawTransport(Graphics g) + { + if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + Pen pen = new(Color.Black); + Brush bodyBrush = new SolidBrush(EntityLocomotive.BodyColor); + //границы Электровоза + //колеса + g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 65, 20, 20); + g.DrawEllipse(pen, _startPosX.Value + 30, _startPosY.Value + 65, 20, 20); + g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 65, 20, 20); + g.DrawEllipse(pen, _startPosX.Value + 120, _startPosY.Value + 65, 20, 20); + //кузов + g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 50, 155, 40); + g.DrawLine(pen, _startPosX.Value, _startPosY.Value + 50, _startPosX.Value + 20, _startPosY.Value + 30); + g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 30, 135, 20); + //покраска кузова + g.FillEllipse(Brushes.Black, _startPosX.Value + 10, _startPosY.Value + 85, 20, 20); + g.FillEllipse(Brushes.Black, _startPosX.Value + 30, _startPosY.Value + 85, 20, 20); + g.FillEllipse(Brushes.Black, _startPosX.Value + 100, _startPosY.Value + 85, 20, 20); + g.FillEllipse(Brushes.Black, _startPosX.Value + 120, _startPosY.Value + 85, 20, 20); + g.FillRectangle(bodyBrush, _startPosX.Value + 1, _startPosY.Value + 51, 154, 39); + g.FillRectangle(bodyBrush, _startPosX.Value + 21, _startPosY.Value + 31, 134, 19); + + g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 50, 155, 10); + g.FillRectangle(bodyBrush, _startPosX.Value + 1, _startPosY.Value + 51, 154, 9); + + } + + +} diff --git a/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs b/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs new file mode 100644 index 0000000..344ab1d --- /dev/null +++ b/ProjectElectricLocomotive/Entities/EntityElectricLocomotive.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.Design; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Entities +{ + public class EntityElectricLocomotive : EntityLocomotive + { + + + public Color AdditionalColor { get; private set; } + /// + /// Признак (опция) "рогов" + /// + public bool Pantograph { get; private set; } + /// + /// Признак (опция) наличия отсека под батареи + /// + public bool BatteryStorage { get; private set; } + /// + /// Шаг перемещения Локомотива + /// + public double Step => Speed * 100 / Weight; + /// + /// Инициализация полей объекта-класса ЭлектроЛокомотива + /// + /// Дополнительный цвет + /// Признак "рогов" + /// Признак наличия отсека под батареи + /// ------------------------------------------------------------------------------ + /// Переписать!!!!!!!!! + /// САМИМ ТО ЧТО СНИЗУ!!!!!!!!!!!!!!!!!! + public EntityElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool pantograph + , bool batteryStorage) : base(speed, weight, bodyColor) + { + AdditionalColor = additionalColor; + Pantograph = pantograph; + BatteryStorage = batteryStorage; + } + + } +} diff --git a/ProjectElectricLocomotive/Entities/EntityLocomotive.cs b/ProjectElectricLocomotive/Entities/EntityLocomotive.cs new file mode 100644 index 0000000..30336a5 --- /dev/null +++ b/ProjectElectricLocomotive/Entities/EntityLocomotive.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.Entities +{ + /// + /// Класс-сущность "Локомотив" + /// + public class EntityLocomotive + { + /// + /// Скорость + /// + 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 EntityLocomotive(int speed, double weight, Color bodyColor) + { + Speed = speed; + Weight = weight; + BodyColor = bodyColor; + + + } + + } +} diff --git a/ProjectElectricLocomotive/EntityElectricLocomotive.cs b/ProjectElectricLocomotive/EntityElectricLocomotive.cs deleted file mode 100644 index a50bb96..0000000 --- a/ProjectElectricLocomotive/EntityElectricLocomotive.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectElectricLocomotive -{ - public class EntityElectricLocomotive - { - - /// - /// Скорость - /// - public int Speed { get; private set; } - /// - /// Вес - /// - public double Weight { get; private set; } - /// - /// Основной цвет - /// - public Color BodyColor { get; private set; } - /// - /// Дополнительный цвет (для опциональных элементов) - /// - public Color AdditionalColor { get; private set; } - /// - /// Признак (опция) "рогов" - /// - public bool Pantograph{ get; private set; } - /// - /// Признак (опция) наличия отсека под батареи - /// - public bool BatteryStorage { get; private set; } - /// - /// Шаг перемещения Локомотива - /// - public double Step => Speed * 100 / Weight; - /// - /// Инициализация полей объекта-класса ЭлектроЛокомотива - /// - /// Скорость - /// Вес локомотива - /// Основной цвет - /// Дополнительный цвет - /// Признак "рогов" - /// Признак наличия отсека под батареи - public void Init(int speed, double weight, Color bodyColor, Color - additionalColor, bool pantograph, bool batterystorage) - { - Speed = speed; - Weight = weight; - BodyColor = bodyColor; - AdditionalColor = additionalColor; - Pantograph = pantograph; - BatteryStorage = batterystorage; - - } - - } -} diff --git a/ProjectElectricLocomotive/FormlectricLocomotive.Designer.cs b/ProjectElectricLocomotive/FormlectricLocomotive.Designer.cs index 63d526c..5f21c43 100644 --- a/ProjectElectricLocomotive/FormlectricLocomotive.Designer.cs +++ b/ProjectElectricLocomotive/FormlectricLocomotive.Designer.cs @@ -34,6 +34,7 @@ buttonLeft = new Button(); buttonRight = new Button(); buttonDown = new Button(); + buttonCreateLocomotive = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit(); SuspendLayout(); // @@ -46,16 +47,15 @@ pictureBoxElectricLocomotive.Size = new Size(779, 411); pictureBoxElectricLocomotive.TabIndex = 0; pictureBoxElectricLocomotive.TabStop = false; - // // buttonCreate // buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreate.Location = new Point(12, 353); buttonCreate.Name = "buttonCreate"; - buttonCreate.Size = new Size(112, 34); + buttonCreate.Size = new Size(263, 34); buttonCreate.TabIndex = 1; - buttonCreate.Text = "Создать"; + buttonCreate.Text = "Создать ЭлектроЛокомотив"; buttonCreate.UseVisualStyleBackColor = true; buttonCreate.Click += buttonCreate_Click; // @@ -107,11 +107,23 @@ buttonDown.UseVisualStyleBackColor = true; buttonDown.Click += ButtonMove_Click; // + // buttonCreateLocomotive + // + buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonCreateLocomotive.Location = new Point(281, 353); + buttonCreateLocomotive.Name = "buttonCreateLocomotive"; + buttonCreateLocomotive.Size = new Size(263, 34); + buttonCreateLocomotive.TabIndex = 6; + buttonCreateLocomotive.Text = "Создать Локомотив"; + buttonCreateLocomotive.UseVisualStyleBackColor = true; + buttonCreateLocomotive.Click += buttonCreateLocomotive_Click; + // // FormlectricLocomotive // AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(788, 399); + Controls.Add(buttonCreateLocomotive); Controls.Add(buttonDown); Controls.Add(buttonRight); Controls.Add(buttonLeft); @@ -120,7 +132,6 @@ Controls.Add(pictureBoxElectricLocomotive); Name = "FormlectricLocomotive"; Text = "ЭлектроВоз"; - ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).EndInit(); ResumeLayout(false); } @@ -133,5 +144,6 @@ private Button buttonLeft; private Button buttonRight; private Button buttonDown; + private Button buttonCreateLocomotive; } } \ No newline at end of file diff --git a/ProjectElectricLocomotive/FormlectricLocomotive.cs b/ProjectElectricLocomotive/FormlectricLocomotive.cs index 9d821fe..7f2d59b 100644 --- a/ProjectElectricLocomotive/FormlectricLocomotive.cs +++ b/ProjectElectricLocomotive/FormlectricLocomotive.cs @@ -8,6 +8,7 @@ using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using ProjectElectricLocomotive.Drawnings; namespace ProjectElectricLocomotive { @@ -15,41 +16,63 @@ namespace ProjectElectricLocomotive { private void Draw() { - if (_drawnningElectricLocomotive == null) + if (_drawnningLocomotive == null) { return; } Bitmap bmp = new(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); Graphics gr = Graphics.FromImage(bmp); - _drawnningElectricLocomotive.DrawTransport(gr); + _drawnningLocomotive.DrawTransport(gr); pictureBoxElectricLocomotive.Image = bmp; } - private DrawningElectricLocomotive? _drawnningElectricLocomotive; + private void CreateObject(string type) + { + Random random = new(); + switch (type) + { + case nameof(DrawningLocomotive): + _drawnningLocomotive = new DrawningLocomotive(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); + break; + case nameof(DrawningElectricLocomotive): + _drawnningLocomotive = new DrawningElectricLocomotive(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; + } + _drawnningLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); + _drawnningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); + + Draw(); + } + + private DrawningLocomotive? _drawnningLocomotive; public FormlectricLocomotive() { InitializeComponent(); } - - private void buttonCreate_Click(object sender, EventArgs e) - { - Random random = new(); - _drawnningElectricLocomotive = new DrawningElectricLocomotive(); - _drawnningElectricLocomotive.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))); - _drawnningElectricLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); - _drawnningElectricLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); - - Draw(); - } + /// + /// Обработка кнопки создать "ЭлектроЛокомотив" + /// + /// + /// + private void buttonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningElectricLocomotive)); + /// + /// Обработка нажатия кнопки создать "Локомотив" + /// + /// + /// + private void buttonCreateLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLocomotive)); private void ButtonMove_Click(object sender, EventArgs e) { - if (_drawnningElectricLocomotive == null) + if (_drawnningLocomotive == null) { return; } @@ -59,19 +82,19 @@ namespace ProjectElectricLocomotive { case "buttonUp": result = - _drawnningElectricLocomotive.MoveTransport(DirectionType.Up); + _drawnningLocomotive.MoveTransport(DirectionType.Up); break; case "buttonDown": result = - _drawnningElectricLocomotive.MoveTransport(DirectionType.Down); + _drawnningLocomotive.MoveTransport(DirectionType.Down); break; case "buttonLeft": result = - _drawnningElectricLocomotive.MoveTransport(DirectionType.Left); + _drawnningLocomotive.MoveTransport(DirectionType.Left); break; case "buttonRight": result = - _drawnningElectricLocomotive.MoveTransport(DirectionType.Right); + _drawnningLocomotive.MoveTransport(DirectionType.Right); break; } if (result) @@ -80,5 +103,7 @@ namespace ProjectElectricLocomotive } } + + } } -- 2.25.1 From a8fa0803252ef5ec738e310f2475961433f48778 Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Sun, 3 Mar 2024 17:28:20 +0300 Subject: [PATCH 2/3] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D1=8F?= =?UTF-8?q?=D0=B5=D1=82=D1=81=D1=8F=20=D1=81=D1=82=D1=80=D0=B0=D1=82=D0=B5?= =?UTF-8?q?=D0=B3=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Drawnings/DirectionType.cs | 4 + .../Drawnings/DrawningLocomotive.cs | 19 +++ .../FormlectricLocomotive.Designer.cs | 26 ++++ .../FormlectricLocomotive.cs | 56 ++++++- .../MovementStrategy/AbstractStrategy.cs | 142 ++++++++++++++++++ .../MovementStrategy/IMovableObject.cs | 32 ++++ .../MovementStrategy/MoveToBorder.cs | 57 +++++++ .../MovementStrategy/MoveToCenter.cs | 57 +++++++ .../MovementStrategy/MoveableLocomotive.cs | 65 ++++++++ .../MovementStrategy/MovementDirection.cs | 27 ++++ .../MovementStrategy/ObjectParameters.cs | 78 ++++++++++ .../MovementStrategy/StrategyStatus.cs | 23 +++ 12 files changed, 580 insertions(+), 6 deletions(-) create mode 100644 ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs create mode 100644 ProjectElectricLocomotive/MovementStrategy/IMovableObject.cs create mode 100644 ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs create mode 100644 ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs create mode 100644 ProjectElectricLocomotive/MovementStrategy/MoveableLocomotive.cs create mode 100644 ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs create mode 100644 ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs create mode 100644 ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs diff --git a/ProjectElectricLocomotive/Drawnings/DirectionType.cs b/ProjectElectricLocomotive/Drawnings/DirectionType.cs index db3f0e7..ba08627 100644 --- a/ProjectElectricLocomotive/Drawnings/DirectionType.cs +++ b/ProjectElectricLocomotive/Drawnings/DirectionType.cs @@ -8,6 +8,10 @@ namespace ProjectElectricLocomotive.Drawnings { public enum DirectionType { + /// + /// Неизвестное направление + /// + Unknow = -1, /// /// Вверх /// diff --git a/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs b/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs index 42fce8c..e05df50 100644 --- a/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs +++ b/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs @@ -39,7 +39,26 @@ public class DrawningLocomotive /// Высота прорисовки локомотива /// private readonly int _drawningLocomotiveHeight = 90; + + /// + /// Координата X объекта + /// + public int? GetPosX => _startPosX; + + /// + /// Координата Y объекта + /// + public int? GetPosY => _startPosY; + + /// + /// Ширина объекта + /// + public int GetWidth => _drawningLocomotiveWidth; + /// + /// Высота объекта + /// + public int GetHeight => _drawningLocomotiveHeight; /// /// Пустой конструктор /// diff --git a/ProjectElectricLocomotive/FormlectricLocomotive.Designer.cs b/ProjectElectricLocomotive/FormlectricLocomotive.Designer.cs index 5f21c43..725b4ff 100644 --- a/ProjectElectricLocomotive/FormlectricLocomotive.Designer.cs +++ b/ProjectElectricLocomotive/FormlectricLocomotive.Designer.cs @@ -35,6 +35,8 @@ buttonRight = new Button(); buttonDown = new Button(); buttonCreateLocomotive = new Button(); + comboBoxStrategy = new ComboBox(); + buttonStrategyStep = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit(); SuspendLayout(); // @@ -118,11 +120,33 @@ buttonCreateLocomotive.UseVisualStyleBackColor = true; buttonCreateLocomotive.Click += buttonCreateLocomotive_Click; // + // comboBoxStrategy + // + comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); + comboBoxStrategy.Location = new Point(594, 12); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(182, 33); + comboBoxStrategy.TabIndex = 7; + // + // buttonStrategyStep + // + buttonStrategyStep.Location = new Point(664, 51); + buttonStrategyStep.Name = "buttonStrategyStep"; + buttonStrategyStep.Size = new Size(112, 34); + buttonStrategyStep.TabIndex = 8; + buttonStrategyStep.Text = "Шаг"; + buttonStrategyStep.UseVisualStyleBackColor = true; + buttonStrategyStep.Click += buttonStrategyStep_Click; + // // FormlectricLocomotive // AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(788, 399); + Controls.Add(buttonStrategyStep); + Controls.Add(comboBoxStrategy); Controls.Add(buttonCreateLocomotive); Controls.Add(buttonDown); Controls.Add(buttonRight); @@ -145,5 +169,7 @@ private Button buttonRight; private Button buttonDown; private Button buttonCreateLocomotive; + private ComboBox comboBoxStrategy; + private Button buttonStrategyStep; } } \ No newline at end of file diff --git a/ProjectElectricLocomotive/FormlectricLocomotive.cs b/ProjectElectricLocomotive/FormlectricLocomotive.cs index 7f2d59b..68036f4 100644 --- a/ProjectElectricLocomotive/FormlectricLocomotive.cs +++ b/ProjectElectricLocomotive/FormlectricLocomotive.cs @@ -9,11 +9,23 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ProjectElectricLocomotive.Drawnings; +using ProjectElectricLocomotive.MovementStrategy; namespace ProjectElectricLocomotive { public partial class FormlectricLocomotive : Form { + /// + /// Стратегия перемещения + /// + private AbstractStrategy? _strategy; + + public FormlectricLocomotive() + { + InitializeComponent(); + _strategy = null; + } + private void Draw() { if (_drawnningLocomotive == null) @@ -47,15 +59,13 @@ namespace ProjectElectricLocomotive } _drawnningLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); _drawnningLocomotive.SetPosition(random.Next(10, 100), random.Next(10, 100)); - + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } private DrawningLocomotive? _drawnningLocomotive; - public FormlectricLocomotive() - { - InitializeComponent(); - } + /// /// Обработка кнопки создать "ЭлектроЛокомотив" @@ -104,6 +114,40 @@ namespace ProjectElectricLocomotive } - + + private void buttonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawnningLocomotive == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCenter(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableLocomotive(_drawnningLocomotive), + pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } } diff --git a/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs b/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..c1c9b32 --- /dev/null +++ b/ProjectElectricLocomotive/MovementStrategy/AbstractStrategy.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public abstract class AbstractStrategy +{ + /// + /// Перемещаемый объект + /// + private IMovableObject _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(IMovableObject 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/ProjectElectricLocomotive/MovementStrategy/IMovableObject.cs b/ProjectElectricLocomotive/MovementStrategy/IMovableObject.cs new file mode 100644 index 0000000..f67d1b3 --- /dev/null +++ b/ProjectElectricLocomotive/MovementStrategy/IMovableObject.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +/// +/// Интерфейс для работы с перемещаемыми объектами +/// +public interface IMovableObject +{ + + /// + /// Получение координаты объекта + /// + ObjectParameters? GetObjectPosition { get; } + + /// + /// Шаг объекта + /// + int GetStep { get; } + + /// + /// Попытка переместить объект в указанном направлении + /// + /// направление + /// true - объект перемещен , false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); + +} diff --git a/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs b/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs new file mode 100644 index 0000000..b03ad9e --- /dev/null +++ b/ProjectElectricLocomotive/MovementStrategy/MoveToBorder.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestinaion() + { + ObjectParameters? objParams = GetObjectParameters; + if (objParams == null) + { + return false; + } + + return objParams.RightBorder - GetStep() <= FieldWidth && objParams.RightBorder + GetStep() >= FieldWidth && + objParams.DownBorder - GetStep() <= 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/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs b/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs new file mode 100644 index 0000000..3203774 --- /dev/null +++ b/ProjectElectricLocomotive/MovementStrategy/MoveToCenter.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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/ProjectElectricLocomotive/MovementStrategy/MoveableLocomotive.cs b/ProjectElectricLocomotive/MovementStrategy/MoveableLocomotive.cs new file mode 100644 index 0000000..fe58fb3 --- /dev/null +++ b/ProjectElectricLocomotive/MovementStrategy/MoveableLocomotive.cs @@ -0,0 +1,65 @@ +using ProjectElectricLocomotive.Drawnings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy +{ + public class MoveableLocomotive : IMovableObject + { + + private readonly DrawningLocomotive? _locomotive = null; + + public MoveableLocomotive(DrawningLocomotive locomotive) + { + _locomotive = locomotive; + } + + public ObjectParameters? GetObjectPosition + { + get + { + if (_locomotive == null || _locomotive.EntityLocomotive == null || !_locomotive.GetPosX.HasValue || !_locomotive.GetPosY.HasValue) + { + return null; + } + return new ObjectParameters(_locomotive.GetPosX.Value, _locomotive.GetPosY.Value, _locomotive.GetWidth, _locomotive.GetHeight); + } + } + + + + public int GetStep => (int)(_locomotive?.EntityLocomotive?.Step ?? 0); + + + + public bool TryMoveObject(MovementDirection direction) + { + if (_locomotive == null || _locomotive.EntityLocomotive == null) + { + return false; + } + + return _locomotive.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/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs b/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs new file mode 100644 index 0000000..b2965ea --- /dev/null +++ b/ProjectElectricLocomotive/MovementStrategy/MovementDirection.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public enum MovementDirection +{ + /// + /// Вверх + /// + Up = 1, + /// + /// Вниз + /// + Down = 2, + /// + /// Влево + /// + Left = 3, + /// + /// Вправо + /// + Right = 4 +} diff --git a/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs b/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs new file mode 100644 index 0000000..9a0f6eb --- /dev/null +++ b/ProjectElectricLocomotive/MovementStrategy/ObjectParameters.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.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/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs b/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs new file mode 100644 index 0000000..737c149 --- /dev/null +++ b/ProjectElectricLocomotive/MovementStrategy/StrategyStatus.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectElectricLocomotive.MovementStrategy; + +public enum StrategyStatus +{ + /// + /// Все готово к началу + /// + NotInit, + /// + /// Выполняется + /// + InProgress, + /// + /// Завершено + /// + Finish +} -- 2.25.1 From 7fb180fd99d56f69e65fb7a66cbff088cf16511a Mon Sep 17 00:00:00 2001 From: Tonb73 Date: Mon, 4 Mar 2024 07:54:59 +0300 Subject: [PATCH 3/3] =?UTF-8?q?=D0=9F=D0=BE=D0=BB=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8C=D1=8E=20=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Drawnings/DrawningElectricLocomotive.cs | 1 + ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs b/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs index 2270eb2..6fb4841 100644 --- a/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs +++ b/ProjectElectricLocomotive/Drawnings/DrawningElectricLocomotive.cs @@ -32,6 +32,7 @@ namespace ProjectElectricLocomotive.Drawnings pantograph, batterystorage); } + public override void DrawTransport(Graphics g) { if (EntityLocomotive == null || EntityLocomotive is not EntityElectricLocomotive electricLocomotive || !_startPosX.HasValue || !_startPosY.HasValue) diff --git a/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs b/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs index e05df50..605506c 100644 --- a/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs +++ b/ProjectElectricLocomotive/Drawnings/DrawningLocomotive.cs @@ -34,11 +34,11 @@ public class DrawningLocomotive /// /// Ширина прорисовки Локомотива /// - private readonly int _drawningLocomotiveWidth = 155; + public readonly int _drawningLocomotiveWidth = 155; /// /// Высота прорисовки локомотива /// - private readonly int _drawningLocomotiveHeight = 90; + public readonly int _drawningLocomotiveHeight = 90; /// /// Координата X объекта @@ -146,7 +146,7 @@ public class DrawningLocomotive _startPosX = x; _startPosY = y; } - public bool MoveTransport(DirectionType direction) + public bool MoveTransport(DirectionType direction) { if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) -- 2.25.1