Compare commits

...

9 Commits
main ... lab7

Author SHA1 Message Date
ffa3f822d9 laba 7 2023-12-29 20:25:33 +04:00
2bb5d0e57a f 2023-12-15 23:59:17 +04:00
7a60c03c4a laba 6 2023-12-15 23:53:20 +04:00
45f44fe42f laba 5 2023-12-15 22:22:18 +04:00
31f294023d laba 4 2023-12-02 00:24:08 +04:00
b68ea11c6f laba 3 2023-12-01 21:10:50 +04:00
f89951adef laba 2 2023-11-30 14:13:38 +04:00
ed306e312a laba1 2023-11-27 13:18:25 +04:00
5ce38895b8 test 2023-11-24 11:49:06 +04:00
37 changed files with 3490 additions and 0 deletions

View File

@ -0,0 +1,38 @@
<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>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</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

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32901.215
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Airbus_Base", "Airbus_Base.csproj", "{D58BBEF6-D90E-4076-A60A-4A373E8D8FA9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D58BBEF6-D90E-4076-A60A-4A373E8D8FA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D58BBEF6-D90E-4076-A60A-4A373E8D8FA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D58BBEF6-D90E-4076-A60A-4A373E8D8FA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D58BBEF6-D90E-4076-A60A-4A373E8D8FA9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EC7CDE98-FBF3-46D7-A3C0-DC9088B5F922}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base
{
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,81 @@
using Airbus_Base.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirbus : DrawningAirplane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalEngine">Признак наличия двигателей</param>
/// <param name="additionalPassengerCompartment">Признак наличия отсека для пассажиров</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningAirbus(int speed, double weight, Color bodyColor, Color
additionalColor, bool additionalEngine, bool additionalPassengerCompartment, int width, int height) :
base(speed, weight, bodyColor, width, height, 159, 103)
{
if (EntityAirplane != null)
{
EntityAirplane = new EntityAirbus(speed, weight, bodyColor,
additionalColor, additionalEngine, additionalPassengerCompartment);
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityAirplane is not EntityAirbus airBus)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(airBus.AdditionalColor);
//Дополнительные двигатели
if (airBus.AdditionalEngine)
{
Point[] enginedraw = { new Point(_startPosX + 55, _startPosY + 30),
new Point(_startPosX + 69, _startPosY + 25), new Point(_startPosX + 55, _startPosY + 20)};
g.FillPolygon(additionalBrush, enginedraw);
Point[] enginedraw1 = { new Point(_startPosX + 55, _startPosY + 75),
new Point(_startPosX + 70, _startPosY + 70), new Point(_startPosX + 55, _startPosY + 65)};
g.FillPolygon(additionalBrush, enginedraw1);
}
base.DrawTransport(g);
//Дополнительный отсек для пассажиров
if (airBus.AdditionalPassengerCompartment)
{
Point[] points = { new Point(_startPosX + 90, _startPosY + 30),
new Point(_startPosX + 100, _startPosY + 15), new Point(_startPosX + 130, _startPosY + 15),
new Point(_startPosX + 140, _startPosY + 30) };
g.FillPolygon(additionalBrush, points);
g.DrawLine(pen, _startPosX + 90, _startPosY + 30, _startPosX + 100, _startPosY + 15);
g.DrawLine(pen, _startPosX + 100, _startPosY + 15, _startPosX + 130, _startPosY + 15);
g.DrawLine(pen, _startPosX + 130, _startPosY + 15, _startPosX + 140, _startPosY + 30);
}
}
public void SetAddColor(Color color)
{
((EntityAirbus)EntityAirplane).AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,248 @@
using Airbus_Base.Entities;
using Airbus_Base.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirplane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirplane? EntityAirplane { get; protected set; }
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningAirplane
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectAirplane(this);
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки самолёта
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки самолёта
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки самолёта
/// </summary>
protected readonly int _airplaneWidth = 159;
/// <summary>
/// Высота прорисовки самолёта
/// </summary>
protected readonly int _airplaneHeight = 103;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _airplaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _airplaneHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningAirplane(int speed, double weight, Color bodyColor, int
width, int height)
{
if (width < _airplaneHeight || height < _airplaneWidth)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="airWidth">Ширина прорисовки cамолёта</param>
/// <param name="airHeight">Высота прорисовки cамолёта</param>
protected DrawningAirplane(int speed, double weight, Color bodyColor, int
width, int height, int airWidth, int airHeight)
{
if (width < _airplaneHeight || height < _airplaneWidth)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_airplaneWidth = airWidth;
_airplaneHeight = airHeight;
EntityAirplane = new EntityAirplane(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x < 0 || x + _airplaneWidth > _pictureWidth)
{
x = Math.Max(0, _pictureWidth - _airplaneWidth);
}
if (y < 0 || y + _airplaneHeight > _pictureHeight)
{
y = Math.Max(0, _pictureHeight - _airplaneHeight);
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityAirplane == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityAirplane.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityAirplane.Step > 0,
//вправо
DirectionType.Right => _startPosX + _airplaneWidth + EntityAirplane.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _airplaneHeight + EntityAirplane.Step < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityAirplane == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityAirplane.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityAirplane.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityAirplane.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityAirplane.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityAirplane == null)
{
return;
}
Pen pen = new(Color.Black);
Brush brBlack = new SolidBrush(Color.Black);
Brush bodybrush = new SolidBrush(EntityAirplane.BodyColor);
//передняя часть
Point[] k = { new Point(_startPosX + 140, _startPosY + 30),
new Point(_startPosX + 160, _startPosY + 56), new Point(_startPosX + 140, _startPosY + 81)};
g.FillPolygon(brBlack, k);
//корпус
g.FillRectangle(bodybrush, _startPosX + 20, _startPosY + 30, 120, 50);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 30, 120, 50);
//колеса
g.DrawLine(pen, _startPosX + 45, _startPosY + 81, _startPosX + 45, _startPosY + 90);
g.DrawLine(pen, _startPosX + 110, _startPosY + 81, _startPosX + 110, _startPosY + 90);
g.FillEllipse(brBlack, _startPosX + 45, _startPosY + 85, 10, 10);
g.FillEllipse(brBlack, _startPosX + 35, _startPosY + 85, 10, 10);
g.FillEllipse(brBlack, _startPosX + 100, _startPosY + 85, 10, 10);
g.FillEllipse(brBlack, _startPosX + 110, _startPosY + 85, 10, 10);
//хвост
Point[] points1 = { new Point(_startPosX + 20, _startPosY + 30),
new Point(_startPosX + 20, _startPosY + 0), new Point(_startPosX + 50, _startPosY + 30)};
g.FillPolygon(bodybrush, points1);
g.DrawLine(pen, _startPosX + 20, _startPosY + 30, _startPosX + 20, _startPosY + 0);
g.DrawLine(pen, _startPosX + 20, _startPosY + 0, _startPosX + 50, _startPosY + 30);
//крылья
Point[] points2 = { new Point(_startPosX + 65, _startPosY + 30),
new Point(_startPosX + 45, _startPosY + 10), new Point(_startPosX + 88, _startPosY + 30)};
g.FillPolygon(bodybrush, points2);
g.DrawLine(pen, _startPosX + 65, _startPosY + 30, _startPosX + 45, _startPosY + 10);
g.DrawLine(pen, _startPosX + 45, _startPosY + 10, _startPosX + 88, _startPosY + 30);
Point[] points3 = { new Point(_startPosX + 65, _startPosY + 60),
new Point(_startPosX + 45, _startPosY + 100), new Point(_startPosX + 100, _startPosY + 60)};
g.FillPolygon(bodybrush, points3);
g.DrawLine(pen, _startPosX + 65, _startPosY + 60, _startPosX + 45, _startPosY + 100);
g.DrawLine(pen, _startPosX + 45, _startPosY + 100, _startPosX + 100, _startPosY + 60);
g.FillEllipse(brBlack, _startPosX + 16, _startPosY + 27, 30, 6);
}
public void SetColor(Color color)
{
if (EntityAirplane == null)
{
return;
}
EntityAirplane.BodyColor = color;
}
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
}
}

View File

@ -0,0 +1,61 @@
using Airbus_Base.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityAirplane
/// </summary>
public static class ExtentionDrawningAirplane
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningAirplane? CreateDrawningAirplane(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningAirplane(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningAirbus(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirplane">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningAirplane drawningairplane, char separatorForObject)
{
var airplane = drawningairplane.EntityAirplane;
if (airplane == null)
{
return string.Empty;
}
var str = $"{airplane.Speed}{separatorForObject}{airplane.Weight}{separatorForObject}{airplane.BodyColor.Name}";
if (airplane is not EntityAirbus airBus)
{
return str;
}
return
$"{str}{separatorForObject}{airBus.AdditionalColor.Name}{separatorForObject}{airBus.AdditionalEngine}" +
$"{separatorForObject}{airBus.AdditionalPassengerCompartment}";
}
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.Entities
{
/// <summary>
/// Класс-сущность "Аэробус"
/// </summary>
public class EntityAirbus : EntityAirplane
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия двигателей
/// </summary>
public bool AdditionalEngine { get; private set; }
/// <summary>
/// Признак (опция) наличия отсека для пассажиров
/// </summary>
public bool AdditionalPassengerCompartment { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса аэробуса
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес аэробуса</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="additionalEngine">Признак наличия двигателей</param>
/// <param name="additionalPassengerCompartment">Признак наличия отсека для пассажиров</param>
public EntityAirbus(int speed, double weight, Color bodyColor, Color additionalColor, bool additionalEngine, bool additionalPassengerCompartment) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
AdditionalEngine = additionalEngine;
AdditionalPassengerCompartment = additionalPassengerCompartment;
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.Entities
{
/// <summary>
/// Класс-сущность "Самолёт"
/// </summary>
public class EntityAirplane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; 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 EntityAirplane(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.Exceptions
{
[Serializable]
internal class AirplaneNotFoundException : ApplicationException
{
public AirplaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public AirplaneNotFoundException() : base() { }
public AirplaneNotFoundException(string message) : base(message) { }
public AirplaneNotFoundException(string message, Exception exception) : base(message, exception) { }
protected AirplaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

196
Airbus_Base/FormAirbus.Designer.cs generated Normal file
View File

@ -0,0 +1,196 @@
namespace Airbus_Base
{
partial class FormAirbus
{
/// <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.pictureBoxAirbus = new System.Windows.Forms.PictureBox();
this.buttonCreateAirplane = new System.Windows.Forms.Button();
this.buttonCreateAirbus = new System.Windows.Forms.Button();
this.ButtonSelectedAirplane = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonStep = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirbus)).BeginInit();
this.SuspendLayout();
//
// pictureBoxAirbus
//
this.pictureBoxAirbus.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxAirbus.Location = new System.Drawing.Point(0, 0);
this.pictureBoxAirbus.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.pictureBoxAirbus.Name = "pictureBoxAirbus";
this.pictureBoxAirbus.Size = new System.Drawing.Size(882, 453);
this.pictureBoxAirbus.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxAirbus.TabIndex = 0;
this.pictureBoxAirbus.TabStop = false;
//
// buttonCreateAirplane
//
this.buttonCreateAirplane.Location = new System.Drawing.Point(12, 393);
this.buttonCreateAirplane.Name = "buttonCreateAirplane";
this.buttonCreateAirplane.Size = new System.Drawing.Size(75, 52);
this.buttonCreateAirplane.TabIndex = 6;
this.buttonCreateAirplane.Text = "Создать самолёт";
this.buttonCreateAirplane.UseVisualStyleBackColor = true;
this.buttonCreateAirplane.Click += new System.EventHandler(this.buttonCreateAirplane_Click);
//
// buttonCreateAirbus
//
this.buttonCreateAirbus.Location = new System.Drawing.Point(115, 393);
this.buttonCreateAirbus.Name = "buttonCreateAirbus";
this.buttonCreateAirbus.Size = new System.Drawing.Size(75, 52);
this.buttonCreateAirbus.TabIndex = 7;
this.buttonCreateAirbus.Text = "Создать аэробус";
this.buttonCreateAirbus.UseVisualStyleBackColor = true;
this.buttonCreateAirbus.Click += new System.EventHandler(this.buttonCreateAirbus_Click);
//
// ButtonSelectedAirplane
//
this.ButtonSelectedAirplane.Location = new System.Drawing.Point(216, 393);
this.ButtonSelectedAirplane.Name = "ButtonSelectedAirplane";
this.ButtonSelectedAirplane.Size = new System.Drawing.Size(115, 52);
this.ButtonSelectedAirplane.TabIndex = 3;
this.ButtonSelectedAirplane.Text = "Добавить в коллекцию";
this.ButtonSelectedAirplane.UseVisualStyleBackColor = true;
this.ButtonSelectedAirplane.Click += new System.EventHandler(this.ButtonSelectedAirplane_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Airbus_Base.Properties.Resources.Left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonLeft.Location = new System.Drawing.Point(756, 407);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 2;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Airbus_Base.Properties.Resources.Up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonUp.Location = new System.Drawing.Point(792, 368);
this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 3;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Airbus_Base.Properties.Resources.Right;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(828, 407);
this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 4;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Airbus_Base.Properties.Resources.Down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonDown.Location = new System.Drawing.Point(792, 406);
this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 5;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonStep
//
this.buttonStep.Location = new System.Drawing.Point(797, 51);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(75, 29);
this.buttonStep.TabIndex = 8;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"К центру",
"К краю"});
this.comboBoxStrategy.Location = new System.Drawing.Point(753, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(121, 28);
this.comboBoxStrategy.TabIndex = 9;
//
// FormAirbus
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(882, 453);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonCreateAirbus);
this.Controls.Add(this.buttonCreateAirplane);
this.Controls.Add(this.ButtonSelectedAirplane);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.pictureBoxAirbus);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormAirbus";
this.Text = "FormAirbus";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirbus)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private PictureBox pictureBoxAirbus;
private Button buttonCreateAirplane;
private Button buttonCreateAirbus;
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button ButtonSelectedAirplane;
}
}

181
Airbus_Base/FormAirbus.cs Normal file
View File

@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Airbus_Base.DrawningObjects;
using Airbus_Base.MovementStrategy;
namespace Airbus_Base
{
/// <summary>
/// Форма работы с объектом "Аэробус"
/// </summary>
public partial class FormAirbus : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningAirplane? _drawningAirplane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Выбранный самолёт
/// </summary>
public DrawningAirplane? SelectedAirplane { get; private set; }
/// <summary>
/// Инициализация формы
/// </summary>
public FormAirbus()
{
InitializeComponent();
_abstractStrategy = null;
SelectedAirplane = null;
}
/// <summary>
/// Метод прорисовки аэробуса
/// </summary>
private void Draw()
{
if (_drawningAirplane == null)
{
return;
}
Bitmap bmp = new(pictureBoxAirbus.Width,
pictureBoxAirbus.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningAirplane.DrawTransport(gr);
pictureBoxAirbus.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать самолёт"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAirplane_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
_drawningAirplane = new DrawningAirplane(random.Next(100, 300), random.Next(1000, 3000),
color, pictureBoxAirbus.Width, pictureBoxAirbus.Height);
_drawningAirplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать aэробус"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateAirbus_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDopColor = new();
if (dialogDopColor.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDopColor.Color;
}
_drawningAirplane = new DrawningAirbus(random.Next(100, 300),
random.Next(1000, 3000), color, dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxAirbus.Width, pictureBoxAirbus.Height);
_drawningAirplane.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 (_drawningAirplane == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningAirplane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningAirplane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningAirplane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningAirplane.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningAirplane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(_drawningAirplane.GetMoveableObject,
pictureBoxAirbus.Width, pictureBoxAirbus.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void ButtonSelectedAirplane_Click(object sender, EventArgs e)
{
SelectedAirplane = _drawningAirplane;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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

@ -0,0 +1,273 @@
using System.Windows.Forms;
namespace Airbus_Base
{
partial class FormAirplaneCollection
{
/// <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.toolsPanel = new System.Windows.Forms.Panel();
this.panelSets = new System.Windows.Forms.Panel();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.listBoxObjects = new System.Windows.Forms.ListBox();
this.ButtonAddObject = new System.Windows.Forms.Button();
this.ButtonDelObject = new System.Windows.Forms.Button();
this.SetsLabel = new System.Windows.Forms.Label();
this.ButtonAddAirplane = new System.Windows.Forms.Button();
this.ButtonDeleteAirplane = new System.Windows.Forms.Button();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.TextBox();
this.LabelTools = new System.Windows.Forms.Label();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.menuStrip = new MenuStrip();
this.FileToolStripMenuItem = new ToolStripMenuItem();
this.SaveToolStripMenuItem = new ToolStripMenuItem();
this.LoadToolStripMenuItem = new ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.toolsPanel.SuspendLayout();
this.panelSets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// toolsPanel
//
this.toolsPanel.Controls.Add(this.panelSets);
this.toolsPanel.Controls.Add(this.ButtonAddAirplane);
this.toolsPanel.Controls.Add(this.ButtonDeleteAirplane);
this.toolsPanel.Controls.Add(this.ButtonRefreshCollection);
this.toolsPanel.Controls.Add(this.maskedTextBoxNumber);
this.toolsPanel.Controls.Add(this.LabelTools);
this.toolsPanel.Location = new System.Drawing.Point(675, -2);
this.toolsPanel.Name = "toolsPanel";
this.toolsPanel.Size = new System.Drawing.Size(220, 451);
this.toolsPanel.TabIndex = 0;
//
// panelSets
//
this.panelSets.Controls.Add(this.textBoxStorageName);
this.panelSets.Controls.Add(this.listBoxObjects);
this.panelSets.Controls.Add(this.ButtonAddObject);
this.panelSets.Controls.Add(this.ButtonDelObject);
this.panelSets.Controls.Add(this.SetsLabel);
this.panelSets.Location = new System.Drawing.Point(8, 20);
this.panelSets.Name = "panelSets";
this.panelSets.Size = new System.Drawing.Size(210, 208);
this.panelSets.TabIndex = 6;
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(10, 27);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(190, 27);
this.textBoxStorageName.TabIndex = 12;
//
// listBoxObjects
//
this.listBoxObjects.FormattingEnabled = true;
this.listBoxObjects.ItemHeight = 20;
this.listBoxObjects.Location = new System.Drawing.Point(10, 99);
this.listBoxObjects.Name = "listBoxObjects";
this.listBoxObjects.Size = new System.Drawing.Size(190, 64);
this.listBoxObjects.TabIndex = 11;
this.listBoxObjects.SelectedIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged);
//
// ButtonAddObject
//
this.ButtonAddObject.Location = new System.Drawing.Point(10, 60);
this.ButtonAddObject.Name = "ButtonAddObject";
this.ButtonAddObject.Size = new System.Drawing.Size(191, 33);
this.ButtonAddObject.TabIndex = 8;
this.ButtonAddObject.Text = "Добавить набор";
this.ButtonAddObject.UseVisualStyleBackColor = true;
this.ButtonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// ButtonDelObject
//
this.ButtonDelObject.Location = new System.Drawing.Point(10, 169);
this.ButtonDelObject.Name = "ButtonDelObject";
this.ButtonDelObject.Size = new System.Drawing.Size(192, 33);
this.ButtonDelObject.TabIndex = 7;
this.ButtonDelObject.Text = "Удалить набор\r\n";
this.ButtonDelObject.UseVisualStyleBackColor = true;
this.ButtonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click);
//
// SetsLabel
//
this.SetsLabel.AutoSize = true;
this.SetsLabel.Location = new System.Drawing.Point(13, 4);
this.SetsLabel.Name = "SetsLabel";
this.SetsLabel.Size = new System.Drawing.Size(66, 20);
this.SetsLabel.TabIndex = 0;
this.SetsLabel.Text = "Наборы";
//
// ButtonAddAirplane
//
this.ButtonAddAirplane.Location = new System.Drawing.Point(61, 234);
this.ButtonAddAirplane.Name = "ButtonAddAirplane";
this.ButtonAddAirplane.Size = new System.Drawing.Size(103, 49);
this.ButtonAddAirplane.TabIndex = 1;
this.ButtonAddAirplane.Text = "Добавить объект";
this.ButtonAddAirplane.UseVisualStyleBackColor = true;
this.ButtonAddAirplane.Click += new System.EventHandler(this.ButtonAddAirplane_Click);
//
// ButtonDeleteAirplane
//
this.ButtonDeleteAirplane.Location = new System.Drawing.Point(61, 301);
this.ButtonDeleteAirplane.Name = "ButtonDeleteAirplane";
this.ButtonDeleteAirplane.Size = new System.Drawing.Size(103, 55);
this.ButtonDeleteAirplane.TabIndex = 2;
this.ButtonDeleteAirplane.Text = "Удалить объект";
this.ButtonDeleteAirplane.UseVisualStyleBackColor = true;
this.ButtonDeleteAirplane.Click += new System.EventHandler(this.ButtonDeleteAirplane_Click);
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(61, 395);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(103, 56);
this.ButtonRefreshCollection.TabIndex = 4;
this.ButtonRefreshCollection.Text = "Обновить коллекцию";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
this.ButtonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(48, 362);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(125, 27);
this.maskedTextBoxNumber.TabIndex = 2;
//
// LabelTools
//
this.LabelTools.AutoSize = true;
this.LabelTools.Location = new System.Drawing.Point(18, 0);
this.LabelTools.Name = "LabelTools";
this.LabelTools.Size = new System.Drawing.Size(103, 20);
this.LabelTools.TabIndex = 0;
this.LabelTools.Text = "Инструменты";
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(1, 31);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(676, 471);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// menuStrip1
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(882, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(59, 24);
FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(224, 26);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(224, 26);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormAirplaneCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(900, 450);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.toolsPanel);
this.Controls.Add(menuStrip);
this.MainMenuStrip = menuStrip;
this.Name = "FormAirplaneCollection";
this.Text = "FormAirplaneCollection";
this.toolsPanel.ResumeLayout(false);
this.toolsPanel.PerformLayout();
this.panelSets.ResumeLayout(false);
this.panelSets.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
PerformLayout();
}
private void LoadToolStripMenuItem_Click1(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private Panel toolsPanel;
private Label LabelTools;
private PictureBox pictureBoxCollection;
private Button ButtonAddAirplane;
private Button ButtonDeleteAirplane;
public TextBox maskedTextBoxNumber;
private Panel panelSets;
private Label SetsLabel;
private Button ButtonDelObject;
private Button ButtonAddObject;
private Button ButtonRefreshCollection;
private ListBox listBoxObjects;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,264 @@
using Airbus_Base.DrawningObjects;
using Airbus_Base.Generics;
using Airbus_Base.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Airbus_Base.Exceptions;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
using Serilog;
namespace Airbus_Base
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningAirbus
/// </summary>
public partial class FormAirplaneCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly TheAirplaneGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormAirplaneCollection()
{
InitializeComponent();
_storage = new TheAirplaneGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxObjects.SelectedIndex;
listBoxObjects.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxObjects.Items.Add(_storage.Keys[i]);
}
if (listBoxObjects.Items.Count > 0 && (index == -1 || index >= listBoxObjects.Items.Count))
{
listBoxObjects.SelectedIndex = 0;
}
else if (listBoxObjects.Items.Count > 0 && index > -1 && index < listBoxObjects.Items.Count)
{
listBoxObjects.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxObjects.SelectedItem?.ToString() ?? string.Empty]?.ShowTheAirplanes();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект{listBoxObjects.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
string name = (listBoxObjects.SelectedItem.ToString() ?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAirplane_Click(object sender, EventArgs e)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxObjects.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormAirplaneConfig form = new();
form.Show();
Action<DrawningAirplane>? airplaneDelegate = new((airplane) =>
{
try
{
bool isAdditionSuccessful = obj + airplane;
MessageBox.Show("Объект добавлен");
airplane.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowTheAirplanes();
Log.Information($"Добавлен объект в коллекцию {listBoxObjects.SelectedItem.ToString() ?? string.Empty}");
}
catch (StorageOverflowException ex)
{
Log.Warning($"Коллекция {listBoxObjects.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
});
form.AddEvent(airplaneDelegate);
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteAirplane_Click(object sender, EventArgs e)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxObjects.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var isAdditionSuccessful = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxObjects.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowTheAirplanes();
}
catch (AirplaneNotFoundException ex)
{
Log.Warning($"Не получилось удалить объект из коллекции {listBoxObjects.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxObjects.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowTheAirplanes();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxObjects.Items.Add(collection);
}
ReloadObjects();
}
catch (Exception ex)
{
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

379
Airbus_Base/FormAirplaneConfig.Designer.cs generated Normal file
View File

@ -0,0 +1,379 @@
namespace Airbus_Base
{
partial class FormAirplaneConfig
{
/// <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.groupBoxParameters = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxPassengerCompartment = new System.Windows.Forms.CheckBox();
this.checkBoxEngine = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.panelObject = new System.Windows.Forms.Panel();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.labelExtraColor = new System.Windows.Forms.Label();
this.labelColor = new System.Windows.Forms.Label();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxParameters.SuspendLayout();
this.groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxParameters
//
this.groupBoxParameters.Controls.Add(this.labelModifiedObject);
this.groupBoxParameters.Controls.Add(this.labelSimpleObject);
this.groupBoxParameters.Controls.Add(this.groupBoxColor);
this.groupBoxParameters.Controls.Add(this.checkBoxPassengerCompartment);
this.groupBoxParameters.Controls.Add(this.checkBoxEngine);
this.groupBoxParameters.Controls.Add(this.numericUpDownWeight);
this.groupBoxParameters.Controls.Add(this.numericUpDownSpeed);
this.groupBoxParameters.Controls.Add(this.labelWeight);
this.groupBoxParameters.Controls.Add(this.labelSpeed);
this.groupBoxParameters.Location = new System.Drawing.Point(25, 12);
this.groupBoxParameters.Name = "groupBoxParameters";
this.groupBoxParameters.Size = new System.Drawing.Size(673, 280);
this.groupBoxParameters.TabIndex = 0;
this.groupBoxParameters.TabStop = false;
this.groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(528, 196);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(101, 43);
this.labelModifiedObject.TabIndex = 9;
this.labelModifiedObject.Text = "Сложный";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(412, 196);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(101, 43);
this.labelSimpleObject.TabIndex = 8;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// groupBoxColor
//
this.groupBoxColor.Controls.Add(this.panelPurple);
this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelYellow);
this.groupBoxColor.Controls.Add(this.panelGray);
this.groupBoxColor.Controls.Add(this.panelBlue);
this.groupBoxColor.Controls.Add(this.panelGreen);
this.groupBoxColor.Controls.Add(this.panelWhite);
this.groupBoxColor.Controls.Add(this.panelRed);
this.groupBoxColor.Location = new System.Drawing.Point(385, 32);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Size = new System.Drawing.Size(272, 151);
this.groupBoxColor.TabIndex = 7;
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(207, 92);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(47, 47);
this.panelPurple.TabIndex = 4;
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(143, 92);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(47, 47);
this.panelBlack.TabIndex = 4;
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(207, 32);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(47, 47);
this.panelYellow.TabIndex = 3;
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(81, 92);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(47, 47);
this.panelGray.TabIndex = 2;
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(143, 32);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(47, 47);
this.panelBlue.TabIndex = 3;
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(81, 32);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(47, 47);
this.panelGreen.TabIndex = 1;
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(18, 92);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(47, 47);
this.panelWhite.TabIndex = 1;
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(18, 32);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(47, 47);
this.panelRed.TabIndex = 0;
//
// checkBoxPassengerCompartment
//
this.checkBoxPassengerCompartment.AutoSize = true;
this.checkBoxPassengerCompartment.Location = new System.Drawing.Point(17, 184);
this.checkBoxPassengerCompartment.Name = "checkBoxPassengerCompartment";
this.checkBoxPassengerCompartment.Size = new System.Drawing.Size(320, 24);
this.checkBoxPassengerCompartment.TabIndex = 5;
this.checkBoxPassengerCompartment.Text = "Признак наличия отсека для пассажиров";
this.checkBoxPassengerCompartment.UseVisualStyleBackColor = true;
//
// checkBoxEngine
//
this.checkBoxEngine.AutoSize = true;
this.checkBoxEngine.Location = new System.Drawing.Point(17, 138);
this.checkBoxEngine.Name = "checkBoxEngine";
this.checkBoxEngine.Size = new System.Drawing.Size(236, 24);
this.checkBoxEngine.TabIndex = 4;
this.checkBoxEngine.Text = "Признак наличия двигателей";
this.checkBoxEngine.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(108, 94);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(86, 27);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(108, 44);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(86, 27);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(17, 94);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(36, 20);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес:";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(17, 44);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(76, 20);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость:";
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Controls.Add(this.labelExtraColor);
this.panelObject.Controls.Add(this.labelColor);
this.panelObject.Location = new System.Drawing.Point(714, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(338, 228);
this.panelObject.TabIndex = 1;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(0, 52);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(331, 167);
this.pictureBoxObject.TabIndex = 2;
this.pictureBoxObject.TabStop = false;
//
// labelExtraColor
//
this.labelExtraColor.AllowDrop = true;
this.labelExtraColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelExtraColor.Location = new System.Drawing.Point(169, 14);
this.labelExtraColor.Name = "labelExtraColor";
this.labelExtraColor.Size = new System.Drawing.Size(150, 35);
this.labelExtraColor.TabIndex = 1;
this.labelExtraColor.Text = "Доп. цвет";
this.labelExtraColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelExtraColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
this.labelExtraColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelColor
//
this.labelColor.AllowDrop = true;
this.labelColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelColor.Location = new System.Drawing.Point(13, 14);
this.labelColor.Name = "labelColor";
this.labelColor.Size = new System.Drawing.Size(150, 35);
this.labelColor.TabIndex = 0;
this.labelColor.Text = "Цвет";
this.labelColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(717, 246);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(160, 46);
this.buttonAdd.TabIndex = 2;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(883, 246);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(160, 46);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Отменить";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormAirplaneConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1059, 304);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxParameters);
this.Name = "FormAirplaneConfig";
this.Text = "Создание объекта";
this.groupBoxParameters.ResumeLayout(false);
this.groupBoxParameters.PerformLayout();
this.groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private Label labelWeight;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private CheckBox checkBoxEngine;
private CheckBox checkBoxPassengerCompartment;
private GroupBox groupBoxColor;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelYellow;
private Panel panelGray;
private Panel panelBlue;
private Label labelSimpleObject;
private Label labelModifiedObject;
private Panel panelObject;
private Button buttonAdd;
private Button buttonCancel;
private PictureBox pictureBoxObject;
private Label labelExtraColor;
private Label labelColor;
}
}

View File

@ -0,0 +1,199 @@
using Airbus_Base.DrawningObjects;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Airbus_Base
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormAirplaneConfig : Form
{
/// <summary>
/// Переменная-выбранный самолёт
/// </summary>
DrawningAirplane? _airplane = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningAirplane>? EventAddAirplane;
/// <summary>
/// Конструктор
/// </summary>
public FormAirplaneConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать самолёт
/// </summary>
private void DrawAirplane()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_airplane?.SetPosition(5, 5);
_airplane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawningAirplane> ev)
{
if (EventAddAirplane == null)
{
EventAddAirplane = ev;
}
else
{
EventAddAirplane += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_airplane = new DrawningAirplane((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value,
Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelModifiedObject":
_airplane = new DrawningAirbus((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value,
Color.White, Color.Black, checkBoxEngine.Checked, checkBoxPassengerCompartment.Checked,
pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
labelColor.BackColor = Color.Empty;
labelExtraColor.BackColor = Color.Empty;
DrawAirplane();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_airplane == null)
{
return;
}
labelColor.BackColor = (Color)e.Data.GetData(typeof(Color));
_airplane.SetColor(labelColor.BackColor);
DrawAirplane();
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if ((_airplane == null) || (_airplane is DrawningAirbus == false))
{
return;
}
labelExtraColor.BackColor = (Color)e.Data.GetData(typeof(Color));
((DrawningAirbus)_airplane).SetAddColor(labelExtraColor.BackColor);
DrawAirplane();
}
/// <summary>
/// Добавление самолёта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
EventAddAirplane?.Invoke(_airplane);
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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

@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Airbus_Base.Exceptions;
namespace Airbus_Base.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в cписке
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в cписке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="airplane">Добавляемый самолёт</param>
/// <returns></returns>
public void Insert(T airplane)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
Insert(airplane, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="airplane">Добавляемый самолёт</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public void Insert(T airplane, int position)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (!(position >= 0 && position <= Count))
{
throw new Exception("Неверная позиция для вставки");
}
_places.Insert(position, airplane);
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public void Remove(int position)
{
if (!(position >= 0 && position < Count))
{
throw new AirplaneNotFoundException(position);
}
_places.RemoveAt(position);
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (!(position >= 0 && position < Count))
{
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetTheAirplanes(int? maxTheAirplanes = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxTheAirplanes.HasValue && i == maxTheAirplanes.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,191 @@
using Airbus_Base.DrawningObjects;
using Airbus_Base.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class TheAirplaneGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, TheAirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>> _airplaneStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _airplaneStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public TheAirplaneGenericStorage(int pictureWidth, int pictureHeight)
{
_airplaneStorages = new Dictionary<string, TheAirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Сохранение информации по самолётам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, TheAirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>> record in _airplaneStorages)
{
StringBuilder records = new();
foreach (DrawningAirplane? elem in record.Value.GetTheAirplanes)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
string toWrite = $"AirplaneStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
}
}
/// <summary>
/// Загрузка информации по самолётам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("AirplaneStorage"))
{
throw new IOException("Неверный формат данных");
}
_airplaneStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
TheAirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if (airplane != null)
{
if (!(collection + airplane))
{
throw new IOException("Ошибка добавления в коллекцию");
}
}
}
_airplaneStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_airplaneStorages.Add(name, new TheAirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_airplaneStorages.ContainsKey(name))
{
return;
}
_airplaneStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public TheAirplanesGenericCollection<DrawningAirplane, DrawningObjectAirplane>? this[string ind]
{
get
{
if (_airplaneStorages.ContainsKey(ind))
{
return _airplaneStorages[ind];
}
return null;
}
}
}
}

View File

@ -0,0 +1,159 @@
using Airbus_Base.DrawningObjects;
using Airbus_Base.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningAirplane
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class TheAirplanesGenericCollection<T, U>
where T : DrawningAirplane
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTheAirplanes => _collection.GetTheAirplanes();
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 103;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public TheAirplanesGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static bool operator +(TheAirplanesGenericCollection<T, U> collect, T? obj)
{
if (obj == null || collect == null)
{
return false;
}
collect?._collection.Insert(obj);
return true;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(TheAirplanesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowTheAirplanes()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight,
i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth,
_pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param
private void DrawObjects(Graphics g)
{
int x = _pictureWidth / _placeSizeWidth - 1;
int y = _pictureHeight / _placeSizeHeight - 1;
foreach (var airplane in _collection.GetTheAirplanes())
{
if (airplane != null)
{
if (x < 0)
{
x = _pictureWidth / _placeSizeWidth - 1;
--y;
}
airplane.SetPosition(_placeSizeWidth * x, _placeSizeHeight * y);
airplane.DrawTransport(g);
--x;
}
}
}
}
}

View File

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Airbus_Base.MovementStrategy;
namespace Airbus_Base.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,43 @@
using Airbus_Base.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningAirplane (паттерн Adapter)
/// </summary>
public class DrawningObjectAirplane : IMoveableObject
{
private readonly DrawningAirplane? _drawningAirplane = null;
public DrawningObjectAirplane(DrawningAirplane drawningAirplane)
{
_drawningAirplane = drawningAirplane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningAirplane == null || _drawningAirplane.EntityAirplane == null)
{
return null;
}
return new ObjectParameters(_drawningAirplane.GetPosX,
_drawningAirplane.GetPosY, _drawningAirplane.GetWidth, _drawningAirplane.GetHeight);
}
}
public int GetStep => (int)(_drawningAirplane?.EntityAirplane?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawningAirplane?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawningAirplane?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.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,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.MovementStrategy
{
// <summary>
/// Стратегия перемещения объекта в правый нижний край экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.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,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airbus_Base.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

43
Airbus_Base/Program.cs Normal file
View File

@ -0,0 +1,43 @@
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace Airbus_Base
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormAirplaneCollection());
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Airbus_Base.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("Airbus_Base.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 Down {
get {
object obj = ResourceManager.GetObject("Down", 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 Right {
get {
object obj = ResourceManager.GetObject("Right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Up {
get {
object obj = ResourceManager.GetObject("Up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,133 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<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="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="Up" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Up.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Down" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Down.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}