Compare commits

...

5 Commits

31 changed files with 2240 additions and 50 deletions

View File

@ -0,0 +1,137 @@
using ProjectSeaplane.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectSeaplane.Direction;
namespace ProjectSeaplane.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,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane
{
public class Direction
{
/// <summary>
/// Направление перемещения
/// </summary>
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}
}

View File

@ -0,0 +1,249 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectSeaplane.Entities;
using ProjectSeaplane.MovementStrategy;
using static ProjectSeaplane.Direction;
namespace ProjectSeaplane.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
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 int _planeWidth = 200;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private int _planeHeight = 90;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningPlane(int speed, double weight, Color bodyColor, int width, int height)
{
// TODO: Продумать проверки
if (width > _planeWidth && height > _planeHeight)
{
_pictureWidth = width;
_pictureHeight = height;
EntityPlane = new EntityPlane(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="planeWidth">Ширина прорисовки автомобиля</param>
/// <param name="planeHeight">Высота прорисовки автомобиля</param>
protected DrawningPlane(int speed, double weight, Color bodyColor, int width, int height, int planeWidth, int planeHeight)
{
// TODO: Продумать проверки
if (width > _planeWidth && height > _planeHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_planeWidth = planeWidth;
_planeHeight = planeHeight;
EntityPlane = new EntityPlane(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 < _pictureWidth - _planeWidth))
_startPosX = x;
else _startPosX = 0;
if ((y > 0) && (y < _pictureHeight - _planeHeight))
_startPosY = y;
else _startPosY = 0;
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _planeWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _planeHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityPlane == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityPlane.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityPlane.Step > 0,
// вправо
DirectionType.Right => _startPosX + _planeWidth + EntityPlane.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _planeHeight + EntityPlane.Step < _pictureHeight,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityPlane == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityPlane.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityPlane.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityPlane.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityPlane.Step;
break;
}
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectPlane(this);
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityPlane == null)
{
return;
}
Brush BodyBrush = new SolidBrush(EntityPlane.BodyColor);
Pen pen = new(Color.Black);
g.DrawLine(pen, _startPosX + 10, _startPosY, _startPosX + 10, _startPosY + 30);
g.DrawLine(pen, _startPosX + 10, _startPosY, _startPosX + 40, _startPosY + 30);
g.DrawLine(pen, _startPosX + 10, _startPosY + 30, _startPosX + 150, _startPosY + 30);
g.DrawLine(pen, _startPosX + 150, _startPosY + 30, _startPosX + 150, _startPosY + 80);
g.DrawLine(pen, _startPosX + 10, _startPosY + 80, _startPosX + 150, _startPosY + 80);
g.DrawLine(pen, _startPosX + 150, _startPosY + 30, _startPosX + 200, _startPosY + 55);
g.DrawLine(pen, _startPosX + 200, _startPosY + 55, _startPosX + 150, _startPosY + 55);
g.DrawLine(pen, _startPosX + 200, _startPosY + 55, _startPosX + 150, _startPosY + 80);
g.DrawPie(pen, _startPosX, _startPosY + 30, 20, 50, 90, 180);
g.DrawEllipse(pen, _startPosX, _startPosY + 25, 35, 10);
g.DrawEllipse(pen, _startPosX + 40, _startPosY + 50, 80, 10);
//вертикальная стабилизация
Brush mainBrush = new SolidBrush(EntityPlane.BodyColor);
Point point7 = new Point(_startPosX + 11, _startPosY + 1);
Point point8 = new Point(_startPosX + 11, _startPosY + 31);
Point point9 = new Point(_startPosX + 39, _startPosY + 31);
Point[] vert_stab = { point7, point8, point9, point7 };
g.FillPolygon(mainBrush, vert_stab);
//хвостовая часть
g.FillPie(mainBrush, _startPosX, _startPosY + 30, 20, 50, 90, 180);
//нос
Brush brGray = new SolidBrush(Color.Gray);
Point point1 = new Point(_startPosX + 150, _startPosY + 30);
Point point2 = new Point(_startPosX + 200, _startPosY + 55);
Point point3 = new Point(_startPosX + 150, _startPosY + 55);
Point[] nos1 = { point1, point2, point3, point1 };
g.FillPolygon(brGray, nos1);
Point point4 = new Point(_startPosX + 150, _startPosY + 55);
Point point5 = new Point(_startPosX + 200, _startPosY + 55);
Point point6 = new Point(_startPosX + 150, _startPosY + 80);
Point[] nos2 = { point4, point5, point6, point4 };
g.FillPolygon(brGray, nos2);
g.DrawLine(pen, _startPosX + 200, _startPosY + 55, _startPosX + 150, _startPosY + 55);
//корпус
Point point10 = new Point(_startPosX + 10, _startPosY + 31);
Point point11 = new Point(_startPosX + 149, _startPosY + 31);
Point point12 = new Point(_startPosX + 149, _startPosY + 79);
Point point13 = new Point(_startPosX + 10, _startPosY + 79);
Point[] body = { point10, point11, point12, point13, point10 };
g.FillPolygon(mainBrush, body);
//крылья
Brush brBlack = new SolidBrush(Color.Black);
g.FillEllipse(brBlack, _startPosX + 40, _startPosY + 50, 80, 10);
g.FillEllipse(brBlack, _startPosX, _startPosY + 25, 35, 10);
}
}
}

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectSeaplane.Entities;
namespace ProjectSeaplane.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningSeaplane : DrawningPlane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// /// <param name="boat">Лодка</param>
/// /// <param name="floater">Дополнительный цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningSeaplane(int speed, double weight, Color bodyColor, Color additionalColor, bool boat, bool floater, int width, int height) :
base(speed, weight, bodyColor, width, height, 200, 110)
{
if (EntityPlane != null)
{
EntityPlane = new EntitySeaplane(speed, weight, bodyColor, additionalColor, boat, floater);
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityPlane is not EntitySeaplane seaPlane)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(seaPlane.AdditionalColor);
// лодка
if (seaPlane.Boat)
{
g.DrawEllipse(pen, _startPosX + 40, _startPosY, 90, 20);
g.DrawLine(pen, _startPosX + 60, _startPosY + 20, _startPosX + 50, _startPosY + 30);
g.DrawLine(pen, _startPosX + 60, _startPosY + 20, _startPosX + 70, _startPosY + 30);
g.DrawLine(pen, _startPosX + 110, _startPosY + 20, _startPosX + 100, _startPosY + 30);
g.DrawLine(pen, _startPosX + 110, _startPosY + 20, _startPosX + 120, _startPosY + 30);
g.FillEllipse(additionalBrush, _startPosX + 40, _startPosY, 90, 20);
}
//поплавок
if(seaPlane.Floater)
{
g.DrawLine(pen, _startPosX + 70, _startPosY + 80, _startPosX + 50, _startPosY + 100);
g.DrawLine(pen, _startPosX + 70, _startPosY + 80, _startPosX + 70, _startPosY + 100);
g.DrawLine(pen, _startPosX + 120, _startPosY + 80, _startPosX + 90, _startPosY + 100);
g.DrawLine(pen, _startPosX + 120, _startPosY + 80, _startPosX + 110, _startPosY + 100);
g.DrawLine(pen, _startPosX + 120, _startPosY + 80, _startPosX + 140, _startPosY + 100);
g.DrawEllipse(pen, _startPosX + 30, _startPosY + 100, 140, 10);
g.FillEllipse(additionalBrush, _startPosX + 30, _startPosY + 100, 140, 10);
}
base.DrawTransport(g);
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectSeaplane.MovementStrategy;
using ProjectSeaplane.DrawningObjects;
using static ProjectSeaplane.Direction;
namespace ProjectSeaplane.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningPlane (паттерн Adapter)
/// </summary>
public class DrawningObjectPlane : IMoveableObject
{
private readonly DrawningPlane? _drawningPlane = null;
public DrawningObjectPlane(DrawningPlane drawningPlane)
{
_drawningPlane = drawningPlane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningPlane == null || _drawningPlane.EntityPlane == null)
{
return null;
}
return new ObjectParameters(_drawningPlane.GetPosX, _drawningPlane.GetPosY, _drawningPlane.GetWidth, _drawningPlane.GetHeight);
}
}
public int GetStep => (int)(_drawningPlane?.EntityPlane?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawningPlane?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawningPlane?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.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 => (double)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

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Entities
{
public class EntitySeaplane : EntityPlane
{
/// <summary>
/// Лодка
/// </summary>
public bool Boat { get; private set; }
/// <summary>
/// Лодка
/// </summary>
public bool Floater { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// /// <param name="Boat">Признак наличия лодки</param>
/// <param name="Floater">Признак наличия поплавка</param>
public EntitySeaplane(int speed, double weight, Color bodyColor, Color additionalColor, bool boat, bool floater) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Boat = boat;
Floater = floater;
}
}
}

View File

@ -1,39 +0,0 @@
namespace ProjectSeaplane
{
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 ProjectSeaplane
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,188 @@
namespace ProjectSeaplane
{
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()
{
pictureBoxCollection = new PictureBox();
groupBox1 = new GroupBox();
groupBox2 = new GroupBox();
buttonDeleteObject = new Button();
listBoxStorages = new ListBox();
buttonAddObject = new Button();
textBoxStorageName = new TextBox();
buttonRefreshCollection = new Button();
buttonRemovePlane = new Button();
maskedTextBoxNumber = new MaskedTextBox();
buttonAddPlane = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(1026, 446);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// groupBox1
//
groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(buttonRefreshCollection);
groupBox1.Controls.Add(buttonRemovePlane);
groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(buttonAddPlane);
groupBox1.Location = new Point(852, 0);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(174, 439);
groupBox1.TabIndex = 2;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
//
// groupBox2
//
groupBox2.Controls.Add(buttonDeleteObject);
groupBox2.Controls.Add(listBoxStorages);
groupBox2.Controls.Add(buttonAddObject);
groupBox2.Controls.Add(textBoxStorageName);
groupBox2.Location = new Point(12, 39);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(150, 219);
groupBox2.TabIndex = 4;
groupBox2.TabStop = false;
groupBox2.Text = "Наборы";
//
// buttonDeleteObject
//
buttonDeleteObject.Location = new Point(6, 190);
buttonDeleteObject.Name = "buttonDeleteObject";
buttonDeleteObject.Size = new Size(138, 23);
buttonDeleteObject.TabIndex = 3;
buttonDeleteObject.Text = "Удалить набор";
buttonDeleteObject.UseVisualStyleBackColor = true;
buttonDeleteObject.Click += ButtonDelObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(6, 85);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(138, 94);
listBoxStorages.TabIndex = 2;
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(6, 56);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(138, 23);
buttonAddObject.TabIndex = 1;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(6, 22);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(138, 23);
textBoxStorageName.TabIndex = 0;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(14, 407);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(149, 23);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// buttonRemovePlane
//
buttonRemovePlane.Location = new Point(14, 377);
buttonRemovePlane.Name = "buttonRemovePlane";
buttonRemovePlane.Size = new Size(149, 24);
buttonRemovePlane.TabIndex = 2;
buttonRemovePlane.Text = "Удалить самолет";
buttonRemovePlane.UseVisualStyleBackColor = true;
buttonRemovePlane.Click += buttonRemovePlane_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(14, 348);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(149, 23);
maskedTextBoxNumber.TabIndex = 1;
//
// buttonAddPlane
//
buttonAddPlane.Location = new Point(14, 317);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(149, 25);
buttonAddPlane.TabIndex = 0;
buttonAddPlane.Text = "Добавить самолет";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += buttonAddPlane_Click;
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1026, 446);
Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection);
Name = "FormPlaneCollection";
Text = "Набор самолетов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCollection;
private GroupBox groupBox1;
private Button buttonRefreshCollection;
private Button buttonRemovePlane;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonAddPlane;
private GroupBox groupBox2;
private Button buttonDeleteObject;
private ListBox listBoxStorages;
private Button buttonAddObject;
private TextBox textBoxStorageName;
}
}

View File

@ -0,0 +1,184 @@
using ProjectSeaplane.DrawningObjects;
using ProjectSeaplane.Generics;
using ProjectSeaplane.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 ProjectSeaplane
{
public partial class FormPlaneCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly PlanesGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection()
{
InitializeComponent();
_storage = new PlanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
foreach (var key in _storage.Keys)
{
listBoxStorages.Items.Add(key);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.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();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowPlanes();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?",
"Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddPlane_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormSeaplane form = new FormSeaplane();
if (form.ShowDialog() == DialogResult.OK)
{
if (obj + form.SelectedPlane)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemovePlane_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowPlanes();
}
}
}
}

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,188 @@
namespace ProjectSeaplane
{
partial class FormSeaplane
{
/// <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()
{
pictureBoxSeaplane = new PictureBox();
buttonCreatePlane = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonUp = new Button();
ComboBox = new ComboBox();
buttonCreateSeaplane = new Button();
buttonStep = new Button();
buttonSelectPlane = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSeaplane).BeginInit();
SuspendLayout();
//
// pictureBoxSeaplane
//
pictureBoxSeaplane.Dock = DockStyle.Fill;
pictureBoxSeaplane.Location = new Point(0, 0);
pictureBoxSeaplane.Name = "pictureBoxSeaplane";
pictureBoxSeaplane.Size = new Size(884, 461);
pictureBoxSeaplane.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxSeaplane.TabIndex = 0;
pictureBoxSeaplane.TabStop = false;
//
// buttonCreatePlane
//
buttonCreatePlane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreatePlane.Location = new Point(174, 431);
buttonCreatePlane.Name = "buttonCreatePlane";
buttonCreatePlane.Size = new Size(147, 23);
buttonCreatePlane.TabIndex = 1;
buttonCreatePlane.Text = "Создать самолет";
buttonCreatePlane.UseVisualStyleBackColor = true;
buttonCreatePlane.Click += buttonCreatePlane_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight2;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(854, 431);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 2;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown2;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(818, 431);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(782, 431);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp2;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(818, 395);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 5;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// ComboBox
//
ComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
ComboBox.FormattingEnabled = true;
ComboBox.Location = new Point(751, 12);
ComboBox.Name = "ComboBox";
ComboBox.Size = new Size(121, 23);
ComboBox.TabIndex = 6;
//
// buttonCreateSeaplane
//
buttonCreateSeaplane.Location = new Point(9, 431);
buttonCreateSeaplane.Name = "buttonCreateSeaplane";
buttonCreateSeaplane.Size = new Size(159, 23);
buttonCreateSeaplane.TabIndex = 7;
buttonCreateSeaplane.Text = "Создать гидросамолет";
buttonCreateSeaplane.UseVisualStyleBackColor = true;
buttonCreateSeaplane.Click += buttonCreateSeaplane_Click;
//
// buttonStep
//
buttonStep.Location = new Point(797, 41);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 23);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonSelectPlane
//
buttonSelectPlane.Location = new Point(338, 431);
buttonSelectPlane.Name = "buttonSelectPlane";
buttonSelectPlane.Size = new Size(118, 23);
buttonSelectPlane.TabIndex = 9;
buttonSelectPlane.Text = "Выбрать объект";
buttonSelectPlane.UseVisualStyleBackColor = true;
buttonSelectPlane.Click += buttonSelectPlane_Click;
//
// FormSeaplane
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(buttonSelectPlane);
Controls.Add(buttonStep);
Controls.Add(buttonCreateSeaplane);
Controls.Add(ComboBox);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonCreatePlane);
Controls.Add(pictureBoxSeaplane);
Name = "FormSeaplane";
StartPosition = FormStartPosition.CenterScreen;
Text = "Гидросамолет";
((System.ComponentModel.ISupportInitialize)pictureBoxSeaplane).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxSeaplane;
private Button buttonCreatePlane;
private Button buttonRight;
private Button buttonDown;
private Button buttonLeft;
private Button buttonUp;
private ComboBox ComboBox;
private Button buttonCreateSeaplane;
private Button buttonStep;
private Button buttonSelectPlane;
}
}

View File

@ -0,0 +1,149 @@
using ProjectSeaplane.DrawningObjects;
using ProjectSeaplane.MovementStrategy;
using static ProjectSeaplane.Direction;
using System;
namespace ProjectSeaplane
{
public partial class FormSeaplane : Form
{
private DrawningPlane? _drawningSeaplane;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âûáðàííûé ñàìîëåò
/// </summary>
public DrawningPlane? SelectedPlane { get; private set; }
public FormSeaplane()
{
InitializeComponent();
ComboBox.Items.Add(0);
ComboBox.Items.Add(1);
_abstractStrategy = null;
SelectedPlane = null;
}
private void Draw()
{
if (_drawningSeaplane == null)
{
return;
}
Bitmap bmp = new(pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
Graphics g = Graphics.FromImage(bmp);
_drawningSeaplane.DrawTransport(g);
pictureBoxSeaplane.Image = bmp;
}
private void buttonCreatePlane_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 dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawningSeaplane = new DrawningPlane(random.Next(100, 300), random.Next(1000, 3000),
color, pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
_drawningSeaplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningSeaplane == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningSeaplane.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningSeaplane.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningSeaplane.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningSeaplane.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void buttonCreateSeaplane_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 dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog2 = new();
if (dialog2.ShowDialog() == DialogResult.OK)
{
dopColor = dialog2.Color;
}
_drawningSeaplane = new DrawningSeaplane(random.Next(100, 300), random.Next(1000, 3000),
color, dopColor, true, true,
pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
_drawningSeaplane.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningSeaplane == null)
{
return;
}
if (ComboBox.Enabled)
{
_abstractStrategy = ComboBox.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawningObjectPlane(_drawningSeaplane), pictureBoxSeaplane.Width, pictureBoxSeaplane.Height);
ComboBox.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
ComboBox.Enabled = true;
_abstractStrategy = null;
}
}
private void buttonSelectPlane_Click(object sender, EventArgs e)
{
SelectedPlane = _drawningSeaplane;
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,37 @@
using ProjectSeaplane.MovementStrategy;
using ProjectSeaplane;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectSeaplane.Direction;
namespace ProjectSeaplane.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,57 @@
using ProjectSeaplane.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectRightBorder <= FieldWidth &&
objParams.ObjectRightBorder + GetStep() >= FieldWidth &&
objParams.ObjectDownBorder <= FieldHeight &&
objParams.ObjectDownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectRightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectDownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,60 @@
using ProjectSeaplane.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.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 ProjectSeaplane.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>
public int ObjectRightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int ObjectDownBorder => _y + _height;
/// <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,141 @@
using ProjectSeaplane.DrawningObjects;
using ProjectSeaplane.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Generics
{
internal class PlanesGenericCollection<T, U>
where T : DrawningPlane
where U : IMoveableObject
{
/// <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 = 110;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public PlanesGenericCollection(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 +(PlanesGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return false;
}
return (bool)collect?._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(PlanesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
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 ShowPlanes()
{
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, 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 width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int i = 0;
foreach (var plane in _collection.GetPlanes())
{
if (plane != null)
{
plane.SetPosition((width - 1 - (i % width)) * _placeSizeWidth, (width - (i / width) - 1) * _placeSizeHeight);
plane.DrawTransport(g);
}
i++;
}
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectSeaplane.DrawningObjects;
using ProjectSeaplane.MovementStrategy;
using ProjectSeaplane.Generics;
namespace ProjectSeaplane.Generics
{
internal class PlanesGenericStorage
{
readonly Dictionary<string, PlanesGenericCollection<DrawningPlane, DrawningObjectPlane>> _planeStorages;
public List<string> Keys => _planeStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
public PlanesGenericStorage(int pictureWidth, int pictureHeight)
{
_planeStorages = new Dictionary<string, PlanesGenericCollection<DrawningPlane, DrawningObjectPlane>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
if (_planeStorages.ContainsKey(name)) return;
_planeStorages[name] = new PlanesGenericCollection<DrawningPlane, DrawningObjectPlane>(_pictureWidth, _pictureHeight);
}
public void DelSet(string name)
{
if (!_planeStorages.ContainsKey(name)) return;
_planeStorages.Remove(name);
}
public PlanesGenericCollection<DrawningPlane, DrawningObjectPlane>?
this[string ind]
{
get
{
if (_planeStorages.ContainsKey(ind)) return _planeStorages[ind];
return null;
}
}
}
}

View File

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

View File

@ -8,4 +8,19 @@
<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

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </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="car">Добавляемый автомобиль</param>
/// <returns></returns>
public bool Insert(T plane)
{
return Insert(plane, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T plane, int position)
{
if (position < 0 || position >= _maxCount)
return false;
if (Count >= _maxCount)
return false;
_places.Insert(0, plane);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position > _maxCount)
return false;
if (position >= Count)
return false;
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (position < 0 || position > _maxCount)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetPlanes(int? maxPlanes = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxPlanes.HasValue && i == maxPlanes.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.MovementStrategy
{
public enum Status
{
NotInit, InProgress, Finish
}
}