Compare commits

...

10 Commits
main ... lab8

Author SHA1 Message Date
b17f2d743d done 2023-12-30 13:14:20 +04:00
3e75f73a19 fix 2023-12-26 23:00:14 +04:00
44df2f7cac done 2023-12-15 20:50:00 +04:00
ecffc2f002 fix 2023-12-10 23:51:40 +04:00
339545f735 done 2023-12-02 00:46:08 +04:00
83429b9e53 done 2023-12-01 21:18:58 +04:00
c4e6dfff50 done 2023-12-01 18:41:28 +04:00
2b49eedbc1 done 2023-11-24 22:20:23 +04:00
0b7ab5180d finish 2023-11-24 22:12:36 +04:00
feaa0587c1 test 2023-11-24 11:49:07 +04:00
42 changed files with 3868 additions and 0 deletions

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
//// <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,243 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningShip
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityShip? EntityShip { get; protected set; }
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningShip
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectShip(this);
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки корабля
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки корабля
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки корабля
/// </summary>
protected readonly int _shipWidth = 140;
/// <summary>
/// Высота прорисовки корабля
/// </summary>
protected readonly int _shipHeight = 60;
/// <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="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)
{
if (width < _shipWidth || height < _shipHeight)
{
return;
}
_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)
{
if (width < _shipWidth || height < _shipHeight)
{
return;
}
_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 + _shipWidth > _pictureWidth)
{
x = Math.Max(0, _pictureWidth - _shipWidth);
}
if (y < 0 || y + _shipHeight > _pictureHeight)
{
y = Math.Max(0, _pictureHeight - _shipHeight);
}
_startPosX = x;
_startPosY = y;
}
/// <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,
_ => false,
};
}
/// <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;
}
Pen pen = new(Color.Black);
Brush BodyBrush = new SolidBrush(EntityShip.BodyColor);
// корпус
Point point1 = new Point(_startPosX, _startPosY + 30);
Point point2 = new Point(_startPosX + 140, _startPosY + 30);
Point point3 = new Point(_startPosX + 120, _startPosY + 60);
Point point4 = new Point(_startPosX + 20, _startPosY + 60);
Point[] curvePoints = { point1, point2, point3, point4 };
g.FillPolygon(BodyBrush, curvePoints);
g.DrawPolygon(pen, curvePoints);
// палуба
Brush brBeige = new SolidBrush(Color.Beige);
g.FillRectangle(brBeige, _startPosX + 10, _startPosY + 20, 110, 10);
g.DrawRectangle(pen, _startPosX + 10, _startPosY + 20, 110, 10);
// якорь
Point point_1 = new Point(_startPosX + 130, _startPosY + 40);
Point point_2 = new Point(_startPosX + 130, _startPosY + 33);
g.DrawLine(pen, point_1, point_2);
Point point_3 = new Point(_startPosX + 130, _startPosY + 40);
Point point_4 = new Point(_startPosX + 127, _startPosY + 37);
g.DrawLine(pen, point_3, point_4);
Point point_5 = new Point(_startPosX + 130, _startPosY + 40);
Point point_6 = new Point(_startPosX + 133, _startPosY + 37);
g.DrawLine(pen, point_5, point_6);
Point point_7 = new Point(_startPosX + 129, _startPosY + 35);
Point point_8 = new Point(_startPosX + 131, _startPosY + 35);
g.DrawLine(pen, point_7, point_8);
}
public void SetColor(Color color)
{
if (EntityShip == null)
{
return;
}
EntityShip.BodyColor = color;
}
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
}
}

View File

@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
namespace WarmlyShip.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningWarmlyShip : DrawningShip
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipe">Признак наличия труб</param>
/// <param name="fuelCompartment">Признак наличия отсека для топлива</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах</returns>
public DrawningWarmlyShip(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipe, bool fuelCompartment, int width, int height) :
base(speed, weight, bodyColor, width, height, 140, 60)
{
if (EntityShip != null)
{
EntityShip = new EntityWarmlyShip(speed, weight, bodyColor,
additionalColor, pipe, fuelCompartment);
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (EntityShip is not EntityWarmlyShip warmlyShip)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(warmlyShip.AdditionalColor);
if (warmlyShip.Pipe)
{
//трубы
g.FillRectangle(additionalBrush, _startPosX + 20, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 5, 10, 15);
g.FillRectangle(additionalBrush, _startPosX + 60, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 60, _startPosY + 5, 10, 15);
g.FillRectangle(additionalBrush, _startPosX + 100, _startPosY + 5, 10, 15);
g.DrawRectangle(pen, _startPosX + 100, _startPosY + 5, 10, 15);
Brush brBlack = new SolidBrush(Color.Black);
g.FillRectangle(brBlack, _startPosX + 20, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 20, _startPosY, 10, 5);
g.FillRectangle(brBlack, _startPosX + 60, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 60, _startPosY, 10, 5);
g.FillRectangle(brBlack, _startPosX + 100, _startPosY, 10, 5);
g.DrawRectangle(pen, _startPosX + 100, _startPosY, 10, 5);
}
base.DrawTransport(g);
if (warmlyShip.FuelCompartment)
{
// отсек под топливо
g.FillRectangle(additionalBrush, _startPosX + 30, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 30, _startPosY + 45, 20, 15);
g.FillRectangle(additionalBrush, _startPosX + 50, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 50, _startPosY + 45, 20, 15);
g.FillRectangle(additionalBrush, _startPosX + 70, _startPosY + 45, 20, 15);
g.DrawRectangle(pen, _startPosX + 70, _startPosY + 45, 20, 15);
}
}
public void SetAddColor(Color color)
{
((EntityWarmlyShip)EntityShip).AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,61 @@
using WarmlyShip.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityShip
/// </summary>
public static class ExtentionDrawningShip
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningShip">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningShip drawningship, char separatorForObject)
{
var ship = drawningship.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.Pipe}" +
$"{separatorForObject}{warmlyShip.FuelCompartment}";
}
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.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,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Entities
{
/// <summary>
/// Класс-сущность "Теплоход"
/// </summary>
public class EntityWarmlyShip : EntityShip
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия труб
/// </summary>
public bool Pipe { get; private set; }
/// <summary>
/// Признак (опция) наличия отсека под топливо
/// </summary>
public bool FuelCompartment { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса теплохода
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес теплохода</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipe">Признак наличия труб</param>
/// <param name="fuelCompartment">Признак наличия отсека под топливо</param>
public EntityWarmlyShip(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipe, bool fuelCompartment) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Pipe = pipe;
FuelCompartment = fuelCompartment;
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace WarmlyShip.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,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.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) { }
}
}

296
WarmlyShip/FormShipCollection.Designer.cs generated Normal file
View File

@ -0,0 +1,296 @@
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()
{
pictureBoxCollection = new PictureBox();
toolsPanel = new Panel();
LabelSets = new Label();
panelSets = new Panel();
ListBoxObjects = new ListBox();
textBoxStorageName = new TextBox();
ButtonDelObject = new Button();
ButtonAddObject = new Button();
LabelTools = new Label();
ButtonRefreshCollection = new Button();
ButtonDeleteShip = new Button();
maskedTextBoxNumber = new TextBox();
ButtonAddShip = new Button();
menuStrip = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
toolsPanel.SuspendLayout();
panelSets.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(1, 31);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(655, 471);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// toolsPanel
//
toolsPanel.Controls.Add(ButtonSortByType);
toolsPanel.Controls.Add(ButtonSortByColor);
toolsPanel.Controls.Add(LabelSets);
toolsPanel.Controls.Add(panelSets);
toolsPanel.Controls.Add(LabelTools);
toolsPanel.Controls.Add(ButtonRefreshCollection);
toolsPanel.Controls.Add(ButtonDeleteShip);
toolsPanel.Controls.Add(maskedTextBoxNumber);
toolsPanel.Controls.Add(ButtonAddShip);
toolsPanel.Location = new Point(660, 12);
toolsPanel.Name = "toolsPanel";
toolsPanel.Size = new Size(230, 495);
toolsPanel.TabIndex = 0;
//
// LabelSets
//
LabelSets.AutoSize = true;
LabelSets.Location = new Point(89, 21);
LabelSets.Name = "LabelSets";
LabelSets.Size = new Size(52, 15);
LabelSets.TabIndex = 0;
LabelSets.Text = "Наборы";
//
// panelSets
//
panelSets.Controls.Add(ListBoxObjects);
panelSets.Controls.Add(textBoxStorageName);
panelSets.Controls.Add(ButtonDelObject);
panelSets.Controls.Add(ButtonAddObject);
panelSets.Location = new Point(17, 30);
panelSets.Name = "panelSets";
panelSets.Size = new Size(200, 225);
panelSets.TabIndex = 3;
//
// ListBoxObjects
//
ListBoxObjects.FormattingEnabled = true;
ListBoxObjects.ItemHeight = 15;
ListBoxObjects.Location = new Point(28, 76);
ListBoxObjects.Name = "ListBoxObjects";
ListBoxObjects.Size = new Size(142, 94);
ListBoxObjects.TabIndex = 3;
ListBoxObjects.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(28, 9);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(142, 23);
textBoxStorageName.TabIndex = 2;
//
// ButtonDelObject
//
ButtonDelObject.Location = new Point(28, 180);
ButtonDelObject.Name = "ButtonDelObject";
ButtonDelObject.Size = new Size(142, 33);
ButtonDelObject.TabIndex = 1;
ButtonDelObject.Text = "Удалить набор";
ButtonDelObject.UseVisualStyleBackColor = true;
ButtonDelObject.Click += ButtonDelObject_Click;
//
// ButtonAddObject
//
ButtonAddObject.Location = new Point(28, 38);
ButtonAddObject.Name = "ButtonAddObject";
ButtonAddObject.Size = new Size(142, 32);
ButtonAddObject.TabIndex = 0;
ButtonAddObject.Text = "Добавить набор";
ButtonAddObject.UseVisualStyleBackColor = true;
ButtonAddObject.Click += ButtonAddObject_Click;
//
// LabelTools
//
LabelTools.AutoSize = true;
LabelTools.Location = new Point(85, -3);
LabelTools.Name = "LabelTools";
LabelTools.Size = new Size(83, 15);
LabelTools.TabIndex = 1;
LabelTools.Text = "Инструменты";
//
// ButtonRefreshCollection
//
ButtonRefreshCollection.Location = new Point(45, 453);
ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(142, 37);
ButtonRefreshCollection.TabIndex = 2;
ButtonRefreshCollection.Text = "Обновить коллекцию";
ButtonRefreshCollection.UseVisualStyleBackColor = true;
ButtonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// ButtonDeleteShip
//
ButtonDeleteShip.Location = new Point(45, 410);
ButtonDeleteShip.Name = "ButtonDeleteShip";
ButtonDeleteShip.Size = new Size(142, 37);
ButtonDeleteShip.TabIndex = 2;
ButtonDeleteShip.Text = "Удалить корабль";
ButtonDeleteShip.UseVisualStyleBackColor = true;
ButtonDeleteShip.Click += ButtonDeleteShip_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(68, 381);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(100, 23);
maskedTextBoxNumber.TabIndex = 2;
//
// ButtonAddShip
//
ButtonAddShip.Location = new Point(45, 339);
ButtonAddShip.Name = "ButtonAddShip";
ButtonAddShip.Size = new Size(142, 36);
ButtonAddShip.TabIndex = 2;
ButtonAddShip.Text = "Добавить корабль";
ButtonAddShip.UseVisualStyleBackColor = true;
ButtonAddShip.Click += ButtonAddShip_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(889, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(48, 20);
FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(141, 22);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(141, 22);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(45, 306);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(142, 27);
ButtonSortByColor.TabIndex = 4;
ButtonSortByColor.Text = "Сортировать по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(45, 273);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(142, 27);
ButtonSortByType.TabIndex = 5;
ButtonSortByType.Text = "Сортировать по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(889, 508);
Controls.Add(toolsPanel);
Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection";
Text = "Набор кораблей";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
toolsPanel.ResumeLayout(false);
toolsPanel.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
private void LoadToolStripMenuItem_Click1(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private PictureBox pictureBoxCollection;
private Panel toolsPanel;
private Button ButtonAddShip;
private Label LabelTools;
private TextBox maskedTextBoxNumber;
private Button ButtonDeleteShip;
private Button ButtonRefreshCollection;
private Label LabelSets;
private Panel panelSets;
private ListBox ListBoxObjects;
private TextBox textBoxStorageName;
private Button ButtonDelObject;
private Button ButtonAddObject;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByType;
private Button ButtonSortByColor;
}
}

View File

@ -0,0 +1,279 @@
using WarmlyShip.Generics;
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.DrawningObjects;
using WarmlyShip.MovementStrategy;
using Microsoft.Extensions.Logging;
using WarmlyShip.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace WarmlyShip
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningShip
/// </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 = ListBoxObjects.SelectedIndex;
ListBoxObjects.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
ListBoxObjects.Items.Add(_storage.Keys[i].Name);
}
if (ListBoxObjects.Items.Count > 0 && (index == -1 || index >= ListBoxObjects.Items.Count))
{
ListBoxObjects.SelectedIndex = 0;
}
else if (ListBoxObjects.Items.Count > 0 && index > -1 && index < ListBoxObjects.Items.Count)
{
ListBoxObjects.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[ListBoxObjects.SelectedItem?.ToString() ?? string.Empty]?.ShowShips();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (ListBoxObjects.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {ListBoxObjects.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
string name = (ListBoxObjects.SelectedItem.ToString() ?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
if (ListBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[ListBoxObjects.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormShipConfig form = new();
form.Show();
Action<DrawningShip>? shipDelegate = new((ship) =>
{
try
{
bool isAdditionSuccessful = obj + ship;
MessageBox.Show("Объект добавлен");
ship.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowShips();
Log.Information($"Добавлен объект в коллекцию {ListBoxObjects.SelectedItem.ToString() ?? string.Empty}");
}
catch (ArgumentException ex)
{
Log.Warning($"Добавляемый объект уже существует в коллекции {ListBoxObjects.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
form.AddEvent(shipDelegate);
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteShip_Click(object sender, EventArgs e)
{
if (ListBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[ListBoxObjects.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var isAdditionSuccessful = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {ListBoxObjects.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowShips();
}
catch (ShipNotFoundException ex)
{
Log.Warning($"Не получилось удалить объект из коллекции {ListBoxObjects.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (ListBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[ListBoxObjects.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.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);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
ListBoxObjects.Items.Add(collection);
}
ReloadObjects();
}
catch (Exception ex)
{
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareShips(new ShipCompareByColor());
private void CompareShips(IComparer<DrawningShip?> comparer)
{
if (ListBoxObjects.SelectedIndex == -1)
{
return;
}
var obj = _storage[ListBoxObjects.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowShips();
}
}
}

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>

355
WarmlyShip/FormShipConfig.Designer.cs generated Normal file
View File

@ -0,0 +1,355 @@
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()
{
groupBoxParameters = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
groupBoxColor = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxFuelCompartment = new CheckBox();
checkBoxPipe = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
panelObject = new Panel();
pictureBoxObject = new PictureBox();
labelExtraColor = new Label();
labelColor = new Label();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxParameters.SuspendLayout();
groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxParameters
//
groupBoxParameters.Controls.Add(labelModifiedObject);
groupBoxParameters.Controls.Add(labelSimpleObject);
groupBoxParameters.Controls.Add(groupBoxColor);
groupBoxParameters.Controls.Add(checkBoxFuelCompartment);
groupBoxParameters.Controls.Add(checkBoxPipe);
groupBoxParameters.Controls.Add(numericUpDownWeight);
groupBoxParameters.Controls.Add(numericUpDownSpeed);
groupBoxParameters.Controls.Add(labelWeight);
groupBoxParameters.Controls.Add(labelSpeed);
groupBoxParameters.Location = new Point(12, 12);
groupBoxParameters.Name = "groupBoxParameters";
groupBoxParameters.Size = new Size(407, 207);
groupBoxParameters.TabIndex = 0;
groupBoxParameters.TabStop = false;
groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(309, 150);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(88, 30);
labelModifiedObject.TabIndex = 8;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(215, 150);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(88, 30);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
//
// groupBoxColor
//
groupBoxColor.Controls.Add(panelPurple);
groupBoxColor.Controls.Add(panelYellow);
groupBoxColor.Controls.Add(panelBlack);
groupBoxColor.Controls.Add(panelBlue);
groupBoxColor.Controls.Add(panelGray);
groupBoxColor.Controls.Add(panelGreen);
groupBoxColor.Controls.Add(panelWhite);
groupBoxColor.Controls.Add(panelRed);
groupBoxColor.Location = new Point(215, 22);
groupBoxColor.Name = "groupBoxColor";
groupBoxColor.Size = new Size(183, 115);
groupBoxColor.TabIndex = 6;
groupBoxColor.TabStop = false;
groupBoxColor.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(138, 66);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(38, 38);
panelPurple.TabIndex = 5;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(138, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(38, 38);
panelYellow.TabIndex = 4;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(94, 66);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(38, 38);
panelBlack.TabIndex = 3;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(94, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(38, 38);
panelBlue.TabIndex = 2;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(50, 66);
panelGray.Name = "panelGray";
panelGray.Size = new Size(38, 38);
panelGray.TabIndex = 1;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(50, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(38, 38);
panelGreen.TabIndex = 0;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(6, 66);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(38, 38);
panelWhite.TabIndex = 0;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(6, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(38, 38);
panelRed.TabIndex = 0;
//
// checkBoxFuelCompartment
//
checkBoxFuelCompartment.AutoSize = true;
checkBoxFuelCompartment.Location = new Point(6, 138);
checkBoxFuelCompartment.Name = "checkBoxFuelCompartment";
checkBoxFuelCompartment.Size = new Size(186, 19);
checkBoxFuelCompartment.TabIndex = 5;
checkBoxFuelCompartment.Text = "Наличие отсека под топливо";
checkBoxFuelCompartment.UseVisualStyleBackColor = true;
//
// checkBoxPipe
//
checkBoxPipe.AutoSize = true;
checkBoxPipe.Location = new Point(6, 102);
checkBoxPipe.Name = "checkBoxPipe";
checkBoxPipe.Size = new Size(103, 19);
checkBoxPipe.TabIndex = 4;
checkBoxPipe.Text = "Наличие труб";
checkBoxPipe.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(76, 61);
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(74, 23);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(76, 27);
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(74, 23);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(6, 63);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(6, 29);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(pictureBoxObject);
panelObject.Controls.Add(labelExtraColor);
panelObject.Controls.Add(labelColor);
panelObject.Location = new Point(434, 12);
panelObject.Name = "panelObject";
panelObject.Size = new Size(345, 217);
panelObject.TabIndex = 2;
panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(7, 40);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(331, 167);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// labelExtraColor
//
labelExtraColor.AllowDrop = true;
labelExtraColor.BorderStyle = BorderStyle.FixedSingle;
labelExtraColor.Location = new Point(215, 7);
labelExtraColor.Name = "labelExtraColor";
labelExtraColor.Size = new Size(89, 30);
labelExtraColor.TabIndex = 2;
labelExtraColor.Text = "Доп. цвет";
labelExtraColor.TextAlign = ContentAlignment.MiddleCenter;
labelExtraColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
labelExtraColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(44, 7);
labelColor.Name = "labelColor";
labelColor.Size = new Size(89, 30);
labelColor.TabIndex = 1;
labelColor.Text = "Цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
labelColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// buttonAdd
//
buttonAdd.Location = new Point(478, 235);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(89, 32);
buttonAdd.TabIndex = 3;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonCancel
//
buttonCancel.Location = new Point(649, 235);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(89, 32);
buttonCancel.TabIndex = 4;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormShipConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(791, 279);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxParameters);
Name = "FormShipConfig";
Text = "Создание объекта";
groupBoxParameters.ResumeLayout(false);
groupBoxParameters.PerformLayout();
groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private Label labelWeight;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private CheckBox checkBoxFuelCompartment;
private CheckBox checkBoxPipe;
private GroupBox groupBoxColor;
private Panel panelPurple;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelBlue;
private Panel panelGray;
private Panel panelGreen;
private Panel panelWhite;
private Panel panelRed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Panel panelObject;
private Button buttonAdd;
private Button buttonCancel;
private PictureBox pictureBoxObject;
private Label labelExtraColor;
private Label labelColor;
}
}

View File

@ -0,0 +1,198 @@
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 System.Windows.Forms.VisualStyles;
using WarmlyShip.DrawningObjects;
namespace WarmlyShip
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormShipConfig : Form
{
/// <summary>
/// Переменная-выбранный корабль
/// </summary>
DrawningShip? _ship = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningShip>? 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;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
labelModifiedObject.MouseDown += LabelObject_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>
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, checkBoxPipe.Checked, checkBoxFuelCompartment.Checked,
pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
labelColor.BackColor = Color.Empty;
labelExtraColor.BackColor = Color.Empty;
DrawShip();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship == null)
{
return;
}
labelColor.BackColor = (Color)e.Data.GetData(typeof(Color));
_ship.SetColor(labelColor.BackColor);
DrawShip();
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if ((_ship == null) || (_ship is DrawningWarmlyShip == false))
{
return;
}
labelExtraColor.BackColor = (Color)e.Data.GetData(typeof(Color));
((DrawningWarmlyShip)_ship).SetAddColor(labelExtraColor.BackColor);
DrawShip();
}
/// <summary>
/// Добавление корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_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>

194
WarmlyShip/FormWarmlyShip.Designer.cs generated Normal file
View File

@ -0,0 +1,194 @@
namespace WarmlyShip
{
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()
{
pictureBoxWarmlyShip = new PictureBox();
buttonLeft = new Button();
buttonRight = new Button();
buttonUp = new Button();
buttonDown = new Button();
comboBoxStrategy = new ComboBox();
buttonCreateShip = new Button();
buttonStep = new Button();
buttonCreateWarmlyShip = new Button();
ButtonSelectedShip = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyShip).BeginInit();
SuspendLayout();
//
// pictureBoxWarmlyShip
//
pictureBoxWarmlyShip.Dock = DockStyle.Fill;
pictureBoxWarmlyShip.Location = new Point(0, 0);
pictureBoxWarmlyShip.Name = "pictureBoxWarmlyShip";
pictureBoxWarmlyShip.Size = new Size(884, 461);
pictureBoxWarmlyShip.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxWarmlyShip.TabIndex = 0;
pictureBoxWarmlyShip.TabStop = false;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.влево;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(770, 419);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.вправо;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(842, 419);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 3;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.вверх;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(806, 383);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 4;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.вниз;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(806, 419);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 5;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "к центру", "к краю" });
comboBoxStrategy.Location = new Point(751, 24);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 6;
//
// buttonCreateShip
//
buttonCreateShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateShip.Location = new Point(108, 407);
buttonCreateShip.Name = "buttonCreateShip";
buttonCreateShip.Size = new Size(80, 42);
buttonCreateShip.TabIndex = 7;
buttonCreateShip.Text = "Создать корабль";
buttonCreateShip.UseVisualStyleBackColor = true;
buttonCreateShip.Click += buttonCreateShip_Click;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(797, 53);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 23);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonCreateWarmlyShip
//
buttonCreateWarmlyShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateWarmlyShip.Location = new Point(12, 407);
buttonCreateWarmlyShip.Name = "buttonCreateWarmlyShip";
buttonCreateWarmlyShip.Size = new Size(80, 42);
buttonCreateWarmlyShip.TabIndex = 9;
buttonCreateWarmlyShip.Text = "Создать теплоход";
buttonCreateWarmlyShip.UseVisualStyleBackColor = true;
buttonCreateWarmlyShip.Click += buttonCreateWarmlyShip_Click;
//
// ButtonSelectedShip
//
ButtonSelectedShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonSelectedShip.Location = new Point(213, 407);
ButtonSelectedShip.Name = "ButtonSelectedShip";
ButtonSelectedShip.Size = new Size(105, 42);
ButtonSelectedShip.TabIndex = 10;
ButtonSelectedShip.Text = "Добавить корабль";
ButtonSelectedShip.UseVisualStyleBackColor = true;
ButtonSelectedShip.Click += ButtonSelectedShip_Click;
//
// FormWarmlyShip
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(ButtonSelectedShip);
Controls.Add(buttonCreateWarmlyShip);
Controls.Add(buttonStep);
Controls.Add(buttonCreateShip);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(pictureBoxWarmlyShip);
Name = "FormWarmlyShip";
StartPosition = FormStartPosition.CenterScreen;
Text = "Теплоход";
Click += ButtonMove_Click;
((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyShip).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxWarmlyShip;
private Button buttonLeft;
private Button buttonRight;
private Button buttonUp;
private Button buttonDown;
private ComboBox comboBoxStrategy;
private Button buttonCreateShip;
private Button buttonStep;
private Button buttonCreateWarmlyShip;
private Button ButtonSelectedShip;
}
}

View File

@ -0,0 +1,175 @@
using WarmlyShip.DrawningObjects;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
{
public partial class FormWarmlyShip : Form
{
/// <summary>
/// Форма работы с объектом "Теплоход"
/// </summary>
private DrawningShip? _drawningShip;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Выбранный корабль
/// </summary>
public DrawningShip? SelectedShip { get; private set; }
/// <summary>
/// Инициализация формы
/// </summary>
public FormWarmlyShip()
{
InitializeComponent();
_strategy = null;
SelectedShip = null;
}
/// <summary>
/// Метод прорисовки корабля
/// </summary>
private void Draw()
{
if (_drawningShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningShip.DrawTransport(gr);
pictureBoxWarmlyShip.Image = bmp;
}
/// <summary>
/// Обработка нажатия кнопки "Создать теплоход"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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 dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDopColor = new();
if (dialogDopColor.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDopColor.Color;
}
_drawningShip = new DrawningWarmlyShip(random.Next(100, 300),
random.Next(1000, 3000), color, dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать корабль"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateShip_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;
}
_drawningShip = new DrawningShip(random.Next(100, 300), random.Next(1000, 3000),
color, pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawningShip.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 (_drawningShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningShip.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningShip == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(_drawningShip.GetMoveableObject,
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
private void ButtonSelectedShip_Click(object sender, EventArgs e)
{
SelectedShip = _drawningShip;
DialogResult = DialogResult.OK;
}
}
}

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,66 @@
using WarmlyShip.DrawningObjects;
using WarmlyShip.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Generics
{
internal class DrawiningShipEqutables : IEqualityComparer<DrawningShip?>
{
public bool Equals(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityShip == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityShip.Speed != y.EntityShip.Speed)
{
return false;
}
if (x.EntityShip.Weight != y.EntityShip.Weight)
{
return false;
}
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
{
return false;
}
if (x is DrawningWarmlyShip && y is DrawningWarmlyShip)
{
EntityWarmlyShip EntityX = (EntityWarmlyShip)x.EntityShip;
EntityWarmlyShip EntityY = (EntityWarmlyShip)y.EntityShip;
if (EntityX.Pipe != EntityY.Pipe)
{
return false;
}
if (EntityX.FuelCompartment != EntityY.FuelCompartment)
{
return false;
}
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip? obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,145 @@
using WarmlyShip.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.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>
/// Максимальное количество объектов в cписке
/// </summary>
private readonly int _maxCount;
//// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="ship">Добавляемый корабль</param>
/// <returns></returns>
public void Insert(T ship, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
Insert(ship, 0, equal);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="ship">Добавляемый корабль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public void Insert(T ship, int position, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (!(position >= 0 && position <= Count))
{
throw new Exception("Неверная позиция для вставки");
}
if (equal != null)
{
if (_places.Contains(ship, equal))
{
throw new ArgumentException(nameof(ship));
}
}
_places.Insert(position, ship);
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public void Remove(int position)
{
if (!(position >= 0 && position < Count))
{
throw new ShipNotFoundException(position);
}
_places.RemoveAt(position);
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (!(position >= 0 && position < Count))
{
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
return;
}
_places.Insert(position, value);
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> 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,39 @@
using WarmlyShip.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Generics
{
internal class ShipCompareByColor : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityShip == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.EntityShip.BodyColor.Name != y.EntityShip.BodyColor.Name)
{
return x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}
}

View File

@ -0,0 +1,36 @@
using WarmlyShip.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Generics
{
internal class ShipCompareByType : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityShip == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Generics
{
internal class ShipsCollectionInfo : IEquatable<ShipsCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public ShipsCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(ShipsCollectionInfo? other)
{
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
using WarmlyShip.DrawningObjects;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningShip
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class ShipsGenericCollection<T, U>
where T : DrawningShip
where U : IMoveableObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetShips => _collection.GetShips();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <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 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 || collect == null)
{
return false;
}
collect?._collection.Insert(obj, new DrawiningShipEqutables());
return true;
}
/// <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];
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 inRow = _pictureWidth / _placeSizeWidth;
ship.SetPosition((inRow - 1 - (i % inRow)) * _placeSizeWidth, i / inRow * _placeSizeHeight);
ship.DrawTransport(g);
}
i++;
}
}
}
}

View File

@ -0,0 +1,194 @@
using WarmlyShip.DrawningObjects;
using WarmlyShip.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class ShipsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<ShipsCollectionInfo, ShipsGenericCollection<DrawningShip,
DrawningObjectShip>> _shipStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<ShipsCollectionInfo> 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<ShipsCollectionInfo, ShipsGenericCollection<DrawningShip, DrawningObjectShip>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Сохранение информации по кораблям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<ShipsCollectionInfo, 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.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new IOException("Невалидная операция, нет данных для сохранения");
}
string toWrite = $"ShipStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
}
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("ShipStorage"))
{
throw new IOException("Неверный формат данных");
}
_shipStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
ShipsGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningShip? ship =
elem?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null)
{
if (!(collection + ship))
{
throw new IOException("Ошибка добавления в коллекцию");
}
}
}
_shipStorages.Add(new ShipsCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine();
} while (str != null);
}
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_shipStorages.Add(new ShipsCollectionInfo(name, string.Empty), new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_shipStorages.ContainsKey(new ShipsCollectionInfo(name, string.Empty)))
{
return;
}
_shipStorages.Remove(new ShipsCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public ShipsGenericCollection<DrawningShip, DrawningObjectShip>? this[string ind]
{
get
{
ShipsCollectionInfo indObj = new ShipsCollectionInfo(ind, string.Empty);
if (_shipStorages.ContainsKey(indObj))
{
return _shipStorages[indObj];
}
return null;
}
}
}
}

View File

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

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawningObjects;
namespace WarmlyShip.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,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

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

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

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

View File

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

39
WarmlyShip/Program.cs Normal file
View File

@ -0,0 +1,39 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace WarmlyShip
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormShipCollection());
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WarmlyShip.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("WarmlyShip.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap вверх {
get {
object obj = ResourceManager.GetObject("вверх", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap влево {
get {
object obj = ResourceManager.GetObject("влево", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap вниз {
get {
object obj = ResourceManager.GetObject("вниз", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap вправо {
get {
object obj = ResourceManager.GetObject("вправо", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project>

25
WarmlyShip/WarmlyShip.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34009.444
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarmlyShip", "WarmlyShip.csproj", "{0018A18F-D303-49EF-A7D8-E6683502F37E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0018A18F-D303-49EF-A7D8-E6683502F37E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0018A18F-D303-49EF-A7D8-E6683502F37E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0018A18F-D303-49EF-A7D8-E6683502F37E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0018A18F-D303-49EF-A7D8-E6683502F37E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9E1BEB6C-AFC9-4992-A796-6725C50A2411}
EndGlobalSection
EndGlobal

View File

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

13
WarmlyShip/nlog.config Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>