PIbd-13 Suslin_V.S. LabWork02 Simple #2

Closed
Sivby wants to merge 1 commits from LabWork02 into LabWork01
23 changed files with 1195 additions and 390 deletions

View File

@ -0,0 +1,31 @@

Review

Левые файлы

Левые файлы
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ProjectAiSD", "ProjectAiSD\ProjectAiSD.vcxproj", "{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}"
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
{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}.Debug|x64.ActiveCfg = Debug|x64
{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}.Debug|x64.Build.0 = Debug|x64
{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}.Debug|x86.ActiveCfg = Debug|Win32
{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}.Debug|x86.Build.0 = Debug|Win32
{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}.Release|x64.ActiveCfg = Release|x64
{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}.Release|x64.Build.0 = Release|x64
{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}.Release|x86.ActiveCfg = Release|Win32
{1203BB93-5B4B-446F-9CD3-4E1FBC19A791}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6902D87F-9F53-4C0D-8571-543876503D6B}
EndGlobalSection
EndGlobal

View File

View File

@ -0,0 +1,138 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{1203bb93-5b4b-446f-9cd3-4e1fbc19a791}</ProjectGuid>
<RootNamespace>ProjectAiSD</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared" >
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup></ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Исходные файлы">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Файлы заголовков">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Файлы ресурсов">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
</Project>

View File

@ -1,249 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHoistingCrane;
public class DrawningHoistingCrane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityHoistingCrane? EntityHoistingCrane { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
private int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
private int? _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _drawningCraneWidth = 110;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _drawningCraneHeight = 56;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="counterweight">Признак наличия противовеса</param>
/// <param name="crane">Признак наличия крана</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool counterweight, bool crane)
{
EntityHoistingCrane = new EntityHoistingCrane();
EntityHoistingCrane.Init(speed, weight, bodyColor, additionalColor,
counterweight, crane);
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (width <= _drawningCraneWidth || height <= _drawningCraneHeight)
{
return false;
}
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null || _startPosY != null)
{
if (_startPosX + _drawningCraneWidth > _pictureWidth) _startPosX = _pictureWidth - _drawningCraneWidth;
if (_startPosY + _drawningCraneHeight > _pictureHeight) _startPosY = _pictureHeight - _drawningCraneHeight;
if (_startPosX < 0) _startPosX = 0;
if (_startPosY < 0) _startPosY = 0;
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
// TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
_startPosX = x;
_startPosY = y;
if (_startPosX + _drawningCraneWidth > _pictureWidth) _startPosX = _pictureWidth - _drawningCraneWidth;
if (_startPosY + _drawningCraneHeight > _pictureHeight) _startPosY = _pictureHeight - _drawningCraneHeight;
if (_startPosX < 0) _startPosX = 0;
if (_startPosY < 0) _startPosY = 0;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityHoistingCrane == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityHoistingCrane.Step > 0)
{
_startPosX -= (int)EntityHoistingCrane.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityHoistingCrane.Step > 0)
{
_startPosY -= (int)EntityHoistingCrane.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + EntityHoistingCrane.Step < _pictureWidth - _drawningCraneWidth)
{
_startPosX += (int)EntityHoistingCrane.Step;
}
//TODO прописать логику сдвига в право
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityHoistingCrane.Step < _pictureHeight - _drawningCraneHeight)
{
_startPosY += (int)EntityHoistingCrane.Step;
}
//TODO прописать логику сдвига в вниз
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntityHoistingCrane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(EntityHoistingCrane.AdditionalColor);
Brush BodyBrush = new SolidBrush(EntityHoistingCrane.BodyColor);
Brush CraneBrush = new SolidBrush(Color.Black);
//корпус
g.FillRectangle(BodyBrush, _startPosX.Value + 10, _startPosY.Value + 30, 62, 12);
g.DrawRectangle(pen, _startPosX.Value + 10, _startPosY.Value + 30, 62, 12);
g.FillRectangle(BodyBrush, _startPosX.Value + 22, _startPosY.Value + 16, 4, 15);
g.DrawRectangle(pen, _startPosX.Value + 22, _startPosY.Value + 16, 4, 14);
g.FillRectangle(BodyBrush, _startPosX.Value + 37, _startPosY.Value + 8, 5, 23);
g.DrawRectangle(pen, _startPosX.Value + 37, _startPosY.Value + 8, 5, 22);
//стекло
g.FillRectangle(additionalBrush, _startPosX.Value + 52, _startPosY.Value + 14, 21, 16);
g.DrawRectangle(pen, _startPosX.Value + 52, _startPosY.Value + 14, 20, 16);
//гусеницы
g.DrawLine(pen, _startPosX.Value + 8, _startPosY.Value + 42, _startPosX.Value + 10, _startPosY.Value + 42);
g.DrawLine(pen, _startPosX.Value + 7, _startPosY.Value + 43, _startPosX.Value + 7, _startPosY.Value + 53);
g.DrawLine(pen, _startPosX.Value + 8, _startPosY.Value + 54, _startPosX.Value + 12, _startPosY.Value + 54);
g.DrawLine(pen, _startPosX.Value + 13, _startPosY.Value + 55, _startPosX.Value + 69, _startPosY.Value + 55);
g.DrawLine(pen, _startPosX.Value + 70, _startPosY.Value + 54, _startPosX.Value + 73, _startPosY.Value + 54);
g.DrawLine(pen, _startPosX.Value + 74, _startPosY.Value + 53, _startPosX.Value + 74, _startPosY.Value + 43);
g.DrawLine(pen, _startPosX.Value + 71, _startPosY.Value + 42, _startPosX.Value + 73, _startPosY.Value + 42);
//колеса
g.FillEllipse(BodyBrush, _startPosX.Value + 10, _startPosY.Value + 44, 9, 9);
g.DrawEllipse(pen, _startPosX.Value + 10, _startPosY.Value + 44, 9, 9);
g.FillEllipse(BodyBrush, _startPosX.Value + 63, _startPosY.Value + 44, 9, 9);
g.DrawEllipse(pen, _startPosX.Value + 63, _startPosY.Value + 44, 9, 9);
g.FillEllipse(BodyBrush, _startPosX.Value + 25, _startPosY.Value + 48, 6, 6);
g.DrawEllipse(pen, _startPosX.Value + 25, _startPosY.Value + 48, 6, 6);
g.FillEllipse(BodyBrush, _startPosX.Value + 38, _startPosY.Value + 48, 6, 6);
g.DrawEllipse(pen, _startPosX.Value + 38, _startPosY.Value + 48, 6, 6);
g.FillEllipse(BodyBrush, _startPosX.Value + 50, _startPosY.Value + 48, 6, 6);
g.DrawEllipse(pen, _startPosX.Value + 50, _startPosY.Value + 48, 6, 6);
g.FillEllipse(BodyBrush, _startPosX.Value + 33, _startPosY.Value + 44, 4, 4);
g.DrawEllipse(pen, _startPosX.Value + 33, _startPosY.Value + 44, 4, 4);
g.FillEllipse(BodyBrush, _startPosX.Value + 45, _startPosY.Value + 44, 4, 4);
g.DrawEllipse(pen, _startPosX.Value + 45, _startPosY.Value + 44, 4, 4);
//кран
if (EntityHoistingCrane.Crane)
{
//балка
g.FillRectangle(BodyBrush, _startPosX.Value, _startPosY.Value, 110, 9);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 109, 8);
//крюк
g.FillRectangle(CraneBrush , _startPosX.Value + 107, _startPosY.Value + 8, 3, 13);
g.FillRectangle(CraneBrush, _startPosX.Value + 102, _startPosY.Value + 18, 8, 3);
g.FillRectangle(CraneBrush, _startPosX.Value + 102, _startPosY.Value + 16, 3, 5);
}
//противовес
if (EntityHoistingCrane.Сounterweight)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value, 10, 9);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value, 9, 8);
g.DrawLine(pen, _startPosX.Value + 35, _startPosY.Value + 2, _startPosX.Value + 44, _startPosY.Value + 2);
g.DrawLine(pen, _startPosX.Value + 35, _startPosY.Value + 4, _startPosX.Value + 44, _startPosY.Value + 4);
g.DrawLine(pen, _startPosX.Value + 35, _startPosY.Value + 6, _startPosX.Value + 44, _startPosY.Value + 6);
}
}
}

View File

@ -4,13 +4,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHoistingCrane;
namespace ProjectHoistingCrane.Drawnings;
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Неизвестное направление
/// </summary>
Unknow = -1,
/// <summary>
/// Вверх
/// </summary>

View File

@ -0,0 +1,252 @@
using ProjectHoistingCrane.Entities;
namespace ProjectHoistingCrane.Drawnings;
public class DrawningCrane
Review

Имя элемента проекта не соответствует указанному в задании

Имя элемента проекта не соответствует указанному в задании
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityCrane? EntityCrane { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _drawningCraneWidth = 68;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _drawningCraneHeight = 48;
/// <summary>
/// Координата X объекта
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningCraneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningCraneHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningCrane()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningCrane(int speed, double weight, Color bodyColor) : this()
{
EntityCrane = new EntityCrane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningCraneWidth">Ширина прорисовки крана</param>
/// <param name="drawningCraneHeight">Высота прорисовки крана</param>
protected DrawningCrane(int drawningCraneWidth, int drawningCraneHeight) : this()
{
_drawningCraneWidth = drawningCraneWidth;
_drawningCraneHeight = drawningCraneHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height)
{
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (width <= _drawningCraneWidth || height <= _drawningCraneHeight)
{
return false;
}
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null || _startPosY != null)
{
if (_startPosX + _drawningCraneWidth > _pictureWidth) _startPosX = _pictureWidth - _drawningCraneWidth;
if (_startPosY + _drawningCraneHeight > _pictureHeight) _startPosY = _pictureHeight - _drawningCraneHeight;
if (_startPosX < 0) _startPosX = 0;
if (_startPosY < 0) _startPosY = 0;
}
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
// TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
_startPosX = x;
_startPosY = y;
if (_startPosX + _drawningCraneWidth > _pictureWidth) _startPosX = _pictureWidth - _drawningCraneWidth;
if (_startPosY + _drawningCraneHeight > _pictureHeight) _startPosY = _pictureHeight - _drawningCraneHeight;
if (_startPosX < 0) _startPosX = 0;
if (_startPosY < 0) _startPosY = 0;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - перемещене выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction)
{
if (EntityCrane == null || !_startPosX.HasValue ||
!_startPosY.HasValue)
{
return false;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityCrane.Step > 0)
{
_startPosX -= (int)EntityCrane.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityCrane.Step > 0)
{
_startPosY -= (int)EntityCrane.Step;
}
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + EntityCrane.Step < _pictureWidth - _drawningCraneWidth)
{
_startPosX += (int)EntityCrane.Step;
}
//TODO прописать логику сдвига в право
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + EntityCrane.Step < _pictureHeight - _drawningCraneHeight)
{
_startPosY += (int)EntityCrane.Step;
}
//TODO прописать логику сдвига в вниз
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityCrane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush BodyBrush = new SolidBrush(EntityCrane.BodyColor);
Brush WindowBrush = new SolidBrush(Color.Blue);
//корпус
g.FillRectangle(BodyBrush, _startPosX.Value + 3, _startPosY.Value + 22, 62, 12);
g.DrawRectangle(pen, _startPosX.Value + 3, _startPosY.Value + 22, 62, 12);
g.FillRectangle(BodyBrush, _startPosX.Value + 15, _startPosY.Value + 8, 4, 15);
g.DrawRectangle(pen, _startPosX.Value + 15, _startPosY.Value + 8, 4, 14);
g.FillRectangle(BodyBrush, _startPosX.Value + 30, _startPosY.Value, 5, 23);
g.DrawRectangle(pen, _startPosX.Value + 30, _startPosY.Value, 5, 22);
//стекло
g.FillRectangle(WindowBrush, _startPosX.Value + 45, _startPosY.Value + 6, 21, 16);
g.DrawRectangle(pen, _startPosX.Value + 45, _startPosY.Value + 6, 20, 16);
//гусеницы
g.DrawLine(pen, _startPosX.Value + 1, _startPosY.Value + 34, _startPosX.Value + 3, _startPosY.Value + 34);
g.DrawLine(pen, _startPosX.Value, _startPosY.Value + 35, _startPosX.Value, _startPosY.Value + 45);
g.DrawLine(pen, _startPosX.Value + 1, _startPosY.Value + 46, _startPosX.Value + 5, _startPosY.Value + 46);
g.DrawLine(pen, _startPosX.Value + 6, _startPosY.Value + 47, _startPosX.Value + 62, _startPosY.Value + 47);
g.DrawLine(pen, _startPosX.Value + 63, _startPosY.Value + 46, _startPosX.Value + 66, _startPosY.Value + 46);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value + 45, _startPosX.Value + 67, _startPosY.Value + 35);
g.DrawLine(pen, _startPosX.Value + 64, _startPosY.Value + 34, _startPosX.Value + 66, _startPosY.Value + 34);
//колеса
g.FillEllipse(BodyBrush, _startPosX.Value + 3, _startPosY.Value + 36, 9, 9);
g.DrawEllipse(pen, _startPosX.Value + 3, _startPosY.Value + 36, 9, 9);
g.FillEllipse(BodyBrush, _startPosX.Value + 56, _startPosY.Value + 36, 9, 9);
g.DrawEllipse(pen, _startPosX.Value + 56, _startPosY.Value + 36, 9, 9);
g.FillEllipse(BodyBrush, _startPosX.Value + 18, _startPosY.Value + 40, 6, 6);
g.DrawEllipse(pen, _startPosX.Value + 18, _startPosY.Value + 40, 6, 6);
g.FillEllipse(BodyBrush, _startPosX.Value + 31, _startPosY.Value + 40, 6, 6);
g.DrawEllipse(pen, _startPosX.Value + 31, _startPosY.Value + 40, 6, 6);
g.FillEllipse(BodyBrush, _startPosX.Value + 43, _startPosY.Value + 40, 6, 6);
g.DrawEllipse(pen, _startPosX.Value + 43, _startPosY.Value + 40, 6, 6);
g.FillEllipse(BodyBrush, _startPosX.Value + 26, _startPosY.Value + 36, 4, 4);
g.DrawEllipse(pen, _startPosX.Value + 26, _startPosY.Value + 36, 4, 4);
g.FillEllipse(BodyBrush, _startPosX.Value + 38, _startPosY.Value + 36, 4, 4);
g.DrawEllipse(pen, _startPosX.Value + 38, _startPosY.Value + 36, 4, 4);
}
}

View File

@ -0,0 +1,76 @@
using ProjectHoistingCrane.Entities;
namespace ProjectHoistingCrane.Drawnings;
public class DrawningHoistingCrane : DrawningCrane
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="counterweight">Признак наличия противовеса</param>
/// <param name="crane">Признак наличия крана</param>
public DrawningHoistingCrane(int speed, double weight, Color bodyColor, Color additionalColor, bool counterweight, bool crane) : base(110, 56)
{
EntityCrane = new EntityHoistingCrane(speed, weight, bodyColor, additionalColor,
counterweight, crane);
}
public override void DrawTransport(Graphics g)
{
if (EntityCrane == null || EntityCrane is not EntityHoistingCrane hoistingCrane || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(hoistingCrane.AdditionalColor);
_startPosX += 7;
_startPosY += 8;
base.DrawTransport(g);
_startPosX -= 7;
_startPosY -= 8;
//кран
if (hoistingCrane.Crane)
{
//балка
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value, 110, 9);
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value, 109, 8);
//крюк
g.FillRectangle(additionalBrush, _startPosX.Value + 107, _startPosY.Value + 8, 3, 13);
g.FillRectangle(additionalBrush, _startPosX.Value + 102, _startPosY.Value + 18, 8, 3);
g.FillRectangle(additionalBrush, _startPosX.Value + 102, _startPosY.Value + 16, 3, 5);
}
//противовес
if (hoistingCrane.Сounterweight)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 35, _startPosY.Value, 10, 9);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value, 9, 8);
g.DrawLine(pen, _startPosX.Value + 35, _startPosY.Value + 2, _startPosX.Value + 44, _startPosY.Value + 2);
g.DrawLine(pen, _startPosX.Value + 35, _startPosY.Value + 4, _startPosX.Value + 44, _startPosY.Value + 4);
g.DrawLine(pen, _startPosX.Value + 35, _startPosY.Value + 6, _startPosX.Value + 44, _startPosY.Value + 6);
}
}
}
Review

Много пустых строк

Много пустых строк

View File

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

View File

@ -1,25 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectHoistingCrane.Drawnings;
namespace ProjectHoistingCrane.Entities;
namespace ProjectHoistingCrane;
public class EntityHoistingCrane
public class EntityHoistingCrane : EntityCrane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
@ -32,12 +15,9 @@ public class EntityHoistingCrane
/// Признак (опция) наличия крана
/// </summary>
public bool Crane { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
@ -45,11 +25,8 @@ public class EntityHoistingCrane
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="counterweight">Признак наличия обвеса</param>
/// <param name="crane">Признак наличия крана</param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool counterweight, bool crane)
public EntityHoistingCrane(int speed, double weight, Color bodyColor, Color additionalColor, bool counterweight, bool crane):base(speed, weight, bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Сounterweight = counterweight;
Crane = crane;

View File

@ -1,94 +0,0 @@
namespace ProjectHoistingCrane
{
public partial class Form1 : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningHoistingCrane? _drawningHoistingCrane;
/// <summary>
/// Êîíñòðóêòîð ôîðìû
/// </summary>
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè êðàíà
/// </summary>
private void Draw()
{
if (_drawningHoistingCrane == null)
{
return;
}
Bitmap bmp = new(pictureBoxHoistingCrane.Width,
pictureBoxHoistingCrane.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningHoistingCrane.DrawTransport(gr);
pictureBoxHoistingCrane.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawningHoistingCrane = new DrawningHoistingCrane();
_drawningHoistingCrane.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)));
_drawningHoistingCrane.SetPictureSize(pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height);
_drawningHoistingCrane.SetPosition(random.Next(10, 100), random.Next(10, 100));
//_drawningHoistingCrane.SetPosition(random.Next(pictureBoxHoistingCrane.Width - 210, pictureBoxHoistingCrane.Width - 66), random.Next(10, 100));
Draw();
}
/// <summary>
/// Ïåðåìåùåíèå îáúåêòà ïî ôîðìå (íàæàòèå êíîïîê íàâèãàöèè)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningHoistingCrane == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result =
_drawningHoistingCrane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningHoistingCrane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningHoistingCrane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningHoistingCrane.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
}
}

View File

@ -1,6 +1,6 @@
namespace ProjectHoistingCrane
{
partial class Form1
partial class FormHoistingCrane
{
/// <summary>
/// Required designer variable.
@ -30,11 +30,14 @@
{
pictureBox1 = new PictureBox();
pictureBoxHoistingCrane = new PictureBox();
buttonCreate = new Button();
buttonCreateHoistingCrane = new Button();
buttonLeft = new Button();
buttonUp = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonCreateCrane = new Button();
comboBoxStrategy = new ComboBox();
StepButton = new Button();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxHoistingCrane).BeginInit();
SuspendLayout();
@ -59,16 +62,16 @@
pictureBoxHoistingCrane.TabIndex = 1;
pictureBoxHoistingCrane.TabStop = false;
//
// buttonCreate
// buttonCreateHoistingCrane
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(24, 402);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29);
buttonCreate.TabIndex = 2;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
buttonCreateHoistingCrane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateHoistingCrane.Location = new Point(24, 402);
buttonCreateHoistingCrane.Name = "buttonCreateHoistingCrane";
buttonCreateHoistingCrane.Size = new Size(210, 29);
buttonCreateHoistingCrane.TabIndex = 2;
buttonCreateHoistingCrane.Text = "Создать подъёмный кран";
buttonCreateHoistingCrane.UseVisualStyleBackColor = true;
buttonCreateHoistingCrane.Click += buttonCreateHoistingCrane_Click;
//
// buttonLeft
//
@ -118,22 +121,55 @@
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// Form1
// buttonCreateCrane
//
buttonCreateCrane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateCrane.Location = new Point(240, 401);
buttonCreateCrane.Name = "buttonCreateCrane";
buttonCreateCrane.Size = new Size(210, 29);
buttonCreateCrane.TabIndex = 7;
buttonCreateCrane.Text = "Создать кран";
buttonCreateCrane.UseVisualStyleBackColor = true;
buttonCreateCrane.Click += buttonCreateCrane_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Стратегия движения к центру", "Стратегия движения в угол" });
comboBoxStrategy.Location = new Point(413, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(257, 28);
comboBoxStrategy.TabIndex = 8;
//
// StepButton
//
StepButton.Location = new Point(576, 46);
StepButton.Name = "StepButton";
StepButton.Size = new Size(94, 35);
StepButton.TabIndex = 10;
StepButton.Text = "Шаг";
StepButton.UseVisualStyleBackColor = true;
StepButton.Click += ButtonStrategyStep_Click;
//
// FormHoistingCrane
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(682, 453);
Controls.Add(StepButton);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateCrane);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonCreate);
Controls.Add(buttonCreateHoistingCrane);
Controls.Add(pictureBoxHoistingCrane);
Controls.Add(pictureBox1);
Name = "Form1";
Name = "FormHoistingCrane";
StartPosition = FormStartPosition.CenterScreen;
Text = "Form1";
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxHoistingCrane).EndInit();
ResumeLayout(false);
@ -144,10 +180,13 @@
private PictureBox pictureBox1;
private PictureBox pictureBoxHoistingCrane;
private Button buttonCreate;
private Button buttonCreateHoistingCrane;
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonCreateCrane;
private ComboBox comboBoxStrategy;
private Button StepButton;
}
}

View File

@ -0,0 +1,170 @@
using ProjectHoistingCrane.Drawnings;
using ProjectHoistingCrane.MovementStrategy;
namespace ProjectHoistingCrane;
public partial class FormHoistingCrane : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningCrane? _drawningCrane;
/// <summary>
/// Êîíñòðóêòîð ôîðìû
/// </summary>
///<summary>
///Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Êîíñòðóêòîð ôîðìû
/// </summary>
public FormHoistingCrane()
{
InitializeComponent();
_strategy = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè êðàíà
/// </summary>
private void Draw()
{
if (_drawningCrane == null)
{
return;
}
Bitmap bmp = new(pictureBoxHoistingCrane.Width,
pictureBoxHoistingCrane.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningCrane.DrawTransport(gr);
pictureBoxHoistingCrane.Image = bmp;
}
/// <summary>
/// Ñîçäàíèå îáúåêòà êëàññà-ïåðåìåùåíèÿ
/// </summary>
/// <param name="type"> Òèï ñîçäàâàåìîãî îáúåêòà </param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningCrane):
_drawningCrane = new DrawningCrane(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(DrawningHoistingCrane):
_drawningCrane = new DrawningHoistingCrane(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;
}
_drawningCrane.SetPictureSize(pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height);
_drawningCrane.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü ïîäú¸ìíûé êðàí"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateHoistingCrane_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningHoistingCrane));
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü êðàí"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCrane_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningCrane));
}
/// <summary>
/// Ïåðåìåùåíèå îáúåêòà ïî ôîðìå (íàæàòèå êíîïîê íàâèãàöèè)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningCrane == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result =
_drawningCrane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result =
_drawningCrane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result =
_drawningCrane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result =
_drawningCrane.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningCrane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableCrane(_drawningCrane), pictureBoxHoistingCrane.Width, pictureBoxHoistingCrane.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}

View File

@ -0,0 +1,124 @@
namespace ProjectHoistingCrane.MovementStrategy;
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private StrategyStatus _state = StrategyStatus.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public StrategyStatus GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(MovementDirection.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(MovementDirection.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveDown() => MoveTo(MovementDirection.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="movementDirection">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHoistingCrane.MovementStrategy;
public interface IMoveableObject
{
/// <summary>
/// Получение координаты объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Попытка переместить объект в указанном направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - объект перемещен, false - перемещение невозможно</returns>
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,34 @@
namespace ProjectHoistingCrane.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth && 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())
{
MoveRight();
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,52 @@
namespace ProjectHoistingCrane.MovementStrategy;
/// <summary>
/// Стратегия перемещения объекта к центру экрана
/// </summary>
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();
}
}
}
}

View File

@ -0,0 +1,62 @@
using ProjectHoistingCrane.Drawnings;
namespace ProjectHoistingCrane.MovementStrategy;
///<summary>
///Класс-реализация IMoveableObject с использованием DrawningCrane
///</summary>
public class MoveableCrane : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningCrane или его наследника
/// </summary>
private readonly DrawningCrane? _crane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="сrane">Объект класса DrawningCrane</param>
public MoveableCrane(DrawningCrane crane)
{
_crane = crane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_crane == null || _crane.EntityCrane == null || !_crane.GetPosX.HasValue || !_crane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_crane.GetPosX.Value, _crane.GetPosY.Value, _crane.GetWidth, _crane.GetHeight);
}
}
public int GetStep => (int)(_crane?.EntityCrane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_crane == null || _crane.EntityCrane == null)
{
return false;
}
return _crane.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
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,
};
}
}

View File

@ -0,0 +1,21 @@
namespace ProjectHoistingCrane.MovementStrategy;
public enum MovementDirection
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHoistingCrane.MovementStrategy;
public class ObjectParameters
{
/// <summary>
/// Координата X
/// </summary>
private readonly int _x;
/// <summary>
/// Координата Y
/// </summary>
private readonly int _y;
/// <summary>
/// Ширина объекта
/// </summary>
private readonly int _width;
/// <summary>
/// Высота объекта
/// </summary>
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина объекта</param>
/// <param name="height">Высота объекта</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@ -0,0 +1,17 @@
namespace ProjectHoistingCrane.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Все готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}

View File

@ -11,7 +11,7 @@ namespace ProjectHoistingCrane
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
Application.Run(new FormHoistingCrane());
}
}
}