Compare commits

...

8 Commits
main ... lab07

Author SHA1 Message Date
kagbie3nn@mail.ru
4699d561d4 7 лабораторная работа 2023-12-19 01:09:12 +04:00
kagbie3nn@mail.ru
9f3af0505b 7 базовая лабораторная 2023-12-19 01:03:37 +04:00
kagbie3nn@mail.ru
00cde777e1 6 базовая лабораторная 2023-12-19 00:33:54 +04:00
kagbie3nn@mail.ru
028c5c7ee9 5 базовая лабораторная 2023-11-19 18:02:52 +04:00
kagbie3nn@mail.ru
398534d097 4 базовая лабораторная 2023-11-19 16:41:27 +04:00
kagbie3nn@mail.ru
dea0c71159 3 базовая лабораторная 2023-11-19 15:13:34 +04:00
kagbie3nn@mail.ru
42d5d0a67c 2 базовая лабораторная 2023-11-17 12:59:09 +04:00
kagbie3nn@mail.ru
cc64fa0731 1 базовая лабораторная 2023-10-29 15:21:41 +04:00
35 changed files with 3340 additions and 50 deletions

View File

@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectWarmlyShip.DirectionType;
namespace ProjectWarmlyShip.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,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip
{
/// <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,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectWarmlyShip.DirectionType;
using ProjectWarmlyShip.Entities;
namespace ProjectWarmlyShip.DrawningObjects
{
// Класс, отвечающий за прорисовку и перемещение объекта-сущности
public class DrawningWarmlyShip : DrawningShip
{
public void setAdditionalColor(Color color)
{
(EntityShip as EntityWarmlyShip).AdditionalColor = color;
}
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет палубы</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="shipPipes">Признак наличия труб</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningWarmlyShip(int speed, double weight, Color bodyColor, Color additionalColor, bool shipPipes, bool shipFuel, int width, int height) :
base(speed, weight, bodyColor, width, height, 200, 30)
{
if (EntityShip != null)
{
EntityShip = new EntityWarmlyShip(speed, weight, bodyColor, additionalColor, shipPipes, shipFuel);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityShip is not EntityWarmlyShip warmlyShip)
{
return;
}
Brush additionalBrush = new SolidBrush(warmlyShip.AdditionalColor);
//трубы
if (warmlyShip.ShipPipes)
{
g.FillRectangle(additionalBrush, _startPosX + 180, _startPosY + 2, 3, 12);
g.FillRectangle(additionalBrush, _startPosX + 185, _startPosY + 4, 5, 10);
}
//топливо
if (warmlyShip.ShipFuel)
{
g.FillRectangle(additionalBrush, _startPosX + 12, _startPosY + 5, 27, 7);
}
base.DrawTransport(g);
}
}
}

View File

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

View File

@ -0,0 +1,218 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectWarmlyShip.DirectionType;
using ProjectWarmlyShip.Entities;
using ProjectWarmlyShip.MovementStrategy;
namespace ProjectWarmlyShip.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningShip
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityShip? EntityShip { 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>
protected readonly int _shipWidth = 200;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
protected readonly int _shipHeight = 30;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningShip(int speed, double weight, Color bodyColor, int width, int height)
{
// TODO: Продумать проверки
if (width > _shipWidth && height > _shipHeight)
{
_pictureWidth = width;
_pictureHeight = height;
EntityShip = new EntityShip(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="shipWidth">Ширина прорисовки автомобиля</param>
/// <param name="shipHeight">Высота прорисовки автомобиля</param>
protected DrawningShip(int speed, double weight, Color bodyColor, int width, int height, int shipWidth, int shipHeight)
{
// TODO: Продумать проверки
if (width > _shipWidth && height > _shipHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_shipWidth = shipWidth;
_shipHeight = shipHeight;
EntityShip = new EntityShip(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))
_startPosX = x;
else _startPosX = 0;
if ((y > 0) && (y < _pictureHeight))
_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 => _shipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _shipHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityShip == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityShip.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityShip.Step > 0,
// вправо
DirectionType.Right => _startPosX + _shipWidth + EntityShip.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _shipHeight + EntityShip.Step < _pictureHeight,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityShip == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityShip.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityShip.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityShip.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityShip.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityShip == null)
{
return;
}
Brush BodyBrush = new SolidBrush(EntityShip.BodyColor);
//границы корабля
Point point1 = new Point(_startPosX, _startPosY + 12);
Point point2 = new Point(_startPosX + 25, _startPosY + 35);
Point point3 = new Point(_startPosX + 175, _startPosY + 35);
Point point4 = new Point(_startPosX + 200, _startPosY + 12);
Point[] curvePoints1 = { point1, point2, point3, point4 };
g.FillPolygon(BodyBrush, curvePoints1);
//граница палубы
Brush brBl = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBl, _startPosX + 50, _startPosY + 0, 125, 12);
}
public void setBodyColor(Color color)
{
EntityShip.BodyColor = color;
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectShip(this);
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.Entities
{
/// <summary>
/// Класс-сущность "Корабль"
/// </summary>
public class EntityShip
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityShip(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 ProjectWarmlyShip.Entities
{
internal class EntityWarmlyShip : EntityShip
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия труб
/// </summary>
public bool ShipPipes { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительного топлива
/// </summary>
public bool ShipFuel { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса теплохода
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес </param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="ShipPipes">Признак наличия труб</param>
/// <param name="ShipFuel">Признак наличия топлива</param>
public EntityWarmlyShip(int speed, double weight, Color bodyColor, Color additionalColor, bool shipPipes, bool shipFuel) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
ShipPipes = shipPipes;
ShipFuel = shipFuel;
}
}
}

View File

@ -0,0 +1,53 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip
{
/// <summary>
/// Расширение для класса EntityShip
/// </summary>
public static class ExtentionShip
{
public static DrawningShip? CreateDrawningShip(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningWarmlyShip(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
public static string GetDataForSave(this DrawningShip ship, char separatorForObject)
{
var Ship = ship.EntityShip;
if (Ship == null)
{
return string.Empty;
}
var str = $"{Ship.Speed}{separatorForObject}{Ship.Weight}{separatorForObject}{Ship.BodyColor.Name}";
if (Ship is not EntityWarmlyShip warmlyShip)
{
return str;
}
return $"{str}{separatorForObject}{warmlyShip.AdditionalColor.Name}{separatorForObject}{warmlyShip.ShipPipes}{separatorForObject}{warmlyShip.ShipFuel}";
}
}
}

View File

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

View File

@ -0,0 +1,241 @@
namespace ProjectWarmlyShip
{
partial class FormShipCollection
{
/// <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();
maskedTextBoxNumber = new MaskedTextBox();
buttonRefreshCollection = new Button();
buttonRemoveShip = new Button();
ButtonAddShip = new Button();
groupBox2 = new GroupBox();
buttonDelObject = new Button();
listBoxStorages = new ListBox();
buttonAddObject = new Button();
textBoxStorageName = new TextBox();
файлToolStripMenuItem = new ToolStripMenuItem();
сохранениеToolStripMenuItem = new ToolStripMenuItem();
загрузкаToolStripMenuItem = new ToolStripMenuItem();
menuStrip = new MenuStrip();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 24);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(800, 426);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// groupBox1
//
groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(buttonRefreshCollection);
groupBox1.Controls.Add(buttonRemoveShip);
groupBox1.Controls.Add(ButtonAddShip);
groupBox1.Location = new Point(625, 0);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(175, 450);
groupBox1.TabIndex = 1;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(16, 357);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(136, 23);
maskedTextBoxNumber.TabIndex = 3;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(16, 415);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(136, 23);
buttonRefreshCollection.TabIndex = 2;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// buttonRemoveShip
//
buttonRemoveShip.Location = new Point(16, 386);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(136, 23);
buttonRemoveShip.TabIndex = 1;
buttonRemoveShip.Text = "Удалить корабль";
buttonRemoveShip.UseVisualStyleBackColor = true;
buttonRemoveShip.Click += ButtonRemoveShip_Click;
//
// ButtonAddShip
//
ButtonAddShip.Location = new Point(16, 328);
ButtonAddShip.Name = "ButtonAddShip";
ButtonAddShip.Size = new Size(136, 23);
ButtonAddShip.TabIndex = 0;
ButtonAddShip.Text = "Добавить корабль";
ButtonAddShip.UseVisualStyleBackColor = true;
ButtonAddShip.Click += ButtonAddShip_Click;
//
// groupBox2
//
groupBox2.Controls.Add(buttonDelObject);
groupBox2.Controls.Add(listBoxStorages);
groupBox2.Controls.Add(buttonAddObject);
groupBox2.Controls.Add(textBoxStorageName);
groupBox2.Location = new Point(625, 22);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(175, 300);
groupBox2.TabIndex = 4;
groupBox2.TabStop = false;
groupBox2.Text = "Наборы";
//
// buttonDelObject
//
buttonDelObject.Location = new Point(16, 240);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(136, 23);
buttonDelObject.TabIndex = 3;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += ButtonDelObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(16, 113);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(136, 94);
listBoxStorages.TabIndex = 2;
listBoxStorages.Click += ListBoxObjects_SelectedIndexChanged;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(16, 74);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(136, 23);
buttonAddObject.TabIndex = 1;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(16, 31);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(136, 23);
textBoxStorageName.TabIndex = 0;
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { сохранениеToolStripMenuItem, загрузкаToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "файл";
//
// сохранениеToolStripMenuItem
//
сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
сохранениеToolStripMenuItem.Size = new Size(180, 22);
сохранениеToolStripMenuItem.Text = "Сохранение";
сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// загрузкаToolStripMenuItem
//
загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
загрузкаToolStripMenuItem.Size = new Size(180, 22);
загрузкаToolStripMenuItem.Text = "Загрузка";
загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(800, 24);
menuStrip.TabIndex = 5;
menuStrip.Text = "menuStrip1";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(groupBox2);
Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection";
Text = "FormShipCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private GroupBox groupBox1;
private Button buttonRefreshCollection;
private Button buttonRemoveShip;
private Button ButtonAddShip;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBox2;
private Button buttonDelObject;
private ListBox listBoxStorages;
private Button buttonAddObject;
private TextBox textBoxStorageName;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранениеToolStripMenuItem;
private ToolStripMenuItem загрузкаToolStripMenuItem;
private MenuStrip menuStrip;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -0,0 +1,271 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.Generics;
using ProjectWarmlyShip.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
using ProjectWarmlyShip.Exceptions;
namespace ProjectWarmlyShip
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningShip
/// </summary>
public partial class FormShipCollection : Form
{ /// <summary>
/// Набор объектов
/// </summary>
private readonly ShipsGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
/// <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();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
/// <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]?.ShowShips();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
FormShipConfig form = new FormShipConfig();
Action<DrawningShip>? ShipDelegate = new((m) =>
{
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
_ = obj + m;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
});
form.AddEvent(ShipDelegate);
form.Show();
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (ShipNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Некорректные данные");
_logger.LogWarning("Некорректные данные");
}
}
/// <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.ShowShips();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
}
}

View File

@ -0,0 +1,129 @@
<?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>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,356 @@
namespace ProjectWarmlyShip
{
partial class FormShipConfig
{
/// <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()
{
groupBox1 = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
groupBox2 = new GroupBox();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelBlue = new Panel();
panelPurple = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxFuel = new CheckBox();
checkBoxPipes = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
label2 = new Label();
label1 = new Label();
panelReciever = new Panel();
pictureBoxObject = new PictureBox();
labelAdditionalColor = new Label();
labelColor = new Label();
buttonAddObj = new Button();
buttonCancelObj = new Button();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelReciever.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(labelModifiedObject);
groupBox1.Controls.Add(labelSimpleObject);
groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(checkBoxFuel);
groupBox1.Controls.Add(checkBoxPipes);
groupBox1.Controls.Add(numericUpDownWeight);
groupBox1.Controls.Add(numericUpDownSpeed);
groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(label1);
groupBox1.Location = new Point(12, 12);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(459, 207);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(352, 154);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(89, 34);
labelModifiedObject.TabIndex = 8;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(244, 154);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(96, 34);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// groupBox2
//
groupBox2.Controls.Add(panelWhite);
groupBox2.Controls.Add(panelYellow);
groupBox2.Controls.Add(panelBlack);
groupBox2.Controls.Add(panelGray);
groupBox2.Controls.Add(panelBlue);
groupBox2.Controls.Add(panelPurple);
groupBox2.Controls.Add(panelGreen);
groupBox2.Controls.Add(panelRed);
groupBox2.Location = new Point(244, 33);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(203, 100);
groupBox2.TabIndex = 6;
groupBox2.TabStop = false;
groupBox2.Text = "Цвета";
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(167, 58);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(30, 30);
panelWhite.TabIndex = 7;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(167, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(30, 30);
panelYellow.TabIndex = 3;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(114, 58);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(30, 30);
panelBlack.TabIndex = 6;
//
// panelGray
//
panelGray.BackColor = Color.FromArgb(64, 64, 64);
panelGray.Location = new Point(56, 58);
panelGray.Name = "panelGray";
panelGray.Size = new Size(30, 30);
panelGray.TabIndex = 5;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(114, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(30, 30);
panelBlue.TabIndex = 2;
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(6, 58);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(30, 30);
panelPurple.TabIndex = 4;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(56, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(30, 30);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(6, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(30, 30);
panelRed.TabIndex = 0;
//
// checkBoxFuel
//
checkBoxFuel.AutoSize = true;
checkBoxFuel.Location = new Point(19, 153);
checkBoxFuel.Name = "checkBoxFuel";
checkBoxFuel.Size = new Size(222, 19);
checkBoxFuel.TabIndex = 5;
checkBoxFuel.Text = "Признак наличия топливных баков";
checkBoxFuel.UseVisualStyleBackColor = true;
//
// checkBoxPipes
//
checkBoxPipes.AutoSize = true;
checkBoxPipes.Location = new Point(19, 128);
checkBoxPipes.Name = "checkBoxPipes";
checkBoxPipes.Size = new Size(151, 19);
checkBoxPipes.TabIndex = 4;
checkBoxPipes.Text = "Признак наличия труб";
checkBoxPipes.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(74, 76);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(61, 23);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(74, 36);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(61, 23);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(6, 78);
label2.Name = "label2";
label2.Size = new Size(29, 15);
label2.TabIndex = 1;
label2.Text = "Вес:";
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(6, 38);
label1.Name = "label1";
label1.Size = new Size(62, 15);
label1.TabIndex = 0;
label1.Text = "Скорость:";
//
// panelReciever
//
panelReciever.AllowDrop = true;
panelReciever.Controls.Add(pictureBoxObject);
panelReciever.Controls.Add(labelAdditionalColor);
panelReciever.Controls.Add(labelColor);
panelReciever.Location = new Point(489, 12);
panelReciever.Name = "panelReciever";
panelReciever.Size = new Size(278, 169);
panelReciever.TabIndex = 1;
panelReciever.DragDrop += PanelObject_DragDrop;
panelReciever.DragEnter += PanelObject_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(3, 34);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(272, 132);
pictureBoxObject.TabIndex = 2;
pictureBoxObject.TabStop = false;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(157, 11);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(100, 20);
labelAdditionalColor.TabIndex = 1;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(16, 11);
labelColor.Name = "labelColor";
labelColor.Size = new Size(100, 20);
labelColor.TabIndex = 0;
labelColor.Text = "Цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += labelColor_DragDrop;
labelColor.DragEnter += labelColor_DragEnter;
//
// buttonAddObj
//
buttonAddObj.Location = new Point(505, 196);
buttonAddObj.Name = "buttonAddObj";
buttonAddObj.Size = new Size(100, 23);
buttonAddObj.TabIndex = 2;
buttonAddObj.Text = "Добавить";
buttonAddObj.UseVisualStyleBackColor = true;
buttonAddObj.Click += ButtonOk_Click;
//
// buttonCancelObj
//
buttonCancelObj.Location = new Point(646, 196);
buttonCancelObj.Name = "buttonCancelObj";
buttonCancelObj.Size = new Size(100, 23);
buttonCancelObj.TabIndex = 3;
buttonCancelObj.Text = "Отмена";
buttonCancelObj.UseVisualStyleBackColor = true;
//
// FormShipConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 231);
Controls.Add(buttonCancelObj);
Controls.Add(buttonAddObj);
Controls.Add(panelReciever);
Controls.Add(groupBox1);
Name = "FormShipConfig";
Text = "Создание объекта";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelReciever.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBox1;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label label2;
private Label label1;
private GroupBox groupBox2;
private Panel panelRed;
private CheckBox checkBoxFuel;
private CheckBox checkBoxPipes;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelGray;
private Panel panelBlue;
private Panel panelPurple;
private Panel panelGreen;
private Panel panelReciever;
private Label labelColor;
private Label labelModifiedObject;
private Label labelSimpleObject;
private PictureBox pictureBoxObject;
private Label labelAdditionalColor;
private Button buttonAddObj;
private Button buttonCancelObj;
}
}

View File

@ -0,0 +1,169 @@
using ProjectWarmlyShip.DrawningObjects;
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 ProjectWarmlyShip
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormShipConfig : Form
{
/// <summary>
/// Переменная-выбранная машина
/// </summary>
DrawningShip? _ship = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningShip>? EventAddShip;
/// <summary>
/// Конструктор
/// </summary>
public FormShipConfig()
{
InitializeComponent();
buttonCancelObj.Click += (s, e) => Close();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
// TODO buttonCancel.Click with lambda
}
/// <summary>
/// Отрисовать корабль
/// </summary>
private void DrawShip()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_ship?.SetPosition(5, 5);
_ship?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawningShip> ev)
{
if (EventAddShip == null)
{
EventAddShip = ev;
}
else
{
EventAddShip += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_ship = new DrawningShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_ship = new DrawningWarmlyShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxPipes.Checked,
checkBoxFuel.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawShip();
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship == null)
return;
((Label)sender).BackColor = (Color)e.Data.GetData(typeof(Color));
switch (((Label)sender).Name)
{
case "labelColor":
_ship.setBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "labelAdditionalColor":
if (!(_ship is DrawningWarmlyShip))
return;
(_ship as DrawningWarmlyShip).setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
break;
}
DrawShip();
}
/// <summary>
/// Добавление корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddShip?.Invoke(_ship);
Close();
}
}
}

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,183 @@
namespace ProjectWarmlyShip
{
partial class FormWarmlyShip
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormWarmlyShip));
pictureBoxWarmlyShip = new PictureBox();
buttonCreate = new Button();
buttonLeft = new Button();
buttonUp = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonCreateDeckShip = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonSelectShip = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyShip).BeginInit();
SuspendLayout();
//
// pictureBoxWarmlyShip
//
pictureBoxWarmlyShip.BackgroundImageLayout = ImageLayout.Zoom;
pictureBoxWarmlyShip.Dock = DockStyle.Fill;
pictureBoxWarmlyShip.Location = new Point(0, 0);
pictureBoxWarmlyShip.Name = "pictureBoxWarmlyShip";
pictureBoxWarmlyShip.Size = new Size(800, 450);
pictureBoxWarmlyShip.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxWarmlyShip.TabIndex = 0;
pictureBoxWarmlyShip.TabStop = false;
//
// buttonCreate
//
buttonCreate.Location = new Point(195, 415);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 23);
buttonCreate.TabIndex = 1;
buttonCreate.Text = " Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
// buttonLeft
//
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(686, 408);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage");
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(722, 372);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage");
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(758, 408);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 4;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(722, 408);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonCreateDeckShip
//
buttonCreateDeckShip.Location = new Point(12, 415);
buttonCreateDeckShip.Name = "buttonCreateDeckShip";
buttonCreateDeckShip.Size = new Size(177, 23);
buttonCreateDeckShip.TabIndex = 6;
buttonCreateDeckShip.Text = "Создать корабль с обвесами";
buttonCreateDeckShip.UseVisualStyleBackColor = true;
buttonCreateDeckShip.Click += buttonCreateDeckShip_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Location = new Point(637, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Location = new Point(686, 41);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 23);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// buttonSelectShip
//
buttonSelectShip.Location = new Point(276, 415);
buttonSelectShip.Name = "buttonSelectShip";
buttonSelectShip.Size = new Size(75, 23);
buttonSelectShip.TabIndex = 9;
buttonSelectShip.Text = "выбрать";
buttonSelectShip.UseVisualStyleBackColor = true;
buttonSelectShip.Click += ButtonSelectShip_Click;
//
// FormWarmlyShip
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonSelectShip);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateDeckShip);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxWarmlyShip);
Name = "FormWarmlyShip";
Text = "FormWarmlyShip";
((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyShip).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxWarmlyShip;
private Button buttonCreate;
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonCreateDeckShip;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectShip;
}
}

View File

@ -0,0 +1,178 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.MovementStrategy;
using static ProjectWarmlyShip.DirectionType;
namespace ProjectWarmlyShip
{
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Òåïëîõîä"
/// </summary>
public partial class FormWarmlyShip : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningShip? _drawingWarmlyShip;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
/// <summary>
/// Âûáðàííûé êîðàáëü
/// </summary>
public DrawningShip? SelectedShip { get; private set; }
public FormWarmlyShip()
{
InitializeComponent();
comboBoxStrategy.Items.Add("Äâèæåíèå â öåíòð");
comboBoxStrategy.Items.Add("Äâèæåíèå ê ãðàíèöå");
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè êîðàáëÿ
/// </summary>
private void Draw()
{
if (_drawingWarmlyShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingWarmlyShip.DrawTransport(gr);
pictureBoxWarmlyShip.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_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;
}
_drawingWarmlyShip = new DrawningShip(random.Next(100, 300), random.Next(1000, 3000),
color, pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawingWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü êîðàáëü ñ îáâåñàìè"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateDeckShip_Click(object sender, EventArgs e)
{
Random random = new();
//TODO âûáîð îñíîâíîãî öâåòà
Color coloros = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
coloros = dialog.Color;
}
//TODO âûáîð äîïîëíèòåëüíîãî öâåòà
Color colorad = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog2 = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
colorad = dialog2.Color;
}
_drawingWarmlyShip = new DrawningWarmlyShip(random.Next(100, 300), random.Next(1000, 3000),
coloros, colorad, Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawingWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Èçìåíåíèå ïîëîæåíèÿ êîðàáëÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingWarmlyShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingWarmlyShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingWarmlyShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingWarmlyShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingWarmlyShip.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawingWarmlyShip == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawningObjectShip(_drawingWarmlyShip), pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
/// <summary>
/// Âûáîð êîðàáëÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectShip_Click(object sender, EventArgs e)
{
SelectedShip = _drawingWarmlyShip;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,201 @@
<?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.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="buttonLeft.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAABGdBTUEAALGPC/xhBQAAAG9QTFRF////
AAAAWVlZ8fHx9PT0REREtLS0Ojo6+Pj4a2trp6enj4+P3t7eXl5efX1919fXh4eHw8PD6+vrdXV10dHR
5ubmDAwMy8vLTU1NlZWVvLy8iIiINjY2nJycFhYWYWFhJycnUVFRHR0dr6+vKioqoesKnwAAAAlwSFlz
AAAOvAAADrwBlbxySQAAAkFJREFUeF7t3GtT2zAQhWErF5JAnIQQSrmFW///b+wCR6LY/Vg3nqP3+cJE
O5Nhh1kjrSQ3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAACMyVQ/Tc02P1J6WuuToUP6dKfPds6VYErXGjFz
pfTCRkNWpgtl926uQSeHeMR8WWjUyFcJfpho2MdGmWVuD9PpTyWWPSngYvuqxLKVAi7OlFfxqICLnfIq
bhQwseyW4MJsOrP+pcSy1VIRE3fKq7hVwMW98iouFTCxbJVX9mC2Llw/KLFsYlaCl8qruFfAxa3yKsxm
osuV8sqezUpw3y3Bl5kiJm6UV7FTwMWj8irOFHDxR7/pw3GrgIlv/aZ3c7Med68E3dqGnX5TSm8KuOj2
m9JBARPTufLKFmYlmHddiisFXLwpr+JcARe9EjTrN816JbhXxMT2qMQyt4lorwRT207+v91gK7ReCZ7M
hX6jf+xCXz8Ggzy/9/ryUTgOsdLudZxOaohpYq/ldFJDLLb9/4bjqsNB5vr2z9IK/h+OZk6zGbDlZT8v
rWBtEdzXh8F+jV9Bn6aCXltw75cG+553BfsWFew9he7+4avZ/mGw3wOuYB+/grMYFZynCe5nooL9uba/
nE1szc4mVnC+NLifEQ7257yjGJ+VWuZ2Vr9pZu73LYL7nZlgf++pgrtrFdw/DN0eleGFfPt7wBXc5e70
qBzv4wf3dyoE+/diVPBuE72fpvVbJ37j1wMHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFSiaX4DkC8Y5EW8
SJQAAAAASUVORK5CYII=
</value>
</data>
<data name="buttonUp.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAABGdBTUEAALGPC/xhBQAAAG9QTFRF////
AAAAWVlZ8fHx9PT0REREtLS0Ojo6+Pj4a2trp6enj4+P3t7eXl5efX1919fXh4eHw8PD6+vrdXV10dHR
5ubmDAwMy8vLTU1NlZWVvLy8iIiINjY2nJycFhYWYWFhJycnUVFRHR0dr6+vKioqoesKnwAAAAlwSFlz
AAAOvAAADrwBlbxySQAAA01JREFUeF7t3dluo0AURVHwEGdO7DjznPT/f2PHcAgULsD90FKd0l5P7jKR
2FF0jYuWXQAAAAAAAAAAAAAAAADA/7JZP643epyls3LnTP/K0GUVWJaX+nd2vhVYlt9aycyV8nautJaV
xZvqdt4WWs3JUnG1pVYz0kyZRnbTpp0yjcymzVZZXVs9l4W5okJzPZuDcMo0Mpo2/SnTyGbanCpo36mO
MHevnJh7HWMtPmUaOUyblVriVjrK2I1ShtzoOFuvChn2qiNNjU2ZhvW02ShinPHGzfGLGirXF3pQlhfX
elB5Odbxfk6UUFkVncJwwp7oeDuPCqhtipkeleWs9/f7qJ8ws9bp137mSbewN4PW+hkr5zr52u4KNCjs
Xa2eVz9jJZwy1et6WBheCxhOm3as/KivzXqF4bS5qJaMPOvEa/X1db8wvCZ/rtZsPOm0a9qR6Rf2dm+e
6kUP4ZRpdtX2Cns7cEbTZvGhc6787lXsF4b7G398ps2DTrnS7jdFCsM9qgctJi+46Pxq38XHCufduxnl
tVYTd6TTrXXuMsUKgztSZXmk1aQNn3K0cPgXkqr5l861EvzZxQsH/6hTFUyZTy3WBgqLT61Wkp82wfj/
CO+DDhUOvLikafQNw1Bh5G1IssYvwwYL4xd5KZrf6Rwre5fSw4XhhfpdutNm4u3QSGHnuR/JboRPvaUd
K4y8YU7P5LbEWKHDtAmnTGxrabSwt3GV4LRZ6NRq0e3B8cLe5mN6/6UoeKmPb/FOFIYbyOm98HdfKFbx
t7JThcfdWXynxWQEu0q3WuyZKixu9XQluRdFndfO0O2yycJgI1xL6Wj3RwdveU4Xdm6ovmslHb+vZ8M3
kg4obKdNghtvunoe+d0fUli810ckuXl6e7lczcbO7KDC4mm2Wl4OzKrUHVbojEJ/FPqj0B+F/ij0R6E/
Cv1R6I9CfxT6o9Afhf4o9EehPwr9UeiPQn8U+qPQH4X+KPRHoT8K/VHoj0J/FPqj0B+F/ij0R6E/Cv1R
6I9CfxT6o9Afhf4o9EehPwr9UeiPQn/tBw+afDL5P2s/6dvwG0kOU39pddZfW326+xT9t0y+9TBuvj3a
5vhlxwAAAAAAAAAAAAAAAACSUBR/Aa2bGOTQ6k1jAAAAAElFTkSuQmCC
</value>
</data>
<data name="buttonRight.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAABGdBTUEAALGPC/xhBQAAAG9QTFRF////
AAAAWVlZ8fHx9PT0REREtLS0Ojo6+Pj4a2trp6enj4+P3t7eXl5efX1919fXh4eHw8PD6+vrdXV10dHR
5ubmDAwMy8vLTU1NlZWVvLy8iIiINjY2nJycFhYWYWFhJycnUVFRHR0dr6+vKioqoesKnwAAAAlwSFlz
AAAOvAAADrwBlbxySQAAAipJREFUeF7t3NlS20AQRmEJGzAgL+ybIQTy/s8YOfyawtJtZIWT891QVleB
u6iWZnpmVEmSJEmSJEmSJEmSJEmSJEmSJEmSJEmS9F3N8hOqWdb13WqeT0BP9aebfMa5TYJ1fZ4rNKvk
17rOJZjjpLdzirzjnCa7P+6IxXiU5AJYjN2ttLPKdZAfSa3zwCvGs6TWeV8nwPGS1IqTBDjuk1mxSYDj
du+Z0XrADVMX/WJ8axLheExqxVMCHJfJrHhOgKPZJrXOcpEIxqKdCu/Z8orxOakVlwlw9Eep9WMCHM1b
Uuuc4Ypx/jOpdbZXiXBsklpxnwDHSTIrXhLgWL8ntQ6vRzX72p/aAfaovjQZP/GK8SOZFbwe1U0yK3g9
qll/WnzMK8brpFbwGsbnyaz4SIBj0KPiFePVoBh5S6n9YerriA3j9ero8Jb9if+IxXiRPzC9kYpxcF+b
0EW+0181e81v/yeMMSseDKImNUaHajAtndQYDSr+/3COr0P+vfQ/eB5WVbPJOOOQDjmmmcghx6VTwM8t
8PND/Byf3qfB99rw/VJ8z5u+boFfe1r35zG09UP8GjB9HR+/FwO/nwa/J4q+r23RO12C25uI31+K3yNM
3+c92Kv/C1aCw/MWsBLEn5nBn3vCn13Dnz/knyHlnwPee04gz3Lzz+Pz36nAfy8G/90m7bywfSKi30+z
g7zDSJIkSZIkSZIkSZIkSZIkSZIkSZIkSZK+q6r6DXB6GOTqATe4AAAAAElFTkSuQmCC
</value>
</data>
<data name="buttonDown.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAABGdBTUEAALGPC/xhBQAAAG9QTFRF////
AAAAWVlZ8fHx9PT0REREtLS0Ojo6+Pj4a2trp6enj4+P3t7eXl5efX1919fXh4eHw8PD6+vrdXV10dHR
5ubmDAwMy8vLTU1NlZWVvLy8iIiINjY2nJycFhYWYWFhJycnUVFRHR0dr6+vKioqoesKnwAAAAlwSFlz
AAAOvAAADrwBlbxySQAAA2JJREFUeF7t3dtyolAQheHgIZqTicacMznO+z/jBFgoLRtwLqame9f/XUnj
xV6W1UBTBScAAAAAAAAAAAAAAAAA8K/MtqfbqT5n6fytKIq3c21l6OInX+lC29m5VMCiuFYlNzfKVxQr
VXIzUb6imKiSGxLGR8L4SBgfCeMjYXwkjI+E8ZEwPhLGR8L4SBgfCeMjYXwkjI+E8ZEwPhLGR8L4SBgf
CeMjYXwkjI+E8ZEwPhLGR8L4SBgfCeMjYXwkjI+E8ZEwPhLGR8L4SBgfCeMjYXwkjI+E8ZEwPhK6d7ea
LybP2kg5LuHzZDFf3WnDled68e/aTDgq4Xv9jaFf6j/ZParsTIWuYxKe6RvFpQp+6Lf/8UuVjiMS/tIX
iuJKFT+0sNKDSofGEz5of0klN6ZaV6WnT4wmvNPuirsHSN5rYaXFUkVrLOFyod2lexX9WGlllXS3GUu4
6zIlfw8enGlltSdVjZGET9pZm6nqyFZLq61VbRtOuNa+2lZVV861uFrieDaYcP/oz5LTh7jeanmV1263
GUq4fNWuyq2q7rR7YSLFUMIr7aksVPRn2j5kFC+q7gwkfNGOyr3jZynbbnN49tyfUGft4rLLNAa7TW/C
EF2mYQ78H/ag1pdw9qFyxf0zhh+10MqnirW+hJ+qVh5V9Gv6paVWblSt9CTcPyL6x1eAJ7Zfa621U1VL
6YSnqtVCPOm7d8nJhP0/iGPmb/e2/9ulEg78qT0z3WauYjrhXJWK/y7TWP7Wkiu79p9IOHRwcc0ewr9V
7Sb81nbN33htQPI0rJNw+CTPOXMqranSYUIzveqeqHuXuBw6TGgutvzNR8ckLmkPEo5dMLvXvWCwCUeH
Hv7Z0dLDQcL2eDs9uArAjgc3JuFGn2rJ4WMEZsS7aDWfK9tl+m9XeWe7zU0roTl1jdhlGva/2Gejb4dk
+0la3824IPa3PPv03lCNwhzXE9yOt49numaH3/H28ez59aEAg6dxQ90meJdp2DPQtmzehGhmFS0ZvULP
zJt29jOq+NLdJosu07ATmZrrm2h/z07VSs0ELhuH3SbDF3XabpNTl2nMyncBN94CjbeP177LlOnrcvfd
Jrsu02i6TYZdplG/tjrbl1aXNuundeixDAAAAAAAAAAAAAAAAADPTk7+AFMOGOSa0d0UAAAAAElFTkSu
QmCC
</value>
</data>
</root>

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static ProjectWarmlyShip.DirectionType;
namespace ProjectWarmlyShip.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,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
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,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.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,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.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

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
namespace ProjectWarmlyShip
{
internal static class Program
@ -11,7 +17,31 @@ namespace ProjectWarmlyShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider =
services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormShipCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});û
}
}
}

View File

@ -8,4 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectWarmlyShip.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("ProjectWarmlyShip.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;
}
}
}
}

View File

@ -0,0 +1,115 @@
using ProjectWarmlyShip.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.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="ship">Добавляемый корабль</param>
/// <returns></returns>
public bool Insert(T ship)
{
return Insert(ship, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="ship">Добавляемый корабль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T ship, int position)
{
if (position < 0 || position >= _maxCount)
throw new ShipNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(Count);
_places.Insert(0, ship);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position > _places.Count)
throw new ShipNotFoundException(position);
_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?> GetShips(int? maxShips = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxShips.HasValue && i == maxShips.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,16 @@
using ProjectWarmlyShip.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip
{
/// <summary>
/// Делегат для передачи объекта-самолета
/// </summary>
/// <param name="ship"></param>
public delegate void ShipDelegate(DrawningShip ship);
}

View File

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

View File

@ -0,0 +1,147 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningCar
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class ShipsGenericCollection<T, U>
where T : DrawningShip
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 = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public IEnumerable<T?> GetShips => _collection.GetShips();
public ShipsGenericCollection(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 +(ShipsGenericCollection<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 -(ShipsGenericCollection<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 ShowShips()
{
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;
for (int i = 0; i < _collection.Count; i++)
{
// TODO получение объекта
DrawningShip? Ship = _collection[i];
if (Ship == null)
continue;
int r = i / width;
int s = width - 1 - (i % width);
// TODO установка позиции
Ship.SetPosition(s * _placeSizeWidth, r * _placeSizeHeight + 50);
// TODO прорисовка объекта
Ship.DrawTransport(g);
}
}
}
}

View File

@ -0,0 +1,186 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.Generics;
using ProjectWarmlyShip.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.Exceptions;
using System.Numerics;
namespace ProjectWarmlyShip
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class ShipsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>> _shipStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _shipStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// /// <param name="pictureHeight"></param>
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
{
_shipStorages = new Dictionary<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// TODO Прописать логику для добавления
if (_shipStorages.ContainsKey(name)) return;
_shipStorages[name] = new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (!_shipStorages.ContainsKey(name)) return;
_shipStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public ShipsGenericCollection<DrawningShip, DrawningObjectShip>?
this[string ind]
{
get
{
// TODO Продумать логику получения набора
if (_shipStorages.ContainsKey(ind)) return _shipStorages[ind];
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
ShipsGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
{
StringBuilder records = new();
foreach (DrawningShip? elem in record.Value.GetShips)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename, false))
{
writer.WriteLine("ShipStorage");
writer.Write(data.ToString());
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string cheker = reader.ReadLine();
if (cheker == null)
{
throw new Exception("Нет данных для загрузки");
}
if (!cheker.StartsWith("ShipStorage"))
{
throw new Exception("Неверный формат данных");
}
_shipStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
{
throw new Exception("Нет данных для загрузки");
}
if (strs == null)
{
break;
}
firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0];
ShipsGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
{
DrawningShip? ship =
data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null)
{
try { _ = collection + ship; }
catch (ShipNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
_shipStorages.Add(name, collection);
}
}
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "WarmlyShip"
}
}
}