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

This commit is contained in:
victinass 2024-03-24 16:13:12 +04:00
parent 3b0784dd0b
commit 3fa56e548d
8 changed files with 124 additions and 71 deletions

View File

@ -7,7 +7,7 @@ public abstract class AbstractCompany
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 210;
protected readonly int _placeSizeWidth = 238;
/// <summary>
/// Размер места (высота)
@ -29,7 +29,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _pictureHeight);
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight) + 2;
/// <summary>
@ -52,9 +52,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <returns></returns>
public static bool operator +(AbstractCompany company, DrawingWarship car)
public static int operator +(AbstractCompany company, DrawingWarship warship)
{
return company._collection?.Insert(car) ?? false;
return company._collection.Insert(warship);
}
/// <summary>
@ -63,9 +63,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static bool operator -(AbstractCompany company, int position)
public static DrawingWarship operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position) ?? false;
return company._collection.Remove(position);
}
/// <summary>
@ -89,7 +89,7 @@ public abstract class AbstractCompany
DrawBackground(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); i++)
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawingWarship? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);

View File

@ -14,7 +14,7 @@ public interface ICollectionGenericObjects<T>
int Count { get; }
/// <summary>
/// Установка минимального количества элементов
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
@ -23,7 +23,7 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj);
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@ -31,14 +31,14 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position);
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
bool Remove(int position);
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции

View File

@ -1,14 +1,16 @@
namespace Battleship.CollectionGenericObjects;
using Battleship.CollectionGenericObjects;
//namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Параметрированный набор объектов
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые хранили
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
@ -21,76 +23,88 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T>();
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
//TODO проверка позиции
if(position >= _collection.Length || position < 0)
// TODO проверка позиции
if (position >= _collection.Length || position < 0)
{
return null;
}
return _collection[position];
}
public bool Insert(T obj)
public int Insert(T obj)
{
//TODO вставка в свободное место набора
// TODO вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return true;
return index;
}
index++;
}
return false;
return -1;
}
public bool Insert(T obj, int position)
public int Insert(T obj, int position)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
return false;
return -1;
while (position + 1 < _collection.Length)
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
if (_collection[position] != null)
{
if (_collection[position] == null)
// проверка, что после вставляемого элемента в массиве есть пустой элемент
int nullIndex = -1;
for (int i = position + 1; i < Count; i++)
{
_collection[position] = obj;
return true;
if (_collection[i] == null)
{
nullIndex = i;
break;
}
position++;
++index;
}
while (position - 1 >= 0)
// Если пустого элемента нет, то выходим
if (nullIndex < 0)
{
if (_collection[position] == null)
return -1;
}
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
int j = nullIndex - 1;
while (j >= position)
{
_collection[position] = obj;
return true;
_collection[j + 1] = _collection[j];
j--;
}
position--;
}
return false;
// TODO вставка по позиции
_collection[position] = obj;
return position;
}
public bool Remove(int position)
public T? Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{
return false;
return null;
}
T temp = _collection[position];
_collection[position] = null;
return true;
return temp;
}
}

View File

@ -2,16 +2,24 @@
namespace Battleship.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - доки
/// </summary>
public class WarshipSharingService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public WarshipSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingWarship> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
Pen pen = new(Color.DarkSlateBlue, 4);
for (int i = 0; i <= _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j <= _pictureHeight / _placeSizeHeight; j++)
@ -22,20 +30,21 @@ public class WarshipSharingService : AbstractCompany
}
}
//установка объектов
protected override void SetObjectsPosition()
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int posWidth = 0;
int posHeight = height;
int posHeight = height - 1;
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection?.Get(i) != null)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * posWidth + 4, posHeight * _placeSizeHeight + 4, width, height);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * posWidth + 4, posHeight * _placeSizeHeight + 4);
}
if (posWidth < width)

View File

@ -17,9 +17,7 @@ public class DrawingBattleship : DrawingWarship
/// <param name="bodyDeck">Признак наличия палубы</param>
/// <param name="compartment">Признак наличия отсека для ракет</param>
/// <param name="tower">Признак наличия башни</param>
///
public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 60)
public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 80)
{
EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor);
}

View File

@ -37,7 +37,7 @@ public class DrawingWarship
/// <summary>
/// Высота прорисовки военного корабля
/// </summary>
private readonly int _drawingWarshipHeight = 40;
private readonly int _drawingWarshipHeight = 80;
/// <summary>
/// Координата Х объекта
@ -135,7 +135,7 @@ public class DrawingWarship
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y, int width, int height)
public void SetPosition(int x, int y)
{
if (!_pictureWidth.HasValue || !_pictureHeight.HasValue)
{

View File

@ -51,9 +51,9 @@
groupBoxTools.Controls.Add(buttonAddWarship);
groupBoxTools.Controls.Add(comboBoxSelectionCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(706, 0);
groupBoxTools.Location = new Point(861, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(273, 594);
groupBoxTools.Size = new Size(292, 583);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -63,18 +63,18 @@
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(12, 477);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(255, 42);
buttonRefresh.Size = new Size(274, 42);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
buttonRefresh.Click += ButtonRefresh_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(12, 381);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(255, 42);
buttonGoToCheck.Size = new Size(274, 42);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -85,7 +85,7 @@
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveWarship.Location = new Point(12, 283);
buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(255, 42);
buttonRemoveWarship.Size = new Size(274, 42);
buttonRemoveWarship.TabIndex = 4;
buttonRemoveWarship.Text = "Удалить корабль";
buttonRemoveWarship.UseVisualStyleBackColor = true;
@ -96,7 +96,7 @@
maskedTextBox.Location = new Point(12, 238);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(255, 27);
maskedTextBox.Size = new Size(274, 27);
maskedTextBox.TabIndex = 3;
//
// buttonAddBattleship
@ -104,22 +104,22 @@
buttonAddBattleship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBattleship.Location = new Point(12, 143);
buttonAddBattleship.Name = "buttonAddBattleship";
buttonAddBattleship.Size = new Size(255, 42);
buttonAddBattleship.Size = new Size(274, 42);
buttonAddBattleship.TabIndex = 2;
buttonAddBattleship.Text = "Добавление линкора";
buttonAddBattleship.UseVisualStyleBackColor = true;
buttonAddBattleship.Click += buttonAddBattleship_Click;
buttonAddBattleship.Click += ButtonAddBattleship_Click;
//
// buttonAddWarship
//
buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddWarship.Location = new Point(12, 95);
buttonAddWarship.Name = "buttonAddWarship";
buttonAddWarship.Size = new Size(255, 42);
buttonAddWarship.Size = new Size(274, 42);
buttonAddWarship.TabIndex = 1;
buttonAddWarship.Text = "Добавление корабля";
buttonAddWarship.UseVisualStyleBackColor = true;
buttonAddWarship.Click += buttonAddWarship_Click;
buttonAddWarship.Click += ButtonAddWarship_Click;
//
// comboBoxSelectionCompany
//
@ -129,7 +129,7 @@
comboBoxSelectionCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectionCompany.Location = new Point(12, 26);
comboBoxSelectionCompany.Name = "comboBoxSelectionCompany";
comboBoxSelectionCompany.Size = new Size(255, 28);
comboBoxSelectionCompany.Size = new Size(274, 28);
comboBoxSelectionCompany.TabIndex = 0;
comboBoxSelectionCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
@ -138,7 +138,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(706, 594);
pictureBox.Size = new Size(861, 583);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -146,7 +146,7 @@
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(979, 594);
ClientSize = new Size(1153, 583);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormWarshipCollection";

View File

@ -63,7 +63,7 @@ public partial class FormWarshipCollection : Form
return;
}
if (_company + drawingWarship)
if (_company + drawingWarship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
@ -90,12 +90,44 @@ public partial class FormWarshipCollection : Form
return color;
}
/// <summary>
/// Передача на тесты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawingWarship? warship = null;
int counter = 120;
while (warship == null)
{
warship = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
FormBattleship form = new()
{
SetWarship = warship
};
form.ShowDialog();
}
/// <summary>
/// Добавление линкора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddBattleship_Click(object sender, EventArgs e)
private void ButtonAddBattleship_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawingBattleship));
}
@ -105,7 +137,7 @@ public partial class FormWarshipCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddWarship_Click(object sender, EventArgs e)
private void ButtonAddWarship_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawingWarship));
}
@ -115,7 +147,7 @@ public partial class FormWarshipCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveCar_Click(object sender, EventArgs e)
private void buttonRemoveWarship_Click_1(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
@ -128,7 +160,7 @@ public partial class FormWarshipCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos)
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
@ -174,7 +206,7 @@ public partial class FormWarshipCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefresh_Click(object sender, EventArgs e)
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{