Compare commits

...

4 Commits
main ... lab2

Author SHA1 Message Date
I1nur
29c5d47017 deleted unnecessary 2023-10-20 07:31:32 +04:00
I1nur
a286f8ba08 Merge branch 'lab2' of http://student.git.athene.tech/Ilnur/Pibd-22.TukhtarovI.N.AntiAircraftGun.Base into lab2 2023-10-20 00:40:53 +04:00
I1nur
de7cafdec7 changes 2023-10-20 00:40:49 +04:00
I1nur
cb33fc2659 completed 2023-10-20 00:12:23 +04:00
39 changed files with 1027 additions and 557 deletions

View File

@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.33808.371
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AntiAircraftGun", "AntiAircraftGun\AntiAircraftGun.csproj", "{08E6BE2F-AC65-4661-8FB9-CC82073D7BA4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{08E6BE2F-AC65-4661-8FB9-CC82073D7BA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{08E6BE2F-AC65-4661-8FB9-CC82073D7BA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{08E6BE2F-AC65-4661-8FB9-CC82073D7BA4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{08E6BE2F-AC65-4661-8FB9-CC82073D7BA4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {71FC936E-B675-45C0-A3BA-F16DAF0C20ED}
EndGlobalSection
EndGlobal

View File

@ -1,32 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Include="ProjectAntiAircraftGun.csproj" />
<None Include="ProjectAntiAircraftGun.csproj.user" />
<None Include="ProjectAntiAircraftGun.sln" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -1,39 +0,0 @@
namespace AntiAircraftGun
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace AntiAircraftGun
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -1,120 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,78 +0,0 @@
namespace ProjectAntiAircraftGun
{
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Çåíèòíàÿ óñòàíîâêà"
/// </summary>
public partial class FormAntiAircraftGun : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingAntiAircraftGun? _drawingAntiAircraftGun;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormAntiAircraftGun()
{
InitializeComponent();
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè çåíèòíîé óñòàíîâêè
/// </summary>
private void Draw()
{
if (_drawingAntiAircraftGun == null) { return; }
Bitmap bmp = new(pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingAntiAircraftGun.DrawTransport(gr);
pictureBoxAntiAircraftGun.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateAntiAircraftGun(object sender, EventArgs e)
{
Random random = new();
_drawingAntiAircraftGun = new DrawingAntiAircraftGun();
_drawingAntiAircraftGun.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)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
_drawingAntiAircraftGun.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèé êíîïîê óïðàâëåíèÿ çåíèòíîé óñòàíîâêîé
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingAntiAircraftGun == null) return;
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingAntiAircraftGun.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingAntiAircraftGun.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingAntiAircraftGun.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingAntiAircraftGun.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
}
}

View File

@ -1,103 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AntiAircraftGun.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AntiAircraftGun.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap bottom {
get {
object obj = ResourceManager.GetObject("bottom", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap left {
get {
object obj = ResourceManager.GetObject("left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right {
get {
object obj = ResourceManager.GetObject("right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap top {
get {
object obj = ResourceManager.GetObject("top", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectAntiAircraftGun.Entities;
namespace ProjectAntiAircraftGun.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingAntiAircraftGun : DrawingTank
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="hatch">Признак наличия люка</param>
/// <param name="cannon">Признак наличия пушки</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingAntiAircraftGun(int speed, double weight, Color bodyColor, Color
additionalColor, bool radar, bool hatch, bool cannon, int width, int height) :
base(speed, weight, bodyColor, additionalColor, width, height, 102, 139)
{
if (EntityTank != null)
{
EntityTank = new EntityAntiAircraftGun(speed, weight, bodyColor,
additionalColor, radar, hatch, cannon);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityTank is not EntityAntiAircraftGun antiAircraftGun)
{
return;
}
Pen pen = new(Color.Black);
pen.Width = 2;
base.DrawTransport(g);
// радар
if (antiAircraftGun.Radar)
{
Pen penRadar = new(Color.DarkGreen);
g.DrawEllipse(penRadar, _startPosX + 52, _startPosY + 46, 21, 12);
g.DrawEllipse(penRadar, _startPosX + 55, _startPosY + 48, 14, 8);
pen = new(Color.Green);
g.DrawLine(penRadar, _startPosX + 61, _startPosY + 52, _startPosX + 70, _startPosY + 48);
}
// пушка
if (antiAircraftGun.Cannon)
{
g.DrawLine(pen, _startPosX + 54, _startPosY + 33, _startPosX + 113, _startPosY + 2);
g.DrawLine(pen, _startPosX + 57, _startPosY + 35, _startPosX + 122, _startPosY + 2);
}
// люк
if (antiAircraftGun.Hatch)
{
pen = new(antiAircraftGun.AdditionalColor);
g.DrawRectangle(pen, _startPosX + 88, _startPosY + 64, 17, 6);
g.DrawLine(pen, _startPosX + 88, _startPosY + 67, _startPosX + 105, _startPosY + 67);
g.DrawLine(pen, _startPosX + 94, _startPosY + 64, _startPosX + 94, _startPosY + 70);
}
}
}
}

View File

@ -3,141 +3,207 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectAntiAircraftGun.Entities;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectAntiAircraftGun
namespace ProjectAntiAircraftGun.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
internal class DrawingAntiAircraftGun
public class DrawingTank
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAntiAircraftGun? EntityAntiAircraftGun { get; private set; }
public EntityTank? EntityTank { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private static int _pictureWidth;
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private static int _pictureHeight;
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки зенитной установки
/// Левая координата прорисовки танка
/// </summary>
private int _startPosX;
protected int _startPosX;
/// <summary>
/// Верхняя координата прорисовки зенитной установки
/// Верхняя кооридната прорисовки танка
/// </summary>
private int _startPosY;
protected int _startPosY;
/// <summary>
/// Ширина прорисовки зенитной установки
/// Ширина прорисовки танка
/// </summary>
private readonly int _AntiAircraftGunWidth = 125;
protected readonly int _tankWidth = 130;
/// <summary>
/// Высота прорисовки зенитной установки
/// Высота прорисовки танка
/// </summary>
private readonly int _AntiAircraftGunHeight = 100;
protected readonly int _tankHeight = 102;
/// <summary>
/// Инициализация свойств
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _tankWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _tankHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес зенитной установки</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="radar">Признак наличия радара</param>
/// <param name="hatch">Признак наличия люка зенитной установки</param>
/// <param name="cannon">Признак наличия пушки зенитной установки</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public bool Init(int speed, int weight, Color bodyColor, Color additionalColor, bool radar, bool hatch, bool cannon, int width, int height)
public DrawingTank(int speed, double weight, Color bodyColor, Color additionalColor, int
width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
EntityTank = new EntityTank(speed, weight, bodyColor, additionalColor);
if (_pictureWidth > _tankWidth && _pictureHeight > _tankHeight)
{
EntityTank = new EntityTank(speed, weight, bodyColor, additionalColor);
}
else
{
EntityTank = null;
}
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="tankWidth">Ширина прорисовки танка</param>
/// <param name="tankHeight">Высота прорисовки танка</param>
protected DrawingTank(int speed, double weight, Color bodyColor, Color additionalColor, int
width, int height, int tankWidth, int tankHeight)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth > _AntiAircraftGunWidth && _pictureHeight > _AntiAircraftGunHeight) {
EntityAntiAircraftGun = new EntityAntiAircraftGun();
EntityAntiAircraftGun.Init(speed, weight, bodyColor, additionalColor, radar, hatch, cannon);
return true;
EntityTank = new EntityTank(speed, weight, bodyColor, additionalColor);
if (_pictureWidth > _tankWidth && _pictureHeight > _tankHeight)
{
EntityTank = new EntityTank(speed, weight, bodyColor, additionalColor);
}
else
{
EntityTank = null;
}
return false;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityTank == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityTank.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityTank.Step > 0,
// вправо
DirectionType.Right => _startPosX + _tankWidth + EntityTank.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _tankHeight + EntityTank.Step < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityTank == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityTank.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityTank.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityTank.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityTank.Step;
break;
}
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата Х</param>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (EntityAntiAircraftGun == null) return;
while (x + _AntiAircraftGunWidth > _pictureWidth)
if (EntityTank == null) return;
while (x + _tankWidth > _pictureWidth)
{
x -= (int)EntityAntiAircraftGun.Step;
x -= (int)EntityTank.Step;
}
while (x < 0)
{
x += (int)EntityAntiAircraftGun.Step;
x += (int)EntityTank.Step;
}
while (y + _AntiAircraftGunHeight > _pictureHeight)
while (y + _tankHeight > _pictureHeight)
{
y -= (int)EntityAntiAircraftGun.Step;
y -= (int)EntityTank.Step;
}
while (y < 0)
{
y += (int)EntityAntiAircraftGun.Step;
y += (int)EntityTank.Step;
}
_startPosX = x;
_startPosY = y;
}
public void MoveTransport(DirectionType direction)
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityAntiAircraftGun == null)
{ return; }
switch (direction)
{
case DirectionType.Left:
if (_startPosX - EntityAntiAircraftGun.Step > 0)
{
_startPosX -= (int)EntityAntiAircraftGun.Step;
}
break;
case DirectionType.Right:
if (_startPosX + _AntiAircraftGunWidth + EntityAntiAircraftGun.Step < DrawingAntiAircraftGun._pictureWidth)
{
_startPosX += (int)EntityAntiAircraftGun.Step;
}
break;
case DirectionType.Up:
if (_startPosY - EntityAntiAircraftGun.Step > 0)
{
_startPosY -= (int)EntityAntiAircraftGun.Step;
}
break;
case DirectionType.Down:
if (_startPosY + _AntiAircraftGunHeight + EntityAntiAircraftGun.Step < DrawingAntiAircraftGun._pictureHeight)
{
_startPosY += (int)EntityAntiAircraftGun.Step;
}
break;
}
}
public void DrawTransport(Graphics g)
{
if (EntityAntiAircraftGun == null) { return; }
if (EntityTank == null) { return; }
Pen pen = new(Color.Black);
pen.Width = 2;
Brush brush = new SolidBrush(EntityAntiAircraftGun.BodyColor);
Brush additionalBrush = new SolidBrush(EntityAntiAircraftGun.AdditionalColor);
Brush brush = new SolidBrush(EntityTank.BodyColor);
Random random = new Random();
Brush additionalBrush = new SolidBrush(EntityTank.AdditionalColor);
// границы зенитной установки
g.DrawRectangle(pen, _startPosX + 3, _startPosY + 60, 121, 23);
@ -194,32 +260,6 @@ namespace ProjectAntiAircraftGun
g.FillEllipse(brush, _startPosX + 43, _startPosY + 83, 7, 5);
g.FillEllipse(brush, _startPosX + 64, _startPosY + 83, 7, 5);
g.FillEllipse(brush, _startPosX + 82, _startPosY + 83, 7, 5);
// радар
if (EntityAntiAircraftGun.Radar)
{
Pen penRadar = new(Color.DarkGreen);
g.DrawEllipse(penRadar, _startPosX + 52, _startPosY + 46, 21, 12);
g.DrawEllipse(penRadar, _startPosX + 55, _startPosY + 48, 14, 8);
pen = new(Color.Green);
g.DrawLine(penRadar, _startPosX + 61, _startPosY + 52, _startPosX + 70, _startPosY + 48);
}
// пушка
if (EntityAntiAircraftGun.Cannon)
{
g.DrawLine(pen, _startPosX + 54, _startPosY + 33, _startPosX + 113, _startPosY + 2);
g.DrawLine(pen, _startPosX + 57, _startPosY + 35, _startPosX + 122, _startPosY + 2);
}
// люк
if (EntityAntiAircraftGun.Hatch)
{
pen = new(EntityAntiAircraftGun.AdditionalColor);
g.DrawRectangle(pen, _startPosX + 88, _startPosY + 64, 17, 6);
g.DrawLine(pen, _startPosX + 88, _startPosY + 67, _startPosX + 105, _startPosY + 67);
g.DrawLine(pen, _startPosX + 94, _startPosY + 64, _startPosX + 94, _startPosY + 70);
}
}
}
}

View File

@ -4,24 +4,10 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAntiAircraftGun
namespace ProjectAntiAircraftGun.Entities
{
public class EntityAntiAircraftGun
public class EntityAntiAircraftGun : EntityTank
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public int Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
@ -58,11 +44,8 @@ namespace ProjectAntiAircraftGun
/// <param name="radar">Признак наличия радара</param>
/// <param name="hatch">Признак наличия люка зенитной установки</param>
/// <param name="cannon">Признак наличия пушки зенитной установки</param>
public void Init(int speed, int weight, Color bodyColor, Color additionalColor, bool radar, bool hatch, bool cannon)
public EntityAntiAircraftGun(int speed, double weight, Color bodyColor, Color additionalColor, bool radar, bool hatch, bool cannon) : base(speed, weight, bodyColor, additionalColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Hatch = hatch;
Radar = radar;

View File

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

View File

@ -29,11 +29,14 @@
private void InitializeComponent()
{
pictureBoxAntiAircraftGun = new PictureBox();
createButton = new Button();
buttonCreateAntiAircraftGun = new Button();
buttonRight = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonUp = new Button();
comboBoxStrategy = new ComboBox();
buttonCreateTank = new Button();
buttonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAntiAircraftGun).BeginInit();
SuspendLayout();
//
@ -47,21 +50,21 @@
pictureBoxAntiAircraftGun.TabIndex = 0;
pictureBoxAntiAircraftGun.TabStop = false;
//
// createButton
// buttonCreateAntiAircraftGun
//
createButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
createButton.Location = new Point(12, 415);
createButton.Name = "createButton";
createButton.Size = new Size(75, 23);
createButton.TabIndex = 1;
createButton.Text = "создать";
createButton.UseVisualStyleBackColor = true;
createButton.Click += ButtonCreateAntiAircraftGun;
buttonCreateAntiAircraftGun.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateAntiAircraftGun.Location = new Point(12, 415);
buttonCreateAntiAircraftGun.Name = "buttonCreateAntiAircraftGun";
buttonCreateAntiAircraftGun.Size = new Size(174, 23);
buttonCreateAntiAircraftGun.TabIndex = 1;
buttonCreateAntiAircraftGun.Text = "создать зенитную установку";
buttonCreateAntiAircraftGun.UseVisualStyleBackColor = true;
buttonCreateAntiAircraftGun.Click += ButtonCreateAntiAircraftGun;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = AntiAircraftGun.Properties.Resources.right;
buttonRight.BackgroundImage = Properties.Resources.png_transparent_grammatical_person_paper_narration_direzione_didattica_statale_gestione_scuola_elementare_copy_print_right_arrow_miscellaneous_game_angle;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(739, 413);
buttonRight.Name = "buttonRight";
@ -73,7 +76,7 @@
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = AntiAircraftGun.Properties.Resources.left;
buttonLeft.BackgroundImage = Properties.Resources.left;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(605, 413);
buttonLeft.Name = "buttonLeft";
@ -85,7 +88,7 @@
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = AntiAircraftGun.Properties.Resources.bottom;
buttonDown.BackgroundImage = Properties.Resources.bottom;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(672, 415);
buttonDown.Name = "buttonDown";
@ -97,7 +100,7 @@
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = AntiAircraftGun.Properties.Resources.top;
buttonUp.BackgroundImage = Properties.Resources.top;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(672, 379);
buttonUp.Name = "buttonUp";
@ -106,16 +109,52 @@
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "0", "1" });
comboBoxStrategy.Location = new Point(679, 0);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 9;
//
// buttonCreateTank
//
buttonCreateTank.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTank.Location = new Point(192, 415);
buttonCreateTank.Name = "buttonCreateTank";
buttonCreateTank.Size = new Size(108, 23);
buttonCreateTank.TabIndex = 10;
buttonCreateTank.Text = "создать танк";
buttonCreateTank.UseVisualStyleBackColor = true;
buttonCreateTank.Click += ButtonCreateTank_Click;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(704, 29);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 23);
buttonStep.TabIndex = 11;
buttonStep.Text = "шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// FormAntiAircraftGun
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonStep);
Controls.Add(buttonCreateTank);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonUp);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonRight);
Controls.Add(createButton);
Controls.Add(buttonCreateAntiAircraftGun);
Controls.Add(pictureBoxAntiAircraftGun);
Name = "FormAntiAircraftGun";
Text = "Зенитная установка";
@ -127,10 +166,13 @@
#endregion
private PictureBox pictureBoxAntiAircraftGun;
private Button createButton;
private Button buttonCreateAntiAircraftGun;
private Button buttonRight;
private Button buttonLeft;
private Button buttonDown;
private Button buttonUp;
private Button buttonCreateTank;
private Button buttonStep;
private ComboBox comboBoxStrategy;
}
}

View File

@ -0,0 +1,156 @@
using ProjectAntiAircraftGun.DrawingObjects;
using ProjectAntiAircraftGun.MovementStrategy;
namespace ProjectAntiAircraftGun
{
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Çåíèòíàÿ óñòàíîâêà"
/// </summary>
public partial class FormAntiAircraftGun : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingTank? _drawingTank;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormAntiAircraftGun()
{
InitializeComponent();
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè çåíèòíîé óñòàíîâêè
/// </summary>
private void Draw()
{
if (_drawingTank == null)
{
return;
}
Bitmap bmp = new(pictureBoxAntiAircraftGun.Width,
pictureBoxAntiAircraftGun.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingTank.DrawTransport(gr);
pictureBoxAntiAircraftGun.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü òàíê"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTank_Click(object sender, EventArgs e)
{
Random random = new();
_drawingTank = new DrawingTank(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)),
pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
_drawingTank.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü çåíèòíóþ óñòàíîâêó"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateAntiAircraftGun(object sender, EventArgs e)
{
Random random = new();
_drawingTank = new DrawingAntiAircraftGun(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)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxAntiAircraftGun.Width, pictureBoxAntiAircraftGun.Height);
_drawingTank.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèé êíîïîê óïðàâëåíèÿ çåíèòíîé óñòàíîâêîé
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingTank == null) return;
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingTank.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingTank.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingTank.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingTank.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawingTank == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawingObjectTank(_drawingTank), pictureBoxAntiAircraftGun.Width,
pictureBoxAntiAircraftGun.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

@ -0,0 +1,132 @@
using ProjectAntiAircraftGun;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectAntiAircraftGun.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status 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 = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</ returns >
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</ returns >
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</ returns >
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</ returns >
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,32 @@
using ProjectAntiAircraftGun.DrawingObjects;
namespace ProjectAntiAircraftGun.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом Drawning (паттерн Adapter)
public class DrawingObjectTank : IMoveableObject
{
private readonly DrawingTank? _drawingTank = null;
public DrawingObjectTank(DrawingTank drawingTank)
{
_drawingTank = drawingTank;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingTank == null || _drawingTank.EntityTank == null)
{
return null;
}
return new ObjectParameters(_drawingTank.GetPosX,
_drawingTank.GetPosY, _drawingTank.GetWidth, _drawingTank.GetHeight);
}
}
public int GetStep => (int)(_drawingTank?.EntityTank?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawingTank?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawingTank?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,29 @@
using ProjectAntiAircraftGun;
namespace ProjectAntiAircraftGun.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,60 @@
using ProjectAntiAircraftGun.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAntiAircraftGun.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта к правому нижнему краю формы
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth &&
objParams.ObjectMiddleVertical <= FieldHeight &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAntiAircraftGun.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,51 @@
namespace ProjectAntiAircraftGun.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
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,12 @@
namespace ProjectAntiAircraftGun.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -0,0 +1,145 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectAntiAircraftGun.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectAntiAircraftGun.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap bottom {
get {
object obj = ResourceManager.GetObject("bottom", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap left {
get {
object obj = ResourceManager.GetObject("left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap png_clipart_computer_icons_uma_musume_pretty_derby_fate_grand_order_saber_kemono_friends_three_arrow_game_angle {
get {
object obj = ResourceManager.GetObject("png-clipart-computer-icons-uma-musume-pretty-derby-fate-grand-order-saber-kemono-" +
"friends-three-arrow-game-angle", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap png_transparent_arrow_arrow_cdr_angle_triangle {
get {
object obj = ResourceManager.GetObject("png-transparent-arrow-arrow-cdr-angle-triangle", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap png_transparent_arrow_left_thin_zondicons_icon {
get {
object obj = ResourceManager.GetObject("png-transparent-arrow-left-thin-zondicons-icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap png_transparent_grammatical_person_paper_narration_direzione_didattica_statale_gestione_scuola_elementare_copy_print_right_arrow_miscellaneous_game_angle {
get {
object obj = ResourceManager.GetObject("png-transparent-grammatical-person-paper-narration-direzione-didattica-statale-ge" +
"stione-scuola-elementare-copy-print-right-arrow-miscellaneous-game-angle", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right {
get {
object obj = ResourceManager.GetObject("right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap top {
get {
object obj = ResourceManager.GetObject("top", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -118,16 +118,28 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="left" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\left.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
<data name="png-transparent-arrow-arrow-cdr-angle-triangle" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\png-transparent-arrow-arrow-cdr-angle-triangle.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="right" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\right.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
<data name="png-clipart-computer-icons-uma-musume-pretty-derby-fate-grand-order-saber-kemono-friends-three-arrow-game-angle" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\png-clipart-computer-icons-uma-musume-pretty-derby-fate-grand-order-saber-kemono-friends-three-arrow-game-angle.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="top" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\top.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
<data name="png-transparent-grammatical-person-paper-narration-direzione-didattica-statale-gestione-scuola-elementare-copy-print-right-arrow-miscellaneous-game-angle" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\png-transparent-grammatical-person-paper-narration-direzione-didattica-statale-gestione-scuola-elementare-copy-print-right-arrow-miscellaneous-game-angle.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="png-transparent-arrow-left-thin-zondicons-icon" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\png-transparent-arrow-left-thin-zondicons-icon.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="bottom" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\bottom.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
<value>..\Resources\bottom.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="left" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\left.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="right" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\right.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="top" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\top.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

View File

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB