Compare commits

...

18 Commits

Author SHA1 Message Date
738bf04e38 fix 6 2023-12-05 21:47:38 +03:00
1275e0791a Готовая 6ая лаба 2023-11-22 10:56:27 +03:00
a1f41941b2 6 лаба (вроде готова) 2023-11-21 17:33:05 +03:00
4f3c6390c4 Лаба 6. Осталось доработать форму 2023-11-21 16:48:30 +03:00
6fe7112791 Готовая 5ая лаба (вроде) 2023-11-20 23:30:45 +03:00
62b4c50aee Почти рабочая 5ая лаба 2023-11-20 23:15:16 +03:00
b2745aa120 сделала форму 2023-11-08 08:38:24 +03:00
32531e96a7 Создала форму 2023-11-06 19:04:06 +03:00
58c0c8d87b вроде готовая лаба 2023-11-06 00:33:43 +03:00
d55c245c5e Исправила недочеты 2023-11-05 15:52:59 +03:00
a0f62132e3 Изменила форму и классы 2023-11-04 21:42:55 +03:00
18022795a3 Готовая лаба 2023-10-25 09:44:00 +03:00
7ead025329 Исправила недочеты 2023-10-25 08:33:48 +03:00
1f59d32cf7 Создала вторую формочку 2023-10-24 20:35:26 +03:00
38b8cbf1fc Создала классы, придумала проверки 2023-10-24 19:05:51 +03:00
7a45baf1c5 Внесла корректировки 2023-10-24 13:21:27 +03:00
d71beac455 Готовая лабораторная 2023-10-23 22:50:37 +03:00
6dceedfa0d Создала классы 2023-10-18 22:15:49 +03:00
25 changed files with 2399 additions and 250 deletions

View File

@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
namespace WarmlyShip.MovementStrategy
{
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private Status _state = Status.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public Status GetStatus() { return _state; }
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;
}
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,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
namespace WarmlyShip.MovementStrategy
{
public class DrawingObjectShip : IMoveableObject
{
private readonly DrawingWarmlyShip? _drawingWarmlyShip = null;
public DrawingObjectShip(DrawingWarmlyShip drawingWarmlyShip)
{
_drawingWarmlyShip = drawingWarmlyShip;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingWarmlyShip == null || _drawingWarmlyShip.EntityWarmlyShip == null)
{
return null;
}
return new ObjectParameters(_drawingWarmlyShip.GetPosX,
_drawingWarmlyShip.GetPosY, _drawingWarmlyShip.GetWidth, _drawingWarmlyShip.GetHeight);
}
}
public int GetStep => (int)(_drawingWarmlyShip?.EntityWarmlyShip?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawingWarmlyShip?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawingWarmlyShip?.MoveTransport(direction);
}
}

View File

@ -3,72 +3,42 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
namespace WarmlyShip.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingWarmlyShip
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityWarmlyShip? EntityWarmlyShip { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
public EntityWarmlyShip? EntityWarmlyShip { get; protected set; }
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки теплохода
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки теплохода
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки теплохода
/// </summary>
private readonly int _WarmlyShipWidth = 180;
/// <summary>
/// Высота прорисовки теплохода
/// </summary>
private readonly int _WarmlyShipHeight = 185;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipes">Признак наличия труб</param>
/// <param name="section">Признак наличия отсека для топлива</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена,нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool pipes, bool section,
int width, int height)
protected int _startPosX;
protected int _startPosY;
protected readonly int _WarmlyShipWidth = 185;
protected readonly int _WarmlyShipHeight = 180;
public DrawingWarmlyShip(int speed, double weight, Color bodyColor, int width, int height)
{
if (width <_WarmlyShipWidth || height <_WarmlyShipHeight)
if (width < _WarmlyShipWidth || height < _WarmlyShipHeight)
{
return false;
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityWarmlyShip = new EntityWarmlyShip();
EntityWarmlyShip.Init(speed, weight, bodyColor, additionalColor, pipes, section);
return true;
EntityWarmlyShip = new EntityWarmlyShip(speed, weight, bodyColor);
}
protected DrawingWarmlyShip(int speed, double weight, Color bodyColor, int
width, int height, int warmlyShipWidth, int warmlyShipHeight)
{
if (width <= _WarmlyShipWidth || height <= _WarmlyShipHeight)
return;
_pictureWidth = width;
_pictureHeight = height;
_WarmlyShipWidth = warmlyShipWidth;
_WarmlyShipHeight = warmlyShipHeight;
EntityWarmlyShip = new EntityWarmlyShip(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 + _WarmlyShipWidth <= _pictureWidth && y >= 0 && y + _WarmlyShipHeight <= _pictureHeight)
@ -77,53 +47,7 @@ namespace WarmlyShip
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityWarmlyShip == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX - EntityWarmlyShip.Step > 0)
{
_startPosX -= (int)EntityWarmlyShip.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityWarmlyShip.Step > 0)
{
_startPosY -= (int)EntityWarmlyShip.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + _WarmlyShipWidth + EntityWarmlyShip.Step < _pictureWidth)
{
_startPosX += (int)EntityWarmlyShip.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _WarmlyShipHeight + EntityWarmlyShip.Step < _pictureHeight)
{
_startPosY += (int)EntityWarmlyShip.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityWarmlyShip == null)
{
@ -131,7 +55,7 @@ namespace WarmlyShip
}
Pen pen = new(Color.Black, 2);
Pen anchor = new(Color.Black, 4);
Brush additionalBrush = new SolidBrush(EntityWarmlyShip.BodyColor);
Brush bodyBrush = new SolidBrush(EntityWarmlyShip.BodyColor);
//корпус теплохода
Point[] hull = new Point[]
{
@ -140,31 +64,79 @@ namespace WarmlyShip
new Point(_startPosX + 140, _startPosY + 185),
new Point(_startPosX + 40, _startPosY + 185),
};
g.FillPolygon(additionalBrush, hull);
g.FillPolygon(bodyBrush, hull);
g.DrawPolygon(pen, hull);
Brush bra = new SolidBrush(EntityWarmlyShip.AdditionalColor);
//палуба
g.FillRectangle(bra, _startPosX + 25, _startPosY + 80, 130, 30);
g.FillRectangle(bodyBrush, _startPosX + 25, _startPosY + 80, 130, 30);
g.DrawRectangle(pen, _startPosX + 25, _startPosY + 80, 130, 30);
//отсек для топлива
Brush brGray = new SolidBrush(Color.Gray);
if (EntityWarmlyShip.Section)
{
g.FillEllipse(brGray, _startPosX + 130, _startPosY + 130, 20, 20);
g.DrawEllipse(pen, _startPosX + 130, _startPosY + 130, 20, 20);
}
//трубы
if (EntityWarmlyShip.Pipes)
{
g.FillRectangle(brGray, _startPosX + 55, _startPosY, 25, 80);
g.DrawRectangle(pen, _startPosX + 55, _startPosY, 25, 80);
g.FillRectangle(brGray, _startPosX + 90, _startPosY + 20, 25, 60);
g.DrawRectangle(pen, _startPosX + 90, _startPosY + 20, 25, 60);
}
//якорь
g.DrawLine(anchor, new Point(_startPosX + 50, _startPosY + 130), new Point(_startPosX + 50,_startPosY + 150));
g.DrawLine(anchor, new Point(_startPosX + 40, _startPosY + 140), new Point(_startPosX + 60, _startPosY + 140));
g.DrawLine(anchor, new Point(_startPosX + 45, _startPosY + 150), new Point(_startPosX + 55, _startPosY + 150));
}
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _WarmlyShipWidth;
public int GetHeight => _WarmlyShipHeight;
public bool CanMove(DirectionType direction)
{
if (EntityWarmlyShip == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityWarmlyShip.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityWarmlyShip.Step > 0,
//вправо
DirectionType.Right => _startPosX + EntityWarmlyShip.Step + _WarmlyShipWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityWarmlyShip.Step + _WarmlyShipHeight < _pictureHeight,
_ => false,
};
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityWarmlyShip == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityWarmlyShip.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityWarmlyShip.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityWarmlyShip.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityWarmlyShip.Step;
break;
}
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawingCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectShip(this);
public void SetBodyColor(Color color)
{
EntityWarmlyShip.BodyColor = color;
}
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
}
}

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
namespace WarmlyShip.DrawingObjects
{
public class DrawingWarmlyShipWithPipes : DrawingWarmlyShip
{
public DrawingWarmlyShipWithPipes(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipes, bool section, int width, int height)
: base(speed, weight, bodyColor, width, height, 185, 180)
{
if (EntityWarmlyShip != null)
{
EntityWarmlyShip = new EntityWarmlyShipWithPipes(speed, weight, bodyColor, additionalColor, pipes, section);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityWarmlyShip is not EntityWarmlyShipWithPipes warmlyShip)
{
return;
}
Pen pen = new(Color.Black, 2);
Brush additionalBrush = new SolidBrush(warmlyShip.AdditionalColor);
base.DrawTransport(g);
//отсек для топлива
Brush brGray = new SolidBrush(Color.Gray);
if (warmlyShip.Section)
{
g.FillEllipse(brGray, _startPosX + 130, _startPosY + 130, 20, 20);
g.DrawEllipse(pen, _startPosX + 130, _startPosY + 130, 20, 20);
}
//трубы
if (warmlyShip.Pipes)
{
g.FillRectangle(additionalBrush, _startPosX + 55, _startPosY, 25, 80);
g.DrawRectangle(pen, _startPosX + 55, _startPosY, 25, 80);
g.FillRectangle(additionalBrush, _startPosX + 90, _startPosY + 20, 25, 60);
g.DrawRectangle(pen, _startPosX + 90, _startPosY + 20, 25, 60);
}
}
public void SetAddColor(Color color)
{
(EntityWarmlyShip as EntityWarmlyShipWithPipes).AdditionalColor = color;
}
}
}

View File

@ -4,56 +4,23 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
namespace WarmlyShip.Entities
{
public class EntityWarmlyShip
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия труб
/// </summary>
public bool Pipes { get; private set; }
/// <summary>
/// Признак (опция) наличия отсека для топлива
/// </summary>
public bool Section { get; private set; }
/// <summary>
/// Шаг перемещения теплохода
/// </summary>
public Color BodyColor { get; set; }
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса теплохода
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес теплохода</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipes">Признак наличия труб</param>
/// <param name="section">Признак наличия отсека для топлива</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipes, bool section)
public EntityWarmlyShip(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Pipes = pipes;
Section = section;
}
public void setBodyColor(Color color)
{
BodyColor = color;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Entities
{
public class EntityWarmlyShipWithPipes : EntityWarmlyShip
{
public Color AdditionalColor { get; set; }
public bool Pipes { get; private set; }
public bool Section { get; private set; }
public EntityWarmlyShipWithPipes(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipes, bool section)
: base (speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Pipes = pipes;
Section = section;
}
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
namespace WarmlyShip.DrawingObjects
{
public static class ExtentionDrawingShip
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingWarmlyShip? CreateDrawingShip(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingWarmlyShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingWarmlyShipWithPipes(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingWarmlyShip drawingShip,
char separatorForObject)
{
var ship = drawingShip.EntityWarmlyShip;
if (ship == null)
{
return string.Empty;
}
var str =
$"{ship.Speed}{separatorForObject}{ship.Weight}{separatorForObject}{ship.BodyColor.Name}";
if (ship is not EntityWarmlyShipWithPipes warmlyShip)
{
return str;
}
return
$"{str}{separatorForObject}{warmlyShip.AdditionalColor.Name}{separatorForObject}{warmlyShip.Pipes}{separatorForObject}{warmlyShip.Section}";
}
}
}

View File

@ -0,0 +1,258 @@
namespace WarmlyShip
{
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()
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.panelCollection = new System.Windows.Forms.Panel();
this.groupBoxSets = new System.Windows.Forms.GroupBox();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.buttonDelObject = new System.Windows.Forms.Button();
this.buttonnAddObject = new System.Windows.Forms.Button();
this.listBoxStorages = new System.Windows.Forms.ListBox();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.labelCollection = new System.Windows.Forms.Label();
this.buttonRefreshCollection = new System.Windows.Forms.Button();
this.buttonRemoveShip = new System.Windows.Forms.Button();
this.buttonAddShip = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.сохранениеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.загрузкаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.panelCollection.SuspendLayout();
this.groupBoxSets.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(864, 625);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// panelCollection
//
this.panelCollection.Controls.Add(this.groupBoxSets);
this.panelCollection.Controls.Add(this.maskedTextBoxNumber);
this.panelCollection.Controls.Add(this.labelCollection);
this.panelCollection.Controls.Add(this.buttonRefreshCollection);
this.panelCollection.Controls.Add(this.buttonRemoveShip);
this.panelCollection.Controls.Add(this.buttonAddShip);
this.panelCollection.Controls.Add(this.menuStrip1);
this.panelCollection.Location = new System.Drawing.Point(870, 0);
this.panelCollection.Name = "panelCollection";
this.panelCollection.Size = new System.Drawing.Size(218, 625);
this.panelCollection.TabIndex = 1;
//
// groupBoxSets
//
this.groupBoxSets.Controls.Add(this.textBoxStorageName);
this.groupBoxSets.Controls.Add(this.buttonDelObject);
this.groupBoxSets.Controls.Add(this.buttonnAddObject);
this.groupBoxSets.Controls.Add(this.listBoxStorages);
this.groupBoxSets.Location = new System.Drawing.Point(12, 117);
this.groupBoxSets.Name = "groupBoxSets";
this.groupBoxSets.Size = new System.Drawing.Size(199, 242);
this.groupBoxSets.TabIndex = 7;
this.groupBoxSets.TabStop = false;
this.groupBoxSets.Text = "Наборы";
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(0, 26);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(193, 27);
this.textBoxStorageName.TabIndex = 3;
//
// buttonDelObject
//
this.buttonDelObject.Location = new System.Drawing.Point(6, 207);
this.buttonDelObject.Name = "buttonDelObject";
this.buttonDelObject.Size = new System.Drawing.Size(187, 29);
this.buttonDelObject.TabIndex = 2;
this.buttonDelObject.Text = "Удалить набор";
this.buttonDelObject.UseVisualStyleBackColor = true;
this.buttonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click);
//
// buttonnAddObject
//
this.buttonnAddObject.Location = new System.Drawing.Point(4, 71);
this.buttonnAddObject.Name = "buttonnAddObject";
this.buttonnAddObject.Size = new System.Drawing.Size(189, 29);
this.buttonnAddObject.TabIndex = 1;
this.buttonnAddObject.Text = "Добавить набор";
this.buttonnAddObject.UseVisualStyleBackColor = true;
this.buttonnAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 20;
this.listBoxStorages.Location = new System.Drawing.Point(6, 117);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(187, 84);
this.listBoxStorages.TabIndex = 0;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.ListBoxObjects_SelectedIndexChanged);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(16, 438);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(171, 27);
this.maskedTextBoxNumber.TabIndex = 6;
//
// labelCollection
//
this.labelCollection.AutoSize = true;
this.labelCollection.Location = new System.Drawing.Point(3, 82);
this.labelCollection.Name = "labelCollection";
this.labelCollection.Size = new System.Drawing.Size(103, 20);
this.labelCollection.TabIndex = 2;
this.labelCollection.Text = "Инструменты";
//
// buttonRefreshCollection
//
this.buttonRefreshCollection.Location = new System.Drawing.Point(18, 555);
this.buttonRefreshCollection.Name = "buttonRefreshCollection";
this.buttonRefreshCollection.Size = new System.Drawing.Size(171, 40);
this.buttonRefreshCollection.TabIndex = 5;
this.buttonRefreshCollection.Text = "Обновить коллекцию";
this.buttonRefreshCollection.UseVisualStyleBackColor = true;
this.buttonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(16, 490);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(171, 40);
this.buttonRemoveShip.TabIndex = 4;
this.buttonRemoveShip.Text = "Удалить теплоход";
this.buttonRemoveShip.UseVisualStyleBackColor = true;
this.buttonRemoveShip.Click += new System.EventHandler(this.ButtonRemoveShip_Click);
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(16, 375);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(171, 40);
this.buttonAddShip.TabIndex = 2;
this.buttonAddShip.Text = "Добавить теплоход";
this.buttonAddShip.UseVisualStyleBackColor = true;
this.buttonAddShip.Click += new System.EventHandler(this.ButtonAddShip_Click);
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(218, 28);
this.menuStrip1.TabIndex = 8;
this.menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.сохранениеToolStripMenuItem,
this.загрузкаToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
this.файлToolStripMenuItem.Text = "Файл";
//
// сохранениеToolStripMenuItem
//
this.сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
this.сохранениеToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.сохранениеToolStripMenuItem.Text = "Сохранение";
this.сохранениеToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// загрузкаToolStripMenuItem
//
this.загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
this.загрузкаToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.загрузкаToolStripMenuItem.Text = "Загрузка";
this.загрузкаToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormShipCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1093, 627);
this.Controls.Add(this.panelCollection);
this.Controls.Add(this.pictureBoxCollection);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormShipCollection";
this.Text = "Набор теплоходов";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.panelCollection.ResumeLayout(false);
this.panelCollection.PerformLayout();
this.groupBoxSets.ResumeLayout(false);
this.groupBoxSets.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panelCollection;
private Button buttonAddShip;
private Button buttonRemoveShip;
private Button buttonRefreshCollection;
private Label labelCollection;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBoxSets;
private Button buttonDelObject;
private Button buttonnAddObject;
private ListBox listBoxStorages;
private TextBox textBoxStorageName;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранениеToolStripMenuItem;
private ToolStripMenuItem загрузкаToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,256 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WarmlyShip.DrawingObjects;
using WarmlyShip.Generics;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningCar
/// </summary>
public partial class FormShipCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly ShipsGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
{
InitializeComponent();
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowShips();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
var formShipConfig = new FormShipConfig();
formShipConfig.Show();
Action<DrawingWarmlyShip>? shipDelegate = new((m) =>
{
bool isAddSuccessful = (obj + m);
if (isAddSuccessful)
{
MessageBox.Show("Объект добавлен");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowShips();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
});
formShipConfig.AddEvent(shipDelegate);
}
private void AddShip(DrawingWarmlyShip drawningShip)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (obj + drawningShip)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowShips();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowShips();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowShips();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
ReloadObjects();
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>152, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>311, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,393 @@
namespace WarmlyShip
{
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()
{
this.groupBoxParameters = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelRed = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.checkBoxSection = new System.Windows.Forms.CheckBox();
this.checkBoxPipes = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.panelColor = new System.Windows.Forms.Panel();
this.buttonCancel = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.labelAddColor = new System.Windows.Forms.Label();
this.labelBodyColor = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.groupBoxParameters.SuspendLayout();
this.groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panelColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxParameters
//
this.groupBoxParameters.Controls.Add(this.labelModifiedObject);
this.groupBoxParameters.Controls.Add(this.labelSimpleObject);
this.groupBoxParameters.Controls.Add(this.groupBoxColor);
this.groupBoxParameters.Controls.Add(this.checkBoxSection);
this.groupBoxParameters.Controls.Add(this.checkBoxPipes);
this.groupBoxParameters.Controls.Add(this.numericUpDownWeight);
this.groupBoxParameters.Controls.Add(this.numericUpDownSpeed);
this.groupBoxParameters.Controls.Add(this.labelWeight);
this.groupBoxParameters.Controls.Add(this.labelSpeed);
this.groupBoxParameters.Location = new System.Drawing.Point(20, 12);
this.groupBoxParameters.Name = "groupBoxParameters";
this.groupBoxParameters.Size = new System.Drawing.Size(599, 347);
this.groupBoxParameters.TabIndex = 0;
this.groupBoxParameters.TabStop = false;
this.groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelModifiedObject.Location = new System.Drawing.Point(456, 273);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(121, 36);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelSimpleObject.Location = new System.Drawing.Point(313, 273);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(124, 36);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColor
//
this.groupBoxColor.Controls.Add(this.panelRed);
this.groupBoxColor.Controls.Add(this.panelBlue);
this.groupBoxColor.Controls.Add(this.panelYellow);
this.groupBoxColor.Controls.Add(this.panelWhite);
this.groupBoxColor.Controls.Add(this.panelGray);
this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelPurple);
this.groupBoxColor.Controls.Add(this.panelGreen);
this.groupBoxColor.Location = new System.Drawing.Point(313, 38);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Size = new System.Drawing.Size(271, 216);
this.groupBoxColor.TabIndex = 6;
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(6, 39);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(50, 50);
this.panelRed.TabIndex = 1;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(143, 39);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(50, 50);
this.panelBlue.TabIndex = 1;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(214, 39);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(50, 50);
this.panelYellow.TabIndex = 1;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(6, 114);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(50, 50);
this.panelWhite.TabIndex = 1;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(74, 114);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(50, 50);
this.panelGray.TabIndex = 1;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(143, 114);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(50, 50);
this.panelBlack.TabIndex = 1;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(214, 114);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(50, 50);
this.panelPurple.TabIndex = 1;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(74, 39);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(50, 50);
this.panelGreen.TabIndex = 0;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxSection
//
this.checkBoxSection.AutoSize = true;
this.checkBoxSection.Location = new System.Drawing.Point(15, 182);
this.checkBoxSection.Name = "checkBoxSection";
this.checkBoxSection.Size = new System.Drawing.Size(292, 24);
this.checkBoxSection.TabIndex = 5;
this.checkBoxSection.Text = "Признак наличия отсека для топлива";
this.checkBoxSection.UseVisualStyleBackColor = true;
//
// checkBoxPipes
//
this.checkBoxPipes.AutoSize = true;
this.checkBoxPipes.Location = new System.Drawing.Point(15, 152);
this.checkBoxPipes.Name = "checkBoxPipes";
this.checkBoxPipes.Size = new System.Drawing.Size(189, 24);
this.checkBoxPipes.TabIndex = 4;
this.checkBoxPipes.Text = "Признак наличия труб";
this.checkBoxPipes.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(117, 90);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(58, 27);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(117, 38);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(67, 27);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(20, 97);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(33, 20);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(20, 45);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(73, 20);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость";
//
// panelColor
//
this.panelColor.AllowDrop = true;
this.panelColor.Controls.Add(this.buttonCancel);
this.panelColor.Controls.Add(this.button1);
this.panelColor.Controls.Add(this.labelAddColor);
this.panelColor.Controls.Add(this.labelBodyColor);
this.panelColor.Controls.Add(this.pictureBoxObject);
this.panelColor.Location = new System.Drawing.Point(625, 11);
this.panelColor.Name = "panelColor";
this.panelColor.Size = new System.Drawing.Size(355, 351);
this.panelColor.TabIndex = 1;
this.panelColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(200, 297);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(124, 32);
this.buttonCancel.TabIndex = 12;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Location = new System.Drawing.Point(44, 297);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(124, 32);
this.button1.TabIndex = 11;
this.button1.Text = "Добавить";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.ButtonOk_Click);
//
// labelAddColor
//
this.labelAddColor.AllowDrop = true;
this.labelAddColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAddColor.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelAddColor.Location = new System.Drawing.Point(200, 30);
this.labelAddColor.Name = "labelAddColor";
this.labelAddColor.Size = new System.Drawing.Size(124, 36);
this.labelAddColor.TabIndex = 10;
this.labelAddColor.Text = "Доп. цвет";
this.labelAddColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAddColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelAddColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// labelBodyColor
//
this.labelBodyColor.AllowDrop = true;
this.labelBodyColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBodyColor.Font = new System.Drawing.Font("Segoe UI", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.labelBodyColor.Location = new System.Drawing.Point(44, 30);
this.labelBodyColor.Name = "labelBodyColor";
this.labelBodyColor.Size = new System.Drawing.Size(124, 36);
this.labelBodyColor.TabIndex = 9;
this.labelBodyColor.Text = "Цвет";
this.labelBodyColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBodyColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelBodyColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(15, 78);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(332, 213);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// FormShipConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(986, 369);
this.Controls.Add(this.panelColor);
this.Controls.Add(this.groupBoxParameters);
this.Name = "FormShipConfig";
this.Text = "FormShipConfig";
this.groupBoxParameters.ResumeLayout(false);
this.groupBoxParameters.PerformLayout();
this.groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panelColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private GroupBox groupBoxColor;
private Panel panelRed;
private Panel panelBlue;
private Panel panelYellow;
private Panel panelWhite;
private Panel panelGray;
private Panel panelBlack;
private Panel panelPurple;
private Panel panelGreen;
private CheckBox checkBoxSection;
private CheckBox checkBoxPipes;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Panel panelColor;
private Button button1;
private Label labelAddColor;
private Label labelBodyColor;
private PictureBox pictureBoxObject;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,168 @@
using Microsoft.VisualBasic.Devices;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WarmlyShip.DrawingObjects;
using WarmlyShip.Entities;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormShipConfig : Form
{
/// <summary>
/// Переменная-выбранный теплоход
/// </summary>
DrawingWarmlyShip? _ship = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingWarmlyShip>? EventAddShip;
/// <summary>
/// Конструктор
/// </summary>
public FormShipConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <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>
internal void AddEvent(Action<DrawingWarmlyShip> 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 DrawingWarmlyShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_ship = new DrawingWarmlyShipWithPipes((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxPipes.Checked,
checkBoxSection.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawShip();
}
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship == null)
return;
switch (((Label)sender).Name)
{
case "labelBodyColor":
_ship.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "labelAddColor":
if (!(_ship is DrawingWarmlyShipWithPipes))
return;
(_ship as DrawingWarmlyShipWithPipes).SetAddColor((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,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -29,11 +29,15 @@
private void InitializeComponent()
{
this.pictureBoxWarmlyShip = new System.Windows.Forms.PictureBox();
this.buttonCreateWarmlyShip = new System.Windows.Forms.Button();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonStep = new System.Windows.Forms.Button();
this.buttonSelectShip = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWarmlyShip)).BeginInit();
this.SuspendLayout();
//
@ -47,73 +51,120 @@
this.pictureBoxWarmlyShip.TabIndex = 0;
this.pictureBoxWarmlyShip.TabStop = false;
//
// buttonCreateWarmlyShip
//
this.buttonCreateWarmlyShip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateWarmlyShip.Location = new System.Drawing.Point(12, 389);
this.buttonCreateWarmlyShip.Name = "buttonCreateWarmlyShip";
this.buttonCreateWarmlyShip.Size = new System.Drawing.Size(163, 50);
this.buttonCreateWarmlyShip.TabIndex = 1;
this.buttonCreateWarmlyShip.Text = "Создать теплоход с трубами";
this.buttonCreateWarmlyShip.UseVisualStyleBackColor = true;
this.buttonCreateWarmlyShip.Click += new System.EventHandler(this.buttonCreateWarmlyShip_Click);
//
// buttonCreate
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(31, 411);
this.buttonCreate.Location = new System.Drawing.Point(197, 389);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(94, 30);
this.buttonCreate.TabIndex = 1;
this.buttonCreate.Text = "Создать";
this.buttonCreate.Size = new System.Drawing.Size(122, 50);
this.buttonCreate.TabIndex = 2;
this.buttonCreate.Text = "Создать теплоход";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click_1);
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::WarmlyShip.Properties.Resources.left_arrow;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonLeft.Location = new System.Drawing.Point(703, 411);
this.buttonLeft.Location = new System.Drawing.Point(720, 411);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 2;
this.buttonLeft.TabIndex = 3;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
this.buttonLeft.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::WarmlyShip.Properties.Resources.upper_arrow;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonUp.Location = new System.Drawing.Point(739, 375);
this.buttonUp.Location = new System.Drawing.Point(756, 375);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 3;
this.buttonUp.TabIndex = 4;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.right_arrow;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(775, 411);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 4;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
this.buttonUp.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::WarmlyShip.Properties.Resources.down_arrow;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonDown.Location = new System.Drawing.Point(739, 411);
this.buttonDown.Location = new System.Drawing.Point(756, 411);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 5;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.right_arrow;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(792, 411);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 6;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"К центру",
"К краю"});
this.comboBoxStrategy.Location = new System.Drawing.Point(720, 13);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(151, 28);
this.comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
this.buttonStep.Location = new System.Drawing.Point(720, 56);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(150, 29);
this.buttonStep.TabIndex = 8;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// buttonSelectShip
//
this.buttonSelectShip.Location = new System.Drawing.Point(720, 107);
this.buttonSelectShip.Name = "buttonSelectShip";
this.buttonSelectShip.Size = new System.Drawing.Size(150, 29);
this.buttonSelectShip.TabIndex = 9;
this.buttonSelectShip.Text = "Выбрать теплоход";
this.buttonSelectShip.UseVisualStyleBackColor = true;
this.buttonSelectShip.Click += new System.EventHandler(this.ButtonSelectShip_Click);
//
// FormWarmlyShip
//
this.ClientSize = new System.Drawing.Size(882, 453);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonSelectShip);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.buttonCreateWarmlyShip);
this.Controls.Add(this.pictureBoxWarmlyShip);
this.Name = "FormWarmlyShip";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
@ -125,12 +176,15 @@
}
#endregion
private PictureBox pictureBoxWarmlyShip;
private Button buttonCreateWarmlyShip;
private Button buttonCreate;
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonRight;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectShip;
}
}

View File

@ -1,21 +1,20 @@
using WarmlyShip.DrawingObjects;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
{
public partial class FormWarmlyShip : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingWarmlyShip? _drawingWarmlyShip;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
private AbstractStrategy? _strategy;
public DrawingWarmlyShip? SelectedShip { get; private set; }
public FormWarmlyShip()
{
InitializeComponent();
_strategy = null;
SelectedShip = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè òåïëîõîäà
/// </summary>
private void Draw()
{
if (_drawingWarmlyShip == null)
@ -28,32 +27,50 @@ namespace WarmlyShip
_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();
_drawingWarmlyShip = new DrawingWarmlyShip();
_drawingWarmlyShip.Init(random.Next(100, 300),
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 DrawingWarmlyShip(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
color,
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawingWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonCreateWarmlyShip_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
Color addColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDopColor = new();
if (dialogDopColor.ShowDialog() == DialogResult.OK)
{
addColor = dialogDopColor.Color;
}
_drawingWarmlyShip = new DrawingWarmlyShipWithPipes(random.Next(100, 300),
random.Next(1000, 3000),
color, addColor,
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)
@ -79,47 +96,51 @@ namespace WarmlyShip
Draw();
}
private void buttonCreate_Click_1(object sender, EventArgs e)
{
Random random = new();
_drawingWarmlyShip = new DrawingWarmlyShip ();
_drawingWarmlyShip.Init(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawingWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingWarmlyShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
if (comboBoxStrategy.Enabled)
{
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;
_strategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(_drawingWarmlyShip.GetMoveableObject, pictureBoxWarmlyShip.Width,
pictureBoxWarmlyShip.Height);
comboBoxStrategy.Enabled = false;
}
if (_strategy == null)
{
return;
}
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = 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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
namespace WarmlyShip.MovementStrategy
{
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
bool CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.MovementStrategy
{
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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.MovementStrategy
{
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
public int LeftBorder => _x;
public int TopBorder => _y;
public int RightBorder => _x + _width;
public int DownBorder => _y + _height;
public int ObjectMiddleHorizontal => _x + _width / 2;
public int ObjectMiddleVertical => _y + _height / 2;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

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

View File

@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Generics
{
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="warmlyship">Добавляемый теплоход</param>
/// <returns></returns>
public bool Insert(T warmlyship)
{
if (_places.Count == _maxCount)
{
return false;
}
Insert(warmlyship, 0);
return true;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="warmlyship">Добавляемый теплоход</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T warmlyship, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
{
return false;
}
_places.Insert(position, warmlyship);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
}
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
return;
}
}
/// <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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
namespace WarmlyShip
{
internal class ShipDelegate
{
/// <summary>
/// Делегат для передачи объекта-теплоход
/// </summary>
/// <param name="ship"></param>
public delegate void Action(DrawingWarmlyShip ship);
}
}

View File

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
using WarmlyShip.MovementStrategy;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace WarmlyShip.Generics
{
internal class ShipsGenericCollection<T, U>
where T : DrawingWarmlyShip
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetShips => _collection.GetShips();
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 185;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 185;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
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 / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// /// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int i = 0;
foreach (var ship in _collection.GetShips())
{
if (ship != null)
{
int width = _pictureWidth / _placeSizeWidth;
ship.SetPosition((width - 1 - (i % width)) * _placeSizeWidth, i / width * _placeSizeHeight);
ship.DrawTransport(g);
}
i++;
}
}
}
}

View File

@ -0,0 +1,185 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip.Generics
{
internal class ShipsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, ShipsGenericCollection<DrawingWarmlyShip,
DrawingObjectShip>> _shipStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _shipStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// /// <param name="pictureHeight"></param>
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
{
_shipStorages = new Dictionary<string,
ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (_shipStorages.ContainsKey(name))
{
return;
}
_shipStorages[name] = new ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_shipStorages.ContainsKey(name))
{
return;
}
_shipStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>?
this[string ind]
{
get
{
if (_shipStorages.ContainsKey(ind))
{
return _shipStorages[ind];
}
return null;
}
}
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>> record in _shipStorages)
{
StringBuilder records = new();
foreach (DrawingWarmlyShip? elem in record.Value.GetShips)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"ShipStorage{Environment.NewLine}{data}");
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith("ShipStorage"))
{
return false;
}
_shipStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
if (strs == null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingWarmlyShip? ship = elem?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null)
{
if (!(collection + ship))
{
return false;
}
}
}
_shipStorages.Add(record[0], collection);
}
return true;
}
}
}
}

View File

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