Compare commits

...

2 Commits

19 changed files with 1093 additions and 169 deletions

31
Project1/Project1.sln Normal file
View File

@ -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}") = "Project1", "Project1\Project1.vcxproj", "{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}"
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
{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}.Debug|x64.ActiveCfg = Debug|x64
{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}.Debug|x64.Build.0 = Debug|x64
{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}.Debug|x86.ActiveCfg = Debug|Win32
{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}.Debug|x86.Build.0 = Debug|Win32
{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}.Release|x64.ActiveCfg = Release|x64
{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}.Release|x64.Build.0 = Release|x64
{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}.Release|x86.ActiveCfg = Release|Win32
{51322AFD-5D22-49A7-BC85-AC24DACBAEE8}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {188BD3AE-A59B-46F9-AEC9-A67BF38B0430}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,135 @@
<?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>{51322afd-5d22-49a7-bc85-ac24dacbaee8}</ProjectGuid>
<RootNamespace>Project1</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>
<ClCompile Include="sove.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?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>
<ItemGroup>
<ClCompile Include="sove.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,56 @@
#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <cassert>
#include <math.h>
#include <numeric>
#include <ctime>
#include <time.h>
#include <deque>
#include <tuple>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef long double ld;
typedef pair<long long, long long> pll;
typedef pair<int, int> pii;
const ll LINF = 100090009990;
const int INF = 1009000999;
const int N = 1002;
const int M = 1002;
const ld PI = 3.1415926535;
const ld E = 2.7182818284;
const ll MOD = 1000000007;
const int MAX = 150010;
const ld EPS = 1e-10;
int main()
{
vector<string> Buttons{ "A", "B","C", "D", "L1", "L2", "R1", "R2" };
vector<string> ButtonsAns{ "A", "B","C", "D", "L1", "L2", "R1", "R2" };
vector<string> used, unused;
int stick;
return 0;
}

View File

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

View File

@ -0,0 +1,84 @@

using ProjectElectricLocomotive.Entities;
namespace ProjectElectricLocomotive.Drawnings;
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта - сущности
/// </summary>
public class DrawningElectricLocomotive : DrawningLocomotive
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="bodyKit"></param>
/// <param name="electricHorns"></param>
/// <param name="batteryPlacement"></param>
public DrawningElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) : base(83,45)
{
EntityLocomotive = new EntityElectricLocomotive(speed, weight, bodyColor, additionalColor, electricHorns, batteryPlacement);
}
public override void DrawTransport(Graphics g)
{
if (EntityLocomotive == null || EntityLocomotive is not EntityElectricLocomotive electricLocomotive || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
//Создание перьев и кистей для прорисовки электровоза
Brush blackBrush = new SolidBrush(Color.Black);
Pen penSolid = new(Color.Black, 2);
Pen penSolidYellow = new(Color.Yellow, 0.5f);
Brush additionalBrush = new SolidBrush(electricLocomotive.AdditionalColor);
//Прорисовка дополнительного элемента (рогов)
if (electricLocomotive.ElectricHorns)
{
//Инициализация опорных точек для прорисовки "рогов"
Point pointHorns1 = new Point(_startPosX.Value + 13, _startPosY.Value + 5);
Point pointHorns2 = new Point(_startPosX.Value + 16, _startPosY.Value + 2);
Point pointHorns3 = new Point(_startPosX.Value + 11, _startPosY.Value);
//Прорисовка "рогов" электровоза
g.DrawLine(penSolid, pointHorns1, pointHorns2);
g.DrawLine(penSolid, pointHorns2, pointHorns3);
}
//Прорисовка дополнительного элемента (места под батарею)
if (electricLocomotive.BatteryPlacement)
{
//Инициализация опорных точек для прорисовки молнии на хранилище батарей
Point pointLightning1 = new Point(_startPosX.Value + 39, _startPosY.Value + 37);
Point pointLightning2 = new Point(_startPosX.Value + 37, _startPosY.Value + 39);
Point pointLightning3 = new Point(_startPosX.Value + 39, _startPosY.Value + 40);
Point pointLightning4 = new Point(_startPosX.Value + 37, _startPosY.Value + 41);
//Прорисовка "хранилища батарей" электровоза
g.FillRectangle(blackBrush, _startPosX.Value + 36, _startPosY.Value + 37, 8, 4.5f);
g.DrawLine(penSolidYellow, pointLightning1, pointLightning2);
g.DrawLine(penSolidYellow, pointLightning2, pointLightning3);
g.DrawLine(penSolidYellow, pointLightning3, pointLightning4);
}
_startPosY += 5;
base.DrawTransport(g);
_startPosY -= 5;
//Опциональная прорисовка цвета передних колёс
g.FillEllipse(additionalBrush, _startPosX.Value + 9, _startPosY.Value + 37, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 24, _startPosY.Value + 37, 8, 8);
//Опциональная прорисовка цвета задних колёс
g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 26, _startPosY.Value + 37, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 37, _startPosY.Value + 37, 8, 8);
}
}

View File

@ -1,15 +1,18 @@
 using ProjectElectricLocomotive.Entities;
namespace ProjectElectricLocomotive; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary> namespace ProjectElectricLocomotive.Drawnings;
/// Класс, отвечающий за прорисовку и перемещение объекта - сущности
/// </summary> public class DrawningLocomotive
public class DrawningElectricLocomotive
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityElectricLocomotive? EntityElectricLocomotive { get; private set; } public EntityLocomotive? EntityLocomotive { get; protected set; }
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@ -22,47 +25,81 @@ public class DrawningElectricLocomotive
private int? _pictureHeight; private int? _pictureHeight;
/// <summary> /// <summary>
/// Левая координата прорисовки электровоза /// Левая координата прорисовки локомотива
/// </summary> /// </summary>
private int? _startPosX; protected int? _startPosX;
/// <summary> /// <summary>
/// Верхняя координата прорисовки электровоза /// Верхняя координата прорисовки локомотива
/// </summary> /// </summary>
private int? _startPosY; protected int? _startPosY;
/// <summary> /// <summary>
/// Ширина прорисовки электровоза /// Ширина прорисовки локомотива
/// </summary> /// </summary>
private readonly int _drawningElectricLocomotiveWidth = 83; private readonly int _drawningLocomotiveWidth = 83;
/// <summary> /// <summary>
/// Высота прорисовки электровоза /// Высота прорисовки локомотива
/// </summary> /// </summary>
private readonly int _drawningElectricLocomotiveHeight = 45; private readonly int _drawningLocomotiveHeight = 40;
/// <summary> /// <summary>
/// Инициализация свойств /// Координата X объекта
/// </summary> /// </summary>
/// <param name="speed"></param> public int? GetPosX => _startPosX;
/// <param name="weight"></param>
/// <param name="bodyColor"></param> /// <summary>
/// <param name="additionalColor"></param> /// Координата Y объекта
/// <param name="bodyKit"></param> /// </summary>
/// <param name="electricHorns"></param> public int? GetPosY => _startPosY;
/// <param name="batteryPlacement"></param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) /// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningLocomotiveWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningLocomotiveHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningLocomotive()
{ {
EntityElectricLocomotive = new EntityElectricLocomotive();
EntityElectricLocomotive.Init(speed, weight, bodyColor, additionalColor, electricHorns, batteryPlacement);
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
_startPosX = null; _startPosX = null;
_startPosY = null; _startPosY = null;
} }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public DrawningLocomotive(int speed, double weight, Color bodyColor) : this()
{
EntityLocomotive = new EntityLocomotive(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>
/// <param name="drawningLocomotiveWidth">Ширина прорисовки локомотива</param>
/// <param name="drawningLocomotiveHeight">Высота прорисовки локомотива</param>
protected DrawningLocomotive(int drawningLocomotiveWidth, int drawningLocomotiveHeight) : this()
{
_drawningLocomotiveWidth = drawningLocomotiveWidth;
_drawningLocomotiveHeight = drawningLocomotiveHeight;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>
@ -71,19 +108,19 @@ public class DrawningElectricLocomotive
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns> /// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {
if(_drawningElectricLocomotiveHeight > height || _drawningElectricLocomotiveWidth > width) if (_drawningLocomotiveHeight > height || _drawningLocomotiveWidth > width)
{ {
return false; return false;
} }
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
if (_startPosY.HasValue && _startPosY + _drawningElectricLocomotiveHeight < _pictureHeight ) if (_startPosY.HasValue && _startPosY + _drawningLocomotiveHeight < _pictureHeight)
{ {
_startPosY = _pictureHeight - _drawningElectricLocomotiveHeight; _startPosY = _pictureHeight - _drawningLocomotiveHeight;
} }
if (_startPosX.HasValue && _startPosX + _drawningElectricLocomotiveWidth < _pictureWidth ) if (_startPosX.HasValue && _startPosX + _drawningLocomotiveWidth < _pictureWidth)
{ {
_startPosX = _pictureWidth - _drawningElectricLocomotiveWidth; _startPosX = _pictureWidth - _drawningLocomotiveWidth;
} }
return true; return true;
} }
@ -95,7 +132,8 @@ public class DrawningElectricLocomotive
/// <param name="y">Координата Y</param> /// <param name="y">Координата Y</param>
public void SetPosition(int x, int y) public void SetPosition(int x, int y)
{ {
if(!_pictureHeight.HasValue || !_pictureWidth.HasValue) { if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return; return;
} }
@ -105,13 +143,13 @@ public class DrawningElectricLocomotive
if ( _drawningElectricLocomotiveHeight + y > _pictureHeight) if (_drawningLocomotiveHeight + y > _pictureHeight)
{ {
_startPosY = _pictureHeight - _drawningElectricLocomotiveHeight; _startPosY = _pictureHeight - _drawningLocomotiveHeight;
} }
if ( _drawningElectricLocomotiveWidth + x > _pictureWidth) if (_drawningLocomotiveWidth + x > _pictureWidth)
{ {
_startPosX = _pictureWidth - _drawningElectricLocomotiveWidth; _startPosX = _pictureWidth - _drawningLocomotiveWidth;
} }
if (x < 0) if (x < 0)
{ {
@ -133,39 +171,39 @@ public class DrawningElectricLocomotive
/// <returns>true - перемещение выполнено, false - перемещение невозможно</returns> /// <returns>true - перемещение выполнено, false - перемещение невозможно</returns>
public bool MoveTransport(DirectionType direction) public bool MoveTransport(DirectionType direction)
{ {
if(EntityElectricLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return false; return false;
} }
switch(direction) switch (direction)
{ {
//влево //влево
case DirectionType.Left: case DirectionType.Left:
if(_startPosX.Value - EntityElectricLocomotive.Step > 0) if (_startPosX.Value - EntityLocomotive.Step > 0)
{ {
_startPosX -= (int)EntityElectricLocomotive.Step; _startPosX -= (int)EntityLocomotive.Step;
} }
return true; return true;
//вверх //вверх
case DirectionType.Up: case DirectionType.Up:
if(_startPosY.Value - EntityElectricLocomotive.Step > 0) if (_startPosY.Value - EntityLocomotive.Step > 0)
{ {
_startPosY -= (int)EntityElectricLocomotive.Step; _startPosY -= (int)EntityLocomotive.Step;
} }
return true; return true;
//вправо //вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + _drawningElectricLocomotiveWidth + EntityElectricLocomotive.Step < _pictureWidth) if (_startPosX.Value + _drawningLocomotiveWidth + EntityLocomotive.Step < _pictureWidth)
{ {
_startPosX += (int)EntityElectricLocomotive.Step; _startPosX += (int)EntityLocomotive.Step;
} }
return true; return true;
//вниз //вниз
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + _drawningElectricLocomotiveHeight + EntityElectricLocomotive.Step < _pictureHeight) if (_startPosY.Value + _drawningLocomotiveHeight + EntityLocomotive.Step < _pictureHeight)
{ {
_startPosY += (int)EntityElectricLocomotive.Step; _startPosY += (int)EntityLocomotive.Step;
} }
return true; return true;
default: default:
@ -177,9 +215,9 @@ public class DrawningElectricLocomotive
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
public void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntityElectricLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityLocomotive == null || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }
@ -189,25 +227,24 @@ public class DrawningElectricLocomotive
Pen penSolid = new(Color.Black, 2); Pen penSolid = new(Color.Black, 2);
Pen penSolidYellow = new(Color.Yellow, 0.5f); Pen penSolidYellow = new(Color.Yellow, 0.5f);
Pen windowPen = new(Color.DeepSkyBlue); Pen windowPen = new(Color.DeepSkyBlue);
Brush additionalBrush = new SolidBrush(EntityElectricLocomotive.AdditionalColor);
Brush blackBrush = new SolidBrush(Color.Black); Brush blackBrush = new SolidBrush(Color.Black);
Brush whiteBrush = new SolidBrush(Color.White); Brush whiteBrush = new SolidBrush(Color.White);
//Инициализация опорных точек для прорисовки корпуса //Инициализация опорных точек для прорисовки корпуса
Point pointStart = new Point(_startPosX.Value + 75, _startPosY.Value + 20); Point pointStart = new Point(_startPosX.Value + 75, _startPosY.Value + 15);
Point point1 = new Point(_startPosX.Value + 75, _startPosY.Value + 5); Point point1 = new Point(_startPosX.Value + 75, _startPosY.Value);
Point point2 = new Point(_startPosX.Value + 10, _startPosY.Value + 5); Point point2 = new Point(_startPosX.Value + 10, _startPosY.Value);
Point pointFinish = new Point(_startPosX.Value + 5, _startPosY.Value + 20); Point pointFinish = new Point(_startPosX.Value + 5, _startPosY.Value + 15);
//Инициализация опорных точек для прорисовки первой "юбки" //Инициализация опорных точек для прорисовки первой "юбки"
Point point3 = new Point(_startPosX.Value + 7, _startPosY.Value + 37); Point point3 = new Point(_startPosX.Value + 7, _startPosY.Value + 32);
Point point4 = new Point(_startPosX.Value + 0, _startPosY.Value + 37 +6 ); Point point4 = new Point(_startPosX.Value, _startPosY.Value + 32 + 6);
Point point5 = new Point(_startPosX.Value + 7, _startPosY.Value + 37 + 6 ); Point point5 = new Point(_startPosX.Value + 7, _startPosY.Value + 32 + 6);
//Инициализация опорных точек для прорисовки второй "юбки" //Инициализация опорных точек для прорисовки второй "юбки"
Point point6 = new Point(_startPosX.Value + 69, _startPosY.Value + 37); Point point6 = new Point(_startPosX.Value + 69, _startPosY.Value + 32);
Point point7 = new Point(_startPosX.Value + 75 + 7, _startPosY.Value + 37 + 6); Point point7 = new Point(_startPosX.Value + 75 + 7, _startPosY.Value + 32 + 6);
Point point8 = new Point(_startPosX.Value + 69, _startPosY.Value + 37 + 6); Point point8 = new Point(_startPosX.Value + 69, _startPosY.Value + 32 + 6);
//Совокупность точек полигона уголка первой "юбки" //Совокупность точек полигона уголка первой "юбки"
Point[] firstTrianglePoints = Point[] firstTrianglePoints =
@ -233,7 +270,7 @@ public class DrawningElectricLocomotive
g.FillPolygon(blackBrush, secondTrianglePoints); g.FillPolygon(blackBrush, secondTrianglePoints);
//Прорисовка корпуса //Прорисовка корпуса
g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 20, 70, 17); g.DrawRectangle(pen, _startPosX.Value + 5, _startPosY.Value + 15, 70, 17);
g.DrawLine(pen, point3, point4); g.DrawLine(pen, point3, point4);
g.DrawLine(pen, pointStart, point1); g.DrawLine(pen, pointStart, point1);
@ -242,68 +279,41 @@ public class DrawningElectricLocomotive
Brush brWhite = new SolidBrush(Color.White); Brush brWhite = new SolidBrush(Color.White);
g.DrawRectangle(windowPen, _startPosX.Value + 24.3f, _startPosY.Value + 9, 8, 8); g.DrawRectangle(windowPen, _startPosX.Value + 24.3f, _startPosY.Value + 4, 8, 8);
g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 14, 8, 12); g.DrawRectangle(pen, _startPosX.Value + 35, _startPosY.Value + 9, 8, 12);
g.FillRectangle(brWhite, _startPosX.Value + 36, _startPosY.Value + 16, 7, 10); g.FillRectangle(brWhite, _startPosX.Value + 36, _startPosY.Value + 11, 7, 10);
//Прорисовка передней и задней "юбки" //Прорисовка передней и задней "юбки"
g.FillRectangle(blackBrush, _startPosX.Value + 7, _startPosY.Value + 37, 25, 5.3f); g.FillRectangle(blackBrush, _startPosX.Value + 7, _startPosY.Value + 32, 25, 5.3f);
g.FillRectangle(blackBrush, _startPosX.Value + 47, _startPosY.Value + 37, 22, 5.3f); g.FillRectangle(blackBrush, _startPosX.Value + 47, _startPosY.Value + 32, 22, 5.3f);
//Прорисовка двух передних колёс //Прорисовка двух передних колёс
g.FillEllipse(whiteBrush, _startPosX.Value + 6.3f, _startPosY.Value + 37, 10, 10); g.FillEllipse(whiteBrush, _startPosX.Value + 6.3f, _startPosY.Value + 32, 10, 10);
g.DrawEllipse(penSolid, _startPosX.Value + 9, _startPosY.Value + 37, 8, 8); g.DrawEllipse(penSolid, _startPosX.Value + 9, _startPosY.Value + 32, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 9, _startPosY.Value + 37, 8, 8); g.DrawEllipse(penSolid, _startPosX.Value + 24, _startPosY.Value + 32, 8, 8);
g.DrawEllipse(penSolid, _startPosX.Value + 24, _startPosY.Value + 37, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 24, _startPosY.Value + 37, 8, 8);
//Прорисовка двух задних колёс //Прорисовка двух задних колёс
g.FillEllipse(whiteBrush, _startPosX.Value + 25 + 38, _startPosY.Value + 37, 10, 10); g.FillEllipse(whiteBrush, _startPosX.Value + 25 + 38, _startPosY.Value + 32, 10, 10);
g.DrawEllipse(penSolid, _startPosX.Value + 25 + 26, _startPosY.Value + 37, 8, 8); g.DrawEllipse(penSolid, _startPosX.Value + 25 + 26, _startPosY.Value + 32, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 26, _startPosY.Value + 37, 8, 8); g.DrawEllipse(penSolid, _startPosX.Value + 25 + 37, _startPosY.Value + 32, 8, 8);
g.DrawEllipse(penSolid, _startPosX.Value+ 25 + 37, _startPosY.Value + 37, 8, 8);
g.FillEllipse(additionalBrush, _startPosX.Value + 25 + 37, _startPosY.Value + 37, 8, 8);
//Прорисовка заднего "шлюза" //Прорисовка заднего "шлюза"
g.FillRectangle(blackBrush, _startPosX.Value + 75, _startPosY.Value + 9, 5.7f, 27.4f); g.FillRectangle(blackBrush, _startPosX.Value + 75, _startPosY.Value + 4, 5.7f, 27.4f);
//Прорисовка первого и третьего окна //Прорисовка первого и третьего окна
g.DrawRectangle(windowPen, _startPosX.Value + 12, _startPosY.Value + 9, 8, 8); g.DrawRectangle(windowPen, _startPosX.Value + 12, _startPosY.Value + 4, 8, 8);
g.DrawRectangle(windowPen, _startPosX.Value + 63, _startPosY.Value + 9, 8, 8); g.DrawRectangle(windowPen, _startPosX.Value + 63, _startPosY.Value + 4, 8, 8);
//Опциональная прорисовка цвета передних колёс
g.FillEllipse(whiteBrush, _startPosX.Value + 9, _startPosY.Value + 32, 8, 8);
g.FillEllipse(whiteBrush, _startPosX.Value + 24, _startPosY.Value + 32, 8, 8);
//Опциональная прорисовка цвета задних колёс
if (EntityElectricLocomotive.ElectricHorns) g.FillEllipse(whiteBrush, _startPosX.Value + 25 + 26, _startPosY.Value + 32, 8, 8);
{ g.FillEllipse(whiteBrush, _startPosX.Value + 25 + 37, _startPosY.Value + 32, 8, 8);
//Инициализация опорных точек для прорисовки "рогов"
Point pointHorns1 = new Point(_startPosX.Value + 13, _startPosY.Value + 5);
Point pointHorns2 = new Point(_startPosX.Value + 16, _startPosY.Value + 2);
Point pointHorns3 = new Point(_startPosX.Value + 11, _startPosY.Value);
//Прорисовка "рогов" электровоза
g.DrawLine(penSolid, pointHorns1, pointHorns2);
g.DrawLine(penSolid, pointHorns2, pointHorns3);
}
if(EntityElectricLocomotive.BatteryPlacement)
{
//Инициализация опорных точек для прорисовки молнии на хранилище батарей
Point pointLightning1 = new Point(_startPosX.Value + 39, _startPosY.Value + 37);
Point pointLightning2 = new Point(_startPosX.Value + 37, _startPosY.Value + 39);
Point pointLightning3 = new Point(_startPosX.Value + 39, _startPosY.Value + 40);
Point pointLightning4 = new Point(_startPosX.Value + 37, _startPosY.Value + 41);
//Прорисовка "хранилища батарей" электровоза
g.FillRectangle(blackBrush, _startPosX.Value + 36, _startPosY.Value + 37, 8, 4.5f);
g.DrawLine(penSolidYellow, pointLightning1, pointLightning2);
g.DrawLine(penSolidYellow, pointLightning2, pointLightning3);
g.DrawLine(penSolidYellow, pointLightning3, pointLightning4);
}
} }
} }

View File

@ -1,26 +1,11 @@
 
namespace ProjectElectricLocomotive; namespace ProjectElectricLocomotive.Entities;
/// <summary> /// <summary>
/// Класс-сущность "Тепловоз" /// Класс-сущность "Электровоз"
/// </summary> /// </summary>
public class EntityElectricLocomotive public class EntityElectricLocomotive : EntityLocomotive
{ {
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary> /// <summary>
/// Дополнительный цвет (для дополнительных элементов) /// Дополнительный цвет (для дополнительных элементов)
/// </summary> /// </summary>
@ -36,11 +21,6 @@ public class EntityElectricLocomotive
/// </summary> /// </summary>
public bool BatteryPlacement { get; private set; } public bool BatteryPlacement { get; private set; }
/// <summary>
/// Шаг перемещения объекта
/// </summary>
public double Step => Speed * 100 / Weight;
/// <summary> /// <summary>
/// Инициализация полей объекта-класса тепловоза /// Инициализация полей объекта-класса тепловоза
/// </summary> /// </summary>
@ -51,14 +31,10 @@ public class EntityElectricLocomotive
/// <param name="electrichorns"></param> /// <param name="electrichorns"></param>
/// <param name="batteryplacement"></param> /// <param name="batteryplacement"></param>
public void Init(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) public EntityElectricLocomotive(int speed, double weight, Color bodyColor, Color additionalColor, bool electricHorns, bool batteryPlacement) : base(speed, weight, bodyColor)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
ElectricHorns = electricHorns; ElectricHorns = electricHorns;
BatteryPlacement = batteryPlacement; BatteryPlacement = batteryPlacement;
} }
} }

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Entities;
/// <summary>
/// Класс-сущность "Локомотив"
/// </summary>
public class EntityLocomotive
{
/// <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>
/// Конструктор сущности
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public EntityLocomotive(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -34,6 +34,9 @@
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonCreateLocomotive = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectricLocomotive).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -49,11 +52,11 @@
// buttonCreate // buttonCreate
// //
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 430); buttonCreate.Location = new Point(12, 436);
buttonCreate.Name = "buttonCreate"; buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(104, 37); buttonCreate.Size = new Size(150, 31);
buttonCreate.TabIndex = 1; buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать"; buttonCreate.Text = "Создать электровоз";
buttonCreate.UseVisualStyleBackColor = true; buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click; buttonCreate.Click += ButtonCreate_Click;
// //
@ -109,11 +112,45 @@
buttonUp.UseVisualStyleBackColor = false; buttonUp.UseVisualStyleBackColor = false;
buttonUp.Click += ButtonMove_Click; buttonUp.Click += ButtonMove_Click;
// //
// buttonCreateLocomotive
//
buttonCreateLocomotive.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateLocomotive.Location = new Point(187, 436);
buttonCreateLocomotive.Name = "buttonCreateLocomotive";
buttonCreateLocomotive.Size = new Size(150, 31);
buttonCreateLocomotive.TabIndex = 6;
buttonCreateLocomotive.Text = "Создать локомотив";
buttonCreateLocomotive.UseVisualStyleBackColor = true;
buttonCreateLocomotive.Click += buttonCreateLocomotive_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(733, 24);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(764, 72);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(90, 33);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormElectricLocomotive // FormElectricLocomotive
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(866, 479); ClientSize = new Size(866, 479);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateLocomotive);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
@ -134,5 +171,8 @@
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonUp; private Button buttonUp;
private Button buttonCreateLocomotive;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -1,4 +1,6 @@
using System; using ProjectElectricLocomotive.Drawnings;
using ProjectElectricLocomotive.MovementStrategy;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -12,11 +14,20 @@ namespace ProjectElectricLocomotive;
public partial class FormElectricLocomotive : Form public partial class FormElectricLocomotive : Form
{ {
private DrawningElectricLocomotive? _drawningElectricLocomotive; /// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningLocomotive? _drawningLocomotive;
private AbstractStrategy? _strategy;
/// <summary>
/// Конструктор формы
/// </summary>
public FormElectricLocomotive() public FormElectricLocomotive()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
} }
/// <summary> /// <summary>
@ -24,33 +35,60 @@ public partial class FormElectricLocomotive : Form
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawningElectricLocomotive == null) if (_drawningLocomotive == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxElectricLocomotive.Width, Bitmap bmp = new(pictureBoxElectricLocomotive.Width,
pictureBoxElectricLocomotive.Height); pictureBoxElectricLocomotive.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningElectricLocomotive.DrawTransport(gr); _drawningLocomotive.DrawTransport(gr);
pictureBoxElectricLocomotive.Image = bmp; pictureBoxElectricLocomotive.Image = bmp;
} }
private void ButtonCreate_Click(object sender, EventArgs e) /// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type"></param>
private void CreateObject(string type)
{ {
Random random = new(); Random random = new();
_drawningElectricLocomotive = new DrawningElectricLocomotive(); switch (type)
_drawningElectricLocomotive.Init(random.Next(100, 300), random.Next(1000, 3000), {
case nameof(DrawningLocomotive):
_drawningLocomotive = 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):
_drawningLocomotive = 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)),
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))); Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningElectricLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height); break;
_drawningElectricLocomotive.SetPosition(random.Next(0,pictureBoxElectricLocomotive.Width), random.Next(0,pictureBoxElectricLocomotive.Height)); default:
return;
Bitmap bmp = new(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningElectricLocomotive.DrawTransport(gr);
pictureBoxElectricLocomotive.Image = bmp;
} }
_drawningLocomotive.SetPictureSize(pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.Height);
_drawningLocomotive.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 ButtonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningElectricLocomotive));
/// <summary>
/// Обработка нажатия кнопки "Создать локомотив"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateLocomotive_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLocomotive));
/// <summary> /// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации) /// Перемещение объекта по форме (нажатие кнопок навигации)
@ -59,7 +97,7 @@ public partial class FormElectricLocomotive : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawningElectricLocomotive == null) if (_drawningLocomotive == null)
{ {
return; return;
} }
@ -69,19 +107,19 @@ public partial class FormElectricLocomotive : Form
{ {
case "buttonUp": case "buttonUp":
result = result =
_drawningElectricLocomotive.MoveTransport(DirectionType.Up); _drawningLocomotive.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = result =
_drawningElectricLocomotive.MoveTransport(DirectionType.Down); _drawningLocomotive.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = result =
_drawningElectricLocomotive.MoveTransport(DirectionType.Left); _drawningLocomotive.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = result =
_drawningElectricLocomotive.MoveTransport(DirectionType.Right); _drawningLocomotive.MoveTransport(DirectionType.Right);
break; break;
} }
if (result) if (result)
@ -89,6 +127,38 @@ public partial class FormElectricLocomotive : Form
Draw(); Draw();
} }
} }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningLocomotive == null) return;
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null) return;
_strategy.SetData(new MoveableLocomotive(_drawningLocomotive), pictureBoxElectricLocomotive.Width, pictureBoxElectricLocomotive.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,140 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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,67 @@
using ProjectElectricLocomotive.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
/// <summary>
/// Класс-реализация IMoveableObject c использованием DrawningLocomotive
/// </summary>
public class MoveableLocomotive : IMoveableObject
{
/// <summary>
/// Поле-объект класса DrawningLocomotive или его наследника
/// </summary>
private readonly DrawningLocomotive? _locomotive = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="locomotive">Объект класса DrawningLocomotive</param>
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));
}
/// <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,41 @@
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.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();
}
}
}

View File

@ -0,0 +1,42 @@
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();
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.MovementStrategy;
public enum StrategyStatus
{
/// <summary>
/// Всё готово к началу
/// </summary>
NotInit,
/// <summary>
/// Выполняется
/// </summary>
InProgress,
/// <summary>
/// Завершено
/// </summary>
Finish
}