Compare commits

..

6 Commits

35 changed files with 2139 additions and 88 deletions

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.9.34622.214 VisualStudioVersion = 17.9.34622.214
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectBomber", "ProjectBomber\ProjectBomber.csproj", "{7F0774DC-8F8B-4C90-922C-4BAB7F02417C}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectAirBomber", "ProjectBomber\ProjectAirBomber.csproj", "{7F0774DC-8F8B-4C90-922C-4BAB7F02417C}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -0,0 +1,105 @@
using ProjectAirBomber.CollectionGenericObject;
using ProjectAirBomber.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.CollectionGenericObject;
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 180;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 170;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция автомобилей
/// </summary>
protected ICollectionGenericObject<DrawningPlane>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция автомобилей</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObject<DrawningPlane> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="plane">Добавляемый объект</param>
/// <returns></returns>
public static int? operator +(AbstractCompany company, DrawningPlane plane)
{
return company._collection?.Insert(plane);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningPlane operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningPlane? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningPlane? obj = _collection?.Get(i);
obj?.DrawPlane(graphics);
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.CollectionGenericObject;
public interface ICollectionGenericObject<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool? Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
}

View File

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.CollectionGenericObject;
public class MassiveGenericObject<T> : ICollectionGenericObject<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
{
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObject()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position) // получение с позиции
{
if (position < 0 || position >= _collection.Length) // если позиция передано неправильно
return null;
return _collection[position];
}
public int Insert(T obj) // вставка объекта на свободное место
{
for (int i = 0; i < _collection.Length; ++i)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
return -1;
}
public bool? Insert(T obj, int position) // вставка объекта на место
{
if (position < 0 || position >= _collection.Length) // если позиция переданна неправильно
return false;
if (_collection[position] == null)//если позиция пуста
{
_collection[position] = obj;
return true;
}
else
{
for (int i = position; i < _collection.Length; ++i) //ищем свободное место справа
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
for (int i = 0; i < position; ++i) // иначе слева
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
}
return false;
}
public T? Remove(int position) // удаление объекта, зануляя его
{
if (position < 0 || position >= _collection.Length || _collection[position] == null)
return null;
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectAirBomber.Drawnings;
namespace ProjectAirBomber.CollectionGenericObject;
public class PlaneHangar : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public PlaneHangar(int picWidth, int picHeight, ICollectionGenericObject<DrawningPlane> collection) : base(picWidth, picHeight, collection) { }
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black, 3);
int posX = 0;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
int posY = 0;
g.DrawLine(pen, posX, posY, posX, posY + _placeSizeHeight * (_pictureHeight / _placeSizeHeight));
for (int j = 0; j <= _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, posX, posY, posX + _placeSizeWidth - 30, posY);
posY += _placeSizeHeight;
}
posX += _placeSizeWidth;
}
}
protected override void SetObjectsPosition()
{
int posX = _pictureWidth / _placeSizeWidth - 1;
int posY = 0;
for (int i = 0; i < _collection?.Count; i++)
{
if (_collection.Get(i) != null)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(posX * _placeSizeWidth + 5, posY * _placeSizeHeight + 5);
}
if (posX > 0)
{
posX--;
}
else
{
posY++;
posX = _pictureWidth / _placeSizeWidth - 1;
}
if (posX < 0) { return; }
}
}
}

View File

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

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using ProjectAirBomber.Entities;
namespace ProjectAirBomber.Drawnings;
public class DrawingAirBomber : DrawningPlane
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engine">Дополнительный цвет</param>
/// <param name="bomb">Дополнительный цвет</param>
public DrawingAirBomber(int speed, double weight, Color bodyColor, Color
additionalColor, bool engine, bool bomb) : base(125, 155)
{
EntityPlane = new EntityAirBomber(speed, weight, bodyColor, additionalColor,
engine, bomb);
}
public override void DrawPlane(Graphics g)
{
if (EntityPlane == null || EntityPlane is not EntityAirBomber airBomber || !_startPosX.HasValue || !_startPosY.HasValue)
return;
base.DrawPlane(g);
Pen pen = new(Color.Black);
//наличие топливных баков
if (airBomber.Engine)
{
Brush brBrown = new SolidBrush(Color.Brown);
g.DrawRectangle(pen, _startPosX.Value + 90, _startPosY.Value + 60, 20, 5);
g.DrawRectangle(pen, _startPosX.Value + 90, _startPosY.Value + 95, 20, 5);
g.FillRectangle(brBrown, _startPosX.Value + 90, _startPosY.Value + 60, 20, 5);
g.FillRectangle(brBrown, _startPosX.Value + 90, _startPosY.Value + 95, 20, 5);
}
//наличие дополнительных бомб
if (airBomber.Bomb)
{
Brush brGreen = new SolidBrush(Color.Green);
g.DrawRectangle(pen, _startPosX.Value + 55, _startPosY.Value + 35, 20, 8);
g.DrawRectangle(pen, _startPosX.Value + 55, _startPosY.Value + 115, 20, 8);
g.FillRectangle(brGreen, _startPosX.Value + 55, _startPosY.Value + 35, 20, 8);
g.FillRectangle(brGreen, _startPosX.Value + 55, _startPosY.Value + 115, 20, 8);
}
}
}

View File

@ -0,0 +1,230 @@
using ProjectAirBomber.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.Drawnings;
public class DrawningPlane
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityPlane? EntityPlane { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int? _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int? _pictureHeight;
/// <summary>
/// Левая координата прорисовки самолета
/// </summary>
protected int? _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки самолета
/// </summary>
protected int? _startPosY;
/// <summary>
/// Ширина прорисовки самолета
/// </summary>
private readonly int _drawningPlaneWidth = 130;
/// <summary>
/// Высота прорисовки самолета
/// </summary>
private readonly int _drawningPlaneHeight = 150;
/// <summary>
/// Координата X
/// </summary>
public int? GetPosX => _startPosX;
/// <summary>
/// Координата Y
/// </summary>
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _drawningPlaneWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _drawningPlaneHeight;
/// <summary>
/// Пустой конструктор
/// </summary>
private DrawningPlane()
{
_pictureWidth = null;
_pictureHeight = null;
_startPosX = null;
_startPosY = null;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
public DrawningPlane(int speed, double weight, Color bodyColor) : this()
{
EntityPlane = new EntityPlane(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор для наследования
/// </summary>
/// <param name="drawningPlaneWidth">ширина самолета</param>
/// <param name="drawningPlaneHeight">высота самолета</param>
protected DrawningPlane(int drawningPlaneWidth, int drawningPlaneHeight) : this()
{
_drawningPlaneWidth = drawningPlaneWidth;
_drawningPlaneHeight = drawningPlaneHeight;
}
/// <summary>
/// Установка границ поля
/// </summary>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя
public bool SetPictureSize(int width, int height)
{
if (_drawningPlaneWidth <= width && _drawningPlaneHeight <= height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
if (_startPosX + _drawningPlaneWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningPlaneWidth;
}
if (_startPosY + _drawningPlaneHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningPlaneHeight;
}
}
return true;
}
return false;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
if (x < 0) x = 0;
else if (x + _drawningPlaneWidth > _pictureWidth) x = _pictureWidth.Value - _drawningPlaneWidth;
if (y < 0) y = 0;
else if (y + _drawningPlaneHeight > _pictureHeight) y = _pictureHeight.Value - _drawningPlaneHeight;
_startPosX = x;
_startPosY = y;
}
public bool MoveTransport(DirectionType direction)
{
if (EntityPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
return false;
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX.Value - EntityPlane.Step > 0)
_startPosX -= (int)EntityPlane.Step;
return true;
//вверх
case DirectionType.Up:
if (_startPosY.Value - EntityPlane.Step > 0)
_startPosY -= (int)EntityPlane.Step;
return true;
// вправо
case DirectionType.Right:
if (_startPosX.Value + _drawningPlaneWidth + EntityPlane.Step < _pictureWidth)
_startPosX += (int)EntityPlane.Step;
return true;
//вниз
case DirectionType.Down:
if (_startPosY.Value + _drawningPlaneHeight + EntityPlane.Step < _pictureHeight)
_startPosY += (int)EntityPlane.Step;
return true;
default:
return false;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
///
public virtual void DrawPlane(Graphics g)
{
if (EntityPlane == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
Pen pen = new(Color.Black);
//главная часть
Brush br = new SolidBrush(EntityPlane.BodyColor);
g.DrawRectangle(pen, _startPosX.Value+25, _startPosY.Value + 65, 100, 30);
g.FillRectangle(br, _startPosX.Value+25, _startPosY.Value + 65, 100, 30);
//носовая часть
Brush brBlack = new SolidBrush(Color.Black);
Point point1 = new Point(_startPosX.Value, _startPosY.Value + 80);
Point point2 = new Point(_startPosX.Value + 25, _startPosY.Value + 95);
Point point3 = new Point(_startPosX.Value + 25, _startPosY.Value + 65);
Point[] curvePointsNos = { point1, point2, point3 };
g.DrawPolygon(pen, curvePointsNos);
g.FillPolygon(brBlack, curvePointsNos);
//верхнее левое крыло
Point point4 = new Point(_startPosX.Value + 75, _startPosY.Value + 25);
Point point5 = new Point(_startPosX.Value + 75, _startPosY.Value + 65);
Point point6 = new Point(_startPosX.Value + 90, _startPosY.Value + 65);
Point point7 = new Point(_startPosX.Value + 80, _startPosY.Value + 25);
Point[] Wings1 = { point4, point5, point6, point7 };
g.DrawPolygon(pen, Wings1);
g.FillPolygon(br, Wings1);
//нижнее левое крыло
Point point8 = new Point(_startPosX.Value + 75, _startPosY.Value + 155);
Point point9 = new Point(_startPosX.Value + 75, _startPosY.Value + 95);
Point point10 = new Point(_startPosX.Value + 90, _startPosY.Value + 95);
Point point11 = new Point(_startPosX.Value + 80, _startPosY.Value + 155);
Point[] Wings2 = { point8, point9, point10, point11 };
g.DrawPolygon(pen, Wings2);
g.FillPolygon(br, Wings2);
//нижнее правое крыло
Point point12 = new Point(_startPosX.Value + 125, _startPosY.Value + 115);
Point point13 = new Point(_startPosX.Value + 125, _startPosY.Value + 95);
Point point14 = new Point(_startPosX.Value + 110, _startPosY.Value + 95);
Point point15 = new Point(_startPosX.Value + 115, _startPosY.Value + 115);
Point[] Wings3 = { point12, point13, point14, point15 };
g.DrawPolygon(pen, Wings3);
g.FillPolygon(br, Wings3);
//верхнее правое крыло
Point point16 = new Point(_startPosX.Value + 125, _startPosY.Value + 45);
Point point17 = new Point(_startPosX.Value + 125, _startPosY.Value + 65);
Point point18 = new Point(_startPosX.Value + 110, _startPosY.Value + 65);
Point point19 = new Point(_startPosX.Value + 115, _startPosY.Value + 45);
Point[] Wings4 = { point16, point17, point18, point19 };
g.DrawPolygon(pen, Wings4);
g.FillPolygon(br, Wings4);
}
}

View File

@ -0,0 +1,35 @@
namespace ProjectAirBomber.Entities;
/// <summary>
/// Класс сущность бомбардировщик
/// </summary>
public class EntityAirBomber : EntityPlane
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// наличие двигателя
/// </summary>
public bool Engine { get; private set; }
/// <summary>
/// наличие бомб
/// </summary>
public bool Bomb { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="engine">наличие двигателя</param>
/// <param name="bomb">наличие двигателя</param>
///
public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool engine, bool bomb) : base (speed,weight,bodyColor)
{
AdditionalColor = additionalColor;
Engine = engine;
Bomb = bomb;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,151 @@
using static System.Net.Mime.MediaTypeNames;
using System.Windows.Forms;
using System.Xml.Linq;
namespace ProjectAirBomber
{
partial class ProjectAirBomber
{
/// <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()
{
pictureBoxAirBomber = new PictureBox();
buttonLeft = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonRight = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).BeginInit();
SuspendLayout();
//
// pictureBoxAirBomber
//
pictureBoxAirBomber.Dock = DockStyle.Fill;
pictureBoxAirBomber.Location = new Point(0, 0);
pictureBoxAirBomber.Name = "pictureBoxAirBomber";
pictureBoxAirBomber.Size = new Size(1555, 684);
pictureBoxAirBomber.TabIndex = 0;
pictureBoxAirBomber.TabStop = false;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(1411, 637);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(1452, 596);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.ImageAlign = ContentAlignment.BottomRight;
buttonDown.Location = new Point(1452, 637);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(1493, 637);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(1392, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(1434, 46);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(94, 29);
buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click;
//
// ProjectAirBomber
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1555, 684);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxAirBomber);
Name = "ProjectAirBomber";
Text = "Бомбардировщик";
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxAirBomber;
private Button buttonLeft;
private Button buttonUp;
private Button buttonDown;
private Button buttonRight;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}
}

View File

@ -0,0 +1,129 @@
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.MovementStrategy;
using System.Windows.Forms;
namespace ProjectAirBomber
{
public partial class ProjectAirBomber : Form
{
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawningPlane? _drawningPlane;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawningPlane SetPlane
{
set
{
_drawningPlane = value;
_drawningPlane.SetPictureSize(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// Конструктор формы
/// </summary>
public ProjectAirBomber()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
{
if (_drawningPlane == null)
{
return;
}
Bitmap bmp = new(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningPlane.DrawPlane(gr);
pictureBoxAirBomber.Image = bmp;
}
/// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningPlane == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningPlane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningPlane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningPlane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningPlane.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
private void ButtonStrategyStep_Click(object sender, EventArgs e)
{
{
if (_drawningPlane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveablePlane(_drawningPlane),
pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->

View File

@ -0,0 +1,169 @@
namespace ProjectAirBomber
{
partial class FormPlaneCollection
{
/// <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()
{
groupBoxTools = new GroupBox();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonDelPlane = new Button();
maskedTextBox = new MaskedTextBox();
buttonAddAirBomber = new Button();
buttonAddPlane = new Button();
comboBoxSelectionCompany = new ComboBox();
pictureBox = new PictureBox();
groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonRefresh);
groupBoxTools.Controls.Add(buttonGoToCheck);
groupBoxTools.Controls.Add(buttonDelPlane);
groupBoxTools.Controls.Add(maskedTextBox);
groupBoxTools.Controls.Add(buttonAddAirBomber);
groupBoxTools.Controls.Add(buttonAddPlane);
groupBoxTools.Controls.Add(comboBoxSelectionCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1035, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(250, 667);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonRefresh
//
buttonRefresh.Location = new Point(6, 291);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(232, 32);
buttonRefresh.TabIndex = 7;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(6, 253);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(232, 32);
buttonGoToCheck.TabIndex = 6;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonDelPlane
//
buttonDelPlane.Location = new Point(9, 211);
buttonDelPlane.Name = "buttonDelPlane";
buttonDelPlane.Size = new Size(232, 36);
buttonDelPlane.TabIndex = 5;
buttonDelPlane.Text = "Удаление бомбардировщика";
buttonDelPlane.UseVisualStyleBackColor = true;
buttonDelPlane.Click += ButtonDelPlane_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(9, 178);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(229, 27);
maskedTextBox.TabIndex = 4;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonAddAirBomber
//
buttonAddAirBomber.Location = new Point(9, 113);
buttonAddAirBomber.Name = "buttonAddAirBomber";
buttonAddAirBomber.Size = new Size(232, 59);
buttonAddAirBomber.TabIndex = 2;
buttonAddAirBomber.Text = "Добавление бомбардировщика";
buttonAddAirBomber.UseVisualStyleBackColor = true;
buttonAddAirBomber.Click += ButtonAddAirBomber_Click;
//
// buttonAddPlane
//
buttonAddPlane.Location = new Point(9, 60);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(232, 47);
buttonAddPlane.TabIndex = 1;
buttonAddPlane.Text = "Добавление самолетов";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += ButtonAddPlane_Click;
//
// comboBoxSelectionCompany
//
comboBoxSelectionCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectionCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectionCompany.FormattingEnabled = true;
comboBoxSelectionCompany.Items.AddRange(new object[] { "Ангар" });
comboBoxSelectionCompany.Location = new Point(6, 26);
comboBoxSelectionCompany.Name = "comboBoxSelectionCompany";
comboBoxSelectionCompany.Size = new Size(232, 28);
comboBoxSelectionCompany.TabIndex = 0;
comboBoxSelectionCompany.SelectedIndexChanged += ComboBoxSelectionCompany_SelectedIndexChanged;
comboBoxSelectionCompany.Click += ComboBoxSelectionCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1035, 667);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1285, 667);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormPlaneCollection";
Text = "Коллекция Самолетов";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectionCompany;
private Button buttonAddPlane;
private Button buttonAddAirBomber;
private PictureBox pictureBox;
private Button buttonDelPlane;
private MaskedTextBox maskedTextBox;
private Button buttonRefresh;
private Button buttonGoToCheck;
}
}

View File

@ -0,0 +1,163 @@
using ProjectAirBomber.CollectionGenericObject;
using ProjectAirBomber;
using ProjectAirBomber.Drawnings;
using ProjectAirBomber.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;
namespace ProjectAirBomber
{
public partial class FormPlaneCollection : Form
{
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractCompany? _company = null;
public FormPlaneCollection()
{
InitializeComponent();
}
private void ComboBoxSelectionCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectionCompany.Text)
{
case "Ангар":
_company = new PlaneHangar(pictureBox.Width,
pictureBox.Height, new MassiveGenericObject<DrawningPlane>());
break;
}
}
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningPlane drawningPlane;
Random rnd = new Random();
switch (type)
{
case nameof(DrawningPlane):
drawningPlane = new DrawningPlane(rnd.Next(100, 300), rnd.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawingAirBomber):
drawningPlane = new DrawingAirBomber(rnd.Next(650, 700), rnd.Next(15760, 16130),
GetColor(random), GetColor(random),
Convert.ToBoolean(rnd.Next(0, 2)),
Convert.ToBoolean(rnd.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningPlane!= -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0,
256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// кнопка добавления самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddPlane_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningPlane));
/// <summary>
/// кнопка добавления бомбардировщика
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAirBomber_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingAirBomber));
/// <summary>
/// кнопка удаления
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelPlane_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningPlane? plane = null;
int counter = 100;
while (plane == null)
{
plane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (plane == null)
{
return;
}
ProjectAirBomber form = new()
{
SetPlane = plane
};
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public class MoveToBorder : AbstractStategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? 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()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public class MoveToCenter : AbstractStategy
{
protected override bool IsTargetDestinaion()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2
&& objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2
&& objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,63 @@
using ProjectAirBomber.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public class MoveablePlane : IMoveableObject
{
/// <summary>
/// Поле-объект класса Drawningplane или его наследника
/// </summary>
private readonly DrawningPlane? _plane = null;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="plane">Объект класса Drawningplane</param>
public MoveablePlane(DrawningPlane plane)
{
_plane = plane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_plane == null || _plane.EntityPlane == null ||
!_plane.GetPosX.HasValue || !_plane.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_plane.GetPosX.Value,
_plane.GetPosY.Value, _plane.GetWidth, _plane.GetHeight);
}
}
public int GetStep => (int)(_plane?.EntityPlane?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if (_plane == null || _plane.EntityPlane == null)
{
return false;
}
return _plane.MoveTransport(GetDirectionType(direction));
}
/// <summary>
/// Конвертация из MovementDirection в DirectionType
/// </summary>
/// <param name="direction">MovementDirection</param>
/// <returns>DirectionType</returns>
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirBomber.MovementStrategy;
public enum MovementDirection
{
Up = 1, Down = 2, Left = 3, Right = 4
}

View File

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

View File

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

View File

@ -1,4 +1,4 @@
namespace ProjectBomber namespace ProjectAirBomber
{ {
internal static class Program internal static class Program
{ {
@ -11,7 +11,7 @@ namespace ProjectBomber
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new Form1()); Application.Run(new FormPlaneCollection());
} }
} }
} }

View File

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

View File

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectAirBomber.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("ProjectAirBomber.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 arrowDown {
get {
object obj = ResourceManager.GetObject("arrowDown", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowLeft {
get {
object obj = ResourceManager.GetObject("arrowLeft", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowRight {
get {
object obj = ResourceManager.GetObject("arrowRight", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowUp {
get {
object obj = ResourceManager.GetObject("arrowUp", 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="arrowDown" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowDown.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowLeft" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowLeft.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowRight" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowRight.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrowUp" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrowUp.jpg;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: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB