Лабораторная работа №3

This commit is contained in:
Aidar 2024-04-19 22:59:06 +04:00
parent 4cf0ced6ca
commit da9d37f184
10 changed files with 841 additions and 85 deletions

View File

@ -0,0 +1,122 @@
using ProjectLiner.Drawnings;
namespace ProjectLiner.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию кораблей
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 159;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 73;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция кораблей
/// </summary>
protected ICollectionGenericObjects<DrawningShip>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount =>(_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция автомобилей</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningShip> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="ship">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningShip ship)
{
if (company._collection == null)
{
return -1;
}
return company._collection.Insert(ship);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningShip operator -(AbstractCompany company, int position)
{
if (company._collection == null)
{
return null;
}
return company._collection.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningShip? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningShip? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,48 @@
namespace ProjectLiner.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
}

View File

@ -0,0 +1,101 @@

namespace ProjectLiner.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
{
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position >= 0 && position < Count) return _collection[position];
else return null;
}
public int Insert(T obj)
{
return Insert(obj, 0);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
return -1;
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
for (int i = position; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
for (int i = position - 1; i >= 0; --i)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
return -1;
}
public T? Remove(int position)
{
if (position < 0 || position >= _collection.Count())
{
return null;
}
if (_collection[position] != null)
{
T obj = _collection[position];
_collection[position] = null;
return obj;
}
return null;
}
}

View File

@ -0,0 +1,66 @@
using ProjectLiner.Drawnings;
namespace ProjectLiner.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - шипшеринг
/// </summary>
public class ShipSharingService : AbstractCompany
{
private List<Tuple<int, int>> locCoord = new List<Tuple<int, int>>();
private int countInRow;
private int countOfRows;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public ShipSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningShip> collection) :
base(picWidth, picHeight, collection) {}
protected override void DrawBackgound(Graphics g)
{
Pen pen = new Pen(Color.Brown);
int x = 0, y = 0;
while (y + _placeSizeHeight <= _pictureHeight)
{
int count = 0;
while (x + _placeSizeWidth <= _pictureWidth)
{
count++;
g.DrawLine(pen, x, y, x + _placeSizeWidth, y);
g.DrawLine(pen, x, y, x, y + _placeSizeHeight);
g.DrawLine(pen, x, y + _placeSizeHeight, x + _placeSizeWidth, y + _placeSizeHeight);
g.DrawLine(pen, x + _placeSizeWidth, y + _placeSizeHeight, x + _placeSizeWidth, y);
locCoord.Add(new Tuple<int, int>(x, y));
x += _placeSizeWidth + 2;
}
countInRow = count;
x = 1;
y += _placeSizeHeight + 5;
countOfRows++;
}
}
protected override void SetObjectsPosition()
{
if (locCoord == null || _collection == null)
{
return;
}
int row = 1, col = 1;
for (int i = 0; i < _collection?.Count; i++, col++)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * countInRow - col].Item1 + 5, locCoord[row * countInRow - col].Item2 + 5);
if (col == countInRow)
{
col = 0;
row++
;
}
}
}
}

View File

@ -29,12 +29,10 @@
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxLiner = new PictureBox(); pictureBoxLiner = new PictureBox();
buttonCreateShip = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonCreateLiner = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button(); buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxLiner).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxLiner).BeginInit();
@ -45,27 +43,16 @@
pictureBoxLiner.Dock = DockStyle.Fill; pictureBoxLiner.Dock = DockStyle.Fill;
pictureBoxLiner.Location = new Point(0, 0); pictureBoxLiner.Location = new Point(0, 0);
pictureBoxLiner.Name = "pictureBoxLiner"; pictureBoxLiner.Name = "pictureBoxLiner";
pictureBoxLiner.Size = new Size(884, 461); pictureBoxLiner.Size = new Size(1184, 661);
pictureBoxLiner.TabIndex = 0; pictureBoxLiner.TabIndex = 0;
pictureBoxLiner.TabStop = false; pictureBoxLiner.TabStop = false;
// //
// buttonCreateShip
//
buttonCreateShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateShip.Location = new Point(12, 426);
buttonCreateShip.Name = "buttonCreateShip";
buttonCreateShip.Size = new Size(154, 23);
buttonCreateShip.TabIndex = 1;
buttonCreateShip.Text = "Создать корабль";
buttonCreateShip.UseVisualStyleBackColor = true;
buttonCreateShip.Click += ButtonCreateShip_Click;
//
// buttonRight // buttonRight
// //
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.buttonRight; buttonRight.BackgroundImage = Properties.Resources.buttonRight;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom; buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(842, 419); buttonRight.Location = new Point(1142, 619);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30); buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 2; buttonRight.TabIndex = 2;
@ -77,7 +64,7 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.buttonDown; buttonDown.BackgroundImage = Properties.Resources.buttonDown;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom; buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(806, 419); buttonDown.Location = new Point(1106, 619);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30); buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3; buttonDown.TabIndex = 3;
@ -89,7 +76,7 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.buttonLeft; buttonLeft.BackgroundImage = Properties.Resources.buttonLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom; buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(770, 419); buttonLeft.Location = new Point(1070, 619);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30); buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4; buttonLeft.TabIndex = 4;
@ -101,37 +88,28 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.buttonUp; buttonUp.BackgroundImage = Properties.Resources.buttonUp;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom; buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(806, 383); buttonUp.Location = new Point(1106, 583);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30); buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 5; buttonUp.TabIndex = 5;
buttonUp.UseVisualStyleBackColor = true; buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click; buttonUp.Click += ButtonMove_Click;
// //
// buttonCreateLiner
//
buttonCreateLiner.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateLiner.Location = new Point(172, 426);
buttonCreateLiner.Name = "buttonCreateLiner";
buttonCreateLiner.Size = new Size(154, 23);
buttonCreateLiner.TabIndex = 6;
buttonCreateLiner.Text = "Создать лайнер";
buttonCreateLiner.UseVisualStyleBackColor = true;
buttonCreateLiner.Click += ButtonCreateLiner_Click;
//
// comboBoxStrategy // comboBoxStrategy
// //
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true; comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(751, 12); comboBoxStrategy.Location = new Point(1051, 12);
comboBoxStrategy.Name = "comboBoxStrategy"; comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23); comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7; comboBoxStrategy.TabIndex = 7;
// //
// buttonStrategyStep // buttonStrategyStep
// //
buttonStrategyStep.Location = new Point(797, 41); buttonStrategyStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStrategyStep.Location = new Point(1097, 41);
buttonStrategyStep.Name = "buttonStrategyStep"; buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23); buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 8; buttonStrategyStep.TabIndex = 8;
@ -143,15 +121,13 @@
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461); ClientSize = new Size(1184, 661);
Controls.Add(buttonStrategyStep); Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateLiner);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonCreateShip);
Controls.Add(pictureBoxLiner); Controls.Add(pictureBoxLiner);
Name = "FormLiner"; Name = "FormLiner";
StartPosition = FormStartPosition.CenterScreen; StartPosition = FormStartPosition.CenterScreen;
@ -163,12 +139,10 @@
#endregion #endregion
private PictureBox pictureBoxLiner; private PictureBox pictureBoxLiner;
private Button buttonCreateShip;
private Button buttonRight; private Button buttonRight;
private Button buttonDown; private Button buttonDown;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonCreateLiner;
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button buttonStrategyStep; private Button buttonStrategyStep;
} }

View File

@ -18,6 +18,21 @@ public partial class FormLiner : Form
/// </summary> /// </summary>
private AbstractStrategy? _strategy; private AbstractStrategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawningShip SetShip
{
set
{
_drawningShip = value;
_drawningShip.SetPictureSize(pictureBoxLiner.Width, pictureBoxLiner.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary> /// <summary>
/// Конструктор формы /// Конструктор формы
/// </summary> /// </summary>
@ -36,59 +51,12 @@ public partial class FormLiner : Form
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxLiner.Width, Bitmap bmp = new(pictureBoxLiner.Width, pictureBoxLiner.Height);
pictureBoxLiner.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningShip.DrawTransport(gr); _drawningShip.DrawTransport(gr);
pictureBoxLiner.Image = bmp; pictureBoxLiner.Image = bmp;
} }
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningShip):
_drawningShip = new DrawningShip(
random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningLiner):
_drawningShip = new DrawningLiner(
random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_drawningShip.SetPictureSize(pictureBoxLiner.Width, pictureBoxLiner.Height);
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать лайнер"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateLiner_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLiner));
/// <summary>
/// Обработка нажатия кнопки "Создать корабль"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateShip_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningShip));
/// <summary> /// <summary>
/// Обработка нажатия кнопок навигации движения /// Обработка нажатия кнопок навигации движения
/// </summary> /// </summary>

View File

@ -0,0 +1,175 @@
namespace ProjectLiner
{
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()
{
groupBoxTools = new GroupBox();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonRemoveShip = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddLiner = new Button();
buttonAddShip = new Button();
ComboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
colorDialog1 = new ColorDialog();
groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonRefresh);
groupBoxTools.Controls.Add(buttonGoToCheck);
groupBoxTools.Controls.Add(buttonRemoveShip);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddLiner);
groupBoxTools.Controls.Add(buttonAddShip);
groupBoxTools.Controls.Add(ComboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(1006, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(178, 561);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 302);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(178, 40);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(0, 256);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(178, 40);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRemoveShip
//
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(0, 191);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(178, 40);
buttonRemoveShip.TabIndex = 4;
buttonRemoveShip.Text = "Удаление корабля";
buttonRemoveShip.UseVisualStyleBackColor = true;
buttonRemoveShip.Click += ButtonRemoveShip_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(0, 162);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(178, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonAddLiner
//
buttonAddLiner.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddLiner.Location = new Point(0, 97);
buttonAddLiner.Name = "buttonAddLiner";
buttonAddLiner.Size = new Size(178, 40);
buttonAddLiner.TabIndex = 2;
buttonAddLiner.Text = "Добавление лайнера";
buttonAddLiner.UseVisualStyleBackColor = true;
buttonAddLiner.Click += buttonAddLiner_Click;
//
// buttonAddShip
//
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(0, 51);
buttonAddShip.Name = "buttonAddShip";
buttonAddShip.Size = new Size(178, 40);
buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавление корабля";
buttonAddShip.UseVisualStyleBackColor = true;
buttonAddShip.Click += buttonAddShip_Click;
//
// ComboBoxSelectorCompany
//
ComboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ComboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
ComboBoxSelectorCompany.FormattingEnabled = true;
ComboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
ComboBoxSelectorCompany.Location = new Point(0, 22);
ComboBoxSelectorCompany.Name = "ComboBoxSelectorCompany";
ComboBoxSelectorCompany.Size = new Size(178, 23);
ComboBoxSelectorCompany.TabIndex = 0;
ComboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1006, 561);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1184, 561);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormShipCollection";
Text = "Коллекция кораблей";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private ComboBox ComboBoxSelectorCompany;
private Button buttonAddLiner;
private Button buttonAddShip;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Button buttonRemoveShip;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private ColorDialog colorDialog1;
}
}

View File

@ -0,0 +1,179 @@
using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Drawnings;
namespace ProjectLiner;
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormShipCollection : Form
{
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
{
InitializeComponent();
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (ComboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new ShipSharingService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningShip>());
break;
}
}
/// <summary>
/// Добавление корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddShip_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningShip));
/// <summary>
/// Добавление лайнера
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddLiner_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningLiner));
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningShip drawningShip;
switch (type)
{
case nameof(DrawningShip):
drawningShip = new DrawningShip(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningLiner):
drawningShip = new DrawningLiner(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random),
GetColor(random),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningShip != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningShip? ship = null;
int counter = 100;
while (ship == null)
{
ship = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (ship == null)
{
return;
}
FormLiner form = new();
form.SetShip = ship;
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
}

View File

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

View File

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